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) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.ComponentModel; using System.Diagnostics; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using System.Text; using System.Threading; using System.Threading.Tasks; using JetBrains.Annotations; using Microsoft.EntityFrameworkCore.Diagnostics; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Internal; using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Metadata.Internal; using Microsoft.EntityFrameworkCore.Storage; using Microsoft.EntityFrameworkCore.Update; using Microsoft.EntityFrameworkCore.Utilities; namespace Microsoft.EntityFrameworkCore.ChangeTracking.Internal { /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public abstract partial class InternalEntityEntry : IUpdateEntry { // ReSharper disable once FieldCanBeMadeReadOnly.Local private readonly StateData _stateData; private OriginalValues _originalValues; private RelationshipsSnapshot _relationshipsSnapshot; private SidecarValues _temporaryValues; private SidecarValues _storeGeneratedValues; /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> protected InternalEntityEntry( [NotNull] IStateManager stateManager, [NotNull] IEntityType entityType) { StateManager = stateManager; EntityType = entityType; _stateData = new StateData(entityType.PropertyCount(), entityType.NavigationCount()); } /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public abstract object Entity { get; } /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> void IUpdateEntry.SetOriginalValue(IProperty property, object value) => SetOriginalValue(property, value); /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> void IUpdateEntry.SetPropertyModified(IProperty property) => SetPropertyModified(property); /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public virtual IEntityType EntityType { [DebuggerStepThrough] get; } /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> EntityState IUpdateEntry.EntityState { get => EntityState; set => SetEntityState(value, modifyProperties: false); } /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public virtual IStateManager StateManager { [DebuggerStepThrough] get; } /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public virtual InternalEntityEntry SharedIdentityEntry { get; [param: CanBeNull] set; } /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public virtual void SetEntityState( EntityState entityState, bool acceptChanges = false, bool modifyProperties = true, EntityState? forceStateWhenUnknownKey = null) { var oldState = _stateData.EntityState; var adding = PrepareForAdd(entityState); entityState = PropagateToUnknownKey(oldState, entityState, adding, forceStateWhenUnknownKey); if (adding) { StateManager.ValueGenerationManager.Generate(this); } SetEntityState(oldState, entityState, acceptChanges, modifyProperties); } /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public virtual async Task SetEntityStateAsync( EntityState entityState, bool acceptChanges = false, bool modifyProperties = true, EntityState? forceStateWhenUnknownKey = null, CancellationToken cancellationToken = default) { var oldState = _stateData.EntityState; var adding = PrepareForAdd(entityState); entityState = PropagateToUnknownKey(oldState, entityState, adding, forceStateWhenUnknownKey); if (adding) { await StateManager.ValueGenerationManager.GenerateAsync(this, cancellationToken); } SetEntityState(oldState, entityState, acceptChanges, modifyProperties); } private EntityState PropagateToUnknownKey( EntityState oldState, EntityState entityState, bool adding, EntityState? forceStateWhenUnknownKey) { var keyUnknown = IsKeyUnknown; if (adding || (oldState == EntityState.Detached && keyUnknown)) { var principalEntry = StateManager.ValueGenerationManager.Propagate(this); if (forceStateWhenUnknownKey.HasValue && keyUnknown && principalEntry != null && principalEntry.EntityState != EntityState.Detached && principalEntry.EntityState != EntityState.Deleted) { entityState = principalEntry.EntityState == EntityState.Added ? EntityState.Added : forceStateWhenUnknownKey.Value; } } return entityState; } private bool PrepareForAdd(EntityState newState) { if (newState != EntityState.Added || EntityState == EntityState.Added) { return false; } if (EntityState == EntityState.Modified) { _stateData.FlagAllProperties( EntityType.PropertyCount(), PropertyFlag.Modified, flagged: false); } // Temporarily change the internal state to unknown so that key generation, including setting key values // can happen without constraints on changing read-only values kicking in _stateData.EntityState = EntityState.Detached; return true; } private void SetEntityState(EntityState oldState, EntityState newState, bool acceptChanges, bool modifyProperties) { var entityType = (EntityType)EntityType; // Prevent temp values from becoming permanent values if (oldState == EntityState.Added && newState != EntityState.Added && newState != EntityState.Detached) { // ReSharper disable once LoopCanBeConvertedToQuery foreach (var property in entityType.GetProperties()) { if (HasTemporaryValue(property)) { throw new InvalidOperationException( CoreStrings.TempValuePersists( property.Name, EntityType.DisplayName(), newState)); } } } // The entity state can be Modified even if some properties are not modified so always // set all properties to modified if the entity state is explicitly set to Modified. if (newState == EntityState.Modified && modifyProperties) { _stateData.FlagAllProperties(entityType.PropertyCount(), PropertyFlag.Modified, flagged: true); // Hot path; do not use LINQ foreach (var property in entityType.GetProperties()) { if (property.GetAfterSaveBehavior() != PropertySaveBehavior.Save) { _stateData.FlagProperty(property.GetIndex(), PropertyFlag.Modified, isFlagged: false); } } } if (oldState == newState) { return; } if (newState == EntityState.Unchanged) { _stateData.FlagAllProperties( EntityType.PropertyCount(), PropertyFlag.Modified, flagged: false); } if (_stateData.EntityState != oldState) { _stateData.EntityState = oldState; } StateManager.StateChanging(this, newState); if (newState == EntityState.Unchanged && oldState == EntityState.Modified) { if (acceptChanges) { _originalValues.AcceptChanges(this); } else { _originalValues.RejectChanges(this); } } SetServiceProperties(oldState, newState); _stateData.EntityState = newState; if (oldState == EntityState.Detached) { StateManager.StartTracking(this); } else if (newState == EntityState.Detached) { StateManager.StopTracking(this, oldState); } if ((newState == EntityState.Deleted || newState == EntityState.Detached) && HasConceptualNull) { _stateData.FlagAllProperties(EntityType.PropertyCount(), PropertyFlag.Null, flagged: false); } if (oldState == EntityState.Detached || oldState == EntityState.Unchanged) { if (newState == EntityState.Added || newState == EntityState.Deleted || newState == EntityState.Modified) { StateManager.ChangedCount++; } } else if (newState == EntityState.Detached || newState == EntityState.Unchanged) { StateManager.ChangedCount--; } FireStateChanged(oldState); if ((newState == EntityState.Deleted || newState == EntityState.Detached) && StateManager.CascadeDeleteTiming == CascadeTiming.Immediate) { StateManager.CascadeDelete(this, force: false); } } private void FireStateChanged(EntityState oldState) { StateManager.InternalEntityEntryNotifier.StateChanged(this, oldState, fromQuery: false); if (oldState != EntityState.Detached) { StateManager.OnStateChanged(this, oldState); } else { StateManager.OnTracked(this, fromQuery: false); } } private void SetServiceProperties(EntityState oldState, EntityState newState) { if (oldState == EntityState.Detached) { foreach (var serviceProperty in ((EntityType)EntityType).GetServiceProperties()) { this[serviceProperty] = serviceProperty .GetParameterBinding() .ServiceDelegate( new MaterializationContext( ValueBuffer.Empty, StateManager.Context), EntityType, Entity); } } else if (newState == EntityState.Detached) { foreach (var serviceProperty in ((EntityType)EntityType).GetServiceProperties()) { this[serviceProperty] = null; } } } /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public virtual void MarkUnchangedFromQuery() { StateManager.InternalEntityEntryNotifier.StateChanging(this, EntityState.Unchanged); _stateData.EntityState = EntityState.Unchanged; StateManager.InternalEntityEntryNotifier.StateChanged(this, EntityState.Detached, fromQuery: true); StateManager.OnTracked(this, fromQuery: true); StateManager.InternalEntityEntryNotifier.TrackedFromQuery(this); } /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public virtual EntityState EntityState => _stateData.EntityState; /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public virtual bool IsModified(IProperty property) { var propertyIndex = property.GetIndex(); return _stateData.EntityState == EntityState.Modified && _stateData.IsPropertyFlagged(propertyIndex, PropertyFlag.Modified) && !_stateData.IsPropertyFlagged(propertyIndex, PropertyFlag.Unknown); } /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public virtual void SetPropertyModified( [NotNull] IProperty property, bool changeState = true, bool isModified = true, bool isConceptualNull = false, bool acceptChanges = false) { var propertyIndex = property.GetIndex(); _stateData.FlagProperty(propertyIndex, PropertyFlag.Unknown, false); var currentState = _stateData.EntityState; if (currentState == EntityState.Added || currentState == EntityState.Detached || !changeState) { var index = property.GetOriginalValueIndex(); if (index != -1 && !IsConceptualNull(property)) { SetOriginalValue(property, this[property], index); } } if (currentState == EntityState.Added) { return; } if (changeState && !isConceptualNull && isModified && !StateManager.SavingChanges && property.IsKey() && property.GetAfterSaveBehavior() == PropertySaveBehavior.Throw) { throw new InvalidOperationException(CoreStrings.KeyReadOnly(property.Name, EntityType.DisplayName())); } if (currentState == EntityState.Deleted) { return; } if (changeState) { if (!isModified && currentState != EntityState.Detached && property.GetOriginalValueIndex() != -1) { if (acceptChanges) { SetOriginalValue(property, GetCurrentValue(property)); } SetProperty(property, GetOriginalValue(property), isMaterialization: false, setModified: false); } _stateData.FlagProperty(propertyIndex, PropertyFlag.Modified, isModified); } if (isModified && (currentState == EntityState.Unchanged || currentState == EntityState.Detached)) { if (changeState) { StateManager.StateChanging(this, EntityState.Modified); SetServiceProperties(currentState, EntityState.Modified); _stateData.EntityState = EntityState.Modified; if (currentState == EntityState.Detached) { StateManager.StartTracking(this); } } if (changeState) { StateManager.ChangedCount++; FireStateChanged(currentState); } } else if (currentState == EntityState.Modified && changeState && !isModified && !_stateData.AnyPropertiesFlagged(PropertyFlag.Modified)) { StateManager.StateChanging(this, EntityState.Unchanged); _stateData.EntityState = EntityState.Unchanged; StateManager.ChangedCount--; FireStateChanged(currentState); } } /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public virtual bool HasConceptualNull => _stateData.AnyPropertiesFlagged(PropertyFlag.Null); /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public virtual bool IsConceptualNull([NotNull] IProperty property) => _stateData.IsPropertyFlagged(property.GetIndex(), PropertyFlag.Null); /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public virtual bool HasTemporaryValue(IProperty property) => GetValueType(property) == CurrentValueType.Temporary; private CurrentValueType GetValueType( IProperty property, Func<object, object, bool> equals = null) { var tempIndex = property.GetStoreGeneratedIndex(); if (tempIndex == -1) { return CurrentValueType.Normal; } if (equals == null) { equals = ValuesEqualFunc(property); } var defaultValue = property.ClrType.GetDefaultValue(); var value = ReadPropertyValue(property); if (!equals(value, defaultValue)) { return CurrentValueType.Normal; } if (_storeGeneratedValues.TryGetValue(tempIndex, out value) && !equals(value, defaultValue)) { return CurrentValueType.StoreGenerated; } if (_temporaryValues.TryGetValue(tempIndex, out value) && !equals(value, defaultValue)) { return CurrentValueType.Temporary; } return CurrentValueType.Normal; } /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public virtual void SetTemporaryValue([NotNull] IProperty property, [CanBeNull] object value, bool setModified = true) { if (property.GetStoreGeneratedIndex() == -1) { throw new InvalidOperationException( CoreStrings.TempValue(property.Name, EntityType.DisplayName())); } SetProperty(property, value, isMaterialization: false, setModified, isCascadeDelete: false, CurrentValueType.Temporary); } /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public virtual void SetStoreGeneratedValue(IProperty property, object value) { if (property.GetStoreGeneratedIndex() == -1) { throw new InvalidOperationException( CoreStrings.StoreGenValue(property.Name, EntityType.DisplayName())); } SetProperty( property, value, isMaterialization: false, setModified: true, isCascadeDelete: false, CurrentValueType.StoreGenerated); } /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> protected virtual void MarkShadowPropertiesNotSet([NotNull] IEntityType entityType) { foreach (var property in entityType.GetProperties()) { if (property.IsShadowProperty()) { _stateData.FlagProperty(property.GetIndex(), PropertyFlag.Unknown, true); } } } /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public virtual void MarkUnknown([NotNull] IProperty property) => _stateData.FlagProperty(property.GetIndex(), PropertyFlag.Unknown, true); internal static readonly MethodInfo ReadShadowValueMethod = typeof(InternalEntityEntry).GetTypeInfo().GetDeclaredMethod(nameof(ReadShadowValue)); /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> [UsedImplicitly] protected virtual T ReadShadowValue<T>(int shadowIndex) => default; internal static readonly MethodInfo ReadOriginalValueMethod = typeof(InternalEntityEntry).GetTypeInfo().GetDeclaredMethod(nameof(ReadOriginalValue)); [UsedImplicitly] private T ReadOriginalValue<T>(IProperty property, int originalValueIndex) => _originalValues.GetValue<T>(this, property, originalValueIndex); internal static readonly MethodInfo ReadRelationshipSnapshotValueMethod = typeof(InternalEntityEntry).GetTypeInfo().GetDeclaredMethod(nameof(ReadRelationshipSnapshotValue)); [UsedImplicitly] private T ReadRelationshipSnapshotValue<T>(IPropertyBase propertyBase, int relationshipSnapshotIndex) => _relationshipsSnapshot.GetValue<T>(this, propertyBase, relationshipSnapshotIndex); internal static readonly MethodInfo ReadStoreGeneratedValueMethod = typeof(InternalEntityEntry).GetTypeInfo().GetDeclaredMethod(nameof(ReadStoreGeneratedValue)); [UsedImplicitly] private T ReadStoreGeneratedValue<T>(int storeGeneratedIndex) => _storeGeneratedValues.GetValue<T>(storeGeneratedIndex); internal static readonly MethodInfo ReadTemporaryValueMethod = typeof(InternalEntityEntry).GetTypeInfo().GetDeclaredMethod(nameof(ReadTemporaryValue)); [UsedImplicitly] private T ReadTemporaryValue<T>(int storeGeneratedIndex) => _temporaryValues.GetValue<T>(storeGeneratedIndex); internal static readonly MethodInfo GetCurrentValueMethod = typeof(InternalEntityEntry).GetTypeInfo().GetDeclaredMethods(nameof(GetCurrentValue)).Single( m => m.IsGenericMethod); /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public virtual TProperty GetCurrentValue<TProperty>(IPropertyBase propertyBase) => ((Func<InternalEntityEntry, TProperty>)propertyBase.GetPropertyAccessors().CurrentValueGetter)(this); /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public virtual TProperty GetOriginalValue<TProperty>(IProperty property) => ((Func<InternalEntityEntry, TProperty>)property.GetPropertyAccessors().OriginalValueGetter)(this); /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public virtual TProperty GetRelationshipSnapshotValue<TProperty>([NotNull] IPropertyBase propertyBase) => ((Func<InternalEntityEntry, TProperty>)propertyBase.GetPropertyAccessors().RelationshipSnapshotGetter)( this); /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> protected virtual object ReadPropertyValue([NotNull] IPropertyBase propertyBase) { Check.DebugAssert(!propertyBase.IsShadowProperty(), "propertyBase is shadow property"); return ((PropertyBase)propertyBase).Getter.GetClrValue(Entity); } /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> protected virtual bool PropertyHasDefaultValue([NotNull] IPropertyBase propertyBase) { Check.DebugAssert(!propertyBase.IsShadowProperty(), "propertyBase is shadow property"); return ((PropertyBase)propertyBase).Getter.HasDefaultValue(Entity); } /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> protected virtual void WritePropertyValue( [NotNull] IPropertyBase propertyBase, [CanBeNull] object value, bool forMaterialization) { Check.DebugAssert(!propertyBase.IsShadowProperty(), "propertyBase is shadow property"); var concretePropertyBase = (PropertyBase)propertyBase; var setter = forMaterialization ? concretePropertyBase.MaterializationSetter : concretePropertyBase.Setter; setter.SetClrValue(Entity, value); } /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public virtual object GetOrCreateCollection([NotNull] INavigation navigation, bool forMaterialization) { Check.DebugAssert(!navigation.IsShadowProperty(), "navigation is shadow property"); return ((Navigation)navigation).CollectionAccessor.GetOrCreate(Entity, forMaterialization); } /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public virtual bool CollectionContains([NotNull] INavigation navigation, [NotNull] InternalEntityEntry value) { Check.DebugAssert(!navigation.IsShadowProperty(), "navigation is shadow property"); return ((Navigation)navigation).CollectionAccessor.Contains(Entity, value.Entity); } /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public virtual bool AddToCollection( [NotNull] INavigation navigation, [NotNull] InternalEntityEntry value, bool forMaterialization) { Check.DebugAssert(!navigation.IsShadowProperty(), "navigation is shadow property"); return ((Navigation)navigation).CollectionAccessor.Add(Entity, value.Entity, forMaterialization); } /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public virtual bool RemoveFromCollection([NotNull] INavigation navigation, [NotNull] InternalEntityEntry value) { Check.DebugAssert(!navigation.IsShadowProperty(), "navigation is shadow property"); return ((Navigation)navigation).CollectionAccessor.Remove(Entity, value.Entity); } /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public virtual object GetCurrentValue(IPropertyBase propertyBase) => !(propertyBase is IProperty property) || !IsConceptualNull(property) ? this[propertyBase] : null; /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public virtual object GetPreStoreGeneratedCurrentValue([NotNull] IPropertyBase propertyBase) => !(propertyBase is IProperty property) || !IsConceptualNull(property) ? ReadPropertyValue(propertyBase) : null; /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public virtual object GetOriginalValue(IPropertyBase propertyBase) => _originalValues.GetValue(this, (IProperty)propertyBase); /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public virtual object GetRelationshipSnapshotValue([NotNull] IPropertyBase propertyBase) => _relationshipsSnapshot.GetValue(this, propertyBase); /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public virtual void SetOriginalValue( [NotNull] IPropertyBase propertyBase, [CanBeNull] object value, int index = -1) { EnsureOriginalValues(); var property = (Property)propertyBase; _originalValues.SetValue(property, value, index); // If setting the original value results in the current value being different from the // original value, then mark the property as modified. if (EntityState == EntityState.Unchanged || (EntityState == EntityState.Modified && !IsModified(property))) { var currentValue = this[propertyBase]; var propertyIndex = property.GetIndex(); if (!ValuesEqualFunc(property)(currentValue, value) && !_stateData.IsPropertyFlagged(propertyIndex, PropertyFlag.Unknown)) { SetPropertyModified(property); } } } /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public virtual void SetRelationshipSnapshotValue([NotNull] IPropertyBase propertyBase, [CanBeNull] object value) { EnsureRelationshipSnapshot(); _relationshipsSnapshot.SetValue(propertyBase, value); } /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public virtual void EnsureOriginalValues() { if (_originalValues.IsEmpty) { _originalValues = new OriginalValues(this); } } /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public virtual void EnsureTemporaryValues() { if (_temporaryValues.IsEmpty) { _temporaryValues = new SidecarValues(((EntityType)EntityType).TemporaryValuesFactory(this)); } } /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public virtual void EnsureStoreGeneratedValues() { if (_storeGeneratedValues.IsEmpty) { _storeGeneratedValues = new SidecarValues(((EntityType)EntityType).StoreGeneratedValuesFactory(this)); } } /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public virtual void EnsureRelationshipSnapshot() { if (_relationshipsSnapshot.IsEmpty) { _relationshipsSnapshot = new RelationshipsSnapshot(this); } } /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public virtual bool HasOriginalValuesSnapshot => !_originalValues.IsEmpty; /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public virtual bool HasRelationshipSnapshot => !_relationshipsSnapshot.IsEmpty; /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public virtual void RemoveFromCollectionSnapshot( [NotNull] IPropertyBase propertyBase, [NotNull] object removedEntity) { EnsureRelationshipSnapshot(); _relationshipsSnapshot.RemoveFromCollection(propertyBase, removedEntity); } /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public virtual void AddToCollectionSnapshot([NotNull] IPropertyBase propertyBase, [NotNull] object addedEntity) { EnsureRelationshipSnapshot(); _relationshipsSnapshot.AddToCollection(propertyBase, addedEntity); } /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public virtual void AddRangeToCollectionSnapshot( [NotNull] IPropertyBase propertyBase, [NotNull] IEnumerable<object> addedEntities) { EnsureRelationshipSnapshot(); _relationshipsSnapshot.AddRangeToCollection(propertyBase, addedEntities); } /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public object this[[NotNull] IPropertyBase propertyBase] // Intentionally non-virtual { get { var value = ReadPropertyValue(propertyBase); var storeGeneratedIndex = propertyBase.GetStoreGeneratedIndex(); if (storeGeneratedIndex != -1) { var propertyClrType = propertyBase.ClrType; var defaultValue = propertyClrType.GetDefaultValue(); var property = (IProperty)propertyBase; var equals = ValuesEqualFunc(property); if (equals(value, defaultValue)) { if (_storeGeneratedValues.TryGetValue(storeGeneratedIndex, out var generatedValue) && !equals(generatedValue, defaultValue)) { return generatedValue; } if (_temporaryValues.TryGetValue(storeGeneratedIndex, out generatedValue) && !equals(generatedValue, defaultValue)) { return generatedValue; } } } return value; } [param: CanBeNull] set => SetProperty(propertyBase, value, isMaterialization: false); } /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public virtual void SetProperty( [NotNull] IPropertyBase propertyBase, [CanBeNull] object value, bool isMaterialization, bool setModified = true, bool isCascadeDelete = false) => SetProperty(propertyBase, value, isMaterialization, setModified, isCascadeDelete, CurrentValueType.Normal); private void SetProperty( [NotNull] IPropertyBase propertyBase, [CanBeNull] object value, bool isMaterialization, bool setModified, bool isCascadeDelete, CurrentValueType valueType) { var currentValue = this[propertyBase]; var asProperty = propertyBase as Property; int propertyIndex; CurrentValueType currentValueType; Func<object, object, bool> equals; if (asProperty != null) { propertyIndex = asProperty.GetIndex(); equals = ValuesEqualFunc(asProperty); currentValueType = GetValueType(asProperty, equals); } else { propertyIndex = -1; equals = ReferenceEquals; currentValueType = CurrentValueType.Normal; } var valuesEqual = equals(currentValue, value); if (!valuesEqual || (propertyIndex != -1 && (_stateData.IsPropertyFlagged(propertyIndex, PropertyFlag.Unknown) || _stateData.IsPropertyFlagged(propertyIndex, PropertyFlag.Null) || valueType != currentValueType))) { var writeValue = true; if (asProperty != null && valueType == CurrentValueType.Normal && (!asProperty.ClrType.IsNullableType() || asProperty.GetContainingForeignKeys().Any( fk => (fk.DeleteBehavior == DeleteBehavior.Cascade || fk.DeleteBehavior == DeleteBehavior.ClientCascade) && fk.DeclaringEntityType.IsAssignableFrom(EntityType)))) { if (value == null) { if (EntityState != EntityState.Deleted && EntityState != EntityState.Detached) { _stateData.FlagProperty(propertyIndex, PropertyFlag.Null, isFlagged: true); if (setModified) { SetPropertyModified( asProperty, changeState: true, isModified: true, isConceptualNull: true); } if (!isCascadeDelete && StateManager.DeleteOrphansTiming == CascadeTiming.Immediate) { HandleConceptualNulls( StateManager.SensitiveLoggingEnabled, force: false, isCascadeDelete: false); } } writeValue = false; } else { _stateData.FlagProperty(propertyIndex, PropertyFlag.Null, isFlagged: false); } } if (writeValue) { StateManager.InternalEntityEntryNotifier.PropertyChanging(this, propertyBase); if (valueType == CurrentValueType.Normal) { WritePropertyValue(propertyBase, value, isMaterialization); if (currentValueType != CurrentValueType.Normal && !_temporaryValues.IsEmpty) { var defaultValue = asProperty.ClrType.GetDefaultValue(); var storeGeneratedIndex = asProperty.GetStoreGeneratedIndex(); _temporaryValues.SetValue(asProperty, defaultValue, storeGeneratedIndex); } } else { var storeGeneratedIndex = asProperty.GetStoreGeneratedIndex(); Check.DebugAssert(storeGeneratedIndex >= 0, $"storeGeneratedIndex is {storeGeneratedIndex}"); if (valueType == CurrentValueType.StoreGenerated) { EnsureStoreGeneratedValues(); _storeGeneratedValues.SetValue(asProperty, value, storeGeneratedIndex); } else { var defaultValue = asProperty.ClrType.GetDefaultValue(); if (!equals(currentValue, defaultValue)) { WritePropertyValue(asProperty, defaultValue, isMaterialization); } if (_storeGeneratedValues.TryGetValue(storeGeneratedIndex, out var generatedValue) && !equals(generatedValue, defaultValue)) { _storeGeneratedValues.SetValue(asProperty, defaultValue, storeGeneratedIndex); } EnsureTemporaryValues(); _temporaryValues.SetValue(asProperty, value, storeGeneratedIndex); } } if (propertyIndex != -1) { _stateData.FlagProperty(propertyIndex, PropertyFlag.Unknown, isFlagged: false); } if (propertyBase is INavigation navigation) { if (!navigation.IsCollection()) { SetIsLoaded(navigation, value != null); } } StateManager.InternalEntityEntryNotifier.PropertyChanged(this, propertyBase, setModified); } } } private static Func<object, object, bool> ValuesEqualFunc(IProperty property) { var comparer = property.GetValueComparer() ?? property.FindTypeMapping()?.Comparer; return comparer != null ? (Func<object, object, bool>)((l, r) => comparer.Equals(l, r)) : (l, r) => Equals(l, r); } /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public virtual void AcceptChanges() { if (!_storeGeneratedValues.IsEmpty) { foreach (var property in EntityType.GetProperties()) { var storeGeneratedIndex = property.GetStoreGeneratedIndex(); if (storeGeneratedIndex != -1 && _storeGeneratedValues.TryGetValue(storeGeneratedIndex, out var value)) { this[property] = value; } } _storeGeneratedValues = new SidecarValues(); _temporaryValues = new SidecarValues(); } var currentState = EntityState; if ((currentState == EntityState.Unchanged) || (currentState == EntityState.Detached)) { return; } if ((currentState == EntityState.Added) || (currentState == EntityState.Modified)) { _originalValues.AcceptChanges(this); SharedIdentityEntry?.AcceptChanges(); SetEntityState(EntityState.Unchanged, true); } else if (currentState == EntityState.Deleted) { SetEntityState(EntityState.Detached); } } /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public virtual InternalEntityEntry PrepareToSave() { var entityType = (EntityType)EntityType; if (EntityState == EntityState.Added) { foreach (var property in entityType.GetProperties()) { if (property.GetBeforeSaveBehavior() == PropertySaveBehavior.Throw && !HasTemporaryValue(property) && !HasDefaultValue(property)) { throw new InvalidOperationException( CoreStrings.PropertyReadOnlyBeforeSave( property.Name, EntityType.DisplayName())); } if (property.IsKey() && property.IsForeignKey() && _stateData.IsPropertyFlagged(property.GetIndex(), PropertyFlag.Unknown)) { throw new InvalidOperationException(CoreStrings.UnknownKeyValue(entityType.DisplayName(), property.Name)); } } } else if (EntityState == EntityState.Modified) { foreach (var property in entityType.GetProperties()) { if (property.GetAfterSaveBehavior() == PropertySaveBehavior.Throw && IsModified(property)) { throw new InvalidOperationException( CoreStrings.PropertyReadOnlyAfterSave( property.Name, EntityType.DisplayName())); } } } DiscardStoreGeneratedValues(); return this; } /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public virtual void HandleConceptualNulls(bool sensitiveLoggingEnabled, bool force, bool isCascadeDelete) { var fks = new List<IForeignKey>(); foreach (var foreignKey in EntityType.GetForeignKeys()) { // ReSharper disable once LoopCanBeConvertedToQuery var properties = foreignKey.Properties; foreach (var property in properties) { if (_stateData.IsPropertyFlagged(property.GetIndex(), PropertyFlag.Null)) { if (properties.Any(p => p.IsNullable) && foreignKey.DeleteBehavior != DeleteBehavior.Cascade && foreignKey.DeleteBehavior != DeleteBehavior.ClientCascade) { foreach (var toNull in properties) { if (toNull.IsNullable) { this[toNull] = null; } else { _stateData.FlagProperty(toNull.GetIndex(), PropertyFlag.Null, isFlagged: false); } } } else if (EntityState != EntityState.Modified || IsModified(property)) { fks.Add(foreignKey); } break; } } } var cascadeFk = fks.FirstOrDefault( fk => fk.DeleteBehavior == DeleteBehavior.Cascade || fk.DeleteBehavior == DeleteBehavior.ClientCascade); if (cascadeFk != null && (force || (!isCascadeDelete && StateManager.DeleteOrphansTiming != CascadeTiming.Never))) { var cascadeState = EntityState == EntityState.Added ? EntityState.Detached : EntityState.Deleted; if (StateManager.SensitiveLoggingEnabled) { StateManager.UpdateLogger.CascadeDeleteOrphanSensitive( this, cascadeFk.PrincipalEntityType, cascadeState); } else { StateManager.UpdateLogger.CascadeDeleteOrphan(this, cascadeFk.PrincipalEntityType, cascadeState); } SetEntityState(cascadeState); } else if (fks.Count > 0) { var foreignKey = fks.First(); if (sensitiveLoggingEnabled) { throw new InvalidOperationException( CoreStrings.RelationshipConceptualNullSensitive( foreignKey.PrincipalEntityType.DisplayName(), EntityType.DisplayName(), this.BuildOriginalValuesString(foreignKey.Properties))); } throw new InvalidOperationException( CoreStrings.RelationshipConceptualNull( foreignKey.PrincipalEntityType.DisplayName(), EntityType.DisplayName())); } else { var property = EntityType.GetProperties().FirstOrDefault( p => (EntityState != EntityState.Modified || IsModified(p)) && _stateData.IsPropertyFlagged(p.GetIndex(), PropertyFlag.Null)); if (property != null) { if (sensitiveLoggingEnabled) { throw new InvalidOperationException( CoreStrings.PropertyConceptualNullSensitive( property.Name, EntityType.DisplayName(), this.BuildOriginalValuesString(new[] { property }))); } throw new InvalidOperationException( CoreStrings.PropertyConceptualNull( property.Name, EntityType.DisplayName())); } } } /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public virtual void DiscardStoreGeneratedValues() { if (!_storeGeneratedValues.IsEmpty) { _storeGeneratedValues = new SidecarValues(); } } /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public virtual bool IsStoreGenerated(IProperty property) => (property.ValueGenerated.ForAdd() && EntityState == EntityState.Added && (property.GetBeforeSaveBehavior() == PropertySaveBehavior.Ignore || HasTemporaryValue(property) || HasDefaultValue(property))) || (property.ValueGenerated.ForUpdate() && EntityState == EntityState.Modified && (property.GetAfterSaveBehavior() == PropertySaveBehavior.Ignore || !IsModified(property))); /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool HasDefaultValue([NotNull] IProperty property) // Intentionally non-virtual { if (!PropertyHasDefaultValue(property)) { return false; } var storeGeneratedIndex = property.GetStoreGeneratedIndex(); if (storeGeneratedIndex == -1) { return true; } var defaultValue = property.ClrType.GetDefaultValue(); var equals = ValuesEqualFunc(property); if (_storeGeneratedValues.TryGetValue(storeGeneratedIndex, out var generatedValue) && !equals(defaultValue, generatedValue)) { return false; } if (_temporaryValues.TryGetValue(storeGeneratedIndex, out generatedValue) && !equals(defaultValue, generatedValue)) { return false; } return true; } /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public virtual (bool IsGenerated, bool IsSet) IsKeySet { get { var isGenerated = false; var keyProperties = ((EntityType)EntityType).FindPrimaryKey().Properties; // ReSharper disable once ForCanBeConvertedToForeach // ReSharper disable once LoopCanBeConvertedToQuery for (var i = 0; i < keyProperties.Count; i++) { var keyProperty = keyProperties[i]; var keyGenerated = keyProperty.ValueGenerated == ValueGenerated.OnAdd; if ((HasTemporaryValue(keyProperty) || HasDefaultValue(keyProperty)) && (keyGenerated || keyProperty.IsForeignKey())) { return (true, false); } if (keyGenerated) { isGenerated = true; } } return (isGenerated, true); } } /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public virtual bool IsKeyUnknown { get { var keyProperties = ((EntityType)EntityType).FindPrimaryKey().Properties; // ReSharper disable once ForCanBeConvertedToForeach // ReSharper disable once LoopCanBeConvertedToQuery for (var i = 0; i < keyProperties.Count; i++) { var keyProperty = keyProperties[i]; if (_stateData.IsPropertyFlagged(keyProperty.GetIndex(), PropertyFlag.Unknown)) { return true; } } return false; } } /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public virtual EntityEntry ToEntityEntry() => new EntityEntry(this); /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public virtual void HandleINotifyPropertyChanging( [NotNull] object sender, [NotNull] PropertyChangingEventArgs eventArgs) { foreach (var propertyBase in EntityType.GetNotificationProperties(eventArgs.PropertyName)) { StateManager.InternalEntityEntryNotifier.PropertyChanging(this, propertyBase); } } /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public virtual void HandleINotifyPropertyChanged( [NotNull] object sender, [NotNull] PropertyChangedEventArgs eventArgs) { foreach (var propertyBase in EntityType.GetNotificationProperties(eventArgs.PropertyName)) { StateManager.InternalEntityEntryNotifier.PropertyChanged(this, propertyBase, setModified: true); } } /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public virtual void HandleINotifyCollectionChanged( [NotNull] object sender, [NotNull] NotifyCollectionChangedEventArgs eventArgs) { var navigation = EntityType.GetNavigations().FirstOrDefault(n => n.IsCollection() && this[n] == sender); if (navigation != null) { switch (eventArgs.Action) { case NotifyCollectionChangedAction.Add: StateManager.InternalEntityEntryNotifier.NavigationCollectionChanged( this, navigation, eventArgs.NewItems.OfType<object>(), Enumerable.Empty<object>()); break; case NotifyCollectionChangedAction.Remove: StateManager.InternalEntityEntryNotifier.NavigationCollectionChanged( this, navigation, Enumerable.Empty<object>(), eventArgs.OldItems.OfType<object>()); break; case NotifyCollectionChangedAction.Replace: StateManager.InternalEntityEntryNotifier.NavigationCollectionChanged( this, navigation, eventArgs.NewItems.OfType<object>(), eventArgs.OldItems.OfType<object>()); break; case NotifyCollectionChangedAction.Reset: throw new InvalidOperationException(CoreStrings.ResetNotSupported); // Note: ignoring Move since index not important } } } /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public virtual void SetIsLoaded([NotNull] INavigation navigation, bool loaded = true) { if (!loaded && !navigation.IsCollection() && this[navigation] != null) { throw new InvalidOperationException( CoreStrings.ReferenceMustBeLoaded(navigation.Name, navigation.DeclaringEntityType.DisplayName())); } _stateData.FlagProperty(navigation.GetIndex(), PropertyFlag.IsLoaded, isFlagged: loaded); var lazyLoaderProperty = EntityType.GetServiceProperties().FirstOrDefault(p => p.ClrType == typeof(ILazyLoader)); if (lazyLoaderProperty != null) { ((ILazyLoader)this[lazyLoaderProperty])?.SetLoaded(Entity, navigation.Name, loaded); } } /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public virtual bool IsLoaded([NotNull] INavigation navigation) => _stateData.IsPropertyFlagged(navigation.GetIndex(), PropertyFlag.IsLoaded); /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public override string ToString() => ToDebugString(StateManagerDebugStringOptions.ShortDefault); /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public virtual DebugView DebugView => new DebugView( () => this.ToDebugString(StateManagerDebugStringOptions.ShortDefault), () => this.ToDebugString(StateManagerDebugStringOptions.LongDefault)); /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public virtual string ToDebugString(StateManagerDebugStringOptions options) { var builder = new StringBuilder(); var keyString = this.BuildCurrentValuesString(EntityType.FindPrimaryKey().Properties); builder .Append(EntityType.DisplayName()) .Append(' ') .Append(SharedIdentityEntry != null ? "(Shared) " : "") .Append(keyString) .Append(' ') .Append(EntityState.ToString()); if ((options & StateManagerDebugStringOptions.IncludeProperties) != 0) { foreach (var property in EntityType.GetProperties()) { builder.AppendLine(); var currentValue = GetCurrentValue(property); builder .Append(" ") .Append(property.Name) .Append(": "); AppendValue(currentValue); if (property.IsPrimaryKey()) { builder.Append(" PK"); } else if (property.IsKey()) { builder.Append(" AK"); } if (property.IsForeignKey()) { builder.Append(" FK"); } if (IsModified(property)) { builder.Append(" Modified"); } if (HasTemporaryValue(property)) { builder.Append(" Temporary"); } if (HasOriginalValuesSnapshot && property.GetOriginalValueIndex() != -1) { var originalValue = GetOriginalValue(property); if (!Equals(originalValue, currentValue)) { builder.Append(" Originally "); AppendValue(originalValue); } } } } else { foreach (var alternateKey in EntityType.GetKeys().Where(k => !k.IsPrimaryKey())) { builder .Append(" AK ") .Append(this.BuildCurrentValuesString(alternateKey.Properties)); } foreach (var foreignKey in EntityType.GetForeignKeys()) { builder .Append(" FK ") .Append(this.BuildCurrentValuesString(foreignKey.Properties)); } } if ((options & StateManagerDebugStringOptions.IncludeNavigations) != 0) { foreach (var navigation in EntityType.GetNavigations()) { builder.AppendLine(); var currentValue = GetCurrentValue(navigation); var targetType = navigation.GetTargetType(); builder .Append(" ") .Append(navigation.Name) .Append(": "); if (currentValue == null) { builder.Append("<null>"); } else if (navigation.IsCollection()) { builder.Append('['); const int maxRelatedToShow = 32; var relatedEntities = ((IEnumerable)currentValue).Cast<object>().Take(maxRelatedToShow + 1).ToList(); for (var i = 0; i < relatedEntities.Count; i++) { if (i != 0) { builder.Append(", "); } if (i < 32) { AppendRelatedKey(targetType, relatedEntities[i]); } else { builder.Append("..."); } } builder.Append(']'); } else { AppendRelatedKey(targetType, currentValue); } } } return builder.ToString(); void AppendValue(object value) { if (value == null) { builder.Append("<null>"); } else if (value.GetType().IsNumeric()) { builder.Append(value); } else if (value is byte[] bytes) { builder.AppendBytes(bytes); } else { var stringValue = value.ToString(); if (stringValue.Length > 63) { stringValue = stringValue.Substring(0, 60) + "..."; } builder .Append('\'') .Append(stringValue) .Append('\''); } } void AppendRelatedKey(IEntityType targetType, object value) { var otherEntry = StateManager.TryGetEntry(value, targetType, throwOnTypeMismatch: false); builder.Append( otherEntry == null ? "<not found>" : otherEntry.BuildCurrentValuesString(targetType.FindPrimaryKey().Properties)); } } IUpdateEntry IUpdateEntry.SharedIdentityEntry => SharedIdentityEntry; private enum CurrentValueType { Normal, StoreGenerated, Temporary } } }
48.052188
132
0.579244
[ "Apache-2.0" ]
Tangtang1997/EntityFrameworkCore
src/EFCore/ChangeTracking/Internal/InternalEntityEntry.cs
91,155
C#
// <copyright file="Pens{TColor}.cs" company="James Jackson-South"> // Copyright (c) James Jackson-South and contributors. // Licensed under the Apache License, Version 2.0. // </copyright> namespace ImageSharp.Drawing.Pens { using System; /// <summary> /// Common Pen styles /// </summary> /// <typeparam name="TColor">The type of the color.</typeparam> public class Pens<TColor> where TColor : struct, IPixel<TColor> { private static readonly float[] DashDotPattern = new[] { 3f, 1f, 1f, 1f }; private static readonly float[] DashDotDotPattern = new[] { 3f, 1f, 1f, 1f, 1f, 1f }; private static readonly float[] DottedPattern = new[] { 1f, 1f }; private static readonly float[] DashedPattern = new[] { 3f, 1f }; /// <summary> /// Create a solid pen with out any drawing patterns /// </summary> /// <param name="color">The color.</param> /// <param name="width">The width.</param> /// <returns>The Pen</returns> public static Pen<TColor> Solid(TColor color, float width) => new Pen<TColor>(color, width); /// <summary> /// Create a solid pen with out any drawing patterns /// </summary> /// <param name="brush">The brush.</param> /// <param name="width">The width.</param> /// <returns>The Pen</returns> public static Pen<TColor> Solid(IBrush<TColor> brush, float width) => new Pen<TColor>(brush, width); /// <summary> /// Create a pen with a 'Dash' drawing patterns /// </summary> /// <param name="color">The color.</param> /// <param name="width">The width.</param> /// <returns>The Pen</returns> public static Pen<TColor> Dash(TColor color, float width) => new Pen<TColor>(color, width, DashedPattern); /// <summary> /// Create a pen with a 'Dash' drawing patterns /// </summary> /// <param name="brush">The brush.</param> /// <param name="width">The width.</param> /// <returns>The Pen</returns> public static Pen<TColor> Dash(IBrush<TColor> brush, float width) => new Pen<TColor>(brush, width, DashedPattern); /// <summary> /// Create a pen with a 'Dot' drawing patterns /// </summary> /// <param name="color">The color.</param> /// <param name="width">The width.</param> /// <returns>The Pen</returns> public static Pen<TColor> Dot(TColor color, float width) => new Pen<TColor>(color, width, DottedPattern); /// <summary> /// Create a pen with a 'Dot' drawing patterns /// </summary> /// <param name="brush">The brush.</param> /// <param name="width">The width.</param> /// <returns>The Pen</returns> public static Pen<TColor> Dot(IBrush<TColor> brush, float width) => new Pen<TColor>(brush, width, DottedPattern); /// <summary> /// Create a pen with a 'Dash Dot' drawing patterns /// </summary> /// <param name="color">The color.</param> /// <param name="width">The width.</param> /// <returns>The Pen</returns> public static Pen<TColor> DashDot(TColor color, float width) => new Pen<TColor>(color, width, DashDotPattern); /// <summary> /// Create a pen with a 'Dash Dot' drawing patterns /// </summary> /// <param name="brush">The brush.</param> /// <param name="width">The width.</param> /// <returns>The Pen</returns> public static Pen<TColor> DashDot(IBrush<TColor> brush, float width) => new Pen<TColor>(brush, width, DashDotPattern); /// <summary> /// Create a pen with a 'Dash Dot Dot' drawing patterns /// </summary> /// <param name="color">The color.</param> /// <param name="width">The width.</param> /// <returns>The Pen</returns> public static Pen<TColor> DashDotDot(TColor color, float width) => new Pen<TColor>(color, width, DashDotDotPattern); /// <summary> /// Create a pen with a 'Dash Dot Dot' drawing patterns /// </summary> /// <param name="brush">The brush.</param> /// <param name="width">The width.</param> /// <returns>The Pen</returns> public static Pen<TColor> DashDotDot(IBrush<TColor> brush, float width) => new Pen<TColor>(brush, width, DashDotDotPattern); } }
40.732143
93
0.56861
[ "Apache-2.0" ]
ststeiger/ImageSharpTestApplication
src/ImageSharp.Drawing/Pens/Pens{TColor}.cs
4,564
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ReactiveTests.Dummies { class DummyObserver<T> : IObserver<T> { public static readonly DummyObserver<T> Instance = new DummyObserver<T>(); DummyObserver() { } public void OnNext(T value) { throw new NotImplementedException(); } public void OnError(Exception exception) { throw new NotImplementedException(); } public void OnCompleted() { throw new NotImplementedException(); } } }
19.84375
82
0.584252
[ "Apache-2.0" ]
Reactive-Extensions/IL2JS
Reactive/ReactiveTests/Dummies/DummyObserver.cs
637
C#
#pragma checksum "E:\Projects\BlazorUpdates\Blazor-CRUD-With-CloudFirestore\BlazorWithFirestore\BlazorWithFirestore\Client\Pages\EmployeeData.razor" "{ff1816ec-aa5e-4d10-87f7-6f4963833460}" "dc5422c69a1b3e194abec6ddc4d2df4931181336" // <auto-generated/> #pragma warning disable 1591 namespace BlazorWithFirestore.Client.Pages { #line hidden using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Components; #nullable restore #line 1 "E:\Projects\BlazorUpdates\Blazor-CRUD-With-CloudFirestore\BlazorWithFirestore\BlazorWithFirestore\Client\_Imports.razor" using System.Net.Http; #line default #line hidden #nullable disable #nullable restore #line 2 "E:\Projects\BlazorUpdates\Blazor-CRUD-With-CloudFirestore\BlazorWithFirestore\BlazorWithFirestore\Client\_Imports.razor" using Microsoft.AspNetCore.Components.Forms; #line default #line hidden #nullable disable #nullable restore #line 3 "E:\Projects\BlazorUpdates\Blazor-CRUD-With-CloudFirestore\BlazorWithFirestore\BlazorWithFirestore\Client\_Imports.razor" using Microsoft.AspNetCore.Components.Routing; #line default #line hidden #nullable disable #nullable restore #line 4 "E:\Projects\BlazorUpdates\Blazor-CRUD-With-CloudFirestore\BlazorWithFirestore\BlazorWithFirestore\Client\_Imports.razor" using Microsoft.AspNetCore.Components.Web; #line default #line hidden #nullable disable #nullable restore #line 5 "E:\Projects\BlazorUpdates\Blazor-CRUD-With-CloudFirestore\BlazorWithFirestore\BlazorWithFirestore\Client\_Imports.razor" using Microsoft.JSInterop; #line default #line hidden #nullable disable #nullable restore #line 6 "E:\Projects\BlazorUpdates\Blazor-CRUD-With-CloudFirestore\BlazorWithFirestore\BlazorWithFirestore\Client\_Imports.razor" using BlazorWithFirestore.Client; #line default #line hidden #nullable disable #nullable restore #line 7 "E:\Projects\BlazorUpdates\Blazor-CRUD-With-CloudFirestore\BlazorWithFirestore\BlazorWithFirestore\Client\_Imports.razor" using BlazorWithFirestore.Client.Shared; #line default #line hidden #nullable disable [Microsoft.AspNetCore.Components.RouteAttribute("/employeerecords")] public partial class EmployeeData : EmployeeDataModel { #pragma warning disable 1998 protected override void BuildRenderTree(Microsoft.AspNetCore.Components.Rendering.RenderTreeBuilder __builder) { __builder.AddMarkupContent(0, "<h1>Employee Data</h1>\r\n"); __builder.AddMarkupContent(1, "<p>CRUD operation using Blazor and Google Cloud Firestore</p>\r\n\r\n"); __builder.OpenElement(2, "div"); __builder.AddAttribute(3, "class", "row"); __builder.AddMarkupContent(4, "\r\n "); __builder.AddMarkupContent(5, "<div class=\"col-md-4\">\r\n <a href=\"/employee/add\" class=\"btn btn-primary\" role=\"button\"><i class=\"fa fa-user-plus\"></i> Add Employee</a>\r\n </div>\r\n "); __builder.OpenElement(6, "div"); __builder.AddAttribute(7, "class", "input-group col-md-4 offset-md-4"); __builder.AddMarkupContent(8, "\r\n "); __builder.OpenElement(9, "input"); __builder.AddAttribute(10, "type", "text"); __builder.AddAttribute(11, "class", "form-control"); __builder.AddAttribute(12, "placeholder", "Search employee by name"); __builder.AddAttribute(13, "value", Microsoft.AspNetCore.Components.BindConverter.FormatValue( #nullable restore #line 12 "E:\Projects\BlazorUpdates\Blazor-CRUD-With-CloudFirestore\BlazorWithFirestore\BlazorWithFirestore\Client\Pages\EmployeeData.razor" SearchString #line default #line hidden #nullable disable )); __builder.AddAttribute(14, "onchange", Microsoft.AspNetCore.Components.EventCallback.Factory.CreateBinder(this, __value => SearchString = __value, SearchString)); __builder.SetUpdatesAttributeName("value"); __builder.CloseElement(); __builder.AddMarkupContent(15, "\r\n "); __builder.OpenElement(16, "div"); __builder.AddAttribute(17, "class", "input-group-append"); __builder.AddMarkupContent(18, "\r\n "); __builder.OpenElement(19, "button"); __builder.AddAttribute(20, "class", "btn btn-info"); __builder.AddAttribute(21, "onclick", Microsoft.AspNetCore.Components.EventCallback.Factory.Create<Microsoft.AspNetCore.Components.Web.MouseEventArgs>(this, #nullable restore #line 14 "E:\Projects\BlazorUpdates\Blazor-CRUD-With-CloudFirestore\BlazorWithFirestore\BlazorWithFirestore\Client\Pages\EmployeeData.razor" SearchEmployee #line default #line hidden #nullable disable )); __builder.AddMarkupContent(22, "\r\n <i class=\"fa fa-search\"></i>\r\n "); __builder.CloseElement(); __builder.AddMarkupContent(23, "\r\n "); __builder.CloseElement(); __builder.AddMarkupContent(24, "\r\n "); __builder.CloseElement(); __builder.AddMarkupContent(25, "\r\n"); __builder.CloseElement(); __builder.AddMarkupContent(26, "\r\n<br>\r\n"); #nullable restore #line 21 "E:\Projects\BlazorUpdates\Blazor-CRUD-With-CloudFirestore\BlazorWithFirestore\BlazorWithFirestore\Client\Pages\EmployeeData.razor" if (empList == null) { #line default #line hidden #nullable disable __builder.AddContent(27, " "); __builder.AddMarkupContent(28, "<p><em>Loading...</em></p>\r\n"); #nullable restore #line 24 "E:\Projects\BlazorUpdates\Blazor-CRUD-With-CloudFirestore\BlazorWithFirestore\BlazorWithFirestore\Client\Pages\EmployeeData.razor" } else { #line default #line hidden #nullable disable __builder.AddContent(29, " "); __builder.OpenElement(30, "table"); __builder.AddAttribute(31, "class", "table"); __builder.AddMarkupContent(32, "\r\n "); __builder.AddMarkupContent(33, "<thead>\r\n <tr>\r\n <th>Name</th>\r\n <th>Gender</th>\r\n <th>Designation</th>\r\n <th>City</th>\r\n <th>Actions</th>\r\n </tr>\r\n </thead>\r\n "); __builder.OpenElement(34, "tbody"); __builder.AddMarkupContent(35, "\r\n"); #nullable restore #line 38 "E:\Projects\BlazorUpdates\Blazor-CRUD-With-CloudFirestore\BlazorWithFirestore\BlazorWithFirestore\Client\Pages\EmployeeData.razor" foreach (var emp in empList) { #line default #line hidden #nullable disable __builder.AddContent(36, " "); __builder.OpenElement(37, "tr"); __builder.AddMarkupContent(38, "\r\n "); __builder.OpenElement(39, "td"); __builder.AddContent(40, #nullable restore #line 41 "E:\Projects\BlazorUpdates\Blazor-CRUD-With-CloudFirestore\BlazorWithFirestore\BlazorWithFirestore\Client\Pages\EmployeeData.razor" emp.EmployeeName #line default #line hidden #nullable disable ); __builder.CloseElement(); __builder.AddMarkupContent(41, "\r\n "); __builder.OpenElement(42, "td"); __builder.AddContent(43, #nullable restore #line 42 "E:\Projects\BlazorUpdates\Blazor-CRUD-With-CloudFirestore\BlazorWithFirestore\BlazorWithFirestore\Client\Pages\EmployeeData.razor" emp.Gender #line default #line hidden #nullable disable ); __builder.CloseElement(); __builder.AddMarkupContent(44, "\r\n "); __builder.OpenElement(45, "td"); __builder.AddContent(46, #nullable restore #line 43 "E:\Projects\BlazorUpdates\Blazor-CRUD-With-CloudFirestore\BlazorWithFirestore\BlazorWithFirestore\Client\Pages\EmployeeData.razor" emp.Designation #line default #line hidden #nullable disable ); __builder.CloseElement(); __builder.AddMarkupContent(47, "\r\n "); __builder.OpenElement(48, "td"); __builder.AddContent(49, #nullable restore #line 44 "E:\Projects\BlazorUpdates\Blazor-CRUD-With-CloudFirestore\BlazorWithFirestore\BlazorWithFirestore\Client\Pages\EmployeeData.razor" emp.CityName #line default #line hidden #nullable disable ); __builder.CloseElement(); __builder.AddMarkupContent(50, "\r\n "); __builder.OpenElement(51, "td"); __builder.AddMarkupContent(52, "\r\n "); __builder.OpenElement(53, "a"); __builder.AddAttribute(54, "href", "/employee/edit/" + ( #nullable restore #line 46 "E:\Projects\BlazorUpdates\Blazor-CRUD-With-CloudFirestore\BlazorWithFirestore\BlazorWithFirestore\Client\Pages\EmployeeData.razor" emp.EmployeeId #line default #line hidden #nullable disable )); __builder.AddAttribute(55, "class", "btn btn-outline-dark"); __builder.AddAttribute(56, "role", "button"); __builder.AddMarkupContent(57, " <i class=\"fa fa-pencil-square-o\"></i> Edit"); __builder.CloseElement(); __builder.AddMarkupContent(58, "\r\n "); __builder.OpenElement(59, "button"); __builder.AddAttribute(60, "class", "btn btn-outline-danger"); __builder.AddAttribute(61, "data-toggle", "modal"); __builder.AddAttribute(62, "data-target", "#deleteEmpModal"); __builder.AddAttribute(63, "onclick", Microsoft.AspNetCore.Components.EventCallback.Factory.Create<Microsoft.AspNetCore.Components.Web.MouseEventArgs>(this, #nullable restore #line 48 "E:\Projects\BlazorUpdates\Blazor-CRUD-With-CloudFirestore\BlazorWithFirestore\BlazorWithFirestore\Client\Pages\EmployeeData.razor" (()=>DeleteConfirm(emp.EmployeeId)) #line default #line hidden #nullable disable )); __builder.AddMarkupContent(64, "\r\n <i class=\"fa fa-trash-o\"></i>\r\n Delete\r\n "); __builder.CloseElement(); __builder.AddMarkupContent(65, "\r\n "); __builder.CloseElement(); __builder.AddMarkupContent(66, "\r\n "); __builder.CloseElement(); __builder.AddMarkupContent(67, "\r\n"); #nullable restore #line 54 "E:\Projects\BlazorUpdates\Blazor-CRUD-With-CloudFirestore\BlazorWithFirestore\BlazorWithFirestore\Client\Pages\EmployeeData.razor" } #line default #line hidden #nullable disable __builder.AddContent(68, " "); __builder.CloseElement(); __builder.AddMarkupContent(69, "\r\n "); __builder.CloseElement(); __builder.AddMarkupContent(70, "\r\n"); #nullable restore #line 57 "E:\Projects\BlazorUpdates\Blazor-CRUD-With-CloudFirestore\BlazorWithFirestore\BlazorWithFirestore\Client\Pages\EmployeeData.razor" } #line default #line hidden #nullable disable __builder.AddMarkupContent(71, "\r\n"); __builder.OpenElement(72, "div"); __builder.AddAttribute(73, "class", "modal fade"); __builder.AddAttribute(74, "id", "deleteEmpModal"); __builder.AddMarkupContent(75, "\r\n "); __builder.OpenElement(76, "div"); __builder.AddAttribute(77, "class", "modal-dialog"); __builder.AddMarkupContent(78, "\r\n "); __builder.OpenElement(79, "div"); __builder.AddAttribute(80, "class", "modal-content"); __builder.AddMarkupContent(81, "\r\n "); __builder.AddMarkupContent(82, @"<div class=""modal-header""> <h3 class=""modal-title"">Confirm Delete !!!</h3> <button type=""button"" class=""close"" data-dismiss=""modal""> <span aria-hidden=""true"">X</span> </button> </div> "); __builder.OpenElement(83, "div"); __builder.AddAttribute(84, "class", "modal-body"); __builder.AddMarkupContent(85, "\r\n "); __builder.OpenElement(86, "table"); __builder.AddAttribute(87, "class", "table"); __builder.AddMarkupContent(88, "\r\n "); __builder.OpenElement(89, "tr"); __builder.AddMarkupContent(90, "\r\n "); __builder.AddMarkupContent(91, "<td>Name</td>\r\n "); __builder.OpenElement(92, "td"); __builder.AddContent(93, #nullable restore #line 72 "E:\Projects\BlazorUpdates\Blazor-CRUD-With-CloudFirestore\BlazorWithFirestore\BlazorWithFirestore\Client\Pages\EmployeeData.razor" emp.EmployeeName #line default #line hidden #nullable disable ); __builder.CloseElement(); __builder.AddMarkupContent(94, "\r\n "); __builder.CloseElement(); __builder.AddMarkupContent(95, "\r\n "); __builder.OpenElement(96, "tr"); __builder.AddMarkupContent(97, "\r\n "); __builder.AddMarkupContent(98, "<td>Gender</td>\r\n "); __builder.OpenElement(99, "td"); __builder.AddContent(100, #nullable restore #line 76 "E:\Projects\BlazorUpdates\Blazor-CRUD-With-CloudFirestore\BlazorWithFirestore\BlazorWithFirestore\Client\Pages\EmployeeData.razor" emp.Gender #line default #line hidden #nullable disable ); __builder.CloseElement(); __builder.AddMarkupContent(101, "\r\n "); __builder.CloseElement(); __builder.AddMarkupContent(102, "\r\n "); __builder.OpenElement(103, "tr"); __builder.AddMarkupContent(104, "\r\n "); __builder.AddMarkupContent(105, "<td>Designation</td>\r\n "); __builder.OpenElement(106, "td"); __builder.AddContent(107, #nullable restore #line 80 "E:\Projects\BlazorUpdates\Blazor-CRUD-With-CloudFirestore\BlazorWithFirestore\BlazorWithFirestore\Client\Pages\EmployeeData.razor" emp.Designation #line default #line hidden #nullable disable ); __builder.CloseElement(); __builder.AddMarkupContent(108, "\r\n "); __builder.CloseElement(); __builder.AddMarkupContent(109, "\r\n "); __builder.OpenElement(110, "tr"); __builder.AddMarkupContent(111, "\r\n "); __builder.AddMarkupContent(112, "<td>City</td>\r\n "); __builder.OpenElement(113, "td"); __builder.AddContent(114, #nullable restore #line 84 "E:\Projects\BlazorUpdates\Blazor-CRUD-With-CloudFirestore\BlazorWithFirestore\BlazorWithFirestore\Client\Pages\EmployeeData.razor" emp.CityName #line default #line hidden #nullable disable ); __builder.CloseElement(); __builder.AddMarkupContent(115, "\r\n "); __builder.CloseElement(); __builder.AddMarkupContent(116, "\r\n "); __builder.CloseElement(); __builder.AddMarkupContent(117, "\r\n "); __builder.CloseElement(); __builder.AddMarkupContent(118, "\r\n "); __builder.OpenElement(119, "div"); __builder.AddAttribute(120, "class", "modal-footer"); __builder.AddMarkupContent(121, "\r\n "); __builder.OpenElement(122, "button"); __builder.AddAttribute(123, "class", "btn btn-danger"); __builder.AddAttribute(124, "onclick", Microsoft.AspNetCore.Components.EventCallback.Factory.Create<Microsoft.AspNetCore.Components.Web.MouseEventArgs>(this, #nullable restore #line 89 "E:\Projects\BlazorUpdates\Blazor-CRUD-With-CloudFirestore\BlazorWithFirestore\BlazorWithFirestore\Client\Pages\EmployeeData.razor" (async () => await DeleteEmployee(emp.EmployeeId)) #line default #line hidden #nullable disable )); __builder.AddAttribute(125, "data-dismiss", "modal"); __builder.AddContent(126, "Delete"); __builder.CloseElement(); __builder.AddMarkupContent(127, "\r\n "); __builder.AddMarkupContent(128, "<button data-dismiss=\"modal\" class=\"btn btn-light\">Cancel</button>\r\n "); __builder.CloseElement(); __builder.AddMarkupContent(129, "\r\n "); __builder.CloseElement(); __builder.AddMarkupContent(130, "\r\n "); __builder.CloseElement(); __builder.AddMarkupContent(131, "\r\n"); __builder.CloseElement(); } #pragma warning restore 1998 } } #pragma warning restore 1591
46.388021
304
0.61573
[ "MIT" ]
AnkitSharma-007/Blazor-CRUD-With-CloudFirestore
BlazorWithFirestore/BlazorWithFirestore/Client/obj/Debug/netstandard2.1/Razor/Pages/EmployeeData.razor.g.cs
17,813
C#
namespace ARS_ProjectSystem.Controllers { using ARS_ProjectSystem.Models.Employees; using ARS_ProjectSystem.Services.Employees; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using System.Collections.Generic; using static WebConstants; public class EmployeesController:Controller { private readonly IEmployeeService employees; public EmployeesController(IEmployeeService employees) { this.employees = employees; } [Authorize] public IActionResult All() { var employeesData = this.employees.All(); if (employeesData != null) { return View(employeesData); } return RedirectToAction("Index", "Home"); } [Authorize] public IActionResult Add() { return View(new EmployeeFormModel { Customers = this.GetEmployeeCustomers() }); } [HttpPost] [Authorize] public IActionResult Add(AddEmployeeFormModel employee) { if (!ModelState.IsValid) { return View(); } this.employees.Create(employee.Id, employee.FirstName, employee.LastName, employee.Jobtitle, employee.CustomerRegistrationNumber, employee.DepartmentName); TempData[GlobalMessageKey] = $"Employee {employee.FirstName} {employee.LastName} is added succesfully!"; return RedirectToAction("Index", "Home"); } private IEnumerable<EmployeeCustomersServiceModel> GetEmployeeCustomers() => this.employees.GetEmployeeCustomers(); private IEnumerable<EmployeeProjectsServiceModel> GetEmployeeProjects() => this.employees.GetEmployeeProjects(); private IEnumerable<EmployeeProposalsServiceModel> GetEmployeeProposals() => this.employees.GetEmployeeProposals(); [Authorize] public IActionResult AddToProject() { return View(new EmployeeProjectsFormModel { Projects = this.GetEmployeeProjects() }); } [HttpPost] [Authorize] public IActionResult AddToProject(AddEmployeeFormModel employee,int employeeId) { var employeeData=this.employees.AddToProject(employee, employeeId); TempData[GlobalMessageKey] = $"Employee {employeeData.FirstName} {employeeData.LastName} is added succesfully to project {employeeData.ProjectName}!"; return RedirectToAction(nameof(All)); } [Authorize] public IActionResult AddToProposal() { return View(new EmployeeProposalsFormModel { Proposals = this.GetEmployeeProposals() }); } [HttpPost] [Authorize] public IActionResult AddToProposal(AddEmployeeFormModel employee, int employeeId) { var employeeData = this.employees.AddToProposal(employee, employeeId); TempData[GlobalMessageKey] = $"Employee {employeeData.FirstName} {employeeData.LastName} is added succesfully to proposal {employeeData.ProposalName}!"; return RedirectToAction(nameof(All)); } } }
30.589286
164
0.607122
[ "MIT" ]
AnetaKoseva/ARS-ProjectSystem
ARS ProjectSystem/Controllers/EmployeesController.cs
3,428
C#
using System; namespace OpenSheets.Contracts.Requests { public class GetPrincipalByIdRequest { public Guid PrincipalId { get; set; } } }
17.555556
45
0.683544
[ "Unlicense" ]
AIAlexRhees/OpenSheets
OpenSheets.Contracts/Requests/Principal/GetPrincipalByIdRequest.cs
160
C#
using System; using System.Diagnostics.CodeAnalysis; using System.Reflection; using Splat; namespace ReactiveUI { internal sealed class DefaultViewLocator : IViewLocator, IEnableLogger { /// <summary> /// Initializes a new instance of the <see cref="DefaultViewLocator"/> class. /// </summary> /// <param name="viewModelToViewFunc">The method which will convert a ViewModel name into a View.</param> [SuppressMessage("Globalization", "CA1307: operator could change based on locale settings", Justification = "Replace() does not have third parameter on all platforms")] public DefaultViewLocator(Func<string, string> viewModelToViewFunc = null) { ViewModelToViewFunc = viewModelToViewFunc ?? (vm => vm.Replace("ViewModel", "View")); } /// <summary> /// Gets or sets a function that is used to convert a view model name to a proposed view name. /// </summary> /// <remarks> /// <para> /// If unset, the default behavior is to change "ViewModel" to "View". If a different convention is followed, assign an appropriate function to this /// property. /// </para> /// <para> /// Note that the name returned by the function is a starting point for view resolution. Variants on the name will be resolved according to the rules /// set out by the <see cref="ResolveView{T}"/> method. /// </para> /// </remarks> public Func<string, string> ViewModelToViewFunc { get; set; } /// <summary> /// Returns the view associated with a view model, deriving the name of the type via <see cref="ViewModelToViewFunc"/>, then discovering it via the /// service locator. /// </summary> /// <typeparam name="T">The type.</typeparam> /// <remarks> /// <para> /// Given view model type <c>T</c> with runtime type <c>RT</c>, this implementation will attempt to resolve the following views: /// <list type="number"> /// <item> /// <description> /// Look for a service registered under the type whose name is given to us by passing <c>RT</c> to <see cref="ViewModelToViewFunc"/> (which defaults to changing "ViewModel" to "View"). /// </description> /// </item> /// <item> /// <description> /// Look for a service registered under the type <c>IViewFor&lt;RT&gt;</c>. /// </description> /// </item> /// <item> /// <description> /// Look for a service registered under the type whose name is given to us by passing <c>T</c> to <see cref="ViewModelToViewFunc"/> (which defaults to changing "ViewModel" to "View"). /// </description> /// </item> /// <item> /// <description> /// Look for a service registered under the type <c>IViewFor&lt;T&gt;</c>. /// </description> /// </item> /// <item> /// <description> /// If <c>T</c> is an interface, change its name to that of a class (i.e. drop the leading "I"). If it's a class, change to an interface (i.e. add a leading "I"). /// </description> /// </item> /// <item> /// <description> /// Repeat steps 1-4 with the type resolved from the modified name. /// </description> /// </item> /// </list> /// </para> /// </remarks> /// <param name="viewModel"> /// The view model whose associated view is to be resolved. /// </param> /// <param name="contract"> /// Optional contract to be used when resolving from Splat. /// </param> /// <returns> /// The view associated with the given view model. /// </returns> public IViewFor ResolveView<T>(T viewModel, string contract = null) where T : class { var view = AttemptViewResolutionFor(viewModel.GetType(), contract); if (view != null) { return view; } view = AttemptViewResolutionFor(typeof(T), contract); if (view != null) { return view; } view = AttemptViewResolutionFor(ToggleViewModelType(viewModel.GetType()), contract); if (view != null) { return view; } view = AttemptViewResolutionFor(ToggleViewModelType(typeof(T)), contract); if (view != null) { return view; } this.Log().Warn("Failed to resolve view for view model type '{0}'.", typeof(T).FullName); return null; } private static Type ToggleViewModelType(Type viewModelType) { var viewModelTypeName = viewModelType.AssemblyQualifiedName; if (viewModelType.GetTypeInfo().IsInterface) { if (viewModelType.Name.StartsWith("I", StringComparison.InvariantCulture)) { var toggledTypeName = DeinterfaceifyTypeName(viewModelTypeName); var toggledType = Reflection.ReallyFindType(toggledTypeName, throwOnFailure: false); return toggledType; } } else { var toggledTypeName = InterfaceifyTypeName(viewModelTypeName); var toggledType = Reflection.ReallyFindType(toggledTypeName, throwOnFailure: false); return toggledType; } return null; } private static string DeinterfaceifyTypeName(string typeName) { var idxComma = typeName.IndexOf(",", 0, StringComparison.InvariantCulture); var idxPeriod = typeName.LastIndexOf('.', idxComma - 1); return typeName.Substring(0, idxPeriod + 1) + typeName.Substring(idxPeriod + 2); } private static string InterfaceifyTypeName(string typeName) { var idxComma = typeName.IndexOf(",", 0, StringComparison.InvariantCulture); var idxPeriod = typeName.LastIndexOf(".", idxComma - 1, StringComparison.InvariantCulture); return typeName.Insert(idxPeriod + 1, "I"); } private IViewFor AttemptViewResolutionFor(Type viewModelType, string contract) { if (viewModelType == null) { return null; } var viewModelTypeName = viewModelType.AssemblyQualifiedName; var proposedViewTypeName = ViewModelToViewFunc(viewModelTypeName); var view = AttemptViewResolution(proposedViewTypeName, contract); if (view != null) { return view; } proposedViewTypeName = typeof(IViewFor<>).MakeGenericType(viewModelType).AssemblyQualifiedName; view = AttemptViewResolution(proposedViewTypeName, contract); if (view != null) { return view; } return null; } private IViewFor AttemptViewResolution(string viewTypeName, string contract) { try { var viewType = Reflection.ReallyFindType(viewTypeName, throwOnFailure: false); if (viewType == null) { this.Log().Debug("Failed to find type named '{0}'.", viewTypeName); return null; } var service = Locator.Current.GetService(viewType, contract); if (service == null) { this.Log().Debug("Failed to resolve service for type '{0}'.", viewType.FullName); return null; } var view = service as IViewFor; if (view == null) { this.Log().Debug("Resolve service type '{0}' does not implement '{1}'.", viewType.FullName, typeof(IViewFor).FullName); return null; } return view; } catch (Exception ex) { this.Log().ErrorException("Exception occurred whilst attempting to resolve type '" + viewTypeName + "' into a view.", ex); throw; } } } }
37.838565
192
0.550723
[ "MIT" ]
SpiegelSoft/ReactiveUI
src/ReactiveUI/View/DefaultViewLocator.cs
8,440
C#
using System; using Android.App; using Android.Content; using Android.Runtime; using Android.Views; using Android.Widget; using Android.OS; namespace App1.Droid { [Activity (Label = "App1.Droid", MainLauncher = true, Icon = "@drawable/icon")] public class MainActivity : Activity { int count = 1; protected override void OnCreate (Bundle bundle) { base.OnCreate (bundle); // Set our view from the "main" layout resource SetContentView (Resource.Layout.Main); // Get our button from the layout resource, // and attach an event to it Button button = FindViewById<Button> (Resource.Id.myButton); button.Click += delegate { button.Text = string.Format ("{0} clicks!", count++); }; } } }
20.416667
80
0.687075
[ "MIT" ]
pankajdey198320/NET_CORE
Core explore/App1/App1/App1.Droid/MainActivity.cs
737
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. using MixedRealityToolkit.Common; using MixedRealityToolkit.SpatialUnderstanding; using System; using System.Collections.Generic; using UnityEngine; namespace MixedRealityToolkit.Examples.SpatialUnderstanding { public class LevelSolver : LineDrawer { // Singleton public static LevelSolver Instance; // Enums public enum QueryStates { None, Processing, Finished } // Structs private struct QueryStatus { public void Reset() { State = QueryStates.None; Name = ""; CountFail = 0; CountSuccess = 0; QueryResult = new List<SpatialUnderstandingDllObjectPlacement.ObjectPlacementResult>(); } public QueryStates State; public string Name; public int CountFail; public int CountSuccess; public List<SpatialUnderstandingDllObjectPlacement.ObjectPlacementResult> QueryResult; } private struct PlacementQuery { public PlacementQuery( SpatialUnderstandingDllObjectPlacement.ObjectPlacementDefinition placementDefinition, List<SpatialUnderstandingDllObjectPlacement.ObjectPlacementRule> placementRules = null, List<SpatialUnderstandingDllObjectPlacement.ObjectPlacementConstraint> placementConstraints = null) { PlacementDefinition = placementDefinition; PlacementRules = placementRules; PlacementConstraints = placementConstraints; } public SpatialUnderstandingDllObjectPlacement.ObjectPlacementDefinition PlacementDefinition; public List<SpatialUnderstandingDllObjectPlacement.ObjectPlacementRule> PlacementRules; public List<SpatialUnderstandingDllObjectPlacement.ObjectPlacementConstraint> PlacementConstraints; } private class PlacementResult { public PlacementResult(float timeDelay, SpatialUnderstandingDllObjectPlacement.ObjectPlacementResult result) { Box = new AnimatedBox(timeDelay, result.Position, Quaternion.LookRotation(result.Forward, result.Up), Color.blue, result.HalfDims); Result = result; } public LineDrawer.AnimatedBox Box; public SpatialUnderstandingDllObjectPlacement.ObjectPlacementResult Result; } // Properties public bool IsSolverInitialized { get; private set; } // Privates private List<PlacementResult> placementResults = new List<PlacementResult>(); private QueryStatus queryStatus = new QueryStatus(); // Functions private void Awake() { Instance = this; } public void ClearGeometry(bool clearAll = true) { placementResults.Clear(); if (SpatialUnderstandingManager.Instance.AllowSpatialUnderstanding) { SpatialUnderstandingDllObjectPlacement.Solver_RemoveAllObjects(); } AppState.Instance.ObjectPlacementDescription = ""; if (clearAll && (SpaceVisualizer.Instance != null)) { SpaceVisualizer.Instance.ClearGeometry(false); } } private bool Draw_PlacementResults() { bool needsUpdate = false; for (int i = 0; i < placementResults.Count; ++i) { needsUpdate |= Draw_AnimatedBox(placementResults[i].Box); } return needsUpdate; } private bool PlaceObjectAsync( string placementName, SpatialUnderstandingDllObjectPlacement.ObjectPlacementDefinition placementDefinition, List<SpatialUnderstandingDllObjectPlacement.ObjectPlacementRule> placementRules = null, List<SpatialUnderstandingDllObjectPlacement.ObjectPlacementConstraint> placementConstraints = null, bool clearObjectsFirst = true) { return PlaceObjectAsync( placementName, new List<PlacementQuery>() { new PlacementQuery(placementDefinition, placementRules, placementConstraints) }, clearObjectsFirst); } private bool PlaceObjectAsync( string placementName, List<PlacementQuery> placementList, bool clearObjectsFirst = true) { // If we already mid-query, reject the request if (queryStatus.State != QueryStates.None) { return false; } // Clear geo if (clearObjectsFirst) { ClearGeometry(); } // Mark it queryStatus.Reset(); queryStatus.State = QueryStates.Processing; queryStatus.Name = placementName; // Tell user we are processing AppState.Instance.ObjectPlacementDescription = placementName + " (processing)"; // Kick off a thread to do process the queries #if UNITY_EDITOR || !UNITY_WSA new System.Threading.Thread #else System.Threading.Tasks.Task.Run #endif (() => { // Go through the queries in the list for (int i = 0; i < placementList.Count; ++i) { // Do the query bool success = PlaceObject( placementName, placementList[i].PlacementDefinition, placementList[i].PlacementRules, placementList[i].PlacementConstraints, clearObjectsFirst, true); // Mark the result queryStatus.CountSuccess = success ? (queryStatus.CountSuccess + 1) : queryStatus.CountSuccess; queryStatus.CountFail = !success ? (queryStatus.CountFail + 1) : queryStatus.CountFail; } // Done queryStatus.State = QueryStates.Finished; } ) #if UNITY_EDITOR || !UNITY_WSA .Start() #endif ; return true; } private bool PlaceObject( string placementName, SpatialUnderstandingDllObjectPlacement.ObjectPlacementDefinition placementDefinition, List<SpatialUnderstandingDllObjectPlacement.ObjectPlacementRule> placementRules = null, List<SpatialUnderstandingDllObjectPlacement.ObjectPlacementConstraint> placementConstraints = null, bool clearObjectsFirst = true, bool isASync = false) { // Clear objects (if requested) if (!isASync && clearObjectsFirst) { ClearGeometry(); } if (!SpatialUnderstandingManager.Instance.AllowSpatialUnderstanding) { return false; } // New query if (SpatialUnderstandingDllObjectPlacement.Solver_PlaceObject( placementName, SpatialUnderstandingManager.Instance.UnderstandingDLL.PinObject(placementDefinition), (placementRules != null) ? placementRules.Count : 0, ((placementRules != null) && (placementRules.Count > 0)) ? SpatialUnderstandingManager.Instance.UnderstandingDLL.PinObject(placementRules.ToArray()) : IntPtr.Zero, (placementConstraints != null) ? placementConstraints.Count : 0, ((placementConstraints != null) && (placementConstraints.Count > 0)) ? SpatialUnderstandingManager.Instance.UnderstandingDLL.PinObject(placementConstraints.ToArray()) : IntPtr.Zero, SpatialUnderstandingManager.Instance.UnderstandingDLL.GetStaticObjectPlacementResultPtr()) > 0) { SpatialUnderstandingDllObjectPlacement.ObjectPlacementResult placementResult = SpatialUnderstandingManager.Instance.UnderstandingDLL.GetStaticObjectPlacementResult(); if (!isASync) { // If not running async, we can just add the results to the draw list right now AppState.Instance.ObjectPlacementDescription = placementName + " (1)"; float timeDelay = (float)placementResults.Count * AnimatedBox.DelayPerItem; placementResults.Add(new PlacementResult(timeDelay, placementResult.Clone() as SpatialUnderstandingDllObjectPlacement.ObjectPlacementResult)); } else { queryStatus.QueryResult.Add(placementResult.Clone() as SpatialUnderstandingDllObjectPlacement.ObjectPlacementResult); } return true; } if (!isASync) { AppState.Instance.ObjectPlacementDescription = placementName + " (0)"; } return false; } private void ProcessPlacementResults() { // Check it if (queryStatus.State != QueryStates.Finished) { return; } if (!SpatialUnderstandingManager.Instance.AllowSpatialUnderstanding) { return; } // Clear results ClearGeometry(); // We will reject any above or below the ceiling/floor SpatialUnderstandingDll.Imports.QueryPlayspaceAlignment(SpatialUnderstandingManager.Instance.UnderstandingDLL.GetStaticPlayspaceAlignmentPtr()); SpatialUnderstandingDll.Imports.PlayspaceAlignment alignment = SpatialUnderstandingManager.Instance.UnderstandingDLL.GetStaticPlayspaceAlignment(); // Copy over the results for (int i = 0; i < queryStatus.QueryResult.Count; ++i) { if ((queryStatus.QueryResult[i].Position.y < alignment.CeilingYValue) && (queryStatus.QueryResult[i].Position.y > alignment.FloorYValue)) { float timeDelay = (float)placementResults.Count * AnimatedBox.DelayPerItem; placementResults.Add(new PlacementResult(timeDelay, queryStatus.QueryResult[i].Clone() as SpatialUnderstandingDllObjectPlacement.ObjectPlacementResult)); } } // Text AppState.Instance.ObjectPlacementDescription = queryStatus.Name + " (" + placementResults.Count + "/" + (queryStatus.CountSuccess + queryStatus.CountFail) + ")"; // Mark done queryStatus.Reset(); } public void Query_OnFloor() { List<PlacementQuery> placementQuery = new List<PlacementQuery>(); for (int i = 0; i < 4; ++i) { float halfDimSize = UnityEngine.Random.Range(0.15f, 0.35f); placementQuery.Add( new PlacementQuery(SpatialUnderstandingDllObjectPlacement.ObjectPlacementDefinition.Create_OnFloor(new Vector3(halfDimSize, halfDimSize, halfDimSize * 2.0f)), new List<SpatialUnderstandingDllObjectPlacement.ObjectPlacementRule>() { SpatialUnderstandingDllObjectPlacement.ObjectPlacementRule.Create_AwayFromOtherObjects(halfDimSize * 3.0f), })); } PlaceObjectAsync("OnFloor", placementQuery); } public void Query_OnWall() { List<PlacementQuery> placementQuery = new List<PlacementQuery>(); for (int i = 0; i < 6; ++i) { float halfDimSize = UnityEngine.Random.Range(0.3f, 0.6f); placementQuery.Add( new PlacementQuery(SpatialUnderstandingDllObjectPlacement.ObjectPlacementDefinition.Create_OnWall(new Vector3(halfDimSize, halfDimSize * 0.5f, 0.05f), 0.5f, 3.0f), new List<SpatialUnderstandingDllObjectPlacement.ObjectPlacementRule>() { SpatialUnderstandingDllObjectPlacement.ObjectPlacementRule.Create_AwayFromOtherObjects(halfDimSize * 4.0f), })); } PlaceObjectAsync("OnWall", placementQuery); } public void Query_OnCeiling() { List<PlacementQuery> placementQuery = new List<PlacementQuery>(); for (int i = 0; i < 2; ++i) { float halfDimSize = UnityEngine.Random.Range(0.3f, 0.4f); placementQuery.Add( new PlacementQuery(SpatialUnderstandingDllObjectPlacement.ObjectPlacementDefinition.Create_OnCeiling(new Vector3(halfDimSize, halfDimSize, halfDimSize)), new List<SpatialUnderstandingDllObjectPlacement.ObjectPlacementRule>() { SpatialUnderstandingDllObjectPlacement.ObjectPlacementRule.Create_AwayFromOtherObjects(halfDimSize * 3.0f), })); } PlaceObjectAsync("OnCeiling", placementQuery); } public void Query_OnEdge() { List<PlacementQuery> placementQuery = new List<PlacementQuery>(); for (int i = 0; i < 8; ++i) { float halfDimSize = UnityEngine.Random.Range(0.05f, 0.1f); placementQuery.Add( new PlacementQuery(SpatialUnderstandingDllObjectPlacement.ObjectPlacementDefinition.Create_OnEdge(new Vector3(halfDimSize, halfDimSize, halfDimSize), new Vector3(halfDimSize, halfDimSize, halfDimSize)), new List<SpatialUnderstandingDllObjectPlacement.ObjectPlacementRule>() { SpatialUnderstandingDllObjectPlacement.ObjectPlacementRule.Create_AwayFromOtherObjects(halfDimSize * 3.0f), })); } PlaceObjectAsync("OnEdge", placementQuery); } public void Query_OnFloorAndCeiling() { SpatialUnderstandingDll.Imports.QueryPlayspaceAlignment(SpatialUnderstandingManager.Instance.UnderstandingDLL.GetStaticPlayspaceAlignmentPtr()); SpatialUnderstandingDll.Imports.PlayspaceAlignment alignment = SpatialUnderstandingManager.Instance.UnderstandingDLL.GetStaticPlayspaceAlignment(); List<PlacementQuery> placementQuery = new List<PlacementQuery>(); for (int i = 0; i < 4; ++i) { float halfDimSize = UnityEngine.Random.Range(0.1f, 0.2f); placementQuery.Add( new PlacementQuery(SpatialUnderstandingDllObjectPlacement.ObjectPlacementDefinition.Create_OnFloorAndCeiling(new Vector3(halfDimSize, (alignment.CeilingYValue - alignment.FloorYValue) * 0.5f, halfDimSize), new Vector3(halfDimSize, (alignment.CeilingYValue - alignment.FloorYValue) * 0.5f, halfDimSize)), new List<SpatialUnderstandingDllObjectPlacement.ObjectPlacementRule>() { SpatialUnderstandingDllObjectPlacement.ObjectPlacementRule.Create_AwayFromOtherObjects(halfDimSize * 3.0f), })); } PlaceObjectAsync("OnFloorAndCeiling", placementQuery); } public void Query_RandomInAir_AwayFromMe() { List<PlacementQuery> placementQuery = new List<PlacementQuery>(); for (int i = 0; i < 8; ++i) { float halfDimSize = UnityEngine.Random.Range(0.1f, 0.2f); placementQuery.Add( new PlacementQuery(SpatialUnderstandingDllObjectPlacement.ObjectPlacementDefinition.Create_RandomInAir(new Vector3(halfDimSize, halfDimSize, halfDimSize)), new List<SpatialUnderstandingDllObjectPlacement.ObjectPlacementRule>() { SpatialUnderstandingDllObjectPlacement.ObjectPlacementRule.Create_AwayFromOtherObjects(halfDimSize * 3.0f), SpatialUnderstandingDllObjectPlacement.ObjectPlacementRule.Create_AwayFromPosition(CameraCache.Main.transform.position, 2.5f), })); } PlaceObjectAsync("RandomInAir - AwayFromMe", placementQuery); } public void Query_OnEdge_NearCenter() { List<PlacementQuery> placementQuery = new List<PlacementQuery>(); for (int i = 0; i < 4; ++i) { float halfDimSize = UnityEngine.Random.Range(0.05f, 0.1f); placementQuery.Add( new PlacementQuery(SpatialUnderstandingDllObjectPlacement.ObjectPlacementDefinition.Create_OnEdge(new Vector3(halfDimSize, halfDimSize, halfDimSize), new Vector3(halfDimSize, halfDimSize, halfDimSize)), new List<SpatialUnderstandingDllObjectPlacement.ObjectPlacementRule>() { SpatialUnderstandingDllObjectPlacement.ObjectPlacementRule.Create_AwayFromOtherObjects(halfDimSize * 2.0f), }, new List<SpatialUnderstandingDllObjectPlacement.ObjectPlacementConstraint>() { SpatialUnderstandingDllObjectPlacement.ObjectPlacementConstraint.Create_NearCenter(), })); } PlaceObjectAsync("OnEdge - NearCenter", placementQuery); } public void Query_OnFloor_AwayFromMe() { List<PlacementQuery> placementQuery = new List<PlacementQuery>(); for (int i = 0; i < 4; ++i) { float halfDimSize = UnityEngine.Random.Range(0.05f, 0.15f); placementQuery.Add( new PlacementQuery(SpatialUnderstandingDllObjectPlacement.ObjectPlacementDefinition.Create_OnFloor(new Vector3(halfDimSize, halfDimSize, halfDimSize)), new List<SpatialUnderstandingDllObjectPlacement.ObjectPlacementRule>() { SpatialUnderstandingDllObjectPlacement.ObjectPlacementRule.Create_AwayFromPosition(CameraCache.Main.transform.position, 2.0f), SpatialUnderstandingDllObjectPlacement.ObjectPlacementRule.Create_AwayFromOtherObjects(halfDimSize * 3.0f), })); } PlaceObjectAsync("OnFloor - AwayFromMe", placementQuery); } public void Query_OnFloor_NearMe() { List<PlacementQuery> placementQuery = new List<PlacementQuery>(); for (int i = 0; i < 4; ++i) { float halfDimSize = UnityEngine.Random.Range(0.05f, 0.2f); placementQuery.Add( new PlacementQuery(SpatialUnderstandingDllObjectPlacement.ObjectPlacementDefinition.Create_OnFloor(new Vector3(halfDimSize, halfDimSize, halfDimSize)), new List<SpatialUnderstandingDllObjectPlacement.ObjectPlacementRule>() { SpatialUnderstandingDllObjectPlacement.ObjectPlacementRule.Create_AwayFromOtherObjects(halfDimSize * 3.0f), }, new List<SpatialUnderstandingDllObjectPlacement.ObjectPlacementConstraint>() { SpatialUnderstandingDllObjectPlacement.ObjectPlacementConstraint.Create_NearPoint(CameraCache.Main.transform.position, 0.5f, 2.0f) })); } PlaceObjectAsync("OnFloor - NearMe", placementQuery); } private void Update_Queries() { if (Input.GetKeyDown(KeyCode.R)) { Query_OnFloor(); } if (Input.GetKeyDown(KeyCode.T)) { Query_OnWall(); } if (Input.GetKeyDown(KeyCode.Y)) { Query_OnCeiling(); } if (Input.GetKeyDown(KeyCode.U)) { Query_OnEdge(); } if (Input.GetKeyDown(KeyCode.I)) { Query_OnFloorAndCeiling(); } if (Input.GetKeyDown(KeyCode.O)) { Query_RandomInAir_AwayFromMe(); } if (Input.GetKeyDown(KeyCode.P)) { Query_OnEdge_NearCenter(); } if (Input.GetKeyDown(KeyCode.LeftBracket)) { Query_OnFloor_AwayFromMe(); } if (Input.GetKeyDown(KeyCode.RightBracket)) { Query_OnFloor_NearMe(); } } public bool InitializeSolver() { if (IsSolverInitialized || !SpatialUnderstandingManager.Instance.AllowSpatialUnderstanding) { return IsSolverInitialized; } if (SpatialUnderstandingDllObjectPlacement.Solver_Init() == 1) { IsSolverInitialized = true; } return IsSolverInitialized; } private void Update() { // Can't do any of this till we're done with the scanning phase if (SpatialUnderstandingManager.Instance.ScanState != SpatialUnderstandingManager.ScanStates.Done) { return; } // Make sure the solver has been initialized if (!IsSolverInitialized && SpatialUnderstandingManager.Instance.AllowSpatialUnderstanding) { InitializeSolver(); } // Constraint queries if (SpatialUnderstandingManager.Instance.ScanState == SpatialUnderstandingManager.ScanStates.Done) { Update_Queries(); } // Handle async query results ProcessPlacementResults(); // Lines: Begin LineDraw_Begin(); // Drawers bool needsUpdate = false; needsUpdate |= Draw_PlacementResults(); // Lines: Finish up LineDraw_End(needsUpdate); } } }
45.298246
225
0.574834
[ "MIT" ]
amngupta/MixedRealityToolkit-Unity
Assets/MixedRealityToolkit-Examples/SpatialUnderstanding/Scripts/LevelSolver.cs
23,240
C#
using NUnit.Framework; using Rebus.Tests.Contracts.Sagas; namespace Rebus.RavenDb.Tests.Sagas { [TestFixture, Category(TestCategory.RavenDb)] public class RavenDbBasicLoadAndSaveAndFindOperations : BasicLoadAndSaveAndFindOperations<RavenDbSagaStorageFactory> { } }
34.25
124
0.824818
[ "MIT" ]
mastreeno/Rebus
Rebus.RavenDb.Tests/Sagas/RavenDbBasicLoadAndSaveAndFindOperations.cs
276
C#
using System; using System.Collections.Generic; using System.Text; using System.Runtime.InteropServices; namespace Microsoft.ML.OnnxRuntime { internal class CpuExecutionProviderFactory: NativeOnnxObjectHandle { protected static readonly Lazy<CpuExecutionProviderFactory> _default = new Lazy<CpuExecutionProviderFactory>(() => new CpuExecutionProviderFactory()); public CpuExecutionProviderFactory(bool useArena=true) :base(IntPtr.Zero) { int useArenaInt = useArena ? 1 : 0; try { NativeApiStatus.VerifySuccess(NativeMethods.OrtCreateCpuExecutionProviderFactory(useArenaInt, out handle)); } catch(OnnxRuntimeException e) { if (IsInvalid) { ReleaseHandle(); handle = IntPtr.Zero; } throw e; } } public static CpuExecutionProviderFactory Default { get { return _default.Value; } } } internal class MklDnnExecutionProviderFactory : NativeOnnxObjectHandle { protected static readonly Lazy<MklDnnExecutionProviderFactory> _default = new Lazy<MklDnnExecutionProviderFactory>(() => new MklDnnExecutionProviderFactory()); public MklDnnExecutionProviderFactory(bool useArena = true) :base(IntPtr.Zero) { int useArenaInt = useArena ? 1 : 0; try { NativeApiStatus.VerifySuccess(NativeMethods.OrtCreateMkldnnExecutionProviderFactory(useArenaInt, out handle)); } catch (OnnxRuntimeException e) { if (IsInvalid) { ReleaseHandle(); handle = IntPtr.Zero; } throw e; } } public static MklDnnExecutionProviderFactory Default { get { return _default.Value; } } } internal class CudaExecutionProviderFactory : NativeOnnxObjectHandle { protected static readonly Lazy<CudaExecutionProviderFactory> _default = new Lazy<CudaExecutionProviderFactory>(() => new CudaExecutionProviderFactory()); public CudaExecutionProviderFactory(int deviceId = 0) : base(IntPtr.Zero) { try { NativeApiStatus.VerifySuccess(NativeMethods.OrtCreateCUDAExecutionProviderFactory(deviceId, out handle)); } catch (OnnxRuntimeException e) { if (IsInvalid) { ReleaseHandle(); handle = IntPtr.Zero; } throw e; } } public static CudaExecutionProviderFactory Default { get { return _default.Value; } } } }
28.616822
167
0.542456
[ "MIT" ]
PaulGureghian1/ONNX_Runtime
csharp/src/Microsoft.ML.OnnxRuntime/ExecutionProviderFactory.cs
3,064
C#
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the iot-2015-05-28.normal.json service model. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Net; using System.Text; using System.Xml.Serialization; using Amazon.IoT.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; using ThirdParty.Json.LitJson; namespace Amazon.IoT.Model.Internal.MarshallTransformations { /// <summary> /// Response Unmarshaller for SigV4Authorization Object /// </summary> public class SigV4AuthorizationUnmarshaller : IUnmarshaller<SigV4Authorization, XmlUnmarshallerContext>, IUnmarshaller<SigV4Authorization, JsonUnmarshallerContext> { /// <summary> /// Unmarshaller the response from the service to the response class. /// </summary> /// <param name="context"></param> /// <returns></returns> SigV4Authorization IUnmarshaller<SigV4Authorization, XmlUnmarshallerContext>.Unmarshall(XmlUnmarshallerContext context) { throw new NotImplementedException(); } /// <summary> /// Unmarshaller the response from the service to the response class. /// </summary> /// <param name="context"></param> /// <returns></returns> public SigV4Authorization Unmarshall(JsonUnmarshallerContext context) { context.Read(); if (context.CurrentTokenType == JsonToken.Null) return null; SigV4Authorization unmarshalledObject = new SigV4Authorization(); int targetDepth = context.CurrentDepth; while (context.ReadAtDepth(targetDepth)) { if (context.TestExpression("roleArn", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; unmarshalledObject.RoleArn = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("serviceName", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; unmarshalledObject.ServiceName = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("signingRegion", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; unmarshalledObject.SigningRegion = unmarshaller.Unmarshall(context); continue; } } return unmarshalledObject; } private static SigV4AuthorizationUnmarshaller _instance = new SigV4AuthorizationUnmarshaller(); /// <summary> /// Gets the singleton. /// </summary> public static SigV4AuthorizationUnmarshaller Instance { get { return _instance; } } } }
35.509615
167
0.623883
[ "Apache-2.0" ]
ChristopherButtars/aws-sdk-net
sdk/src/Services/IoT/Generated/Model/Internal/MarshallTransformations/SigV4AuthorizationUnmarshaller.cs
3,693
C#
using System; using System.Collections; using Softing.OPCToolbox; using Softing.OPCToolbox.Server; namespace SerialIO { public class MyDaAddressSpaceElement : DaAddressSpaceElement { #region Constructors //------------------------------ public MyDaAddressSpaceElement( string anItemID, string aName, uint anUserData, uint anObjectHandle, uint aParentHandle) : base( anItemID, aName, anUserData, anObjectHandle, aParentHandle) { } // end constructor public MyDaAddressSpaceElement() { } // end constructor //-- #endregion #region Public Static Attributes //------------------------------- static public byte TYPE_UNKNOWN = 0x0; static public byte TYPE_NODEMATH = 0x80; static public byte TYPE_SINE = 0x04; static public byte TYPE_ACCEPT = 0x08; //-- #endregion #region Private Attributes //------------------------------- private byte m_Type = TYPE_UNKNOWN; private Hashtable m_properties = new Hashtable(); //-- #endregion #region Public Property //--------------------- public virtual byte Type { get { return m_Type; } set { m_Type = value; } } // Attribute Type //-- #endregion #region Public Methods //--------------------- /// <summary> /// Get elements property value data /// </summary> public void GetPropertyValue(DaRequest aRequest) { if (aRequest.PropertyId == 101) { aRequest.Value = new ValueQT( "description", EnumQuality.GOOD, DateTime.Now); aRequest.Result = EnumResultCode.S_OK; } else { aRequest.Result = EnumResultCode.E_NOTFOUND; } // end if ... else } // end GetPropertyValue public override int QueryProperties(out ArrayList aPropertyList) { if (m_properties.Count > 0) { aPropertyList = new ArrayList(); aPropertyList.AddRange(m_properties.Values); } else { aPropertyList = null; } // end if ... else return (int)(EnumResultCode.S_OK); } // end QueryProperties public uint AddProperty(DaProperty aProperty) { if (aProperty != null) { m_properties.Add( aProperty.Id, aProperty); return (int)EnumResultCode.S_OK; } // end if else { return (int)EnumResultCode.S_FALSE; } // end if...else } // end AddProperty //-- #endregion } // end class MyAddressSpaceElement } // end namespace
18.929134
66
0.617304
[ "MIT" ]
Movares/OPC-Classic-SDK
development/NET/samples/server/Serial_IO/CS/MyDaAddressSpaceElement.cs
2,404
C#
// // DigitalSignatureVerifyException.cs // // Author: Jeffrey Stedfast <jeff@xamarin.com> // // Copyright (c) 2013 Jeffrey Stedfast // // 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; namespace MimeKit.Cryptography { /// <summary> /// An exception that is thrown when an error occurrs in <see cref="IDigitalSignature.Verify"/>. /// </summary> /// <remarks> /// For more information about the error condition, check the <see cref="System.Exception.InnerException"/> property. /// </remarks> public class DigitalSignatureVerifyException : Exception { internal DigitalSignatureVerifyException (string message, Exception innerException) : base (message, innerException) { } internal DigitalSignatureVerifyException (string message) : base (message) { } } }
38.680851
118
0.753025
[ "MIT" ]
anaselhajjaji/MimeKit
MimeKit/Cryptography/DigitalSignatureVerifyException.cs
1,818
C#
#nullable enable using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Syntax; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CodeConnections.Extensions { public static class SyntaxNodeExtensions { /// <summary> /// Retrieves all symbols referenced in the syntax subtree rooted on <paramref name="syntaxNode"/>. /// </summary> /// <param name="includeExternalMetadata"> /// If true, externally-defined symbols from metadata are included. If false, only locally-defined /// symbols in the same solution are returned. /// </param> public static IEnumerable<ISymbol> GetAllReferencedSymbols(this SyntaxNode syntaxNode, SemanticModel model, bool includeExternalMetadata = true) => syntaxNode.DescendantNodesAndSelf() .Select(n => model.GetSymbolInfo(n).Symbol) .Trim() .Where(s => includeExternalMetadata ? true : IsDefinedInSolution(s)) .Distinct(); private static bool IsDefinedInSolution(ISymbol s) { return !s.DeclaringSyntaxReferences.IsEmpty; } /// <summary> /// Retrieves all <see cref="ITypeSymbol"/> symbols referenced in the syntax subtree rooted on <paramref name="syntaxNode"/>. /// </summary> /// <param name="includeExternalMetadata"> /// If true, externally-defined symbols from metadata are included. If false, only locally-defined /// symbols in the same solution are returned. /// </param> public static IEnumerable<ITypeSymbol> GetAllReferencedTypeSymbols(this SyntaxNode syntaxNode, SemanticModel model, bool includeExternalMetadata = true, bool includeTypeParameters = false, bool includeConstructed = false) => GetAllReferencedSymbols(syntaxNode, model, includeExternalMetadata: true) // Get all symbols including external ones, to be able to unpack constructed types (generics etc) .Select(s => s as ITypeSymbol // Extension method invocations typically otherwise yield no explicit reference to the type ?? (s as IMethodSymbol)?.ContainingType) .Trim() .Distinct() .Unpack(includeConstructed) .Trim() .Where(s => includeExternalMetadata ? true : IsDefinedInSolution(s)) // Now we filter out external types (if so requested) .Where(s => includeTypeParameters ? true : !(s is ITypeParameterSymbol)) .Distinct(); /// <summary> /// Get all types (classes/structs, interfaces, and enums) declared by or within <paramref name="syntaxNode"/>. /// </summary> /// <returns>Symbols of declared types.</returns> public static IEnumerable<ITypeSymbol> GetAllDeclaredTypes(this SyntaxNode syntaxNode, SemanticModel model) => syntaxNode.DescendantNodesAndSelf() // This might well be significantly optimized by not entering into nodes that can be known not to contain declarations .OfType<BaseTypeDeclarationSyntax>() .Select(n => model.GetDeclaredSymbol(n) as ITypeSymbol) .Trim(); } }
44.938462
223
0.743923
[ "MIT" ]
davidjohnoliver/CodeConnections
CodeConnections.Shared/Extensions/SyntaxNodeExtensions.cs
2,923
C#
using JadeFramework.Core.Domain.Entities; using JadeFramework.Dapper; using MsSystem.OA.Model; using MsSystem.OA.ViewModel; using System.Threading.Tasks; namespace MsSystem.OA.IRepository { public interface IOaMessageRepository : IDapperRepository<OaMessage> { Task<Page<OaMessage>> GetPageAsync(int pageIndex, int pageSize); Task<Page<OaMessageMyList>> MyListAsync(OaMessageMyListSearch search); } }
28.733333
78
0.772622
[ "MIT" ]
anjoy8/MsSystem-BPM-ServiceAndWebApps
src/Services/OA/MsSystem.OA.IRepository/IOaMessageRepository.cs
433
C#
// Copyright 2007-2011 Chris Patterson, Dru Sellers, Travis Smith, et. al. // // Licensed under the Apache License, Version 2.0 (the "License"); you may not use // this file except in compliance with the License. You may obtain a copy of the // License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software distributed // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR // CONDITIONS OF ANY KIND, either express or implied. See the License for the // specific language governing permissions and limitations under the License. namespace MassTransit.Tests.Saga.StateMachine { using System; using Magnum.StateMachine; using Magnum.TestFramework; using Messages; using NUnit.Framework; [TestFixture] public class SagaStateMachine_Specs { [SetUp] public void Setup() { _transactionId = NewId.NextGuid(); _username = "jblow"; _password = "password1"; _email = "jblow@yourdad.com"; _displayName = "Joe Blow"; } Guid _transactionId; string _username; string _password; string _email; string _displayName; [Test] public void The_good_times_should_roll() { var workflow = new RegisterUserStateMachine(); workflow.CurrentState.ShouldEqual(RegisterUserStateMachine.Initial); workflow.Consume(new RegisterUser(_transactionId, _username, _password, _displayName, _email)); workflow.CurrentState.ShouldEqual(RegisterUserStateMachine.WaitingForEmailValidation); workflow.Consume(new UserValidated(_transactionId)); workflow.CurrentState.ShouldEqual(RegisterUserStateMachine.Completed); } [Test] public void The_saga_state_machine_should_add_value_for_sagas() { var workflow = new RegisterUserStateMachine(); Assert.AreEqual(RegisterUserStateMachine.Initial, workflow.CurrentState); workflow.Consume(new RegisterUser(_transactionId, _username, _password, _displayName, _email)); Assert.AreEqual(RegisterUserStateMachine.WaitingForEmailValidation, workflow.CurrentState); } [Test] public void The_visualizer_should_work() { var workflow = new RegisterUserStateMachine(); StateMachineInspector.Trace(workflow); } } }
34.328947
108
0.649291
[ "Apache-2.0" ]
SeanKilleen/MassTransit
src/MassTransit.Tests/Saga/StateMachine/SagaStateMachine_Specs.cs
2,609
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("VolleyManagement.Crosscutting")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("VolleyManagement.Crosscutting")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("cff5a0c2-4dd4-4675-93f2-4dc9718ebafd")] // 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.540541
84
0.752454
[ "MIT" ]
VolleyManagement/volley-management
archive/src/VolleyManagement.Backend/VolleyManagement.Crosscutting/Properties/AssemblyInfo.cs
1,429
C#
using Torque3D; using Torque3D.Engine; using Torque3D.Util; namespace Game.Modules.ClientServer.Server { class Audio { public static void Init() { } public static void ServerPlay2D(SFXProfile profile) { SimSet ClientGroup = Sim.FindObject<SimSet>("ClientGroup"); // Play the given sound profile on every client. // The sounds will be transmitted as an event, not attached to any object. for (uint i = 0; i < ClientGroup.getCount(); i++) { ClientGroup.getObject(i).As<GameConnectionToClient>().play2D(profile); } } public static void ServerPlay3D(SFXProfile profile, TransformF transform) { SimSet ClientGroup = Sim.FindObject<SimSet>("ClientGroup"); // Play the given sound profile at the given position on every client // The sound will be transmitted as an event, not attached to any object. for (uint i = 0; i < ClientGroup.getCount(); i++) { ClientGroup.getObject(i).As<GameConnectionToClient>().play3D(profile, transform); } } } }
31.527778
93
0.625551
[ "MIT" ]
lukaspj/Torque-BaseGame
Modules/ClientServer/Server/Audio.cs
1,137
C#
using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.ServiceModel; using System.ServiceModel.Channels; using System.Text; using System.Threading; using System.Threading.Tasks; using MagentoAccess.MagentoSoapServiceReference; using MagentoAccess.Misc; namespace MagentoAccess.Services { internal class MagentoServiceLowLevelSoap : IMagentoServiceLowLevelSoap { public string ApiUser { get; private set; } public string ApiKey { get; private set; } public string Store { get; private set; } public string BaseMagentoUrl { get; set; } protected const string SoapApiUrl = "index.php/api/v2_soap/index/"; protected Mage_Api_Model_Server_Wsi_HandlerPortTypeClient _magentoSoapService; protected string _sessionId; protected DateTime _sessionIdCreatedAt; private readonly CustomBinding _customBinding; protected const int SessionIdLifeTime = 3590; private void LogTraceGetResponseException( Exception exception ) { MagentoLogger.Log().Trace( exception, "[magento] SOAP throw an exception." ); } internal async Task< string > GetSessionId( bool throwException = true ) { try { if( !string.IsNullOrWhiteSpace( this._sessionId ) && DateTime.UtcNow.Subtract( this._sessionIdCreatedAt ).TotalSeconds < SessionIdLifeTime ) return this._sessionId; const int maxCheckCount = 2; const int delayBeforeCheck = 120000; var res = string.Empty; var privateClient = this.CreateMagentoServiceClient( this.BaseMagentoUrl ); //await ActionPolicies.GetAsync.Do( async () => //{ // var statusChecker = new StatusChecker(maxCheckCount); // TimerCallback tcb = statusChecker.CheckStatus; if( privateClient.State != CommunicationState.Opened && privateClient.State != CommunicationState.Created && privateClient.State != CommunicationState.Opening ) privateClient = this.CreateMagentoServiceClient( this.BaseMagentoUrl ); // using( var stateTimer = new Timer( tcb, privateClient, 1000, delayBeforeCheck ) ) { var loginResponse = await privateClient.loginAsync( this.ApiUser, this.ApiKey ).ConfigureAwait( false ); this._sessionIdCreatedAt = DateTime.UtcNow; this._sessionId = loginResponse.result; res = this._sessionId; } //} ).ConfigureAwait( false ); return res; } catch( Exception exc ) { if( throwException ) throw new MagentoSoapException( string.Format( "An error occured during GetSessionId()" ), exc ); else { this.LogTraceGetResponseException( exc ); return null; } } } public MagentoServiceLowLevelSoap( string apiUser, string apiKey, string baseMagentoUrl, string store ) { this.ApiUser = apiUser; this.ApiKey = apiKey; this.Store = store; this.BaseMagentoUrl = baseMagentoUrl; _customBinding = CustomBinding( baseMagentoUrl ); this._magentoSoapService = this.CreateMagentoServiceClient( baseMagentoUrl ); } private Mage_Api_Model_Server_Wsi_HandlerPortTypeClient CreateMagentoServiceClient( string baseMagentoUrl ) { var endPoint = new List< string > { baseMagentoUrl, SoapApiUrl }.BuildUrl(); var magentoSoapService = new Mage_Api_Model_Server_Wsi_HandlerPortTypeClient( _customBinding, new EndpointAddress( endPoint ) ); magentoSoapService.Endpoint.Behaviors.Add( new CustomBehavior() ); return magentoSoapService; } private async Task< Mage_Api_Model_Server_Wsi_HandlerPortTypeClient > CreateMagentoServiceClientAsync( string baseMagentoUrl ) { var task = Task.Factory.StartNew( () => CreateMagentoServiceClient( baseMagentoUrl ) ); await Task.WhenAll( task ).ConfigureAwait( false ); return task.Result; } private static CustomBinding CustomBinding( string baseMagentoUrl ) { var textMessageEncodingBindingElement = new TextMessageEncodingBindingElement { MessageVersion = MessageVersion.Soap11, WriteEncoding = new UTF8Encoding() }; BindingElement httpTransportBindingElement; if( baseMagentoUrl.StartsWith( "https" ) ) { httpTransportBindingElement = new HttpsTransportBindingElement { DecompressionEnabled = false, MaxReceivedMessageSize = 999999999, MaxBufferSize = 999999999, MaxBufferPoolSize = 999999999, KeepAliveEnabled = true, AllowCookies = false, }; } else { httpTransportBindingElement = new HttpTransportBindingElement { DecompressionEnabled = false, MaxReceivedMessageSize = 999999999, MaxBufferSize = 999999999, MaxBufferPoolSize = 999999999, KeepAliveEnabled = true, AllowCookies = false, }; } var myTextMessageEncodingBindingElement = new CustomMessageEncodingBindingElement( textMessageEncodingBindingElement, "qwe" ) { MessageVersion = MessageVersion.Soap11, }; ICollection< BindingElement > bindingElements = new List< BindingElement >(); var httpBindingElement = httpTransportBindingElement; var textBindingElement = myTextMessageEncodingBindingElement; bindingElements.Add( textBindingElement ); bindingElements.Add( httpBindingElement ); var customBinding = new CustomBinding( bindingElements ) { ReceiveTimeout = new TimeSpan( 0, 2, 30, 0 ), SendTimeout = new TimeSpan( 0, 2, 30, 0 ), OpenTimeout = new TimeSpan( 0, 2, 30, 0 ), CloseTimeout = new TimeSpan( 0, 2, 30, 0 ), Name = "CustomHttpBinding" }; return customBinding; } public virtual async Task< salesOrderListResponse > GetOrdersAsync( DateTime modifiedFrom, DateTime modifiedTo ) { try { filters filters; if( string.IsNullOrWhiteSpace( this.Store ) ) filters = new filters { complex_filter = new complexFilter[ 2 ] }; else { filters = new filters { complex_filter = new complexFilter[ 3 ] }; filters.complex_filter[ 2 ] = new complexFilter { key = "store_id", value = new associativeEntity { key = "in", value = this.Store } }; } filters.complex_filter[ 1 ] = new complexFilter { key = "updated_at", value = new associativeEntity { key = "from", value = modifiedFrom.ToSoapParameterString() } }; filters.complex_filter[ 0 ] = new complexFilter { key = "updated_at", value = new associativeEntity { key = "to", value = modifiedTo.ToSoapParameterString() } }; const int maxCheckCount = 2; const int delayBeforeCheck = 1800000; var res = new salesOrderListResponse(); var privateClient = this.CreateMagentoServiceClient( this.BaseMagentoUrl ); await ActionPolicies.GetAsync.Do( async () => { var statusChecker = new StatusChecker( maxCheckCount ); TimerCallback tcb = statusChecker.CheckStatus; if( privateClient.State != CommunicationState.Opened && privateClient.State != CommunicationState.Created && privateClient.State != CommunicationState.Opening ) privateClient = this.CreateMagentoServiceClient( this.BaseMagentoUrl ); var sessionId = await this.GetSessionId().ConfigureAwait( false ); using( var stateTimer = new Timer( tcb, privateClient, 1000, delayBeforeCheck ) ) res = await privateClient.salesOrderListAsync( sessionId, filters ).ConfigureAwait( false ); } ).ConfigureAwait( false ); //crutch for magento 1.7 res.result = res.result.Where( x => x.updated_at.ToDateTimeOrDefault() >= modifiedFrom && x.updated_at.ToDateTimeOrDefault() <= modifiedTo ).ToArray(); return res; } catch( Exception exc ) { throw new MagentoSoapException( string.Format( "An error occured during GetOrdersAsync(modifiedFrom:{0},modifiedTo{1})", modifiedFrom, modifiedTo ), exc ); } } public virtual async Task< salesOrderListResponse > GetOrdersAsync( IEnumerable< string > ordersIds ) { var ordersIdsAgregated = string.Empty; try { ordersIdsAgregated = string.Join( ",", ordersIds ); filters filters; if( string.IsNullOrWhiteSpace( this.Store ) ) filters = new filters { complex_filter = new complexFilter[ 1 ] }; else { filters = new filters { complex_filter = new complexFilter[ 2 ] }; filters.complex_filter[ 1 ] = new complexFilter { key = "store_id", value = new associativeEntity { key = "in", value = this.Store } }; } filters.complex_filter[ 0 ] = new complexFilter { key = "increment_id", value = new associativeEntity { key = "in", value = ordersIdsAgregated } }; const int maxCheckCount = 2; const int delayBeforeCheck = 1800000; var res = new salesOrderListResponse(); var privateClient = this.CreateMagentoServiceClient( this.BaseMagentoUrl ); await ActionPolicies.GetAsync.Do( async () => { var statusChecker = new StatusChecker( maxCheckCount ); TimerCallback tcb = statusChecker.CheckStatus; if( privateClient.State != CommunicationState.Opened && privateClient.State != CommunicationState.Created && privateClient.State != CommunicationState.Opening ) privateClient = this.CreateMagentoServiceClient( this.BaseMagentoUrl ); var sessionId = await this.GetSessionId().ConfigureAwait( false ); using( var stateTimer = new Timer( tcb, privateClient, 1000, delayBeforeCheck ) ) res = await privateClient.salesOrderListAsync( sessionId, filters ).ConfigureAwait( false ); } ).ConfigureAwait( false ); return res; } catch( Exception exc ) { throw new MagentoSoapException( string.Format( "An error occured during GetOrdersAsync({0})", ordersIdsAgregated ), exc ); } } public virtual async Task< catalogProductListResponse > GetProductsAsync() { try { var filters = new filters { filter = new associativeEntity[ 0 ] }; var store = string.IsNullOrWhiteSpace( this.Store ) ? null : this.Store; const int maxCheckCount = 2; const int delayBeforeCheck = 1800000; var res = new catalogProductListResponse(); var privateClient = this.CreateMagentoServiceClient( this.BaseMagentoUrl ); await ActionPolicies.GetAsync.Do( async () => { var statusChecker = new StatusChecker( maxCheckCount ); TimerCallback tcb = statusChecker.CheckStatus; if( privateClient.State != CommunicationState.Opened && privateClient.State != CommunicationState.Created && privateClient.State != CommunicationState.Opening ) privateClient = this.CreateMagentoServiceClient( this.BaseMagentoUrl ); var sessionId = await this.GetSessionId().ConfigureAwait( false ); using( var stateTimer = new Timer( tcb, privateClient, 1000, delayBeforeCheck ) ) res = await privateClient.catalogProductListAsync( sessionId, filters, store ).ConfigureAwait( false ); } ).ConfigureAwait( false ); return res; } catch( Exception exc ) { throw new MagentoSoapException( string.Format( "An error occured during GetProductsAsync()" ), exc ); } } public virtual async Task< catalogInventoryStockItemListResponse > GetStockItemsAsync( List< string > skusOrIds ) { try { var skusArray = skusOrIds.ToArray(); const int maxCheckCount = 2; const int delayBeforeCheck = 1800000; var res = new catalogInventoryStockItemListResponse(); var privateClient = this.CreateMagentoServiceClient( this.BaseMagentoUrl ); await ActionPolicies.GetAsync.Do( async () => { var statusChecker = new StatusChecker( maxCheckCount ); TimerCallback tcb = statusChecker.CheckStatus; if( privateClient.State != CommunicationState.Opened && privateClient.State != CommunicationState.Created && privateClient.State != CommunicationState.Opening ) privateClient = this.CreateMagentoServiceClient( this.BaseMagentoUrl ); var sessionId = await this.GetSessionId().ConfigureAwait( false ); using( var stateTimer = new Timer( tcb, privateClient, 1000, delayBeforeCheck ) ) res = await privateClient.catalogInventoryStockItemListAsync( sessionId, skusArray ).ConfigureAwait( false ); } ).ConfigureAwait( false ); return res; } catch( Exception exc ) { var productsBriefInfo = string.Join( "|", skusOrIds ); throw new MagentoSoapException( string.Format( "An error occured during GetStockItemsAsync({0})", productsBriefInfo ), exc ); } } public virtual async Task< bool > PutStockItemsAsync( List< PutStockItem > stockItems, string markForLog = "" ) { try { const string currentMenthodName = "PutStockItemsAsync"; var jsonSoapInfo = this.ToJsonSoapInfo(); var productsBriefInfo = stockItems.ToJson(); stockItems.ForEach( x => { if( x.UpdateEntity.qty.ToDecimalOrDefault() > 0 ) { x.UpdateEntity.is_in_stock = 1; x.UpdateEntity.is_in_stockSpecified = true; } else { x.UpdateEntity.is_in_stock = 0; x.UpdateEntity.is_in_stockSpecified = false; } } ); const int maxCheckCount = 2; const int delayBeforeCheck = 1800000; var res = false; var privateClient = this.CreateMagentoServiceClient( this.BaseMagentoUrl ); await ActionPolicies.GetAsync.Do( async () => { var statusChecker = new StatusChecker( maxCheckCount ); TimerCallback tcb = statusChecker.CheckStatus; if( privateClient.State != CommunicationState.Opened && privateClient.State != CommunicationState.Created && privateClient.State != CommunicationState.Opening ) privateClient = this.CreateMagentoServiceClient( this.BaseMagentoUrl ); var sessionId = await this.GetSessionId().ConfigureAwait( false ); using( var stateTimer = new Timer( tcb, privateClient, 1000, delayBeforeCheck ) ) { MagentoLogger.LogTraceStarted( string.Format( "{{MethodName:{0}, Called From:{1}, SoapInfo:{2}, MethodParameters:{3}}}", currentMenthodName, markForLog, jsonSoapInfo, productsBriefInfo ) ); var temp = await privateClient.catalogInventoryStockItemMultiUpdateAsync( sessionId, stockItems.Select( x => x.Id ).ToArray(), stockItems.Select( x => x.UpdateEntity ).ToArray() ).ConfigureAwait( false ); res = temp.result; var updateBriefInfo = string.Format( "{{Success:{0}}}", res ); MagentoLogger.LogTraceEnded( string.Format( "{{MethodName:{0}, Called From:{1}, SoapInfo:{2}, MethodParameters:{3}, MethodResult:{4}}}", currentMenthodName, markForLog, jsonSoapInfo, productsBriefInfo, updateBriefInfo ) ); } } ).ConfigureAwait( false ); return res; } catch( Exception exc ) { var productsBriefInfo = stockItems.ToJson(); throw new MagentoSoapException( string.Format( "An error occured during PutStockItemsAsync({0})", productsBriefInfo ), exc ); } } public virtual async Task< bool > PutStockItemAsync( PutStockItem putStockItem, string markForLog ) { try { const string currentMenthodName = "PutStockItemAsync"; var jsonSoapInfo = this.ToJsonSoapInfo(); var productsBriefInfo = new List< PutStockItem > { putStockItem }.ToJson(); if( putStockItem.UpdateEntity.qty.ToDecimalOrDefault() > 0 ) { putStockItem.UpdateEntity.is_in_stock = 1; putStockItem.UpdateEntity.is_in_stockSpecified = true; } else { putStockItem.UpdateEntity.is_in_stock = 0; putStockItem.UpdateEntity.is_in_stockSpecified = false; } const int maxCheckCount = 2; const int delayBeforeCheck = 120000; var res = false; var privateClient = this.CreateMagentoServiceClient( this.BaseMagentoUrl ); await ActionPolicies.GetAsync.Do( async () => { var statusChecker = new StatusChecker( maxCheckCount ); TimerCallback tcb = statusChecker.CheckStatus; if( privateClient.State != CommunicationState.Opened && privateClient.State != CommunicationState.Created && privateClient.State != CommunicationState.Opening ) privateClient = this.CreateMagentoServiceClient( this.BaseMagentoUrl ); var sessionId = await this.GetSessionId().ConfigureAwait( false ); using( var stateTimer = new Timer( tcb, privateClient, 1000, delayBeforeCheck ) ) { MagentoLogger.LogTraceStarted( string.Format( "{{MethodName:{0}, Called From:{1}, SoapInfo:{2}, MethodParameters:{3}}}", currentMenthodName, markForLog, jsonSoapInfo, productsBriefInfo ) ); var temp = await privateClient.catalogInventoryStockItemUpdateAsync( sessionId, putStockItem.Id, putStockItem.UpdateEntity ).ConfigureAwait( false ); res = temp.result > 0; var updateBriefInfo = string.Format( "{{Success:{0}}}", res ); MagentoLogger.LogTraceEnded( string.Format( "{{MethodName:{0}, Called From:{1}, SoapInfo:{2}, MethodParameters:{3}, MethodResult:{4}}}", currentMenthodName, markForLog, jsonSoapInfo, productsBriefInfo, updateBriefInfo ) ); } } ).ConfigureAwait( false ); return res; } catch( Exception exc ) { var productsBriefInfo = new List< PutStockItem > { putStockItem }.ToJson(); throw new MagentoSoapException( string.Format( "An error occured during PutStockItemsAsync({0})", productsBriefInfo ), exc ); } } public virtual async Task< salesOrderInfoResponse > GetOrderAsync( string incrementId ) { try { const int maxCheckCount = 2; const int delayBeforeCheck = 300000; var res = new salesOrderInfoResponse(); var privateClient = await this.CreateMagentoServiceClientAsync( this.BaseMagentoUrl ).ConfigureAwait( false ); await ActionPolicies.GetAsync.Do( async () => { var statusChecker = new StatusChecker( maxCheckCount ); TimerCallback tcb = statusChecker.CheckStatus; if( privateClient.State != CommunicationState.Opened && privateClient.State != CommunicationState.Created && privateClient.State != CommunicationState.Opening ) privateClient = this.CreateMagentoServiceClient( this.BaseMagentoUrl ); var sessionId = await this.GetSessionId().ConfigureAwait( false ); using( var stateTimer = new Timer( tcb, privateClient, 1000, delayBeforeCheck ) ) { res = await privateClient.salesOrderInfoAsync( sessionId, incrementId ).ConfigureAwait( false ); } } ).ConfigureAwait( false ); return res; } catch( Exception exc ) { throw new MagentoSoapException( string.Format( "An error occured during GetOrderAsync(incrementId:{0})", incrementId ), exc ); } } public virtual async Task< magentoInfoResponse > GetMagentoInfoAsync() { try { const int maxCheckCount = 2; const int delayBeforeCheck = 1800000; var res = new magentoInfoResponse(); var privateClient = this.CreateMagentoServiceClient( this.BaseMagentoUrl ); await ActionPolicies.GetAsync.Do( async () => { var statusChecker = new StatusChecker( maxCheckCount ); TimerCallback tcb = statusChecker.CheckStatus; if( privateClient.State != CommunicationState.Opened && privateClient.State != CommunicationState.Created && privateClient.State != CommunicationState.Opening ) privateClient = this.CreateMagentoServiceClient( this.BaseMagentoUrl ); var sessionId = await this.GetSessionId().ConfigureAwait( false ); using( var stateTimer = new Timer( tcb, privateClient, 1000, delayBeforeCheck ) ) res = await privateClient.magentoInfoAsync( sessionId ).ConfigureAwait( false ); } ).ConfigureAwait( false ); return res; } catch( Exception exc ) { throw new MagentoSoapException( string.Format( "An error occured during GetMagentoInfoAsync()" ), exc ); } } public string ToJsonSoapInfo() { return string.Format( "{{BaseMagentoUrl:{0}, ApiUser:{1},ApiKey:{2},Store:{3}}}", string.IsNullOrWhiteSpace( this.BaseMagentoUrl ) ? PredefinedValues.NotAvailable : this.BaseMagentoUrl, string.IsNullOrWhiteSpace( this.ApiUser ) ? PredefinedValues.NotAvailable : this.ApiUser, string.IsNullOrWhiteSpace( this.ApiKey ) ? PredefinedValues.NotAvailable : this.ApiKey, string.IsNullOrWhiteSpace( this.Store ) ? PredefinedValues.NotAvailable : this.Store ); } #region JustForTesting public async Task< int > CreateCart( string storeid ) { try { var sessionId = await this.GetSessionId().ConfigureAwait( false ); var res = await this._magentoSoapService.shoppingCartCreateAsync( sessionId, storeid ).ConfigureAwait( false ); return res.result; } catch( Exception exc ) { throw new MagentoSoapException( string.Format( "An error occured during GetMagentoInfoAsync({0})", storeid ), exc ); } } public async Task< string > CreateOrder( int shoppingcartid, string store ) { try { var sessionId = await this.GetSessionId().ConfigureAwait( false ); var res = await this._magentoSoapService.shoppingCartOrderAsync( sessionId, shoppingcartid, store, null ).ConfigureAwait( false ); return res.result; } catch( Exception exc ) { throw new MagentoSoapException( string.Format( "An error occured during GetMagentoInfoAsync()" ), exc ); } } public async Task< int > CreateCustomer( string email = "na@na.com", string firstname = "firstname", string lastname = "lastname", string password = "password", int websiteId = 0, int storeId = 0, int groupId = 0 ) { try { var sessionId = await this.GetSessionId().ConfigureAwait( false ); var customerCustomerEntityToCreate = new customerCustomerEntityToCreate { email = email, firstname = firstname, lastname = lastname, password = password, website_id = websiteId, store_id = storeId, group_id = groupId }; var res = await this._magentoSoapService.customerCustomerCreateAsync( sessionId, customerCustomerEntityToCreate ).ConfigureAwait( false ); return res.result; } catch( Exception exc ) { throw new MagentoSoapException( string.Format( "An error occured during GetMagentoInfoAsync()" ), exc ); } } public async Task< bool > ShoppingCartCustomerSet( int shoppingCart, int customerId, string customerPass, string store ) { try { var sessionId = await this.GetSessionId().ConfigureAwait( false ); var cutomers = await this._magentoSoapService.customerCustomerListAsync( sessionId, new filters() ).ConfigureAwait( false ); var customer = cutomers.result.First( x => x.customer_id == customerId ); var customerShoppingCart = new shoppingCartCustomerEntity { confirmation = ( customer.confirmation ? 1 : 0 ).ToString( CultureInfo.InvariantCulture ), customer_id = customer.customer_id, customer_idSpecified = customer.customer_idSpecified, email = customer.email, firstname = customer.firstname, group_id = customer.group_id, group_idSpecified = customer.group_idSpecified, lastname = customer.lastname, mode = "customer", password = customerPass, store_id = customer.store_id, store_idSpecified = customer.store_idSpecified, website_id = customer.website_id, website_idSpecified = customer.website_idSpecified }; var res = await this._magentoSoapService.shoppingCartCustomerSetAsync( sessionId, shoppingCart, customerShoppingCart, store ).ConfigureAwait( false ); return res.result; } catch( Exception exc ) { throw new MagentoSoapException( string.Format( "An error occured during GetMagentoInfoAsync()" ), exc ); } } public async Task< bool > ShoppingCartGuestCustomerSet( int shoppingCart, string customerfirstname, string customerMail, string customerlastname, string store ) { try { var sessionId = await this.GetSessionId().ConfigureAwait( false ); var customer = new shoppingCartCustomerEntity { email = customerMail, firstname = customerfirstname, lastname = customerlastname, website_id = 0, store_id = 0, mode = "guest", }; var res = await this._magentoSoapService.shoppingCartCustomerSetAsync( sessionId, shoppingCart, customer, store ).ConfigureAwait( false ); return res.result; } catch( Exception exc ) { throw new MagentoSoapException( string.Format( "An error occured during GetMagentoInfoAsync()" ), exc ); } } public async Task< bool > ShoppingCartAddressSet( int shoppingCart, string store ) { try { var sessionId = await this.GetSessionId().ConfigureAwait( false ); var customerAddressEntities = new shoppingCartCustomerAddressEntity[ 2 ]; customerAddressEntities[ 0 ] = new shoppingCartCustomerAddressEntity { mode = "shipping", firstname = "testFirstname", lastname = "testLastname", company = "testCompany", street = "testStreet", city = "testCity", region = "testRegion", postcode = "testPostcode", country_id = "1", telephone = "0123456789", fax = "0123456789", is_default_shipping = 0, is_default_billing = 0 }; customerAddressEntities[ 1 ] = new shoppingCartCustomerAddressEntity { mode = "billing", firstname = "testFirstname", lastname = "testLastname", company = "testCompany", street = "testStreet", city = "testCity", region = "testRegion", postcode = "testPostcode", country_id = "1", telephone = "0123456789", fax = "0123456789", is_default_shipping = 0, is_default_billing = 0 }; var res = await this._magentoSoapService.shoppingCartCustomerAddressesAsync( sessionId, shoppingCart, customerAddressEntities, store ).ConfigureAwait( false ); return res.result; } catch( Exception exc ) { throw new MagentoSoapException( string.Format( "An error occured during GetMagentoInfoAsync()" ), exc ); } } public async Task< bool > DeleteCustomer( int customerId ) { try { var sessionId = await this.GetSessionId().ConfigureAwait( false ); var res = await this._magentoSoapService.customerCustomerDeleteAsync( sessionId, customerId ).ConfigureAwait( false ); return res.result; } catch( Exception exc ) { throw new MagentoSoapException( string.Format( "An error occured during DeleteCustomer()" ), exc ); } } public async Task< bool > ShoppingCartAddProduct( int shoppingCartId, string productId, string store ) { try { var sessionId = await this.GetSessionId().ConfigureAwait( false ); var shoppingCartProductEntities = new shoppingCartProductEntity[ 1 ]; shoppingCartProductEntities[ 0 ] = new shoppingCartProductEntity { product_id = productId, qty = 3 }; var res = await this._magentoSoapService.shoppingCartProductAddAsync( sessionId, shoppingCartId, shoppingCartProductEntities, store ).ConfigureAwait( false ); return res.result; } catch( Exception exc ) { throw new MagentoSoapException( string.Format( "An error occured during ShoppingCartAddProduct()" ), exc ); } } public async Task< bool > ShoppingCartSetPaymentMethod( int shoppingCartId, string store ) { try { var sessionId = await this.GetSessionId().ConfigureAwait( false ); var cartPaymentMethodEntity = new shoppingCartPaymentMethodEntity { po_number = null, //method = "checkmo", method = "checkmo", //method = "'cashondelivery'", cc_cid = null, cc_owner = null, cc_number = null, cc_type = null, cc_exp_year = null, cc_exp_month = null }; var res = await this._magentoSoapService.shoppingCartPaymentMethodAsync( sessionId, shoppingCartId, cartPaymentMethodEntity, store ).ConfigureAwait( false ); return res.result; } catch( Exception exc ) { throw new MagentoSoapException( string.Format( "An error occured during ShoppingCartAddProduct()" ), exc ); } } public async Task< bool > ShoppingCartSetShippingMethod( int shoppingCartId, string store ) { try { var sessionId = await this.GetSessionId().ConfigureAwait( false ); var res = await this._magentoSoapService.shoppingCartShippingListAsync( sessionId, shoppingCartId, store ).ConfigureAwait( false ); var shippings = res.result; var shipping = shippings.First(); var shippingMethodResponse = await this._magentoSoapService.shoppingCartShippingMethodAsync( sessionId, shoppingCartId, shipping.code, store ).ConfigureAwait( false ); return shippingMethodResponse.result; } catch( Exception exc ) { throw new MagentoSoapException( string.Format( "An error occured during ShoppingCartAddProduct()" ), exc ); } } public async Task< int > CreateProduct( string storeId, string name, string sku, int isInStock ) { try { var sessionId = await this.GetSessionId().ConfigureAwait( false ); var res0 = await this._magentoSoapService.catalogCategoryAttributeCurrentStoreAsync( sessionId, storeId ).ConfigureAwait( false ); var catalogProductCreateEntity = new catalogProductCreateEntity { name = name, description = "Product description", short_description = "Product short description", weight = "10", status = "1", visibility = "4", price = "100", tax_class_id = "1", categories = new[] { res0.result.ToString() }, category_ids = new[] { res0.result.ToString() }, stock_data = new catalogInventoryStockItemUpdateEntity { qty = "100", is_in_stockSpecified = true, is_in_stock = isInStock, manage_stock = 1, use_config_manage_stock = 0, use_config_min_qty = 0, use_config_min_sale_qty = 0, is_qty_decimal = 0 } }; var res = await this._magentoSoapService.catalogProductCreateAsync( sessionId, "simple", "4", sku, catalogProductCreateEntity, storeId ).ConfigureAwait( false ); //product id return res.result; } catch( Exception exc ) { throw new MagentoSoapException( string.Format( "An error occured during CreateProduct({0})", storeId ), exc ); } } public async Task< bool > DeleteProduct( string storeId, int categoryId, string productId, string identiferType ) { try { var sessionId = await this.GetSessionId().ConfigureAwait( false ); var res = await this._magentoSoapService.catalogCategoryRemoveProductAsync( sessionId, categoryId, productId, identiferType ).ConfigureAwait( false ); //product id return res.result; } catch( Exception exc ) { throw new MagentoSoapException( string.Format( "An error occured during DeleteProduct({0})", storeId ), exc ); } } #endregion } internal class StatusChecker { private int invokeCount; private readonly int maxCount; public StatusChecker( int count ) { this.invokeCount = 0; this.maxCount = count; } public void CheckStatus( Object stateInfo ) { var serviceClient = ( Mage_Api_Model_Server_Wsi_HandlerPortTypeClient )stateInfo; Interlocked.Increment( ref this.invokeCount ); if( this.invokeCount == this.maxCount ) { Interlocked.Exchange( ref this.invokeCount, 0 ); serviceClient.Abort(); } } } internal class PutStockItem { public PutStockItem( string id, catalogInventoryStockItemUpdateEntity updateEntity ) { this.Id = id; this.UpdateEntity = updateEntity; } public catalogInventoryStockItemUpdateEntity UpdateEntity { get; set; } public string Id { get; set; } } }
35.733259
268
0.687822
[ "BSD-3-Clause" ]
emartech/magentoAccess
src/MagentoAccess/Services/MagentoServiceLowLevelSoap.cs
32,019
C#
#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) using System; using System.Text; using Org.BouncyCastle.Utilities; namespace Org.BouncyCastle.Asn1 { /** * Der PrintableString object. */ public class DerPrintableString : DerStringBase { private readonly string str; /** * return a printable string from the passed in object. * * @exception ArgumentException if the object cannot be converted. */ public static DerPrintableString GetInstance( object obj) { if (obj == null || obj is DerPrintableString) { return (DerPrintableString)obj; } throw new ArgumentException("illegal object in GetInstance: " + Platform.GetTypeName(obj)); } /** * return a Printable string from a tagged object. * * @param obj the tagged object holding the object we want * @param explicitly true if the object is meant to be explicitly * tagged false otherwise. * @exception ArgumentException if the tagged object cannot * be converted. */ public static DerPrintableString GetInstance( Asn1TaggedObject obj, bool isExplicit) { Asn1Object o = obj.GetObject(); if (isExplicit || o is DerPrintableString) { return GetInstance(o); } return new DerPrintableString(Asn1OctetString.GetInstance(o).GetOctets()); } /** * basic constructor - byte encoded string. */ public DerPrintableString( byte[] str) : this(Strings.FromAsciiByteArray(str), false) { } /** * basic constructor - this does not validate the string */ public DerPrintableString( string str) : this(str, false) { } /** * Constructor with optional validation. * * @param string the base string to wrap. * @param validate whether or not to check the string. * @throws ArgumentException if validate is true and the string * contains characters that should not be in a PrintableString. */ public DerPrintableString( string str, bool validate) { if (str == null) throw new ArgumentNullException("str"); if (validate && !IsPrintableString(str)) throw new ArgumentException("string contains illegal characters", "str"); this.str = str; } public override string GetString() { return str; } public byte[] GetOctets() { return Strings.ToAsciiByteArray(str); } internal override void Encode( DerOutputStream derOut) { derOut.WriteEncoded(Asn1Tags.PrintableString, GetOctets()); } protected override bool Asn1Equals( Asn1Object asn1Object) { DerPrintableString other = asn1Object as DerPrintableString; if (other == null) return false; return this.str.Equals(other.str); } /** * return true if the passed in String can be represented without * loss as a PrintableString, false otherwise. * * @return true if in printable set, false otherwise. */ public static bool IsPrintableString( string str) { foreach (char ch in str) { if (ch > 0x007f) return false; if (char.IsLetterOrDigit(ch)) continue; // if (char.IsPunctuation(ch)) // continue; switch (ch) { case ' ': case '\'': case '(': case ')': case '+': case '-': case '.': case ':': case '=': case '?': case '/': case ',': continue; } return false; } return true; } } } #endif
22.520958
103
0.588141
[ "MIT" ]
Manolomon/space-checkers
client/Assets/Libs/Best HTTP (Pro)/Best HTTP (Pro)/BestHTTP/SecureProtocol/asn1/DerPrintableString.cs
3,761
C#
using UnityEngine; using UnityEngine.Events; using TMPro; using UnityEngine.UI; using System.Collections; using UnityEngine.Networking; public class _Lesson : MonoBehaviour { #region Properties #endregion #region Fields //Prefab Button. [SerializeField] TextMeshProUGUI titleTXT; //Prefab Button. [SerializeField] GameObject wordButtonPrefab; //Content of Word Buttons. [SerializeField] GameObject _Word_Content; string[] learnedWords; #endregion #region Public Methods #endregion #region Private Methods void Start() { }//Startttttt public void UpdateVariables(int currentLesson) { Reader.Instance.ReadCurrentLesson(DB.API(currentLesson)); //GetAllSelected_WS(currentLesson); SetWords(); } void GetAllSelected_WS(int currentLesson)//put all of selected words and dialogues from repo to an array { if (!string.IsNullOrEmpty(WordRepo.GetRepo(DB.Word_Repo(currentLesson)))) { learnedWords = WordRepo.GetRepo(DB.Word_Repo(currentLesson)).Split('/'); } else { learnedWords = new string[0]; } } void SetWords() { int currentLesson = Lesson_Repo.GetPassedLesson(); titleTXT.text = "Lesson " + currentLesson; Debug.Log(Reader.Instance.wordsLength); Debug.Log(currentLesson); for (int i = 0; i < Reader.Instance.wordsLength; i++) { GameObject gameObj = Instantiate(wordButtonPrefab); gameObj.transform.SetParent(_Word_Content.transform, false); _WordButton _WordScript = gameObj.GetComponent<_WordButton>(); _WordScript.WordNumbTXT.text = Reader.Instance.words_Matrix[i, 0]; _WordScript.WordTXT.text = Reader.Instance.words_Matrix[i, 1]; //Adding Listener for Word Button. _WordScript.WordButton.onClick.RemoveAllListeners(); _WordScript.WordButton.onClick.AddListener( delegate { OpenCurrentWord(currentLesson); }); //NEED IMPROVMENT. //_WordScript.Ex_Image.sprite = GetCurrentSprite(i, 2); //Adding Listener for UK Voice Button. _WordScript.UK_Button.onClick.RemoveAllListeners(); _WordScript.UK_Button.onClick.AddListener( delegate { Speak_UK_Word(Reader.Instance.words_Matrix[i, 1]); }); //Adding Listener for US Voice Button. _WordScript.US_Button.onClick.RemoveAllListeners(); _WordScript.US_Button.onClick.AddListener( delegate { Speak_US_Word(Reader.Instance.words_Matrix[i, 1]); }); //Determine if Word is Selected or not. if (learnedWords.Length > 0) { if (CompareStrings(learnedWords, Reader.Instance.words_Matrix[i, 1])) { _WordScript.WordNumbIMG.color = _Color.LightGreen; _WordScript.ButtonIMG.color = _Color.SuperLightGreen; } else { _WordScript.WordNumbIMG.color = _Color.LightGray; _WordScript.ButtonIMG.color = _Color.SuperLightGray; } } } } Sprite GetCurrentSprite(int i, int j) { return HelperResourcer.SpriteLoader(""); } void OpenCurrentWord(int currentWord) { } //Word's TTS void Speak_UK_Word(string word) { SpeakUp.Speak(word, GetAudioSource(), "Microsoft Zira Desktop"); } void Speak_US_Word(string word) { SpeakUp.Speak(word, GetAudioSource(), "Microsoft David Desktop"); } bool CompareStrings(string[] learnedWords, string word)//Comparing Words and sentences. { for (int i = 0; i < learnedWords.Length; i++) { if (learnedWords[i].ToLower() == word.ToLower()) { return true; } } return false; } IEnumerator LoadImage(string localUrl)//loading images as texture2D. { UnityWebRequest request = UnityWebRequestTexture.GetTexture("file://" + localUrl); yield return request.SendWebRequest(); if (request.isNetworkError || request.isHttpError) { Debug.Log(request.error); } else { Texture2D texture = ((DownloadHandlerTexture)request.downloadHandler).texture; //frames.Add(texture); } } AudioSource GetAudioSource() { return FindObjectOfType<AudioSource>(); } void Update() { }//Updateeeee #endregion }//EndClasssss
27.526316
108
0.605056
[ "MIT" ]
Sadeqsoli/1100-Words
1100 Words/Assets/Scripts/Mini_Manager/_Lesson.cs
4,709
C#
using Foundation; using UIKit; namespace StoryboardTables1 { // The UIApplicationDelegate for the application. This class is responsible for launching the // User Interface of the application, as well as listening (and optionally responding) to application events from iOS. [Register("AppDelegate")] public class AppDelegate : UIApplicationDelegate { // class-level declarations public override UIWindow Window { get; set; } public override bool FinishedLaunching(UIApplication application, NSDictionary launchOptions) { // Override point for customization after application launch. // If not required for your application you can safely delete this method return true; } public override void OnResignActivation(UIApplication application) { // Invoked when the application is about to move from active to inactive state. // This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) // or when the user quits the application and it begins the transition to the background state. // Games should use this method to pause the game. } public override void DidEnterBackground(UIApplication application) { // Use this method to release shared resources, save user data, invalidate timers and store the application state. // If your application supports background exection this method is called instead of WillTerminate when the user quits. } public override void WillEnterForeground(UIApplication application) { // Called as part of the transiton from background to active state. // Here you can undo many of the changes made on entering the background. } public override void OnActivated(UIApplication application) { // Restart any tasks that were paused (or not yet started) while the application was inactive. // If the application was previously in the background, optionally refresh the user interface. } public override void WillTerminate(UIApplication application) { // Called when the application is about to terminate. Save data, if needed. See also DidEnterBackground. } } }
40.583333
131
0.671458
[ "MIT" ]
Art-Lav/ios-samples
StoryboardTable/StoryboardTables1/AppDelegate.cs
2,437
C#
#region Using Statements using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using GameKit; using UIKit; using WaveEngine.Social; #endregion namespace WaveEngineiOS.Social.Social { /// <summary> /// Game Center Service class /// </summary> public class GameCenterService : ISocial { private UIViewController view; /// <summary> /// Gets a value indicating whether the local user is authenticated. /// </summary> /// <value> /// <c>true</c> if the local user is authenticated; otherwise, <c>false</c>. /// </value> public bool IsAuthenticated { get { return this.InternalIsPlayerAuthenticated().Result; } } /// <summary> /// Initializes this instance. /// </summary> /// <exception cref="NotSupportedException">The current device does not support Game Center</exception> public void Init() { if (!UIDevice.CurrentDevice.CheckSystemVersion(4, 1)) { #if DEBUG new UIAlertView("Game Center Support Required", "The current device does not support Game Center, which this service requires.", null, "OK", null).Show(); #endif throw new NotSupportedException("The current device does not support Game Center"); } this.view = UIApplication.SharedApplication.KeyWindow.RootViewController; } /// <summary> /// Logins local user. /// </summary> /// <returns> /// The logged in user. /// </returns> public Task<Player> Login() { var tcs = new TaskCompletionSource<Player>(); GKLocalPlayer.LocalPlayer.Authenticate(async (error) => { var localPlayer = GKLocalPlayer.LocalPlayer; Player result = null; if (error != null) { #if DEBUG new UIAlertView("Score submittion failed", "Submittion failed because: " + error, null, "OK", null).Show(); #endif } else if (localPlayer != null && localPlayer.Authenticated) { result = await IOSMapper.MapPlayer(localPlayer); } tcs.TrySetResult(result); }); return tcs.Task; } /// <summary> /// Logouts local user. /// </summary> /// <returns> /// <c>true</c> if logout was successful; otherwise, <c>false</c>. /// </returns> public Task<bool> Logout() { return Task.FromResult<bool>(true); } /// <summary> /// Shows a default/system view of the games leaderboards. /// </summary> /// <returns> /// <c>true</c> if the view has been shown; otherwise, <c>false</c>. /// </returns> public async Task<bool> ShowAllLeaderboards() { var gameCenterController = new GKGameCenterViewController(); gameCenterController.ViewState = GKGameCenterViewControllerState.Leaderboards; gameCenterController.Finished += (sender, e) => { gameCenterController.DismissViewController(true, delegate { }); }; await this.view.PresentViewControllerAsync(gameCenterController, true); return true; } /// <summary> /// Shows a default/system view of the given game leaderboard. /// </summary> /// <param name="leaderboardCode">The leaderboard code.</param> /// <returns> /// <c>true</c> if the view has been shown; otherwise, <c>false</c>. /// </returns> public async Task<bool> ShowLeaderboard(string leaderboardCode) { var gameCenterController = new GKGameCenterViewController(); gameCenterController.ViewState = GKGameCenterViewControllerState.Leaderboards; gameCenterController.LeaderboardCategory = leaderboardCode; gameCenterController.LeaderboardIdentifier = leaderboardCode; gameCenterController.Finished += (sender, e) => { gameCenterController.DismissViewController(true, delegate { }); }; await this.view.PresentViewControllerAsync(gameCenterController, true); return true; } /// <summary> /// Adds a new leaderboard score. /// </summary> /// <param name="leaderboardCode">The leaderboard code.</param> /// <param name="score">The score.</param> /// <returns> /// <c>true</c> if the score has been added; otherwise, <c>false</c>. /// </returns> public Task<bool> AddNewScore(string leaderboardCode, long score) { var tcs = new TaskCompletionSource<bool>(); UIKit.UIApplication.SharedApplication.InvokeOnMainThread(async () => { var submitScore = new GKScore(leaderboardCode); submitScore.Value = score; bool result = true; try { await GKScore.ReportScoresAsync(new GKScore[] { submitScore }); } catch { result = false; } tcs.TrySetResult(result); }); return tcs.Task; } /// <summary> /// Gets the top page of scores for a given leaderboard. /// </summary> /// <param name="leaderboardCode">The leaderboard code.</param> /// <param name="count">The maximum number of scores. Must be between 1 and 25.</param> /// <param name="socialOnly">If <c>true</c>, the result will only contain the scores of players in the viewing player's circles.</param> /// <param name="forceReload">If <c>true</c>, this call will clear any locally cached data and attempt to fetch the latest data from the server. This would commonly be used for something like a user-initiated refresh. Normally, this should be set to false to gain advantages of data caching.</param> /// <returns> /// The scores. /// </returns> public Task<IEnumerable<LeaderboardScore>> GetTopScores(string leaderboardCode, int count, bool socialOnly, bool forceReload) { return this.InternalGetScores(leaderboardCode, count, socialOnly, false); } /// <summary> /// Gets the the player-centered page of scores for a given leaderboard. /// </summary> /// <param name="leaderboardCode">The leaderboard code.</param> /// <param name="count">The maximum number of scores. Must be between 1 and 25.</param> /// <param name="socialOnly">If <c>true</c>, the result will only contain the scores of players in the viewing player's circles.</param> /// <param name="forceReload">If <c>true</c>, this call will clear any locally cached data and attempt to fetch the latest data from the server. This would commonly be used for something like a user-initiated refresh. Normally, this should be set to false to gain advantages of data caching.</param> /// <returns> /// The scores. /// </returns> public Task<IEnumerable<LeaderboardScore>> GetPlayerCenteredScores(string leaderboardCode, int count, bool socialOnly, bool forceReload) { return this.InternalGetScores(leaderboardCode, count, socialOnly, true); } /// <summary> /// Shows a default/system view of the games achievements. /// </summary> /// <returns> /// <c>true</c> if the view has been shown; otherwise, <c>false</c>. /// </returns> public async Task<bool> ShowAchievements() { var gameCenterController = new GKGameCenterViewController(); gameCenterController.ViewState = GKGameCenterViewControllerState.Achievements; gameCenterController.Finished += (sender, e) => { gameCenterController.DismissViewController(true, delegate { }); }; await this.view.PresentViewControllerAsync(gameCenterController, true); return true; } /// <summary> /// Unlocks the achievement. /// </summary> /// <param name="achievementCode">The achievement code.</param> /// <returns> /// <c>true</c> if the achievement has been unlocked; otherwise, <c>false</c>. /// </returns> public Task<bool> UnlockAchievement(string achievementCode) { var tcs = new TaskCompletionSource<bool>(); UIKit.UIApplication.SharedApplication.InvokeOnMainThread(async () => { var currentAchievement = new GKAchievement(achievementCode); var percentComplete = 100.0d; var result = await InternalUpdateAchievement(currentAchievement, percentComplete); tcs.TrySetResult(result); }); return tcs.Task; } /// <summary> /// Increments the achievement progress. /// </summary> /// <param name="achievementCode">The achievement code.</param> /// <param name="progress">The progress.</param> /// <returns> /// <c>true</c> if the achievement has been incremented; otherwise, <c>false</c>. /// </returns> public Task<bool> IncrementAchievement(string achievementCode, int progress) { var tcs = new TaskCompletionSource<bool>(); UIKit.UIApplication.SharedApplication.InvokeOnMainThread(async () => { var currentAchievement = new GKAchievement(achievementCode); var finalPercent = currentAchievement.PercentComplete + progress; var result = await InternalUpdateAchievement(currentAchievement, finalPercent); tcs.TrySetResult(result); }); return tcs.Task; } /// <summary> /// Gets the achievements. /// </summary> /// <returns> /// The achievements. /// </returns> public Task<IEnumerable<Achievement>> GetAchievements() { var tcs = new TaskCompletionSource<IEnumerable<Achievement>>(); UIKit.UIApplication.SharedApplication.InvokeOnMainThread(async () => { var achievements = await GKAchievement.LoadAchievementsAsync() ?? new GKAchievement[] { }; var achievementsList = achievements.ToList(); var result = await IOSMapper.MapAchievements(achievementsList); tcs.TrySetResult(result); }); return tcs.Task; } private Task<bool> InternalIsPlayerAuthenticated() { var tcs = new TaskCompletionSource<bool>(); UIKit.UIApplication.SharedApplication.InvokeOnMainThread(() => { var result = false; if (GKLocalPlayer.LocalPlayer != null) { result = GKLocalPlayer.LocalPlayer.Authenticated; } tcs.TrySetResult(result); }); return tcs.Task; } private Task<IEnumerable<LeaderboardScore>> InternalGetScores(string leaderboardCode, int count, bool socialOnly, bool centered) { var tcs = new TaskCompletionSource<IEnumerable<LeaderboardScore>>(); UIKit.UIApplication.SharedApplication.InvokeOnMainThread(async () => { var result = Enumerable.Empty<LeaderboardScore>(); var leaderboards = await GKLeaderboard.LoadLeaderboardsAsync() ?? new GKLeaderboard[] { }; var selectedLeaderboard = leaderboards.FirstOrDefault(l => l.Identifier == leaderboardCode); if (selectedLeaderboard != null) { selectedLeaderboard.PlayerScope = socialOnly ? GKLeaderboardPlayerScope.FriendsOnly : GKLeaderboardPlayerScope.Global; selectedLeaderboard.Range = new Foundation.NSRange(1, count); var scores = await selectedLeaderboard.LoadScoresAsync(); if (centered && selectedLeaderboard.LocalPlayerScore != null) { var playerRank = selectedLeaderboard.LocalPlayerScore.Rank; var fromIndex = playerRank - (count / 2); fromIndex = fromIndex < 1 ? 1 : fromIndex; selectedLeaderboard.Range = new Foundation.NSRange(fromIndex, count); scores = await selectedLeaderboard.LoadScoresAsync(); } result = await IOSMapper.MapLeaderBoards(scores); } tcs.SetResult(result); }); return tcs.Task; } private Task<bool> InternalUpdateAchievement(GKAchievement achievement, double value) { var tcs = new TaskCompletionSource<bool>(); achievement.PercentComplete = value; achievement.ReportAchievement((error) => { var result = true; if (error != null) { result = false; #if DEBUG new UIAlertView("Achievement submittion failed", "Submittion failed because: " + error, null, "OK", null).Show(); #endif } tcs.TrySetResult(result); }); return tcs.Task; } } }
37.258065
307
0.56912
[ "MIT" ]
WaveEngine/Extensions
WaveEngine.Social/Projects/Social/GameCenterService.cs
13,862
C#
using System.Collections.Generic; namespace Crimson.AI.UtilityAI { public abstract class Reasoner : Operator { public IConsideration DefaultConsideration = new FixedScoreConsideration(); protected List<IConsideration> _considerations = new List<IConsideration>(); public Action? Select(Blackboard context) { var consideration = SelectBestConsideration(context); return consideration?.Action; } protected abstract IConsideration SelectBestConsideration(Blackboard context); public Reasoner AddConsideration(IConsideration consideration) { _considerations.Add(consideration); return this; } public Reasoner SetDefaultConsideration(IConsideration defaultConsideration) { DefaultConsideration = defaultConsideration; return this; } public override TaskStatus Update(Blackboard context) { var action = Select(context); return action?.Update(context) ?? TaskStatus.Invalid; } } }
30.189189
86
0.65085
[ "MIT" ]
aszecsei/Crimson
Crimson/AI/UtilityAI/Reasoners/Reasoner.cs
1,119
C#
using System; using System.Threading.Tasks; using CommonServiceLocator; using Foundation; using NDB.Covid19.Enums; using NDB.Covid19.Interfaces; using NDB.Covid19.Models; using NDB.Covid19.Utils; using NDB.Covid19.ViewModels; using UIKit; namespace NDB.Covid19.iOS.Views.ENDeveloperTools { public partial class ENDeveloperToolsViewController : BaseViewController { ENDeveloperToolsViewModel _enDeveloperViewModel; public ENDeveloperToolsViewController(IntPtr handle) : base(handle) { } public override void ViewDidLoad() { base.ViewDidLoad(); _enDeveloperViewModel = new ENDeveloperToolsViewModel(); _enDeveloperViewModel.DevToolUpdateOutput += updateUI; } async partial void ENDevPullKeys_TouchUpInside(UIButton sender) { await _enDeveloperViewModel.PullKeysFromServer(); ENDevOutput.Text = ENDeveloperToolsViewModel.GetLastPullResult(); } async partial void ENDevPullKeysAndGetExposureInfo_TouchUpInside(UIButton sender) { await _enDeveloperViewModel.PullKeysFromServerAndGetExposureInfo(); ENDevOutput.Text = ENDeveloperToolsViewModel.GetLastPullResult(); } async partial void ENDevPushKeys_TouchUpInside(UIButton sender) { ENDevOutput.Text = "Copied to clipboard:\n" + await _enDeveloperViewModel.GetPushKeyInfoFromSharedPrefs(); } partial void ENDevSendExposureMessage_TouchUpInside(UIButton sender) { Task.Run(async () => { await _enDeveloperViewModel.SimulateExposureMessage(); }); } partial void ENDevToggleMessageRetentionBtn_TouchUpInside(UIButton sender) { ENDevOutput.Text = _enDeveloperViewModel.ToggleMessageRetentionTime(); } partial void ENDevPrintLastSymptomOnsetDateBtn_TouchUpInside(UIButton sender) { ENDevOutput.Text = _enDeveloperViewModel.PrintLastSymptomOnsetDate(); } partial void ENDevPrintLastKeysAndTimestampBtn_TouchUpInside(UIButton sender) { ENDevOutput.Text = _enDeveloperViewModel.PrintLastPulledKeysAndTimestamp(); } partial void ENDevShowLatestPullKeysTimesAndStatusesBtn_TouchUpInside(UIButton sender) { ENDevOutput.Text = _enDeveloperViewModel.GetPullHistory(); } partial void ENDevSenExposureMessageAfter10SecBtn_TouchUpInside(UIButton sender) { _enDeveloperViewModel.SimulateExposureMessageAfter10Sec(); ENDevOutput.Text = "Sending Message After 10 Sec..."; } partial void ENDevResetDeviceBtn_TouchUpInside(UIButton sender) { DeviceUtils.CleanDataFromDevice(); ENDevOutput.Text = "Cleaned Device, consider restarting the app"; } partial void ENDevSendExposureDateDecrease_TouchUpInside(UIButton sender) { string res = _enDeveloperViewModel.DecrementExposureDate(); ENDevOutput.Text = res; } partial void ENDevSendExposureDateIncrease_TouchUpInside(UIButton sender) { string res = _enDeveloperViewModel.IncementExposureDate(); ENDevOutput.Text = res; } partial void ENDevExposureHistoryBtn_TouchUpInside(UIButton sender) { Task.Run(async () => { string res = await _enDeveloperViewModel.FetchExposureConfigurationAsync(); ENDevOutput.Text = "Copied to clipboard" + res; }); } void updateUI() { InvokeOnMainThread(() => ENDevOutput.Text = _enDeveloperViewModel.DevToolsOutput); ServiceLocator.Current.GetInstance<IClipboard>().SetTextAsync(_enDeveloperViewModel.DevToolsOutput).GetAwaiter().GetResult(); } partial void ENDevShowSummaryBtn_TouchUpInside(UIButton sender) { ENDevOutput.Text = _enDeveloperViewModel.GetLastExposureSummary(); } partial void ENDevShowExposureInfoBtn_TouchUpInside(UIButton sender) { ENDevOutput.Text = _enDeveloperViewModel.GetExposureInfosFromLastPull(); } partial void ENDevLastUsedConfigurationBtn_TouchUpInside(UIButton sender) { string res = _enDeveloperViewModel.LastUsedExposureConfigurationAsync(); ENDevOutput.Text = "Copied to clipboard:\n" + res; } partial void BackButton_TouchUpInside(UIButton sender) { LeaveController(); } partial void ENDevFakeGatewayBtn_TounchInside(UIButton sender) { ShowModalAlertView( "Fake gateway", "Enter region code (2 chars country code)"); } void ShowModalAlertView(string title, string message) { UIAlertController alert = UIAlertController.Create(title, message, UIAlertControllerStyle.Alert); string region = "no"; alert.AddTextField(textField => { region = textField.Text; }); alert.AddAction(UIAlertAction.Create("Cancel", UIAlertActionStyle.Cancel, obj => { })); alert.AddAction(UIAlertAction.Create("OK", UIAlertActionStyle.Default, async obj => { ApiResponse response = await _enDeveloperViewModel.FakeGateway(alert.TextFields[0].Text); ENDevOutput.Text =$"Pushed keys to region: {alert.TextFields[0].Text}\n" + $"isSuccessful: {response.IsSuccessfull}\n" + $"StatusCode: {response.StatusCode}\n" + $"Error Message: {response.ErrorLogMessage}\n\n"; })); PresentViewController(alert, true, null); } async partial void ENDevPrintPreferencesBtn_TounchInside(UIButton sender) { ENDevOutput.Text = "Actual preferences:\n" + await _enDeveloperViewModel.GetFormattedPreferences(); } partial void GoToForceUpdate_TouchUpInside(UIButton sender) { MessagingCenter.Send<object>(this, MessagingCenterKeys.KEY_FORCE_UPDATE); } partial void NoConsentButton_TouchUpInside(UIButton sender) { OnboardingStatusHelper.Status = OnboardingStatus.NoConsentsGiven; } partial void V1OnlyButton_TouchUpInside(UIButton sender) { OnboardingStatusHelper.Status = OnboardingStatus.OnlyMainOnboardingCompleted; } partial void AllConsentGivenButton_TouchUpInside(UIButton sender) { OnboardingStatusHelper.Status = OnboardingStatus.CountriesOnboardingCompleted; } partial void PullWithDelay_TouchUpInside(UIButton sender) { _enDeveloperViewModel.PullWithDelay(_enDeveloperViewModel.PullKeysFromServer); } } }
37.433155
137
0.655571
[ "MIT" ]
ant3k96/Fhi.Smittestopp.App
NDB.Covid19/NDB.Covid19.iOS/Views/ENDeveloperTools/ENDeveloperToolsViewController.cs
7,000
C#
using System.Collections.Generic; using IdokladSdk.ApiModels; namespace IdokladSdk.Clients { public partial class BatchClient : BaseClient { public const string ResourceUrl = "/Batch"; public BatchClient(ApiContext apiContext) : base(apiContext) { } /// <summary> /// PUT api/Batch/Exported /// Updates an entity's Exported property. Used in communication with external accounting software. /// </summary> public BatchResultWrapper<UpdateExported> UpdateExported(List<UpdateExported> items) { return Put<BatchResultWrapper<UpdateExported>, object>(ResourceUrl + "/" + "Exported", new { Items = items }); } } }
31.478261
122
0.649171
[ "MIT" ]
mholec/IDokladSdk
Src/Idoklad/Clients/BatchClient.cs
724
C#
using Android.App; using Android.Util; using Android.Views; using Android.Widget; using System; using System.Collections.Specialized; using System.ComponentModel; using System.Linq; using Orientation = Android.Widget.Orientation; using Android.Content; using AColor = Android.Graphics.Color; using Android.Text; using Android.Text.Style; namespace Xamarin.Forms.Platform.Android { public class PickerRenderer : ViewRenderer<Picker, EditText>, IPickerRenderer { AlertDialog _dialog; bool _isDisposed; TextColorSwitcher _textColorSwitcher; int _originalHintTextColor; public PickerRenderer(Context context) : base(context) { AutoPackage = false; } [Obsolete("This constructor is obsolete as of version 2.5. Please use PickerRenderer(Context) instead.")] [EditorBrowsable(EditorBrowsableState.Never)] public PickerRenderer() { AutoPackage = false; } IElementController ElementController => Element as IElementController; protected override void Dispose(bool disposing) { if (disposing && !_isDisposed) { _isDisposed = true; ((INotifyCollectionChanged)Element.Items).CollectionChanged -= RowsCollectionChanged; } base.Dispose(disposing); } protected override EditText CreateNativeControl() { return new PickerEditText(Context, this); } protected override void OnElementChanged(ElementChangedEventArgs<Picker> e) { if (e.OldElement != null) ((INotifyCollectionChanged)e.OldElement.Items).CollectionChanged -= RowsCollectionChanged; if (e.NewElement != null) { ((INotifyCollectionChanged)e.NewElement.Items).CollectionChanged += RowsCollectionChanged; if (Control == null) { var textField = CreateNativeControl(); var useLegacyColorManagement = e.NewElement.UseLegacyColorManagement(); _textColorSwitcher = new TextColorSwitcher(textField.TextColors, useLegacyColorManagement); SetNativeControl(textField); _originalHintTextColor = Control.CurrentHintTextColor; } UpdateFont(); UpdatePicker(); UpdateTextColor(); } base.OnElementChanged(e); } protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e) { base.OnElementPropertyChanged(sender, e); if (e.PropertyName == Picker.TitleProperty.PropertyName || e.PropertyName == Picker.TitleColorProperty.PropertyName) UpdatePicker(); else if (e.PropertyName == Picker.SelectedIndexProperty.PropertyName) UpdatePicker(); else if (e.PropertyName == Picker.TextColorProperty.PropertyName) UpdateTextColor(); else if (e.PropertyName == Picker.FontAttributesProperty.PropertyName || e.PropertyName == Picker.FontFamilyProperty.PropertyName || e.PropertyName == Picker.FontSizeProperty.PropertyName) UpdateFont(); } protected override void OnFocusChangeRequested(object sender, VisualElement.FocusRequestArgs e) { base.OnFocusChangeRequested(sender, e); if (e.Focus) CallOnClick(); else if (_dialog != null) { _dialog.Hide(); ElementController.SetValueFromRenderer(VisualElement.IsFocusedPropertyKey, false); _dialog = null; } } void IPickerRenderer.OnClick() { Picker model = Element; var picker = new NumberPicker(Context); if (model.Items != null && model.Items.Any()) { picker.MaxValue = model.Items.Count - 1; picker.MinValue = 0; picker.SetDisplayedValues(model.Items.ToArray()); picker.WrapSelectorWheel = false; picker.DescendantFocusability = DescendantFocusability.BlockDescendants; picker.Value = model.SelectedIndex; } var layout = new LinearLayout(Context) { Orientation = Orientation.Vertical }; layout.AddView(picker); ElementController.SetValueFromRenderer(VisualElement.IsFocusedPropertyKey, true); var builder = new AlertDialog.Builder(Context); builder.SetView(layout); if (!Element.IsSet(Picker.TitleColorProperty)) { builder.SetTitle(model.Title ?? ""); } else { var title = new SpannableString(model.Title ?? ""); title.SetSpan(new ForegroundColorSpan(model.TitleColor.ToAndroid()), 0, title.Length(), SpanTypes.ExclusiveExclusive); builder.SetTitle(title); } builder.SetNegativeButton(global::Android.Resource.String.Cancel, (s, a) => { ElementController.SetValueFromRenderer(VisualElement.IsFocusedPropertyKey, false); _dialog = null; }); builder.SetPositiveButton(global::Android.Resource.String.Ok, (s, a) => { ElementController.SetValueFromRenderer(Picker.SelectedIndexProperty, picker.Value); // It is possible for the Content of the Page to be changed on SelectedIndexChanged. // In this case, the Element & Control will no longer exist. if (Element != null) { if (model.Items.Count > 0 && Element.SelectedIndex >= 0) Control.Text = model.Items[Element.SelectedIndex]; ElementController.SetValueFromRenderer(VisualElement.IsFocusedPropertyKey, false); } _dialog = null; }); _dialog = builder.Create(); _dialog.DismissEvent += (sender, args) => { ElementController?.SetValueFromRenderer(VisualElement.IsFocusedPropertyKey, false); }; _dialog.Show(); } void RowsCollectionChanged(object sender, EventArgs e) { UpdatePicker(); } void UpdateFont() { Control.Typeface = Element.ToTypeface(); Control.SetTextSize(ComplexUnitType.Sp, (float)Element.FontSize); } void UpdatePicker() { Control.Hint = Element.Title; if (Element.IsSet(Picker.TitleColorProperty)) Control.SetHintTextColor(Element.TitleColor.ToAndroid()); else Control.SetHintTextColor(new AColor(_originalHintTextColor)); string oldText = Control.Text; if (Element.SelectedIndex == -1 || Element.Items == null || Element.SelectedIndex >= Element.Items.Count) Control.Text = null; else Control.Text = Element.Items[Element.SelectedIndex]; if (oldText != Control.Text) ((IVisualElementController)Element).NativeSizeChanged(); } void UpdateTextColor() { _textColorSwitcher?.UpdateTextColor(Control, Element.TextColor); } } }
29.278846
191
0.731199
[ "MIT" ]
Opti-Q/Xamarin.Forms
Xamarin.Forms.Platform.Android/Renderers/PickerRenderer.cs
6,090
C#
using ReMi.Contracts.Cqrs.Commands; namespace ReMi.Common.WebApi.Tracking { public interface ICommandTracker : ITracker<ICommand> { } }
15.888889
57
0.762238
[ "MIT" ]
vishalishere/remi
ReMi.Api/Common/ReMi.Common.WebApi/Tracking/ICommandTracker.cs
143
C#
using Microsoft.VisualStudio.LanguageServer.Protocol; using Newtonsoft.Json.Linq; using System; using System.Collections.Generic; using System.Text.RegularExpressions; using System.Threading.Tasks; namespace SvelteVisualStudio.MiddleLayers { class CompletionMiddleLayer : IMiddleLayerProvider { public CompletionMiddleLayer(bool shouldFilterOutJSDocSnippet) { this.shouldFilterOutJSDocSnippet = shouldFilterOutJSDocSnippet; } public string Method => Methods.TextDocumentCompletionName; public Task HandleNotificationAsync(JToken methodParam, Func<JToken, Task> sendNotification) { throw new NotImplementedException(); } public async Task<JToken> HandleRequestAsync(JToken methodParam, Func<JToken, Task<JToken>> sendRequest) { var res = await sendRequest(methodParam); var completion = res.ToObject<CompletionList>(); var filtered = new List<CompletionItem>(); foreach (var item in completion.Items) { // JSDoc template only works when there's block comment auto close // otherwise, the next token would be treated as a comment // thus resulting a wrong result if (!shouldFilterOutJSDocSnippet && item.Label == "/** */") { continue; } if (item.InsertTextFormat != InsertTextFormat.Snippet) { filtered.Add(item); continue; } var processed = TryRemoveSnippet(item); if (processed != null) { processed.InsertTextFormat = InsertTextFormat.Plaintext; filtered.Add(processed); } } res["items"].Replace(JArray.FromObject(filtered)); return res; } private CompletionItem TryRemoveSnippet(CompletionItem item) { if (!string.IsNullOrEmpty(item.TextEdit?.NewText)) { if (TryRemoveSnippet(item.TextEdit.NewText, out var result)) { item.TextEdit.NewText = result; return item; } } else if (!string.IsNullOrEmpty(item.InsertText)) { if (TryRemoveSnippet(item.InsertText, out var result)) { item.InsertText = result; return item; } } else if (TryRemoveSnippet(item.Label, out var result)) { item.Label = result; return item; } return null; } private readonly Regex tabStop = new Regex(@"(\\\$)|(\$[0-9]+|\${[0-9]+})"); private readonly Regex placeHolder = new Regex(@"(\\\$)|\${[0-9]+:(.*)?}"); private readonly Regex notEscaped = new Regex(@"\$(?<!\\\$)"); private readonly bool shouldFilterOutJSDocSnippet; /// <summary> /// remove simple snippet, if it's too complicated filter it out. /// </summary> private bool TryRemoveSnippet(string input, out string result) { result = input; if (string.IsNullOrEmpty(input)) { return false; } if (tabStop.IsMatch(result)) { result = tabStop.Replace(result, match => match.Groups[1].Value); } if (placeHolder.IsMatch(result)) { result = placeHolder.Replace(result, match => { var escaped = match.Groups[1].Value; return string.IsNullOrEmpty(escaped) ? match.Groups[2].Value : escaped; }); } var stillHasDollarSign = notEscaped.IsMatch(result); if (!stillHasDollarSign) { result = result.Replace(@"\$", "$"); } return !stillHasDollarSign; } } }
33.256
112
0.522973
[ "MIT" ]
jasonlyu123/SvelteVisualStudio
SvelteVisualStudioShared/MiddleLayers/CompletionMiddleLayer.cs
4,159
C#
using Beinet.Repository.Repositories; using RemindClockWeb.Repository.Model; namespace RemindClockWeb.Repository { public interface UsersRepository : JpaRepository<Users, int> { [Query("select * from #{#entityName} where account=?1 limit 1", NativeQuery = true)] Users GetByAccount(string account); /// <summary> /// 版本号加1 /// </summary> /// <param name="userId">用户id</param> /// <param name="oldVersion">更新前的版本号</param> /// <returns>更新行数</returns> [Modifing] [Query("update #{#entityName} set version=version+1 where id=?1 and version=?2", NativeQuery = true)] int IncrVersion(int userId, int oldVersion); } }
33.952381
109
0.629734
[ "Apache-2.0" ]
youbl/products
RemindClock/RemindClockWeb/Repository/UsersRepository.cs
749
C#
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ using System; using System.Collections; using System.Collections.Concurrent; using System.Collections.Generic; using System.Reflection; namespace Microsoft.Azure.PowerShell.Cmdlets.ConnectedMachine.Runtime.Json { internal class TypeDetails { private readonly Type info; internal TypeDetails(Type info) { this.info = info ?? throw new ArgumentNullException(nameof(info)); } internal Type NonNullType { get; set; } internal object DefaultValue { get; set; } internal bool IsNullable { get; set; } internal bool IsList { get; set; } internal bool IsStringLike { get; set; } internal bool IsEnum => info.IsEnum; internal bool IsArray => info.IsArray; internal bool IsValueType => info.IsValueType; internal Type ElementType { get; set; } internal IJsonConverter JsonConverter { get; set; } #region Creation private static readonly ConcurrentDictionary<Type, TypeDetails> cache = new ConcurrentDictionary<Type, TypeDetails>(); internal static TypeDetails Get<T>() => Get(typeof(T)); internal static TypeDetails Get(Type type) => cache.GetOrAdd(type, Create); private static TypeDetails Create(Type type) { var isGenericList = !type.IsPrimitive && type.ImplementsOpenGenericInterface(typeof(IList<>)); var isList = !type.IsPrimitive && (isGenericList || typeof(IList).IsAssignableFrom(type)); var isNullable = type.IsNullable(); Type elementType; if (type.IsArray) { elementType = type.GetElementType(); } else if (isGenericList) { var iList = type.GetOpenGenericInterface(typeof(IList<>)); elementType = iList.GetGenericArguments()[0]; } else { elementType = null; } var nonNullType = isNullable ? type.GetGenericArguments()[0] : type; var isStringLike = false; IJsonConverter converter; var jsonConverterAttribute = type.GetCustomAttribute<JsonConverterAttribute>(); if (jsonConverterAttribute != null) { converter = jsonConverterAttribute.Converter; } else if (nonNullType.IsEnum) { converter = new EnumConverter(nonNullType); } else if (JsonConverterFactory.Instances.TryGetValue(nonNullType, out converter)) { } else if (StringLikeHelper.IsStringLike(nonNullType)) { isStringLike = true; converter = new StringLikeConverter(nonNullType); } return new TypeDetails(nonNullType) { NonNullType = nonNullType, DefaultValue = type.IsValueType ? Activator.CreateInstance(type) : null, IsNullable = isNullable, IsList = isList, IsStringLike = isStringLike, ElementType = elementType, JsonConverter = converter }; } #endregion } }
32.491379
127
0.535686
[ "MIT" ]
3quanfeng/azure-powershell
src/ConnectedMachine/generated/runtime/Helpers/TypeDetails.cs
3,656
C#
using UnityEngine; namespace Quester.QuestEditor { public class DeliverNode : QuestNode { public ObjectID Deliverable; public ActorID Receiver; public override void InitializeObjective() { // hmm... var deliverGameObject = ObjectIDMap.Instance.Get(Receiver); var objective = deliverGameObject.AddComponent<DeliverObjective>(); objective.SetNode(this); if (!Active) objective.enabled = false; } public override bool Evaluate() { return complete; } } }
25.083333
79
0.591362
[ "MIT" ]
nmacadam/Quester
Assets/New Quest Graph/DeliverNode.cs
604
C#
 using System; namespace QuizSystem.Library { public class SingleSelectionQuestion : Question { public SingleSelectionQuestion( int id, string text, string[] options, int correctAnswerIndex) :base(id,text) { Options = options; CorrectOptionIndex = correctAnswerIndex; } public string[] Options { get; } public int CorrectOptionIndex { get; } public override decimal GetScoreForAnswer(string answer) { if (string.IsNullOrEmpty(answer)) { return 0M; } if(!int.TryParse(answer, out int resultIdenx)) { return 0M; } return (resultIdenx == CorrectOptionIndex ? 1M : 0M); } } }
21.829268
64
0.488268
[ "MIT" ]
Bogdan748/oop-quiz-system
QuizSystem/QuizSystem.Library/SingleSelectionQuestion.cs
897
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Diagnostics; namespace Microsoft.Win32 { /// <summary>Registry encapsulation. Contains members representing all top level system keys.</summary> public static class Registry { /// <summary>Current User Key. This key should be used as the root for all user specific settings.</summary> public static readonly RegistryKey CurrentUser = RegistryKey.OpenBaseKey(RegistryHive.CurrentUser, RegistryView.Default); /// <summary>Local Machine key. This key should be used as the root for all machine specific settings.</summary> public static readonly RegistryKey LocalMachine = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Default); /// <summary>Classes Root Key. This is the root key of class information.</summary> public static readonly RegistryKey ClassesRoot = RegistryKey.OpenBaseKey(RegistryHive.ClassesRoot, RegistryView.Default); /// <summary>Users Root Key. This is the root of users.</summary> public static readonly RegistryKey Users = RegistryKey.OpenBaseKey(RegistryHive.Users, RegistryView.Default); /// <summary>Performance Root Key. This is where dynamic performance data is stored on NT.</summary> public static readonly RegistryKey PerformanceData = RegistryKey.OpenBaseKey(RegistryHive.PerformanceData, RegistryView.Default); /// <summary>Current Config Root Key. This is where current configuration information is stored.</summary> public static readonly RegistryKey CurrentConfig = RegistryKey.OpenBaseKey(RegistryHive.CurrentConfig, RegistryView.Default); /// <summary> /// Parse a keyName and returns the basekey for it. /// It will also store the subkey name in the out parameter. /// If the keyName is not valid, we will throw ArgumentException. /// The return value shouldn't be null. /// </summary> private static RegistryKey GetBaseKeyFromKeyName(string keyName, out string subKeyName) { if (keyName == null) { throw new ArgumentNullException(nameof(keyName)); } int i = keyName.IndexOf('\\'); int length = i != -1 ? i : keyName.Length; // Determine the potential base key from the length. RegistryKey? baseKey = null; switch (length) { case 10: baseKey = Users; break; // HKEY_USERS case 17: baseKey = char.ToUpperInvariant(keyName[6]) == 'L' ? ClassesRoot : CurrentUser; break; // HKEY_C[L]ASSES_ROOT, otherwise HKEY_CURRENT_USER case 18: baseKey = LocalMachine; break; // HKEY_LOCAL_MACHINE case 19: baseKey = CurrentConfig; break; // HKEY_CURRENT_CONFIG case 21: baseKey = PerformanceData; break; // HKEY_PERFORMANCE_DATA } // If a potential base key was found, see if keyName actually starts with the potential base key's name. if (baseKey != null && keyName.StartsWith(baseKey.Name, StringComparison.OrdinalIgnoreCase)) { subKeyName = (i == -1 || i == keyName.Length) ? string.Empty : keyName.Substring(i + 1, keyName.Length - i - 1); return baseKey; } throw new ArgumentException(SR.Arg_RegInvalidKeyName, nameof(keyName)); } public static object? GetValue(string keyName, string? valueName, object? defaultValue) { RegistryKey basekey = GetBaseKeyFromKeyName(keyName, out string subKeyName); using (RegistryKey? key = basekey.OpenSubKey(subKeyName)) { return key?.GetValue(valueName, defaultValue); } } public static void SetValue(string keyName, string? valueName, object value) { SetValue(keyName, valueName, value, RegistryValueKind.Unknown); } public static void SetValue(string keyName, string? valueName, object value, RegistryValueKind valueKind) { RegistryKey basekey = GetBaseKeyFromKeyName(keyName, out string subKeyName); using (RegistryKey? key = basekey.CreateSubKey(subKeyName)) { Debug.Assert(key != null, "An exception should be thrown if failed!"); key.SetValue(valueName, value, valueKind); } } } }
47.494845
163
0.648795
[ "MIT" ]
Cosifne/runtime
src/libraries/Microsoft.Win32.Registry/src/Microsoft/Win32/Registry.cs
4,607
C#
namespace Miningcore.Blockchain.Bitcoin.DaemonResponses { public class ValidateAddressResponse { public bool IsValid { get; set; } public bool IsMine { get; set; } public bool IsWatchOnly { get; set; } public bool IsScript { get; set; } public string Address { get; set; } public string PubKey { get; set; } public string ScriptPubKey { get; set; } } }
30.071429
55
0.617577
[ "MIT" ]
4AlexG/miningcore
src/Miningcore/Blockchain/Bitcoin/DaemonResponses/ValidateAddressResponse.cs
421
C#
using Microsoft.AspNetCore.Http; using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.IO; using System.Threading.Tasks; namespace FileUploadSample { public class UploadRepository { private readonly ConcurrentBag<File> _files; private readonly string _uploadDirectory; public UploadRepository() { _files = new ConcurrentBag<File>(); _uploadDirectory = Path.Combine(Directory.GetCurrentDirectory(), "uploads"); Directory.CreateDirectory(_uploadDirectory); } public async Task<File> Save(IFormFile formFile) { var id = Guid.NewGuid().ToString().Substring(0, 8); var path = Path.Combine(_uploadDirectory, id + Path.GetExtension(formFile.FileName)); using (var fs = formFile.OpenReadStream()) using (var ws = System.IO.File.Create(path)) { await fs.CopyToAsync(ws); } var file = new File { Id = id, MimeType = formFile.ContentType, Name = formFile.FileName, Path = path }; _files.Add(file); return file; } public IEnumerable<File> Files => _files; } }
27.75
97
0.578078
[ "MIT" ]
JannikLassahn/graphql-dotnet-upload
samples/FileUploadSample/UploadRepository.cs
1,334
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; namespace Microsoft.Templates.Core { public static class Platforms { public const string Uwp = "Uwp"; public const string Web = "Web"; public const string Wpf = "Wpf"; public const string WinUI = "WinUI"; public const string ReactNative = "RN"; public static IEnumerable<string> GetAllPlatforms() { return new[] { Uwp, Web, Wpf, WinUI, ReactNative, }; } public static bool IsValidPlatform(string platform) { bool isValid = false; foreach (string plat in GetAllPlatforms()) { if (plat.Equals(platform, StringComparison.OrdinalIgnoreCase)) { isValid = true; } } return isValid; } } }
24.74
79
0.508488
[ "MIT" ]
Microsoft/CoreTemplateStudio
code/src/CoreTemplateStudio/CoreTemplateStudio.Core/Platforms.cs
1,190
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ public partial class CMSModules_AbuseReport_Controls_AbuseReportList { /// <summary> /// ucAbuseReportGrid control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::CMSAdminControls_UI_UniGrid_UniGrid ucAbuseReportGrid; }
32.043478
81
0.531886
[ "MIT" ]
BryanSoltis/KenticoMVCWidgetShowcase
CMS/CMSModules/AbuseReport/Controls/AbuseReportList.ascx.designer.cs
739
C#
/* * Created by SharpDevelop. * User: kafeinaltor * Date: 20.03.2020 * Time: 19:21 * * To change this template use Tools | Options | Coding | Edit Standard Headers. */ using System; using System.Collections.Generic; using System.Drawing; using System.Windows.Forms; using System.Diagnostics; namespace StringMath { /// <summary> /// Description of MainForm. /// </summary> public partial class MainForm : Form { public MainForm() { // // The InitializeComponent() call is required for Windows Forms designer support. // InitializeComponent(); // // TODO: Add constructor code after the InitializeComponent() call. // Random rnd = new Random(); Clipboard.SetText("100".Factorial()); } public string[] iclerdislar(string a1, string b1, string a2, string b2) { string[] arr = new string[2]; arr[0] = a1.Multiply(b2).Sum(a2.Multiply(b1), false); arr[1] = b1.Multiply(b2); return arr; } } }
20.659574
84
0.654995
[ "MIT" ]
aalitor/StringMath
StringMath/MainForm.cs
973
C#
// Lucene version compatibility level 4.8.1 using System; using System.Collections.Generic; namespace YAF.Lucene.Net.Analysis.Util { /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /// <summary> /// Abstract parent class for analysis factories that create <see cref="TokenFilter"/> /// instances. /// </summary> public abstract class TokenFilterFactory : AbstractAnalysisFactory { private static readonly AnalysisSPILoader<TokenFilterFactory> loader = new AnalysisSPILoader<TokenFilterFactory>(new string[] { "TokenFilterFactory", "FilterFactory" }); /// <summary> /// looks up a tokenfilter by name from the host project's referenced assemblies </summary> public static TokenFilterFactory ForName(string name, IDictionary<string, string> args) { return loader.NewInstance(name, args); } /// <summary> /// looks up a tokenfilter class by name from the host project's referenced assemblies </summary> public static Type LookupClass(string name) { return loader.LookupClass(name); } /// <summary> /// returns a list of all available tokenfilter names from the host project's referenced assemblies </summary> public static ICollection<string> AvailableTokenFilters => loader.AvailableServices; /// <summary> /// Reloads the factory list. /// Changes to the factories are visible after the method ends, all /// iterators (<see cref="AvailableTokenFilters"/>,...) stay consistent. /// /// <para><b>NOTE:</b> Only new factories are added, existing ones are /// never removed or replaced. /// /// </para> /// <para><em>This method is expensive and should only be called for discovery /// of new factories on the given classpath/classloader!</em> /// </para> /// </summary> public static void ReloadTokenFilters() { loader.Reload(); } /// <summary> /// Initialize this factory via a set of key-value pairs. /// </summary> protected TokenFilterFactory(IDictionary<string, string> args) : base(args) { } /// <summary> /// Transform the specified input <see cref="TokenStream"/> </summary> public abstract TokenStream Create(TokenStream input); } }
41.333333
119
0.625747
[ "Apache-2.0" ]
10by10pixel/YAFNET
yafsrc/Lucene.Net/Lucene.Net.Analysis.Common/Analysis/Util/TokenFilterFactory.cs
3,268
C#
namespace GServer.Archestra.Exceptions { public class ObjectIsRequiredException : GalaxyException { public ObjectIsRequiredException(string message) : base(message) { } } }
23.111111
72
0.677885
[ "MIT" ]
tnunnink/GMerge
src/GServer.Archestra/Exceptions/ObjectIsRequiredException.cs
208
C#
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace TimeSpent.Web.Models { public class ProjectModel { public int ProjectId { get; set; } public string Name { get; set; } public string Description { get; set; } } }
21.071429
47
0.657627
[ "MIT" ]
saeidehv/TimeSpent
TimeSpent.Web/Models/ProjectModel.cs
297
C#
using System.Reflection; using System; using NetRuntimeSystem = System; using System.ComponentModel; using NetOffice.Attributes; using NetOffice.VisioApi; namespace NetOffice.VisioApi.Behind { /// <summary> /// Interface IEnumVMenu /// SupportByVersion Visio, 11,12,14,15,16 /// </summary> [SupportByVersion("Visio", 11,12,14,15,16)] [EntityType(EntityType.IsInterface)] public class IEnumVMenu : COMObject, NetOffice.VisioApi.IEnumVMenu { #pragma warning disable #region Type Information /// <summary> /// Contract Type /// </summary> [EditorBrowsable(EditorBrowsableState.Advanced), Browsable(false), Category("NetOffice"), CoreOverridden] public override Type ContractType { get { if(null == _contractType) _contractType = typeof(NetOffice.VisioApi.IEnumVMenu); return _contractType; } } private static Type _contractType; /// <summary> /// Instance Type /// </summary> [EditorBrowsable(EditorBrowsableState.Advanced), Browsable(false), Category("NetOffice"), CoreOverridden] public override Type InstanceType { get { return LateBindingApiWrapperType; } } private static Type _type; [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public static Type LateBindingApiWrapperType { get { if (null == _type) _type = typeof(IEnumVMenu); return _type; } } #endregion #region Ctor /// <summary> /// Stub Ctor, not indented to use /// </summary> public IEnumVMenu() : base() { } #endregion #region Properties #endregion #region Methods /// <summary> /// SupportByVersion Visio 11, 12, 14, 15, 16 /// </summary> /// <param name="celt">Int32 celt</param> /// <param name="rgelt">NetOffice.VisioApi.IVMenu rgelt</param> /// <param name="pceltFetched">Int32 pceltFetched</param> [SupportByVersion("Visio", 11,12,14,15,16)] public virtual Int32 Next(Int32 celt, out NetOffice.VisioApi.IVMenu rgelt, out Int32 pceltFetched) { ParameterModifier[] modifiers = Invoker.CreateParamModifiers(false,true,true); rgelt = null; pceltFetched = 0; object[] paramsArray = Invoker.ValidateParamsArray(celt, rgelt, pceltFetched); object returnItem = Invoker.MethodReturn(this, "Next", paramsArray); rgelt = (NetOffice.VisioApi.IVMenu)paramsArray[1]; pceltFetched = (Int32)paramsArray[2]; return NetRuntimeSystem.Convert.ToInt32(returnItem); } /// <summary> /// SupportByVersion Visio 11, 12, 14, 15, 16 /// </summary> /// <param name="celt">Int32 celt</param> [SupportByVersion("Visio", 11,12,14,15,16)] public virtual Int32 Skip(Int32 celt) { return InvokerService.InvokeInternal.ExecuteInt32MethodGet(this, "Skip", celt); } /// <summary> /// SupportByVersion Visio 11, 12, 14, 15, 16 /// </summary> [SupportByVersion("Visio", 11,12,14,15,16)] public virtual Int32 Reset() { return InvokerService.InvokeInternal.ExecuteInt32MethodGet(this, "Reset"); } /// <summary> /// SupportByVersion Visio 11, 12, 14, 15, 16 /// </summary> /// <param name="ppenm">NetOffice.VisioApi.IEnumVMenu ppenm</param> [SupportByVersion("Visio", 11,12,14,15,16)] public virtual Int32 Clone(out NetOffice.VisioApi.IEnumVMenu ppenm) { ParameterModifier[] modifiers = Invoker.CreateParamModifiers(true); ppenm = null; object[] paramsArray = Invoker.ValidateParamsArray(ppenm); object returnItem = Invoker.MethodReturn(this, "Clone", paramsArray); ppenm = (NetOffice.VisioApi.IEnumVMenu)paramsArray[0]; return NetRuntimeSystem.Convert.ToInt32(returnItem); } #endregion #pragma warning restore } }
27.21831
113
0.658473
[ "MIT" ]
igoreksiz/NetOffice
Source/Visio/Behind/Interfaces/IEnumVMenu.cs
3,867
C#
// Shamelessly ganked from Community Core Library so I can avoid depending on it // Here's its "license": /* This is free and unencumbered software released into the public domain. Anyone is free to copy, modify, publish, use, compile, sell, or distribute this software, either in source code form or as a compiled binary, for any purpose, commercial or non-commercial, and by any means. In jurisdictions that recognize copyright laws, the author or authors of this software dedicate any and all copyright interest in the software to the public domain.We make this dedication for the benefit of the public at large and to the detriment of our heirs and successors.We intend this dedication to be an overt act of relinquishment in perpetuity of all present and future rights to this software under copyright law. 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 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. For more information, please refer to<http://unlicense.org/> */ using UnityEngine; using System; using System.Collections.Generic; using System.Reflection; using Verse; namespace CommunityCoreLibrary_AWorldWithoutHat { public static class Detours { private static List<string> detoured = new List<string>(); private static List<string> destinations = new List<string>(); /** This is a basic first implementation of the IL method 'hooks' (detours) made possible by RawCode's work; https://ludeon.com/forums/index.php?topic=17143.0 Performs detours, spits out basic logs and warns if a method is detoured multiple times. **/ public static unsafe bool TryDetourFromTo ( MethodInfo source, MethodInfo destination ) { // error out on null arguments if( source == null ) { Log.Error("Detours - Source MethodInfo is null"); return false; } if( destination == null ) { Log.Error("Detours - Destination MethodInfo is null"); return false; } // keep track of detours and spit out some messaging string sourceString = source.DeclaringType.FullName + "." + source.Name + " @ 0x" + source.MethodHandle.GetFunctionPointer().ToString( "X" + ( IntPtr.Size * 2 ).ToString() ); string destinationString = destination.DeclaringType.FullName + "." + destination.Name + " @ 0x" + destination.MethodHandle.GetFunctionPointer().ToString( "X" + ( IntPtr.Size * 2 ).ToString() ); #if DEBUG if( detoured.Contains( sourceString ) ) { CCL_Log.Trace( Verbosity.Warnings, "Source method ('" + sourceString + "') is previously detoured to '" + destinations[ detoured.IndexOf( sourceString ) ] + "'", "Detours" ); } CCL_Log.Trace( Verbosity.Injections, "Detouring '" + sourceString + "' to '" + destinationString + "'", "Detours" ); #endif detoured.Add( sourceString ); destinations.Add( destinationString ); if( IntPtr.Size == sizeof( Int64 ) ) { // 64-bit systems use 64-bit absolute address and jumps // 12 byte destructive // Get function pointers long Source_Base = source .MethodHandle.GetFunctionPointer().ToInt64(); long Destination_Base = destination.MethodHandle.GetFunctionPointer().ToInt64(); // Native source address byte* Pointer_Raw_Source = (byte*)Source_Base; // Pointer to insert jump address into native code long* Pointer_Raw_Address = (long*)( Pointer_Raw_Source + 0x02 ); // Insert 64-bit absolute jump into native code (address in rax) // mov rax, immediate64 // jmp [rax] *( Pointer_Raw_Source + 0x00 ) = 0x48; *( Pointer_Raw_Source + 0x01 ) = 0xB8; *Pointer_Raw_Address = Destination_Base; // ( Pointer_Raw_Source + 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09 ) *( Pointer_Raw_Source + 0x0A ) = 0xFF; *( Pointer_Raw_Source + 0x0B ) = 0xE0; } else { // 32-bit systems use 32-bit relative offset and jump // 5 byte destructive // Get function pointers int Source_Base = source .MethodHandle.GetFunctionPointer().ToInt32(); int Destination_Base = destination.MethodHandle.GetFunctionPointer().ToInt32(); // Native source address byte* Pointer_Raw_Source = (byte*)Source_Base; // Pointer to insert jump address into native code int* Pointer_Raw_Address = (int*)( Pointer_Raw_Source + 1 ); // Jump offset (less instruction size) int offset = ( Destination_Base - Source_Base ) - 5; // Insert 32-bit relative jump into native code *Pointer_Raw_Source = 0xE9; *Pointer_Raw_Address = offset; } // done! return true; } } }
39.061224
207
0.602926
[ "MIT" ]
zorbathut/aworldwithouthat
Detours.cs
5,744
C#
using JT808.Protocol.Extensions; using JT808.Protocol.MessageBody; using System; namespace JT808.Protocol.JT808Formatters.MessageBodyFormatters { public class JT808_0x0200_0x2AFormatter : IJT808Formatter<JT808_0x0200_0x2A> { public JT808_0x0200_0x2A Deserialize(ReadOnlySpan<byte> bytes, out int readSize) { int offset = 0; JT808_0x0200_0x2A jT808LocationAttachImpl0X2A = new JT808_0x0200_0x2A { AttachInfoId = JT808BinaryExtensions.ReadByteLittle(bytes, ref offset), AttachInfoLength = JT808BinaryExtensions.ReadByteLittle(bytes, ref offset), IOStatus = JT808BinaryExtensions.ReadUInt16Little(bytes, ref offset) }; readSize = offset; return jT808LocationAttachImpl0X2A; } public int Serialize(ref byte[] bytes, int offset, JT808_0x0200_0x2A value) { offset += JT808BinaryExtensions.WriteByteLittle(bytes, offset, value.AttachInfoId); offset += JT808BinaryExtensions.WriteByteLittle(bytes, offset, value.AttachInfoLength); offset += JT808BinaryExtensions.WriteUInt16Little(bytes, offset, value.IOStatus); return offset; } } }
40.548387
99
0.680191
[ "MIT" ]
NealGao/JT808
src/JT808.Protocol/JT808Formatters/MessageBodyFormatters/JT808_0x0200_0x2AFormatter.cs
1,259
C#
using System.Windows; namespace Zipper { /// <summary> /// Lógica de interacción para App.xaml /// </summary> public partial class App : Application { /// <summary> /// Arranque de la aplicación. /// </summary> /// <param name="e">Argumentos de arranque.</param> protected override void OnStartup(StartupEventArgs e) { new UI.Main().Show(); } } }
23.157895
61
0.545455
[ "MIT" ]
migueladanrm/Zipper.Windows
Zipper/App.xaml.cs
445
C#
/** *** Copyright (c) 2016-2019, Jaguar0625, gimre, BloodyRookie, Tech Bureau, Corp. *** Copyright (c) 2020-present, Jaguar0625, gimre, BloodyRookie. *** All rights reserved. *** *** This file is part of Catapult. *** *** Catapult is free software: you can redistribute it and/or modify *** it under the terms of the GNU Lesser General Public License as published by *** the Free Software Foundation, either version 3 of the License, or *** (at your option) any later version. *** *** Catapult is distributed in the hope that it will be useful, *** but WITHOUT ANY WARRANTY; without even the implied warranty of *** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *** GNU Lesser General Public License for more details. *** *** You should have received a copy of the GNU Lesser General Public License *** along with Catapult. If not, see <http://www.gnu.org/licenses/>. **/ using System; using System.IO; using System.Collections; using System.Collections.Generic; namespace Symbol.Builders { /* * Embedded version of MosaicSupplyRevocationTransaction. */ [Serializable] public class EmbeddedMosaicSupplyRevocationTransactionBuilder: EmbeddedTransactionBuilder { /* Mosaic supply revocation transaction body. */ public MosaicSupplyRevocationTransactionBodyBuilder mosaicSupplyRevocationTransactionBody; /* * Constructor - Creates an object from stream. * * @param stream Byte stream to use to serialize the object. */ internal EmbeddedMosaicSupplyRevocationTransactionBuilder(BinaryReader stream) : base(stream) { try { mosaicSupplyRevocationTransactionBody = MosaicSupplyRevocationTransactionBodyBuilder.LoadFromBinary(stream); } catch (Exception e) { throw new Exception(e.ToString()); } } /* * Creates an instance of EmbeddedMosaicSupplyRevocationTransactionBuilder from a stream. * * @param stream Byte stream to use to serialize the object. * @return Instance of EmbeddedMosaicSupplyRevocationTransactionBuilder. */ public new static EmbeddedMosaicSupplyRevocationTransactionBuilder LoadFromBinary(BinaryReader stream) { return new EmbeddedMosaicSupplyRevocationTransactionBuilder(stream); } /* * Constructor. * * @param signerPublicKey Public key of the signer of the entity.. * @param version Version of this structure.. * @param network Network on which this entity was created.. * @param type Transaction type. * @param sourceAddress Address from which tokens should be revoked.. * @param mosaic Revoked mosaic and amount.. */ internal EmbeddedMosaicSupplyRevocationTransactionBuilder(PublicKeyDto signerPublicKey, byte version, NetworkTypeDto network, TransactionTypeDto type, UnresolvedAddressDto sourceAddress, UnresolvedMosaicBuilder mosaic) : base(signerPublicKey, version, network, type) { GeneratorUtils.NotNull(signerPublicKey, "signerPublicKey is null"); GeneratorUtils.NotNull(version, "version is null"); GeneratorUtils.NotNull(network, "network is null"); GeneratorUtils.NotNull(type, "type is null"); GeneratorUtils.NotNull(sourceAddress, "sourceAddress is null"); GeneratorUtils.NotNull(mosaic, "mosaic is null"); this.mosaicSupplyRevocationTransactionBody = new MosaicSupplyRevocationTransactionBodyBuilder(sourceAddress, mosaic); } /* * Creates an instance of EmbeddedMosaicSupplyRevocationTransactionBuilder. * * @param signerPublicKey Public key of the signer of the entity.. * @param version Version of this structure.. * @param network Network on which this entity was created.. * @param type Transaction type. * @param sourceAddress Address from which tokens should be revoked.. * @param mosaic Revoked mosaic and amount.. * @return Instance of EmbeddedMosaicSupplyRevocationTransactionBuilder. */ public static EmbeddedMosaicSupplyRevocationTransactionBuilder Create(PublicKeyDto signerPublicKey, byte version, NetworkTypeDto network, TransactionTypeDto type, UnresolvedAddressDto sourceAddress, UnresolvedMosaicBuilder mosaic) { return new EmbeddedMosaicSupplyRevocationTransactionBuilder(signerPublicKey, version, network, type, sourceAddress, mosaic); } /* * Gets Address from which tokens should be revoked.. * * @return Address from which tokens should be revoked.. */ public UnresolvedAddressDto GetSourceAddress() { return mosaicSupplyRevocationTransactionBody.GetSourceAddress(); } /* * Gets Revoked mosaic and amount.. * * @return Revoked mosaic and amount.. */ public UnresolvedMosaicBuilder GetMosaic() { return mosaicSupplyRevocationTransactionBody.GetMosaic(); } /* * Gets the size of the object. * * @return Size in bytes. */ public override int GetSize() { var size = base.GetSize(); size += mosaicSupplyRevocationTransactionBody.GetSize(); return size; } /* * Gets the body builder of the object. * * @return Body builder. */ public new MosaicSupplyRevocationTransactionBodyBuilder GetBody() { return mosaicSupplyRevocationTransactionBody; } /* * Serializes an object to bytes. * * @return Serialized bytes. */ public override byte[] Serialize() { var ms = new MemoryStream(); var bw = new BinaryWriter(ms); var superBytes = base.Serialize(); bw.Write(superBytes, 0, superBytes.Length); var mosaicSupplyRevocationTransactionBodyEntityBytes = (mosaicSupplyRevocationTransactionBody).Serialize(); bw.Write(mosaicSupplyRevocationTransactionBodyEntityBytes, 0, mosaicSupplyRevocationTransactionBodyEntityBytes.Length); var result = ms.ToArray(); return result; } } }
40.481013
241
0.664947
[ "MIT" ]
0x070696E65/Symnity
Assets/Plugins/Symnity/Pulgins/catbuffer/EmbeddedMosaicSupplyRevocationTransactionBuilder.cs
6,396
C#
using System; using System.Text; using System.Linq; using DevExpress.ExpressApp; using System.ComponentModel; using DevExpress.ExpressApp.DC; using System.Collections.Generic; using DevExpress.Persistent.Base; using DevExpress.ExpressApp.Model; using DevExpress.ExpressApp.Actions; using DevExpress.ExpressApp.Editors; using DevExpress.ExpressApp.Updating; using DevExpress.ExpressApp.Model.Core; using DevExpress.ExpressApp.Model.DomainLogics; using DevExpress.ExpressApp.Model.NodeGenerators; using System.Data.Entity; using SBD_JTB.Module.BusinessObjects; namespace SBD_JTB.Module { // For more typical usage scenarios, be sure to check out https://documentation.devexpress.com/eXpressAppFramework/clsDevExpressExpressAppModuleBasetopic.aspx. public sealed partial class SBD_JTBModule : ModuleBase { static SBD_JTBModule() { DevExpress.Data.Linq.CriteriaToEFExpressionConverter.SqlFunctionsType = typeof(System.Data.Entity.SqlServer.SqlFunctions); DevExpress.Data.Linq.CriteriaToEFExpressionConverter.EntityFunctionsType = typeof(System.Data.Entity.DbFunctions); DevExpress.ExpressApp.SystemModule.ResetViewSettingsController.DefaultAllowRecreateView = false; // Uncomment this code to delete and recreate the database each time the data model has changed. // Do not use this code in a production environment to avoid data loss. // #if DEBUG // Database.SetInitializer(new DropCreateDatabaseIfModelChanges<SBD_JTBDbContext>()); // #endif } public SBD_JTBModule() { InitializeComponent(); } public override IEnumerable<ModuleUpdater> GetModuleUpdaters(IObjectSpace objectSpace, Version versionFromDB) { ModuleUpdater updater = new DatabaseUpdate.Updater(objectSpace, versionFromDB); return new ModuleUpdater[] { updater }; } public override void Setup(XafApplication application) { base.Setup(application); // Manage various aspects of the application UI and behavior at the module level. } } }
46.977778
163
0.747871
[ "Apache-2.0" ]
kgreed/JobTalkBasic
SBD_JTB.Module/Module.cs
2,116
C#
using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Nameless.EventSource.Domains; using Nameless.EventSource.Events; using Nameless.EventSource.Snapshots; namespace Nameless.EventSource.Repository { public class AggregateRepository : IAggregateRepository { #region Private Read-Only Fields private readonly IAggregateFactory _aggregateFactory; private readonly IClock _clock; private readonly IEventPublisher _eventPublisher; private readonly IEventStore _eventStore; private readonly ISnapshotStore _snapshotStore; private readonly ISnapshotStrategy _snapshotStrategy; #endregion #region Public Constructors public AggregateRepository(IAggregateFactory aggregateFactory, IClock clock, IEventPublisher eventPublisher, IEventStore eventStore, ISnapshotStore snapshotStore, ISnapshotStrategy snapshotStrategy) { Prevent.ParameterNull(aggregateFactory, nameof(aggregateFactory)); Prevent.ParameterNull(clock, nameof(clock)); Prevent.ParameterNull(eventPublisher, nameof(eventPublisher)); Prevent.ParameterNull(eventStore, nameof(eventStore)); Prevent.ParameterNull(snapshotStore, nameof(snapshotStore)); Prevent.ParameterNull(snapshotStrategy, nameof(snapshotStrategy)); _aggregateFactory = aggregateFactory; _clock = clock; _eventPublisher = eventPublisher; _eventStore = eventStore; _snapshotStore = snapshotStore; _snapshotStrategy = snapshotStrategy; } #endregion #region Private Methods private async Task<TAggregate> GetFromSnapshotStoreAsync<TAggregate>(Guid aggregateID, CancellationToken cancellationToken) where TAggregate : AggregateRoot { var isSnapshotable = _snapshotStrategy.IsSnapshottable(typeof(TAggregate)); if (!isSnapshotable) { return null; } var snapshot = await _snapshotStore.GetAsync(aggregateID, cancellationToken); if (snapshot == null) { return null; } var aggregate = _aggregateFactory.Create<TAggregate>() as Snapshottable; aggregate.ApplySnapshot(snapshot); var eventEnumerator = _eventStore.GetAsync(aggregateID, fromVersion: snapshot.Version + 1, cancellationToken).GetAsyncEnumerator(cancellationToken); var events = new List<IEvent>(); while (await eventEnumerator.MoveNextAsync()) { events.Add(eventEnumerator.Current); } aggregate.LoadFromHistory(events); return aggregate as TAggregate; } private async Task<TAggregate> GetFromEventStoreAsync<TAggregate>(Guid aggregateID, CancellationToken cancellationToken) where TAggregate : AggregateRoot { var eventEnumerator = _eventStore.GetAsync(aggregateID, fromVersion: 0, cancellationToken).GetAsyncEnumerator(cancellationToken); var events = new List<IEvent>(); while (await eventEnumerator.MoveNextAsync()) { events.Add(eventEnumerator.Current); } var aggregate = _aggregateFactory.Create<TAggregate>(); aggregate.LoadFromHistory(events); return aggregate; } #endregion #region IRepository<TAggregate> Members public Task<TAggregate> GetAsync<TAggregate>(Guid aggregateID, CancellationToken cancellationToken = default) where TAggregate : AggregateRoot { return GetFromSnapshotStoreAsync<TAggregate>(aggregateID, cancellationToken) ?? GetFromEventStoreAsync<TAggregate>(aggregateID, cancellationToken); } public async Task SaveAsync(AggregateRoot aggregate, CancellationToken cancellationToken = default) { Prevent.ParameterNull(aggregate, nameof(aggregate)); if (aggregate.HasUncommittedEvents()) { var expectedVersion = aggregate.LastCommittedVersion; var lastEvent = await _eventStore.GetLastEventAsync(aggregate.AggregateID, cancellationToken); if (lastEvent != null && expectedVersion == (int)StreamState.NoStream) { throw new InvalidOperationException($"Aggregate ({lastEvent.AggregateID}) can't be created as it already exists with version {lastEvent.Version + 1}"); } if (lastEvent != null && (lastEvent.Version + 1) != expectedVersion) { throw new ConcurrencyException($"Aggregate {lastEvent.AggregateID} has been modified externally and has an updated state. Can't commit changes."); } var eventsToCommit = aggregate.GetUncommittedEvents(); eventsToCommit.Each((evt, idx) => { evt.TimeStamp = _clock.OffsetUtcNow; evt.Version = aggregate.CurrentVersion + idx + 1; }); await _eventStore.SaveAsync(eventsToCommit, cancellationToken); foreach (var evt in eventsToCommit) { await _eventPublisher.PublishAsync(evt, cancellationToken); } var isSnapshottable = _snapshotStrategy.IsSnapshottable(aggregate.GetType()); var shouldMakeSnapshot = _snapshotStrategy.ShouldMakeSnapshot(aggregate); if (isSnapshottable && shouldMakeSnapshot) { var snapshottable = (Snapshottable)aggregate; var snapshot = snapshottable.TakeSnapshot(); await _snapshotStore.SaveAsync(snapshot, cancellationToken); } aggregate.MarkAsCommitted(); } } #endregion } }
39.832
202
0.778871
[ "MIT" ]
marcoaoteixeira/Nameless
src/Nameless.EventSource.Common/Repository/AggregateRepository.cs
4,981
C#
using System; using System.Timers; using Gtk; public partial class MainWindow : Gtk.Window { private const string correctLogin = "Login"; private const string correctPassword = "Password"; private int counter = 6; private bool Lock = false; private Timer _timer; public MainWindow() : base(Gtk.WindowType.Toplevel) { _timer = new Timer(1000); _timer.Elapsed += tick; Build(); _timer.Start(); } private void tick(object sender, ElapsedEventArgs e) { if (counter > 0) { counter--; time.Text = $"Remaining time: {counter} sec."; } else { _timer.Stop(); Lock = true; onLock(); status.Text = "Time is up!"; } } private void onLock() { login.IsEditable = false; login.Sensitive = false; password.IsEditable = false; password.Sensitive = false; auth.Sensitive = false; } protected void OnDeleteEvent(object sender, DeleteEventArgs a) { Application.Quit(); a.RetVal = true; } protected void click(object sender, EventArgs e) { if (!Lock) { if (correctLogin == login.Text && correctPassword == password.Text) { status.Text = "Access granted"; Lock = true; onLock(); _timer.Stop(); } else { status.Text = "Incorrect login or password"; } } } }
22.928571
79
0.507788
[ "MIT" ]
Very1Fake/csharp-labs
Lab4.3/MainWindow.cs
1,607
C#
namespace River.Orqa.Dialogs { partial class OverwriteDialog { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose (bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent () { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(OverwriteDialog)); this.warningMsg = new System.Windows.Forms.Label(); this.warningIcon = new System.Windows.Forms.PictureBox(); this.questionLabel = new System.Windows.Forms.Label(); this.okButton = new System.Windows.Forms.Button(); this.cancelButton = new System.Windows.Forms.Button(); ((System.ComponentModel.ISupportInitialize)(this.warningIcon)).BeginInit(); this.SuspendLayout(); // // warningMsg // this.warningMsg.AutoSize = true; this.warningMsg.Location = new System.Drawing.Point(70, 13); this.warningMsg.Name = "warningMsg"; this.warningMsg.Size = new System.Drawing.Size(276, 13); this.warningMsg.TabIndex = 0; this.warningMsg.Text = "The file {0} cannot be saved because it is write-protected."; // // warningIcon // this.warningIcon.Image = ((System.Drawing.Image)(resources.GetObject("warningIcon.Image"))); this.warningIcon.Location = new System.Drawing.Point(13, 13); this.warningIcon.Margin = new System.Windows.Forms.Padding(3, 3, 20, 3); this.warningIcon.Name = "warningIcon"; this.warningIcon.Size = new System.Drawing.Size(34, 34); this.warningIcon.TabIndex = 1; this.warningIcon.TabStop = false; // // questionLabel // this.questionLabel.AutoSize = true; this.questionLabel.Location = new System.Drawing.Point(70, 34); this.questionLabel.Name = "questionLabel"; this.questionLabel.Size = new System.Drawing.Size(172, 13); this.questionLabel.TabIndex = 2; this.questionLabel.Text = "Would you like to overwrite this file?"; // // okButton // this.okButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.okButton.DialogResult = System.Windows.Forms.DialogResult.OK; this.okButton.Location = new System.Drawing.Point(425, 66); this.okButton.Name = "okButton"; this.okButton.Size = new System.Drawing.Size(75, 23); this.okButton.TabIndex = 3; this.okButton.Text = "&Overwrite"; // // cancelButton // this.cancelButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.cancelButton.DialogResult = System.Windows.Forms.DialogResult.Cancel; this.cancelButton.Location = new System.Drawing.Point(506, 66); this.cancelButton.Name = "cancelButton"; this.cancelButton.Size = new System.Drawing.Size(75, 23); this.cancelButton.TabIndex = 4; this.cancelButton.Text = "&Cancel"; // // OverwriteDialog // this.AcceptButton = this.okButton; this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.CancelButton = this.cancelButton; this.ClientSize = new System.Drawing.Size(594, 102); this.Controls.Add(this.cancelButton); this.Controls.Add(this.okButton); this.Controls.Add(this.questionLabel); this.Controls.Add(this.warningIcon); this.Controls.Add(this.warningMsg); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog; this.MaximizeBox = false; this.MinimizeBox = false; this.Name = "OverwriteDialog"; this.Padding = new System.Windows.Forms.Padding(10); this.ShowInTaskbar = false; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent; this.Text = "Save Read-Only File"; ((System.ComponentModel.ISupportInitialize)(this.warningIcon)).EndInit(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.Label warningMsg; private System.Windows.Forms.PictureBox warningIcon; private System.Windows.Forms.Label questionLabel; private System.Windows.Forms.Button okButton; private System.Windows.Forms.Button cancelButton; } }
38.721311
154
0.722269
[ "MIT" ]
stevencohn/Orqa
River.Orqa/Dialogs/OverwriteDialog.Designer.cs
4,724
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace WbooruPlugin.Saucenao { public class SearchTaskOption { public SaucenaoAPIOption APIOption { get; set; } = new SaucenaoAPIOption(); public bool EnableDownload { get; set; } public string DownloadSavePath { get; set; } public string DownloadFileFormat { get; set; } public bool EnableCompressUploadFile { get; set; } } }
26.368421
83
0.696607
[ "MIT" ]
MikiraSora/WbooruPlugin.Saucenao
SearchTaskOption.cs
503
C#
namespace TestWorker.Http.Extensions { using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; using System; using TestWorker.Http.Options; using TestWorker.Http.Policy; using TestWorker.Services; public static class ServiceCollectionExt { public static IServiceCollection AddTransportHttpClient<TClientOptions>( this IServiceCollection services, TClientOptions options, IConfiguration configuration ) where TClientOptions : ITransportHttpOptions { services.TryAddSingleton<ICredentialStore, CredentialStore>(); services.TryAddSingleton<ITransportHttpOptions>(options); return services .AddHttpClient(options.HttpClientName, (sp, httpClient) => { if (!string.IsNullOrEmpty(options.BaseAddress)) { httpClient.BaseAddress = new Uri(options.BaseAddress); } httpClient.Timeout = options.Timeout.TotalSeconds == 0 ? TimeSpan.FromSeconds(30) : options.Timeout; }) .ConfigurePrimaryHttpMessageHandler(sp => { var credentialStore = sp.GetRequiredService<ICredentialStore>(); var handler = new DefaultHttpClientHandler(10); handler.ConfigureSecurity(options.HttpClientName, options.AbsoluteUri, credentialStore); return handler; }) .SetHandlerLifetime(TimeSpan.FromMinutes(2)) .AddPolicies(configuration.GetSection(PolicyOptions.PoliciesConfigurationSectionName)) .Services; } } }
41.840909
120
0.621945
[ "MIT" ]
BBGONE/TestHHTPClient
TestWorker/Http/Extensions/ServiceCollectionExt.cs
1,843
C#
namespace Exercism.TestRunner.CSharp.IntegrationTests { internal class TestRun { public string Expected { get; } public string Actual { get; } public TestRun(string expected, string actual) => (Expected, Actual) = (expected, actual); } }
26
57
0.629371
[ "MIT" ]
jrr/csharp-test-runner
test/Exercism.TestRunner.CSharp.IntegrationTests/TestRun.cs
286
C#
// // Copyright (c) .NET Foundation and Contributors // Portions Copyright (c) Microsoft Corporation. All rights reserved. // See LICENSE file in the project root for full license information. // using System; using nanoFramework.UI; namespace nanoFramework.Presentation.Media { /// <summary> /// /// </summary> public abstract class Brush { private ushort _opacity = Bitmap.OpacityOpaque; /// <summary> /// /// </summary> public ushort Opacity { get { return _opacity; } set { // clip values if (value > Bitmap.OpacityOpaque) value = Bitmap.OpacityOpaque; _opacity = value; } } /// <summary> /// /// </summary> /// <param name="bmp"></param> /// <param name="outline"></param> /// <param name="x"></param> /// <param name="y"></param> /// <param name="width"></param> /// <param name="height"></param> protected internal abstract void RenderRectangle(Bitmap bmp, Pen outline, int x, int y, int width, int height); /// <summary> /// /// </summary> /// <param name="bmp"></param> /// <param name="outline"></param> /// <param name="x"></param> /// <param name="y"></param> /// <param name="xRadius"></param> /// <param name="yRadius"></param> protected internal virtual void RenderEllipse(Bitmap bmp, Pen outline, int x, int y, int xRadius, int yRadius) { throw new NotSupportedException("RenderEllipse is not supported with this brush."); } /// <summary> /// /// </summary> /// <param name="bmp"></param> /// <param name="outline"></param> /// <param name="pts"></param> protected internal virtual void RenderPolygon(Bitmap bmp, Pen outline, int[] pts) { throw new NotSupportedException("RenderPolygon is not supported with this brush."); } } /// <summary> /// /// </summary> public enum BrushMappingMode { /// <summary> /// /// </summary> Absolute, /// <summary> /// /// </summary> RelativeToBoundingBox } }
26.855556
119
0.501862
[ "MIT" ]
AdrianSoundy/lib-nanoFramework.Graphics
nanoFramework.Graphics/Presentation/Media/Brush.cs
2,417
C#
// Copyright 2020 Energinet DataHub A/S // // Licensed under the Apache License, Version 2.0 (the "License2"); // 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 NodaTime; namespace GreenEnergyHub.Charges.Domain.Charges { public class Charge { private readonly List<Point> _points; public Charge( Guid id, string senderProvidedChargeId, string name, string description, Guid ownerId, Instant startDateTime, Instant endDateTime, ChargeType type, VatClassification vatClassification, Resolution resolution, bool transparentInvoicing, bool taxIndicator, List<Point> points) { Id = id; SenderProvidedChargeId = senderProvidedChargeId; Name = name; Description = description; OwnerId = ownerId; StartDateTime = startDateTime; EndDateTime = endDateTime; Type = type; VatClassification = vatClassification; Resolution = resolution; TransparentInvoicing = transparentInvoicing; TaxIndicator = taxIndicator; _points = points; } /// <summary> /// Minimal ctor to support EF Core. /// </summary> // ReSharper disable once UnusedMember.Local - used by EF Core private Charge() { SenderProvidedChargeId = null!; Name = null!; Description = null!; _points = new List<Point>(); } /// <summary> /// Globally unique identifier of the charge. /// </summary> public Guid Id { get; } /// <summary> /// Unique ID of a charge (Note, unique per market participants and charge type). /// Example: EA-001 /// </summary> public string SenderProvidedChargeId { get; } public ChargeType Type { get; } /// <summary> /// The charge name /// </summary> public string Name { get; } public string Description { get; } /// <summary> /// Valid from, of a charge price list. Also known as Effective Date. /// </summary> public Instant StartDateTime { get; } /// <summary> /// Valid to, of a charge price list. /// </summary> public Instant EndDateTime { get; } public VatClassification VatClassification { get; } /// <summary> /// In Denmark the Energy Supplier invoices the customer, including the charges from the Grid Access Provider and the System Operator. /// This boolean can be use to indicate that a charge must be visible on the invoice sent to the customer. /// </summary> public bool TransparentInvoicing { get; } /// <summary> /// Indicates whether the Charge is tax or not. /// </summary> // ReSharper disable once AutoPropertyCanBeMadeGetOnly.Local - private setter used in unit test public bool TaxIndicator { get; private set; } /// <summary> /// Aggregate ID reference to the owning market participant. /// </summary> public Guid OwnerId { get; } public Resolution Resolution { get; } public IReadOnlyCollection<Point> Points => _points; } }
32.347107
142
0.594788
[ "Apache-2.0" ]
Energinet-DataHub/geh-charges
source/GreenEnergyHub.Charges/source/GreenEnergyHub.Charges.Domain/Charges/Charge.cs
3,916
C#
using HearthDb; namespace HREngine.Bots { class Pen_EX1_014t : PenTemplate //bananas { // verleiht einem diener +1/+1. public override int getPlayPenalty(Playfield p, Minion m, Minion target, int choice, bool isLethal) { if (target.own) { if (!m.Ready) { return 50; } if (m.Hp == 1 && !m.divineshild) { return 10; } } else { foreach (var hc in p.owncards) { if (hc.card.CardId == CardIds.Collectible.Neutral.BigGameHunter || hc.card.CardId == CardIds.Collectible.Priest.ShadowWordDeath) { return 0; } } return 500; } return 0; } } }
24.815789
148
0.399788
[ "MIT" ]
chi-rei-den/Silverfish
penalties/Pen_EX1_014t.cs
943
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace AspnetRunBasics.Models { public class OrderResponseModel { public string UserName { get; set; } public decimal TotalPrice { get; set; } // BillingAddress public string FirstName { get; set; } public string LastName { get; set; } public string EmailAddress { get; set; } public string AddressLine { get; set; } public string Country { get; set; } public string State { get; set; } public string ZipCode { get; set; } // Payment public string CardName { get; set; } public string CardNumber { get; set; } public string Expiration { get; set; } public string CVV { get; set; } public int PaymentMethod { get; set; } } }
26.939394
48
0.614173
[ "MIT" ]
Javilingys/AspnetMicroservices
src/WebApps/AspnetRunBasics/Models/OrderResponseModel.cs
891
C#
// <auto-generated> // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. // </auto-generated> namespace Gov.Jag.Spice.Interfaces { using Microsoft.Rest; using Models; using System.Collections; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; /// <summary> /// Essprocessprocesssession operations. /// </summary> public partial interface IEssprocessprocesssession { /// <summary> /// Get spice_essprocess_ProcessSession from spice_essprocesses /// </summary> /// <param name='businessprocessflowinstanceid'> /// key: businessprocessflowinstanceid of spice_essprocess /// </param> /// <param name='top'> /// </param> /// <param name='skip'> /// </param> /// <param name='search'> /// </param> /// <param name='filter'> /// </param> /// <param name='count'> /// </param> /// <param name='orderby'> /// Order items by property values /// </param> /// <param name='select'> /// Select properties to be returned /// </param> /// <param name='expand'> /// Expand related entities /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.HttpOperationException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<HttpOperationResponse<MicrosoftDynamicsCRMprocesssessionCollection>> GetWithHttpMessagesAsync(string businessprocessflowinstanceid, int? top = default(int?), int? skip = default(int?), string search = default(string), string filter = default(string), bool? count = default(bool?), IList<string> orderby = default(IList<string>), IList<string> select = default(IList<string>), IList<string> expand = default(IList<string>), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get spice_essprocess_ProcessSession from spice_essprocesses /// </summary> /// <param name='businessprocessflowinstanceid'> /// key: businessprocessflowinstanceid of spice_essprocess /// </param> /// <param name='processsessionid'> /// key: processsessionid of processsession /// </param> /// <param name='select'> /// Select properties to be returned /// </param> /// <param name='expand'> /// Expand related entities /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.HttpOperationException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<HttpOperationResponse<MicrosoftDynamicsCRMprocesssession>> ProcessSessionByKeyWithHttpMessagesAsync(string businessprocessflowinstanceid, string processsessionid, IList<string> select = default(IList<string>), IList<string> expand = default(IList<string>), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); } }
44.778947
557
0.627645
[ "Apache-2.0" ]
BrendanBeachBC/jag-spd-spice
interfaces/Dynamics-Autorest/IEssprocessprocesssession.cs
4,254
C#
using NodeEditorFramework; using UnityEngine; namespace Assets.TextureWang.Scripts.Nodes { [Node (false, "Source/Circle")] public class Texture1Circle : CreateOp { public float m_OffsetX; public float m_OffsetY; public const string ID = "Circle"; public bool m_Fill = true; public bool m_InvertFill; public override string GetID { get { return ID; } } public override Node Create (Vector2 pos) { Texture1Circle node = CreateInstance<Texture1Circle> (); node.rect = new Rect(pos.x, pos.y, m_NodeWidth, m_NodeHeight); node.name = "Circle"; // node.CreateInputOutputs(); node.CreateOutput("Texture", "TextureParam", NodeSide.Right, 50); node.m_ShaderOp = ShaderOp.Circle; node.m_TexMode = TexMode.Greyscale; node.m_Value1 = new FloatRemap(0.5f,0,1); node.m_Value2 = new FloatRemap(0.0f, -1, 1); node.m_Value3 = new FloatRemap(0.0f, -1, 1); node.m_Value4 = new FloatRemap(0.5f, 0, 1); node.m_Value5 = new FloatRemap(1.0f, 0, 1); return node; } public override void DrawNodePropertyEditor() { base.DrawNodePropertyEditor(); m_Value1.SliderLabel(this,"RadiusX");//, 0.0f, 1.0f) ;//,new GUIContent("Red", "Float"), m_R); m_Value4.SliderLabel(this,"RadiusY");//, 0.0f, 1.0f);//,new GUIContent("Red", "Float"), m_R); m_Value2.SliderLabel(this,"dx");//, -10.0f, 10.0f);//,new GUIContent("Red", "Float"), m_R); m_Value3.SliderLabel(this,"dy");//, -10.0f, 10.0f);//,new GUIContent("Red", "Float"), m_R); m_Value5.SliderLabel(this, "Fill %"); m_InvertFill = GUILayout.Toggle(m_InvertFill, "InvertFill"); // m_Value6 = (FloatRemap)(m_InvertFill ? 1 : 0); } public override void SetUniqueVars(Material _mat) { _mat.SetVector("_Multiply2", new Vector4(m_Value5, m_InvertFill ? 1 : 0,m_OffsetX, m_OffsetY)); } } }
34.365079
107
0.567206
[ "MIT" ]
ArieLeo/TextureWangBeta
Assets/TextureWang/Scripts/Nodes/Texture1Circle.cs
2,165
C#
/* This file was generated and should not be modified directly */ // Model is Table using System; using System.Collections.Generic; using System.Data; using System.Data.Common; using System.Linq; using System.Threading.Tasks; using Bam.Net; using Bam.Net.Data; using Bam.Net.Data.Qi; namespace Bam.Net.Logging.Data { // schema = DaoLogger2 // connection Name = DaoLogger2 [Serializable] [Bam.Net.Data.Table("Param", "DaoLogger2")] public partial class Param: Bam.Net.Data.Dao { public Param():base() { this.SetKeyColumnName(); this.SetChildren(); } public Param(DataRow data) : base(data) { this.SetKeyColumnName(); this.SetChildren(); } public Param(Database db) : base(db) { this.SetKeyColumnName(); this.SetChildren(); } public Param(Database db, DataRow data) : base(db, data) { this.SetKeyColumnName(); this.SetChildren(); } [Bam.Net.Exclude] public static implicit operator Param(DataRow data) { return new Param(data); } private void SetChildren() { if(_database != null) { this.ChildCollections.Add("EventParam_ParamId", new EventParamCollection(Database.GetQuery<EventParamColumns, EventParam>((c) => c.ParamId == GetULongValue("Id")), this, "ParamId")); } this.ChildCollections.Add("Param_EventParam_Event", new XrefDaoCollection<EventParam, Event>(this, false)); } // property:Id, columnName:Id [Bam.Net.Exclude] [Bam.Net.Data.KeyColumn(Name="Id", DbDataType="BigInt", MaxLength="19")] public ulong? Id { get { return GetULongValue("Id"); } set { SetValue("Id", value); } } // property:Uuid, columnName:Uuid [Bam.Net.Data.Column(Name="Uuid", DbDataType="VarChar", MaxLength="4000", AllowNull=false)] public string Uuid { get { return GetStringValue("Uuid"); } set { SetValue("Uuid", value); } } // property:Cuid, columnName:Cuid [Bam.Net.Data.Column(Name="Cuid", DbDataType="VarChar", MaxLength="4000", AllowNull=true)] public string Cuid { get { return GetStringValue("Cuid"); } set { SetValue("Cuid", value); } } // property:Position, columnName:Position [Bam.Net.Data.Column(Name="Position", DbDataType="Int", MaxLength="10", AllowNull=true)] public int? Position { get { return GetIntValue("Position"); } set { SetValue("Position", value); } } // property:Value, columnName:Value [Bam.Net.Data.Column(Name="Value", DbDataType="VarChar", MaxLength="4000", AllowNull=true)] public string Value { get { return GetStringValue("Value"); } set { SetValue("Value", value); } } [Bam.Net.Exclude] public EventParamCollection EventParamsByParamId { get { if (this.IsNew) { throw new InvalidOperationException("The current instance of type({0}) hasn't been saved and will have no child collections, call Save() or Save(Database) first."._Format(this.GetType().Name)); } if(!this.ChildCollections.ContainsKey("EventParam_ParamId")) { SetChildren(); } var c = (EventParamCollection)this.ChildCollections["EventParam_ParamId"]; if(!c.Loaded) { c.Load(Database); } return c; } } // Xref public XrefDaoCollection<EventParam, Event> Events { get { if (this.IsNew) { throw new InvalidOperationException("The current instance of type({0}) hasn't been saved and will have no child collections, call Save() or Save(Database) first."._Format(this.GetType().Name)); } if(!this.ChildCollections.ContainsKey("Param_EventParam_Event")) { SetChildren(); } var xref = (XrefDaoCollection<EventParam, Event>)this.ChildCollections["Param_EventParam_Event"]; if(!xref.Loaded) { xref.Load(Database); } return xref; } } /// <summary> /// Gets a query filter that should uniquely identify /// the current instance. The default implementation /// compares the Id/key field to the current instance's. /// </summary> [Bam.Net.Exclude] public override IQueryFilter GetUniqueFilter() { if(UniqueFilterProvider != null) { return UniqueFilterProvider(this); } else { var colFilter = new ParamColumns(); return (colFilter.KeyColumn == IdValue); } } /// <summary> /// Return every record in the Param table. /// </summary> /// <param name="database"> /// The database to load from or null /// </param> public static ParamCollection LoadAll(Database database = null) { Database db = database ?? Db.For<Param>(); SqlStringBuilder sql = db.GetSqlStringBuilder(); sql.Select<Param>(); var results = new ParamCollection(db, sql.GetDataTable(db)) { Database = db }; return results; } /// <summary> /// Process all records in batches of the specified size /// </summary> [Bam.Net.Exclude] public static async Task BatchAll(int batchSize, Action<IEnumerable<Param>> batchProcessor, Database database = null) { await System.Threading.Tasks.Task.Run(async ()=> { ParamColumns columns = new ParamColumns(); var orderBy = Bam.Net.Data.Order.By<ParamColumns>(c => c.KeyColumn, Bam.Net.Data.SortOrder.Ascending); var results = Top(batchSize, (c) => c.KeyColumn > 0, orderBy, database); while(results.Count > 0) { await System.Threading.Tasks.Task.Run(()=> { batchProcessor(results); }); long topId = results.Select(d => d.Property<long>(columns.KeyColumn.ToString())).ToArray().Largest(); results = Top(batchSize, (c) => c.KeyColumn > topId, orderBy, database); } }); } /// <summary> /// Process results of a query in batches of the specified size /// </summary> [Bam.Net.Exclude] public static async Task BatchQuery(int batchSize, QueryFilter filter, Action<IEnumerable<Param>> batchProcessor, Database database = null) { await BatchQuery(batchSize, (c) => filter, batchProcessor, database); } /// <summary> /// Process results of a query in batches of the specified size /// </summary> [Bam.Net.Exclude] public static async Task BatchQuery(int batchSize, WhereDelegate<ParamColumns> where, Action<IEnumerable<Param>> batchProcessor, Database database = null) { await System.Threading.Tasks.Task.Run(async ()=> { ParamColumns columns = new ParamColumns(); var orderBy = Bam.Net.Data.Order.By<ParamColumns>(c => c.KeyColumn, Bam.Net.Data.SortOrder.Ascending); var results = Top(batchSize, where, orderBy, database); while(results.Count > 0) { await System.Threading.Tasks.Task.Run(()=> { batchProcessor(results); }); long topId = results.Select(d => d.Property<long>(columns.KeyColumn.ToString())).ToArray().Largest(); results = Top(batchSize, (ParamColumns)where(columns) && columns.KeyColumn > topId, orderBy, database); } }); } /// <summary> /// Process results of a query in batches of the specified size /// </summary> [Bam.Net.Exclude] public static async Task BatchQuery<ColType>(int batchSize, QueryFilter filter, Action<IEnumerable<Param>> batchProcessor, Bam.Net.Data.OrderBy<ParamColumns> orderBy, Database database = null) { await BatchQuery<ColType>(batchSize, (c) => filter, batchProcessor, orderBy, database); } /// <summary> /// Process results of a query in batches of the specified size /// </summary> [Bam.Net.Exclude] public static async Task BatchQuery<ColType>(int batchSize, WhereDelegate<ParamColumns> where, Action<IEnumerable<Param>> batchProcessor, Bam.Net.Data.OrderBy<ParamColumns> orderBy, Database database = null) { await System.Threading.Tasks.Task.Run(async ()=> { ParamColumns columns = new ParamColumns(); var results = Top(batchSize, where, orderBy, database); while(results.Count > 0) { await System.Threading.Tasks.Task.Run(()=> { batchProcessor(results); }); ColType top = results.Select(d => d.Property<ColType>(orderBy.Column.ToString())).ToArray().Largest(); results = Top(batchSize, (ParamColumns)where(columns) && orderBy.Column > top, orderBy, database); } }); } public static Param GetById(uint id, Database database = null) { return GetById((ulong)id, database); } public static Param GetById(int id, Database database = null) { return GetById((long)id, database); } public static Param GetById(long id, Database database = null) { return OneWhere(c => c.KeyColumn == id, database); } public static Param GetById(ulong id, Database database = null) { return OneWhere(c => c.KeyColumn == id, database); } public static Param GetByUuid(string uuid, Database database = null) { return OneWhere(c => Bam.Net.Data.Query.Where("Uuid") == uuid, database); } public static Param GetByCuid(string cuid, Database database = null) { return OneWhere(c => Bam.Net.Data.Query.Where("Cuid") == cuid, database); } [Bam.Net.Exclude] public static ParamCollection Query(QueryFilter filter, Database database = null) { return Where(filter, database); } [Bam.Net.Exclude] public static ParamCollection Where(QueryFilter filter, Database database = null) { WhereDelegate<ParamColumns> whereDelegate = (c) => filter; return Where(whereDelegate, database); } /// <summary> /// Execute a query and return the results. /// </summary> /// <param name="where">A Func delegate that recieves a ParamColumns /// and returns a QueryFilter which is the result of any comparisons /// between ParamColumns and other values /// </param> /// <param name="db"></param> [Bam.Net.Exclude] public static ParamCollection Where(Func<ParamColumns, QueryFilter<ParamColumns>> where, OrderBy<ParamColumns> orderBy = null, Database database = null) { database = database ?? Db.For<Param>(); return new ParamCollection(database.GetQuery<ParamColumns, Param>(where, orderBy), true); } /// <summary> /// Execute a query and return the results. /// </summary> /// <param name="where">A WhereDelegate that recieves a ParamColumns /// and returns a IQueryFilter which is the result of any comparisons /// between ParamColumns and other values /// </param> /// <param name="db"></param> [Bam.Net.Exclude] public static ParamCollection Where(WhereDelegate<ParamColumns> where, Database database = null) { database = database ?? Db.For<Param>(); var results = new ParamCollection(database, database.GetQuery<ParamColumns, Param>(where), true); return results; } /// <summary> /// Execute a query and return the results. /// </summary> /// <param name="where">A WhereDelegate that recieves a ParamColumns /// and returns a IQueryFilter which is the result of any comparisons /// between ParamColumns and other values /// </param> /// <param name="orderBy"> /// Specifies what column and direction to order the results by /// </param> /// <param name="database"></param> [Bam.Net.Exclude] public static ParamCollection Where(WhereDelegate<ParamColumns> where, OrderBy<ParamColumns> orderBy = null, Database database = null) { database = database ?? Db.For<Param>(); var results = new ParamCollection(database, database.GetQuery<ParamColumns, Param>(where, orderBy), true); return results; } /// <summary> /// This method is intended to respond to client side Qi queries. /// Use of this method from .Net should be avoided in favor of /// one of the methods that take a delegate of type /// WhereDelegate&lt;ParamColumns&gt;. /// </summary> /// <param name="where"></param> /// <param name="database"></param> public static ParamCollection Where(QiQuery where, Database database = null) { var results = new ParamCollection(database, Select<ParamColumns>.From<Param>().Where(where, database)); return results; } /// <summary> /// Get one entry matching the specified filter. If none exists /// one will be created; success will depend on the nullability /// of the specified columns. /// </summary> [Bam.Net.Exclude] public static Param GetOneWhere(QueryFilter where, Database database = null) { var result = OneWhere(where, database); if(result == null) { result = CreateFromFilter(where, database); } return result; } /// <summary> /// Execute a query that should return only one result. If more /// than one result is returned a MultipleEntriesFoundException will /// be thrown. /// </summary> /// <param name="where"></param> /// <param name="database"></param> [Bam.Net.Exclude] public static Param OneWhere(QueryFilter where, Database database = null) { WhereDelegate<ParamColumns> whereDelegate = (c) => where; var result = Top(1, whereDelegate, database); return OneOrThrow(result); } /// <summary> /// Get one entry matching the specified filter. If none exists /// one will be created; success will depend on the nullability /// of the specified columns. /// </summary> /// <param name="where"></param> /// <param name="database"></param> [Bam.Net.Exclude] public static Param GetOneWhere(WhereDelegate<ParamColumns> where, Database database = null) { var result = OneWhere(where, database); if(result == null) { ParamColumns c = new ParamColumns(); IQueryFilter filter = where(c); result = CreateFromFilter(filter, database); } return result; } /// <summary> /// Execute a query that should return only one result. If more /// than one result is returned a MultipleEntriesFoundException will /// be thrown. This method is most commonly used to retrieve a /// single Param instance by its Id/Key value /// </summary> /// <param name="where">A WhereDelegate that recieves a ParamColumns /// and returns a IQueryFilter which is the result of any comparisons /// between ParamColumns and other values /// </param> /// <param name="database"></param> [Bam.Net.Exclude] public static Param OneWhere(WhereDelegate<ParamColumns> where, Database database = null) { var result = Top(1, where, database); return OneOrThrow(result); } /// <summary> /// This method is intended to respond to client side Qi queries. /// Use of this method from .Net should be avoided in favor of /// one of the methods that take a delegate of type /// WhereDelegate<ParamColumns>. /// </summary> /// <param name="where"></param> /// <param name="database"></param> public static Param OneWhere(QiQuery where, Database database = null) { var results = Top(1, where, database); return OneOrThrow(results); } /// <summary> /// Execute a query and return the first result. This method will issue a sql TOP clause so only the /// specified number of values will be returned. /// </summary> /// <param name="where">A WhereDelegate that recieves a ParamColumns /// and returns a IQueryFilter which is the result of any comparisons /// between ParamColumns and other values /// </param> /// <param name="database"></param> [Bam.Net.Exclude] public static Param FirstOneWhere(WhereDelegate<ParamColumns> where, Database database = null) { var results = Top(1, where, database); if(results.Count > 0) { return results[0]; } else { return null; } } /// <summary> /// Execute a query and return the first result. This method will issue a sql TOP clause so only the /// specified number of values will be returned. /// </summary> /// <param name="where">A WhereDelegate that recieves a ParamColumns /// and returns a IQueryFilter which is the result of any comparisons /// between ParamColumns and other values /// </param> /// <param name="database"></param> [Bam.Net.Exclude] public static Param FirstOneWhere(WhereDelegate<ParamColumns> where, OrderBy<ParamColumns> orderBy, Database database = null) { var results = Top(1, where, orderBy, database); if(results.Count > 0) { return results[0]; } else { return null; } } /// <summary> /// Shortcut for Top(1, where, orderBy, database) /// </summary> /// <param name="where">A WhereDelegate that recieves a ParamColumns /// and returns a IQueryFilter which is the result of any comparisons /// between ParamColumns and other values /// </param> /// <param name="database"></param> [Bam.Net.Exclude] public static Param FirstOneWhere(QueryFilter where, OrderBy<ParamColumns> orderBy = null, Database database = null) { WhereDelegate<ParamColumns> whereDelegate = (c) => where; var results = Top(1, whereDelegate, orderBy, database); if(results.Count > 0) { return results[0]; } else { return null; } } /// <summary> /// Execute a query and return the specified number /// of values. This method will issue a sql TOP clause so only the /// specified number of values will be returned. /// </summary> /// <param name="count">The number of values to return. /// This value is used in the sql query so no more than this /// number of values will be returned by the database. /// </param> /// <param name="where">A WhereDelegate that recieves a ParamColumns /// and returns a IQueryFilter which is the result of any comparisons /// between ParamColumns and other values /// </param> /// <param name="database"></param> [Bam.Net.Exclude] public static ParamCollection Top(int count, WhereDelegate<ParamColumns> where, Database database = null) { return Top(count, where, null, database); } /// <summary> /// Execute a query and return the specified number of values. This method /// will issue a sql TOP clause so only the specified number of values /// will be returned. /// </summary> /// <param name="count">The number of values to return. /// This value is used in the sql query so no more than this /// number of values will be returned by the database. /// </param> /// <param name="where">A WhereDelegate that recieves a ParamColumns /// and returns a IQueryFilter which is the result of any comparisons /// between ParamColumns and other values /// </param> /// <param name="orderBy"> /// Specifies what column and direction to order the results by /// </param> /// <param name="database"> /// Which database to query or null to use the default /// </param> [Bam.Net.Exclude] public static ParamCollection Top(int count, WhereDelegate<ParamColumns> where, OrderBy<ParamColumns> orderBy, Database database = null) { ParamColumns c = new ParamColumns(); IQueryFilter filter = where(c); Database db = database ?? Db.For<Param>(); QuerySet query = GetQuerySet(db); query.Top<Param>(count); query.Where(filter); if(orderBy != null) { query.OrderBy<ParamColumns>(orderBy); } query.Execute(db); var results = query.Results.As<ParamCollection>(0); results.Database = db; return results; } [Bam.Net.Exclude] public static ParamCollection Top(int count, QueryFilter where, Database database) { return Top(count, where, null, database); } /// <summary> /// Execute a query and return the specified number of values. This method /// will issue a sql TOP clause so only the specified number of values /// will be returned. /// of values /// </summary> /// <param name="count">The number of values to return. /// This value is used in the sql query so no more than this /// number of values will be returned by the database. /// </param> /// <param name="where">A QueryFilter used to filter the /// results /// </param> /// <param name="orderBy"> /// Specifies what column and direction to order the results by /// </param> /// <param name="database"> /// Which database to query or null to use the default /// </param> [Bam.Net.Exclude] public static ParamCollection Top(int count, QueryFilter where, OrderBy<ParamColumns> orderBy = null, Database database = null) { Database db = database ?? Db.For<Param>(); QuerySet query = GetQuerySet(db); query.Top<Param>(count); query.Where(where); if(orderBy != null) { query.OrderBy<ParamColumns>(orderBy); } query.Execute(db); var results = query.Results.As<ParamCollection>(0); results.Database = db; return results; } [Bam.Net.Exclude] public static ParamCollection Top(int count, QueryFilter where, string orderBy = null, SortOrder sortOrder = SortOrder.Ascending, Database database = null) { Database db = database ?? Db.For<Param>(); QuerySet query = GetQuerySet(db); query.Top<Param>(count); query.Where(where); if(orderBy != null) { query.OrderBy(orderBy, sortOrder); } query.Execute(db); var results = query.Results.As<ParamCollection>(0); results.Database = db; return results; } /// <summary> /// Execute a query and return the specified number of values. This method /// will issue a sql TOP clause so only the specified number of values /// will be returned. /// of values /// </summary> /// <param name="count">The number of values to return. /// This value is used in the sql query so no more than this /// number of values will be returned by the database. /// </param> /// <param name="where">A QueryFilter used to filter the /// results /// </param> /// <param name="database"> /// Which database to query or null to use the default /// </param> public static ParamCollection Top(int count, QiQuery where, Database database = null) { Database db = database ?? Db.For<Param>(); QuerySet query = GetQuerySet(db); query.Top<Param>(count); query.Where(where); query.Execute(db); var results = query.Results.As<ParamCollection>(0); results.Database = db; return results; } /// <summary> /// Return the count of Params /// </summary> /// <param name="database"> /// Which database to query or null to use the default /// </param> public static long Count(Database database = null) { Database db = database ?? Db.For<Param>(); QuerySet query = GetQuerySet(db); query.Count<Param>(); query.Execute(db); return (long)query.Results[0].DataRow[0]; } /// <summary> /// Execute a query and return the number of results /// </summary> /// <param name="where">A WhereDelegate that recieves a ParamColumns /// and returns a IQueryFilter which is the result of any comparisons /// between ParamColumns and other values /// </param> /// <param name="database"> /// Which database to query or null to use the default /// </param> [Bam.Net.Exclude] public static long Count(WhereDelegate<ParamColumns> where, Database database = null) { ParamColumns c = new ParamColumns(); IQueryFilter filter = where(c) ; Database db = database ?? Db.For<Param>(); QuerySet query = GetQuerySet(db); query.Count<Param>(); query.Where(filter); query.Execute(db); return query.Results.As<CountResult>(0).Value; } public static long Count(QiQuery where, Database database = null) { Database db = database ?? Db.For<Param>(); QuerySet query = GetQuerySet(db); query.Count<Param>(); query.Where(where); query.Execute(db); return query.Results.As<CountResult>(0).Value; } private static Param CreateFromFilter(IQueryFilter filter, Database database = null) { Database db = database ?? Db.For<Param>(); var dao = new Param(); filter.Parameters.Each(p=> { dao.Property(p.ColumnName, p.Value); }); dao.Save(db); return dao; } private static Param OneOrThrow(ParamCollection c) { if(c.Count == 1) { return c[0]; } else if(c.Count > 1) { throw new MultipleEntriesFoundException(); } return null; } } }
29.88792
209
0.666167
[ "MIT" ]
BryanApellanes/bam.net.shared
Logging/DaoLogger2_Generated/Param.cs
24,000
C#
using System; namespace Persistence.Models { public class ThreadWriteModel { public int ThreadId { get; set; } public string Data { get; set; } public DateTime TimeCreated { get; set; } } }
19
49
0.614035
[ "Apache-2.0" ]
dorotaro/ThreadsApp_V1
Persistence/Models/ThreadWriteModel.cs
230
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.ServiceModel; using System.Reflection; using System.Globalization; //***************************************************************************** // Description.....WS-Discovey for WCF // // Author..........Claudio Masieri, claudio@claudiomasieri.it // Copyright © 2008 ing.Masieri Claudio. (see included license.rtf file) // // Date Created: 06/06/06 // // Date Modified By Description //----------------------------------------------------------------------------- // 01/10/08 Claudio Masieri First Release //***************************************************************************** namespace Masieri.ServiceModel.WSDiscovery.Helpers { /// <summary> /// Helper for ServiceContract /// </summary> static class ServiceContractHelper { /// <summary> /// Gets the physical type from logical one. /// </summary> /// <param name="logicalType">Type of the logical.</param> /// <returns></returns> public static Type GetPhysicalFromLogical(string logicalType) { try { if (Assembly.GetEntryAssembly() == null) return null; //devo risolvere il type fisico da quello logico var physicTypes = from pt in Assembly.GetEntryAssembly().GetTypes() from a in pt.GetCustomAttributes(false) where pt.IsInterface && a is ServiceContractAttribute && CompareLogicalNames(logicalType, ((ServiceContractAttribute)a), pt) select pt; if (physicTypes.Count() == 0) { //provo ad estendere la ricerca physicTypes = from assName in Assembly.GetEntryAssembly().GetReferencedAssemblies() from pt in Assembly.Load(assName).GetTypes() from a in pt.GetCustomAttributes(false) where pt.IsInterface && a is ServiceContractAttribute && CompareLogicalNames(logicalType, ((ServiceContractAttribute)a), pt) select pt; ; } return physicTypes.FirstOrDefault(); } catch (Exception) { return null; } } private static bool CompareLogicalNames(string logicalType, ServiceContractAttribute sca, Type pt) { string ns = "http://tempuri.org/"; if (!string.IsNullOrEmpty(sca.Namespace)) ns =(!sca.Namespace.EndsWith("/"))? sca.Namespace + "/":sca.Namespace; string name = string.IsNullOrEmpty(sca.Name) ? pt.Name : sca.Name; string fullName = ns + name; return fullName.ToLower() == logicalType.Trim().ToLower() ? true : false; } } }
37.461538
102
0.528747
[ "MIT" ]
joergkrause/wcf-workshop
WSDiscovery/WSDiscovery/Helpers/ServiceContractHelper.cs
2,925
C#
// this file is left only for overwrite the old file when updating package.
38.5
76
0.766234
[ "MIT" ]
jonntd/MeshSync
Assets/Runtime/Scripts/MeshSyncServer_impl.cs
77
C#
using System; using System.Threading.Tasks; namespace Leelite.Framework.Domain.Command { public interface ICommandStore { /// <summary> /// Saves the command. /// </summary> /// <param name="command">Command.</param> void SaveCommand<TCommand>(TCommand command); /// <summary> /// Gets the events async. /// </summary> /// <returns>The events async.</returns> /// <param name="aggregateId">Aggregate identifier.</param> Task<TCommand> GetCommandAsync<TCommand>(Guid aggregateId); } }
26.681818
67
0.597956
[ "MIT" ]
liduopie/LeeliteCore
src/Framework/Leelite.Framework.Domain/Command/ICommandStore.cs
589
C#
#pragma checksum "c:\Users\Usuário\Desktop\FinalProject\Views\Home\Index.cshtml" "{ff1816ec-aa5e-4d10-87f7-6f4963833460}" "a6b2d67d72ecb9ea7447bf2729ab9d9a2e167192" // <auto-generated/> #pragma warning disable 1591 [assembly: global::Microsoft.AspNetCore.Razor.Hosting.RazorCompiledItemAttribute(typeof(AspNetCore.Views_Home_Index), @"mvc.1.0.view", @"/Views/Home/Index.cshtml")] [assembly:global::Microsoft.AspNetCore.Mvc.Razor.Compilation.RazorViewAttribute(@"/Views/Home/Index.cshtml", typeof(AspNetCore.Views_Home_Index))] namespace AspNetCore { #line hidden using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Rendering; using Microsoft.AspNetCore.Mvc.ViewFeatures; #line 1 "c:\Users\Usuário\Desktop\FinalProject\Views\_ViewImports.cshtml" using FinalProject; #line default #line hidden #line 1 "c:\Users\Usuário\Desktop\FinalProject\Views\Home\Index.cshtml" using FinalProject.Models; #line default #line hidden [global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"a6b2d67d72ecb9ea7447bf2729ab9d9a2e167192", @"/Views/Home/Index.cshtml")] [global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"f1cd403b176af46e85ea812cbc8b3a7a1a86d4d8", @"/Views/_ViewImports.cshtml")] public class Views_Home_Index : global::Microsoft.AspNetCore.Mvc.Razor.RazorPage<dynamic> { private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_0 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("id", new global::Microsoft.AspNetCore.Html.HtmlString("bt_tabela"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_1 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("asp-controller", "Usuario", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_2 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("asp-action", "Listar", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); #line hidden #pragma warning disable 0169 private string __tagHelperStringValueBuffer; #pragma warning restore 0169 private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperExecutionContext __tagHelperExecutionContext; private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperRunner __tagHelperRunner = new global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperRunner(); private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperScopeManager __backed__tagHelperScopeManager = null; private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperScopeManager __tagHelperScopeManager { get { if (__backed__tagHelperScopeManager == null) { __backed__tagHelperScopeManager = new global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperScopeManager(StartTagHelperWritingScope, EndTagHelperWritingScope); } return __backed__tagHelperScopeManager; } } private global::Microsoft.AspNetCore.Mvc.Razor.TagHelpers.HeadTagHelper __Microsoft_AspNetCore_Mvc_Razor_TagHelpers_HeadTagHelper; private global::Microsoft.AspNetCore.Mvc.Razor.TagHelpers.BodyTagHelper __Microsoft_AspNetCore_Mvc_Razor_TagHelpers_BodyTagHelper; private global::Microsoft.AspNetCore.Mvc.TagHelpers.AnchorTagHelper __Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper; #pragma warning disable 1998 public async override global::System.Threading.Tasks.Task ExecuteAsync() { BeginContext(29, 37, true); WriteLiteral("<!DOCTYPE html>\r\n<html lang=\"en\">\r\n\r\n"); EndContext(); BeginContext(66, 144, false); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("head", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "d30a80d495c547ca88c688a76a6a4fb1", async() => { BeginContext(72, 131, true); WriteLiteral("\r\n <meta charset=\"UTF-8\">\r\n <title>Ponto digital</title>\r\n <link href=\"css/style.css \" rel=\"stylesheet\" type=\"text/css\">\r\n"); EndContext(); } ); __Microsoft_AspNetCore_Mvc_Razor_TagHelpers_HeadTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.Razor.TagHelpers.HeadTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_Razor_TagHelpers_HeadTagHelper); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); EndContext(); BeginContext(210, 12, true); WriteLiteral("\r\n<header>\r\n"); EndContext(); #line 11 "c:\Users\Usuário\Desktop\FinalProject\Views\Home\Index.cshtml" Html.RenderPartial("_NavBar", ViewData["user"]); #line default #line hidden BeginContext(291, 4, true); WriteLiteral(" "); EndContext(); BeginContext(295, 4381, false); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("body", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "4eddb9f5b4104d3298f5f868d5d0d39e", async() => { BeginContext(301, 1643, true); WriteLiteral(@" </header> <section id=""banner""> <h2>Fique de olho em tudo!</h2> <p>Com esse novo sistema de ponto digital será possível ficar de olho em tudo e todos ao mesmo tempo, assim economizando em pontos físicos, dinheiro, e o mais importante no TEMPO!</p> </section> <section id=""linha""> <p>.</p> </section> <section id=""comparacao""> <h2>Veja uma comparação dos nossos escritórios</h2> <div id=""escritorioAntigo""> <h3>1999</h3> <img src=""img/Escritorio_banner.png"" alt=""Primeiro escritório do Ponto digital""> </div> <div id=""escritorioAtual""> <h3>Atualmente</h3> <img src=""img/Escritorio_moderno.png"" alt=""Escritório atual do Ponto Digital""> </div> </div> </section> <section id=""linha""> <p>.</p> </section> <section id=""orcamento""> <div class=""plano""> <div class=""img""> <img src=""img/Moldura.png"" alt=""Moldura de celular"" style=""width: 116px;height: 234;""> </div> <p>1 à 5 funcion"); WriteLiteral(@"ários</p> <br> <p>R$29,99</p> </div> <div class=""plano""> <div class=""img""> <img src=""img/Moldura.png"" alt=""Moldura de celular"" style=""width: 116px;height: 234;""> </div> <p>6 á 50 funcionários</p> <br> <p>R$149,90</p> </div> <div class=""plano""> <div class=""img""> <img src=""img/Moldura.png"" alt=""Moldura de celular"" style=""width: 116px;height: 234;""> </div> <p>51 á 300 funcionários</p> <br> <p>R$300,00</p> </div> </section> <section id=""comentarios""> "); EndContext(); BeginContext(1944, 90, false); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("a", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "870a679872fb449eaf5c10d28c5a3798", async() => { BeginContext(2007, 23, true); WriteLiteral("<h2>Ver depoimentos<h2>"); EndContext(); } ); __Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.AnchorTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper); __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_0); __Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper.Controller = (string)__tagHelperAttribute_1.Value; __tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_1); __Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper.Action = (string)__tagHelperAttribute_2.Value; __tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_2); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); EndContext(); BeginContext(2034, 2635, true); WriteLiteral(@" </section> <section id=""historia""> <h2>História</h2> <p>Desde 1999 com um pequeno escritório, a ideia surgiu de um pequeno problema com o cartão de passar o ponto (que na época era bem antigo), que gerou o projeto e foi seguindo em frente, e cada vez se tornando populare conseguindo esse reconhecimento que temos hoje!</p> </main> <section id=""conheca""> <div class=""produto""> <h3>Conheça o produto</h3> <p> É um produto inovador, sendo o pioneiro, e já está no mercado desde 1999! Com o mesmo princípio de ser um ponto “mais fácil” , assim ajudando muitas empresas!</p> </div> <div class=""equipe""> <h3>Conheça a equipe</h3> <p> A nossa equipe só vem crescendo ao passar dos dias, e a foto de equipe cada vez ficando maior! Abaixo é possível ver cada integrante, e os fundadores!</p> </div> </section> </section> <article> <div class=""fundo""> <img src=""img/Foto_equipe.png"" alt=""Foto da equipe do Ponto Dig"); WriteLiteral(@"ital""> </div> <div class=""fundadores""> <img src=""img/fundadores.png"" alt=""fundadores""> <img src=""img/fundadores.png"" alt=""fundadores""> </div> </article> <section id=""SAC""> <div class=""pai_ctts""> <div class=""ctts""> <h2>Contatos</h2> </div> <div class=""iframe""> <iframe src=""https://www.google.com/maps/embed?pb=!1m18!1m12!1m3!1d3075.2049206112483!2d-46.65231824130764!3d-23.566447533889466!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x94ce59c8da0aa315%3A0xd59f9431f2c9776a!2sAv.+Paulista+-+Bela+Vista%2C+S%C3%A3o+Paulo+-+SP!5e0!3m2!1sen!2sbr!4v1552654580656"" width=""99%"" height=""500"" frameborder=""0"" style=""border: 5px solid #000;"" allowfullscreen></iframe> </div> <section id=""missao""> <h2>Missão</h2> <p>Nossa missão sempre foi facilitar a vida dos usuários do nosso sistema, cada vez com mais atualizações e ouvindo sujestões dos clientes assim"); WriteLiteral(@" podendo ajudar e agradar a todos que desfrutam do nosso software.</p> </section> <div id=""conceitos""> <h2>Conceitos</h2> <p>Os conceitos da empresa ""Agora vai"" são muito flexíveis, pois, podem mudar com o tempo para agradar nossos clientes, onde eles basicamente são ajudar, facilitar, ouvir e melhorar. E com esses fundamentos nosso software consegue evoluir com o tempo. </p> </div> <div id=""conheca""> <a href=""#historia"">Conheça nossa história!</a> </div> "); EndContext(); } ); __Microsoft_AspNetCore_Mvc_Razor_TagHelpers_BodyTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.Razor.TagHelpers.BodyTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_Razor_TagHelpers_BodyTagHelper); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); EndContext(); BeginContext(4676, 9, true); WriteLiteral("\r\n</html>"); EndContext(); } #pragma warning restore 1998 [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.ViewFeatures.IModelExpressionProvider ModelExpressionProvider { get; private set; } [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.IUrlHelper Url { get; private set; } [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.IViewComponentHelper Component { get; private set; } [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.Rendering.IJsonHelper Json { get; private set; } [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.Rendering.IHtmlHelper<dynamic> Html { get; private set; } } } #pragma warning restore 1591
54.134615
344
0.676377
[ "MIT" ]
Pierii/Projeto100-Atualizado
obj/Debug/netcoreapp2.1/Razor/Views/Home/Index.g.cshtml.cs
14,122
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 MakeInvoice.Frontend { 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
70
0.648148
[ "MIT" ]
migihajami/MakeInvoce
MakeInvoice.Frontend/Program.cs
702
C#
using Microsoft.Extensions.DependencyInjection; using AlphaTest.Core.Groups; using AlphaTest.Infrastructure.Checkers; namespace AlphaTest.Infrastructure.Plugins { public static class UtilityServicesPluginExtension { public static void AddUtilityServices(this IServiceCollection services) { services.AddScoped<IGroupUniquenessChecker, EFGroupUniquenessChecker>(); } } }
27.933333
84
0.756563
[ "MIT" ]
Damakshn/AlphaTest
src/AlphaTest.Infrastructure/Plugins/UtilityServicesPluginExtension.cs
421
C#
#pragma checksum "..\..\MainMenuPage.xaml" "{406ea660-64cf-4c82-b6f0-42d48172a799}" "F166E011B8366C838D4C30EE7C0B15BC" //------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ using Connect4; using System; using System.Diagnostics; using System.Windows; using System.Windows.Automation; using System.Windows.Controls; using System.Windows.Controls.Primitives; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Ink; using System.Windows.Input; using System.Windows.Markup; using System.Windows.Media; using System.Windows.Media.Animation; using System.Windows.Media.Effects; using System.Windows.Media.Imaging; using System.Windows.Media.Media3D; using System.Windows.Media.TextFormatting; using System.Windows.Navigation; using System.Windows.Shapes; using System.Windows.Shell; namespace Connect4 { /// <summary> /// MainMenuPage /// </summary> public partial class MainMenuPage : System.Windows.Controls.Page, System.Windows.Markup.IComponentConnector { #line 12 "..\..\MainMenuPage.xaml" [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")] internal System.Windows.Controls.Label Lbl_MainMenu; #line default #line hidden #line 13 "..\..\MainMenuPage.xaml" [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")] internal System.Windows.Controls.Button Btn_StartNewGame; #line default #line hidden #line 14 "..\..\MainMenuPage.xaml" [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")] internal System.Windows.Controls.Button Btn_Scoreboard; #line default #line hidden private bool _contentLoaded; /// <summary> /// InitializeComponent /// </summary> [System.Diagnostics.DebuggerNonUserCodeAttribute()] [System.CodeDom.Compiler.GeneratedCodeAttribute("PresentationBuildTasks", "4.0.0.0")] public void InitializeComponent() { if (_contentLoaded) { return; } _contentLoaded = true; System.Uri resourceLocater = new System.Uri("/Connect4;component/mainmenupage.xaml", System.UriKind.Relative); #line 1 "..\..\MainMenuPage.xaml" System.Windows.Application.LoadComponent(this, resourceLocater); #line default #line hidden } [System.Diagnostics.DebuggerNonUserCodeAttribute()] [System.CodeDom.Compiler.GeneratedCodeAttribute("PresentationBuildTasks", "4.0.0.0")] [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Design", "CA1033:InterfaceMethodsShouldBeCallableByChildTypes")] [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")] [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1800:DoNotCastUnnecessarily")] void System.Windows.Markup.IComponentConnector.Connect(int connectionId, object target) { switch (connectionId) { case 1: this.Lbl_MainMenu = ((System.Windows.Controls.Label)(target)); return; case 2: this.Btn_StartNewGame = ((System.Windows.Controls.Button)(target)); #line 13 "..\..\MainMenuPage.xaml" this.Btn_StartNewGame.Click += new System.Windows.RoutedEventHandler(this.BtnClickNewGame); #line default #line hidden return; case 3: this.Btn_Scoreboard = ((System.Windows.Controls.Button)(target)); #line 14 "..\..\MainMenuPage.xaml" this.Btn_Scoreboard.Click += new System.Windows.RoutedEventHandler(this.BtnShowScores); #line default #line hidden return; } this._contentLoaded = true; } } }
39.120968
142
0.617398
[ "Apache-2.0" ]
PValgento/Connect-4
Connect4/Connect4/obj/Debug/MainMenuPage.g.cs
4,853
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace _06.Prime_Checker { class Program { static void Main(string[] args) { long number = long.Parse(Console.ReadLine()); bool isPrime = PrimeChecking(number); Console.WriteLine(isPrime); } static bool PrimeChecking(long number) { if (number == 1) return false; if (number == 2) return true; if (number % 2 == 0) return false; long boundary = (int)Math.Floor(Math.Sqrt(number)); for (int i = 3; i <= boundary; i += 2) { if (number % i == 0) return false; } return true; } } }
23.823529
63
0.523457
[ "MIT" ]
stoyanovmiroslav/Tech-Module-Practice
Programming Fundamentals/Methods. Debugging and Troubleshooting Code - Exercises/06.Prime Checker/Program.cs
812
C#
// GENERATED AUTOMATICALLY FROM 'Assets/_PROJECT/Scripts/Input/Generic XR Controller.inputactions' using System; using System.Collections; using System.Collections.Generic; using UnityEngine.InputSystem; using UnityEngine.InputSystem.Utilities; public class @GenericXRController : IInputActionCollection, IDisposable { public InputActionAsset asset { get; } public @GenericXRController() { asset = InputActionAsset.FromJson(@"{ ""name"": ""Generic XR Controller"", ""maps"": [ { ""name"": ""Right Controller"", ""id"": ""a388017f-5495-48b9-b140-4059ad23edd9"", ""actions"": [ { ""name"": ""Grip"", ""type"": ""PassThrough"", ""id"": ""e7991c1f-6a67-4159-b02e-4be816335cbe"", ""expectedControlType"": ""Axis"", ""processors"": """", ""interactions"": """" }, { ""name"": ""Trigger"", ""type"": ""PassThrough"", ""id"": ""280899b0-97f4-4e98-9128-a0c1bc05c9a6"", ""expectedControlType"": ""Axis"", ""processors"": """", ""interactions"": """" } ], ""bindings"": [ { ""name"": """", ""id"": ""9633bb6c-339c-4721-bfc1-acaf1e8228f6"", ""path"": ""<XRController>{RightHand}/grip"", ""interactions"": """", ""processors"": """", ""groups"": """", ""action"": ""Grip"", ""isComposite"": false, ""isPartOfComposite"": false }, { ""name"": """", ""id"": ""bebd398b-7fe3-4f1a-9b73-2c15a49d66e6"", ""path"": ""<XRController>{RightHand}/trigger"", ""interactions"": """", ""processors"": """", ""groups"": """", ""action"": ""Trigger"", ""isComposite"": false, ""isPartOfComposite"": false } ] }, { ""name"": ""Left Controller"", ""id"": ""31151949-7b68-4788-b623-01c49f768b51"", ""actions"": [ { ""name"": ""Grip"", ""type"": ""PassThrough"", ""id"": ""8d768d35-eb0e-4d64-80b5-7454c0e1375a"", ""expectedControlType"": ""Axis"", ""processors"": """", ""interactions"": """" }, { ""name"": ""Trigger"", ""type"": ""PassThrough"", ""id"": ""3bf1ac1f-19e6-466a-9b6b-b44d88ee3e12"", ""expectedControlType"": ""Axis"", ""processors"": """", ""interactions"": """" } ], ""bindings"": [ { ""name"": """", ""id"": ""74e1c715-0ee7-4a3d-be09-da20b5428355"", ""path"": ""<XRController>{LeftHand}/grip"", ""interactions"": """", ""processors"": """", ""groups"": """", ""action"": ""Grip"", ""isComposite"": false, ""isPartOfComposite"": false }, { ""name"": """", ""id"": ""0554d7d6-53b5-4eab-8b91-c00b169471c0"", ""path"": ""<XRController>{LeftHand}/trigger"", ""interactions"": """", ""processors"": """", ""groups"": """", ""action"": ""Trigger"", ""isComposite"": false, ""isPartOfComposite"": false } ] } ], ""controlSchemes"": [] }"); // Right Controller m_RightController = asset.FindActionMap("Right Controller", throwIfNotFound: true); m_RightController_Grip = m_RightController.FindAction("Grip", throwIfNotFound: true); m_RightController_Trigger = m_RightController.FindAction("Trigger", throwIfNotFound: true); // Left Controller m_LeftController = asset.FindActionMap("Left Controller", throwIfNotFound: true); m_LeftController_Grip = m_LeftController.FindAction("Grip", throwIfNotFound: true); m_LeftController_Trigger = m_LeftController.FindAction("Trigger", throwIfNotFound: true); } public void Dispose() { UnityEngine.Object.Destroy(asset); } public InputBinding? bindingMask { get => asset.bindingMask; set => asset.bindingMask = value; } public ReadOnlyArray<InputDevice>? devices { get => asset.devices; set => asset.devices = value; } public ReadOnlyArray<InputControlScheme> controlSchemes => asset.controlSchemes; public bool Contains(InputAction action) { return asset.Contains(action); } public IEnumerator<InputAction> GetEnumerator() { return asset.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } public void Enable() { asset.Enable(); } public void Disable() { asset.Disable(); } // Right Controller private readonly InputActionMap m_RightController; private IRightControllerActions m_RightControllerActionsCallbackInterface; private readonly InputAction m_RightController_Grip; private readonly InputAction m_RightController_Trigger; public struct RightControllerActions { private @GenericXRController m_Wrapper; public RightControllerActions(@GenericXRController wrapper) { m_Wrapper = wrapper; } public InputAction @Grip => m_Wrapper.m_RightController_Grip; public InputAction @Trigger => m_Wrapper.m_RightController_Trigger; public InputActionMap Get() { return m_Wrapper.m_RightController; } public void Enable() { Get().Enable(); } public void Disable() { Get().Disable(); } public bool enabled => Get().enabled; public static implicit operator InputActionMap(RightControllerActions set) { return set.Get(); } public void SetCallbacks(IRightControllerActions instance) { if (m_Wrapper.m_RightControllerActionsCallbackInterface != null) { @Grip.started -= m_Wrapper.m_RightControllerActionsCallbackInterface.OnGrip; @Grip.performed -= m_Wrapper.m_RightControllerActionsCallbackInterface.OnGrip; @Grip.canceled -= m_Wrapper.m_RightControllerActionsCallbackInterface.OnGrip; @Trigger.started -= m_Wrapper.m_RightControllerActionsCallbackInterface.OnTrigger; @Trigger.performed -= m_Wrapper.m_RightControllerActionsCallbackInterface.OnTrigger; @Trigger.canceled -= m_Wrapper.m_RightControllerActionsCallbackInterface.OnTrigger; } m_Wrapper.m_RightControllerActionsCallbackInterface = instance; if (instance != null) { @Grip.started += instance.OnGrip; @Grip.performed += instance.OnGrip; @Grip.canceled += instance.OnGrip; @Trigger.started += instance.OnTrigger; @Trigger.performed += instance.OnTrigger; @Trigger.canceled += instance.OnTrigger; } } } public RightControllerActions @RightController => new RightControllerActions(this); // Left Controller private readonly InputActionMap m_LeftController; private ILeftControllerActions m_LeftControllerActionsCallbackInterface; private readonly InputAction m_LeftController_Grip; private readonly InputAction m_LeftController_Trigger; public struct LeftControllerActions { private @GenericXRController m_Wrapper; public LeftControllerActions(@GenericXRController wrapper) { m_Wrapper = wrapper; } public InputAction @Grip => m_Wrapper.m_LeftController_Grip; public InputAction @Trigger => m_Wrapper.m_LeftController_Trigger; public InputActionMap Get() { return m_Wrapper.m_LeftController; } public void Enable() { Get().Enable(); } public void Disable() { Get().Disable(); } public bool enabled => Get().enabled; public static implicit operator InputActionMap(LeftControllerActions set) { return set.Get(); } public void SetCallbacks(ILeftControllerActions instance) { if (m_Wrapper.m_LeftControllerActionsCallbackInterface != null) { @Grip.started -= m_Wrapper.m_LeftControllerActionsCallbackInterface.OnGrip; @Grip.performed -= m_Wrapper.m_LeftControllerActionsCallbackInterface.OnGrip; @Grip.canceled -= m_Wrapper.m_LeftControllerActionsCallbackInterface.OnGrip; @Trigger.started -= m_Wrapper.m_LeftControllerActionsCallbackInterface.OnTrigger; @Trigger.performed -= m_Wrapper.m_LeftControllerActionsCallbackInterface.OnTrigger; @Trigger.canceled -= m_Wrapper.m_LeftControllerActionsCallbackInterface.OnTrigger; } m_Wrapper.m_LeftControllerActionsCallbackInterface = instance; if (instance != null) { @Grip.started += instance.OnGrip; @Grip.performed += instance.OnGrip; @Grip.canceled += instance.OnGrip; @Trigger.started += instance.OnTrigger; @Trigger.performed += instance.OnTrigger; @Trigger.canceled += instance.OnTrigger; } } } public LeftControllerActions @LeftController => new LeftControllerActions(this); public interface IRightControllerActions { void OnGrip(InputAction.CallbackContext context); void OnTrigger(InputAction.CallbackContext context); } public interface ILeftControllerActions { void OnGrip(InputAction.CallbackContext context); void OnTrigger(InputAction.CallbackContext context); } }
40.748062
104
0.552078
[ "MIT" ]
22ndtech/OpenXR
UnityOpenXR/Assets/_PROJECT/Input/Controller/Generic XR Controller.cs
10,513
C#
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Linq; using Microsoft.Azure.Management.Compute.Models; namespace Microsoft.Azure.Management.Compute.Models { /// <summary> /// Contains the parameteres required to list virtual machine extension /// image versions. /// </summary> public partial class VirtualMachineExtensionImageListVersionsParameters : VirtualMachineExtensionImageListTypesParameters { private string _filterExpression; /// <summary> /// Optional. ODAta filter /// expression.https://msdn.microsoft.com/en-us/library/hh169248(v=nav.70).aspxSupported /// operatives: -eq -startswith Examples: To list the all version /// that begin with 1.0 $filter=startswith(name, ‘1.0’) To get the /// latest version $filter= name eq ‘latest’ /// </summary> public string FilterExpression { get { return this._filterExpression; } set { this._filterExpression = value; } } private string _type; /// <summary> /// Required. Unique (across the publisher) identifier to distinguish /// an extension for this publisher. Example: 'BGInfo' or /// 'VMAccess'.The allowed characters are uppercase or lowercase /// letters, digit, hypen(-), period (.)Dot or hyphen is not allowed /// the end of value. Max length is 64. /// </summary> public string Type { get { return this._type; } set { this._type = value; } } /// <summary> /// Initializes a new instance of the /// VirtualMachineExtensionImageListVersionsParameters class. /// </summary> public VirtualMachineExtensionImageListVersionsParameters() { } /// <summary> /// Initializes a new instance of the /// VirtualMachineExtensionImageListVersionsParameters class with /// required arguments. /// </summary> public VirtualMachineExtensionImageListVersionsParameters(string type, string location, string publisherName) : this() { if (type == null) { throw new ArgumentNullException("type"); } if (location == null) { throw new ArgumentNullException("location"); } if (publisherName == null) { throw new ArgumentNullException("publisherName"); } this.Type = type; this.Location = location; this.PublisherName = publisherName; } } }
35.418367
125
0.613944
[ "Apache-2.0" ]
CerebralMischief/azure-sdk-for-net
src/ResourceManagement/Compute/ComputeManagement/Generated/Models/VirtualMachineExtensionImageListVersionsParameters.cs
3,479
C#
/* * LUSID API * * # Introduction This page documents the [LUSID APIs](https://api.lusid.com/swagger), which allows authorised clients to query and update their data within the LUSID platform. SDKs to interact with the LUSID APIs are available in the following languages : * [C#](https://github.com/finbourne/lusid-sdk-csharp) * [Java](https://github.com/finbourne/lusid-sdk-java) * [JavaScript](https://github.com/finbourne/lusid-sdk-js) * [Python](https://github.com/finbourne/lusid-sdk-python) # Data Model The LUSID API has a relatively lightweight but extremely powerful data model. One of the goals of LUSID was not to enforce on clients a single rigid data model but rather to provide a flexible foundation onto which clients can streamline their data. One of the primary tools to extend the data model is through using properties. Properties can be associated with amongst others: - * Transactions * Instruments * Portfolios The LUSID data model is exposed through the LUSID APIs. The APIs provide access to both business objects and the meta data used to configure the systems behaviours. The key business entities are: - * **Portfolios** A portfolio is the primary container for transactions and holdings. * **Derived Portfolios** Derived portfolios allow portfolios to be created based on other portfolios, by overriding or overlaying specific items * **Holdings** A holding is a position account for a instrument within a portfolio. Holdings can only be adjusted via transactions. * **Transactions** A Transaction is a source of transactions used to manipulate holdings. * **Corporate Actions** A corporate action is a market event which occurs to a instrument, for example a stock split * **Instruments** A instrument represents a currency, tradable instrument or OTC contract that is attached to a transaction and a holding. * **Properties** Several entities allow additional user defined properties to be associated with them. For example, a Portfolio manager may be associated with a portfolio Meta data includes: - * **Transaction Types** Transactions are booked with a specific transaction type. The types are client defined and are used to map the Transaction to a series of movements which update the portfolio holdings. * **Properties Types** Types of user defined properties used within the system. This section describes the data model that LUSID exposes via the APIs. ## Scope All data in LUSID is segregated at the client level. Entities in LUSID are identifiable by a unique code. Every entity lives within a logical data partition known as a Scope. Scope is an identity namespace allowing two entities with the same unique code to co-exist within individual address spaces. For example, prices for equities from different vendors may be uploaded into different scopes such as `client/vendor1` and `client/vendor2`. A portfolio may then be valued using either of the price sources by referencing the appropriate scope. LUSID Clients cannot access scopes of other clients. ## Schema A detailed description of the entities used by the API and parameters for endpoints which take a JSON document can be retrieved via the `schema` endpoint. ## Instruments LUSID has its own built-in instrument master which you can use to master your own instrument universe. Every instrument must be created with one or more unique market identifiers, such as [FIGI](https://openfigi.com/). For any non-listed instruments (eg OTCs), you can upload an instrument against a custom ID of your choosing. In addition, LUSID will allocate each instrument a unique 'LUSID instrument identifier'. The LUSID instrument identifier is what is used when uploading transactions, holdings, prices, etc. The API exposes an `instrument/lookup` endpoint which can be used to lookup these LUSID identifiers using their market identifiers. Cash can be referenced using the ISO currency code prefixed with \"`CCY_`\" e.g. `CCY_GBP` ## Instrument Prices (Analytics) Instrument prices are stored in LUSID's Analytics Store | Field|Type|Description | | - --|- --|- -- | | InstrumentUid|string|Unique instrument identifier | | Value|decimal|Value of the analytic, eg price | | Denomination|string|Underlying unit of the analytic, eg currency, EPS etc. | ## Instrument Data Instrument data can be uploaded to the system using the [Instrument Properties](#tag/InstrumentProperties) endpoint. | Field|Type|Description | | - --|- --|- -- | | Key|propertykey|The key of the property. This takes the format {domain}/{scope}/{code} e.g. 'Instrument/system/Name' or 'Transaction/strategy/quantsignal'. | | Value|string|The value of the property. | | EffectiveFrom|datetimeoffset|The effective datetime from which the property is valid. | ## Portfolios Portfolios are the top-level entity containers within LUSID, containing transactions, corporate actions and holdings. The transactions build up the portfolio holdings on which valuations, analytics profit & loss and risk can be calculated. Properties can be associated with Portfolios to add in additional model data. Portfolio properties can be changed over time as well. For example, to allow a Portfolio Manager to be linked with a Portfolio. Additionally, portfolios can be securitised and held by other portfolios, allowing LUSID to perform \"drill-through\" into underlying fund holdings ### Reference Portfolios Reference portfolios are portfolios that contain only weights, as opposed to transactions, and are designed to represent entities such as indices. ### Derived Portfolios LUSID also allows for a portfolio to be composed of another portfolio via derived portfolios. A derived portfolio can contain its own transactions and also inherits any transactions from its parent portfolio. Any changes made to the parent portfolio are automatically reflected in derived portfolio. Derived portfolios in conjunction with scopes are a powerful construct. For example, to do pre-trade what-if analysis, a derived portfolio could be created a new namespace linked to the underlying live (parent) portfolio. Analysis can then be undertaken on the derived portfolio without affecting the live portfolio. ### Portfolio Groups Portfolio groups allow the construction of a hierarchy from portfolios and groups. Portfolio operations on the group are executed on an aggregated set of portfolios in the hierarchy. For example: * Global Portfolios _(group)_ * APAC _(group)_ * Hong Kong _(portfolio)_ * Japan _(portfolio)_ * Europe _(group)_ * France _(portfolio)_ * Germany _(portfolio)_ * UK _(portfolio)_ In this example **Global Portfolios** is a group that consists of an aggregate of **Hong Kong**, **Japan**, **France**, **Germany** and **UK** portfolios. ### Movements Engine The Movements engine sits on top of the immutable event store and is used to manage the relationship between input trading actions and their associated portfolio holdings. The movements engine reads in the following entity types:- * Posting Transactions * Applying Corporate Actions * Holding Adjustments These are converted to one or more movements and used by the movements engine to calculate holdings. At the same time it also calculates running balances, and realised P&L. The outputs from the movements engine are holdings and transactions. ## Transactions A transaction represents an economic activity against a Portfolio. Transactions are processed according to a configuration. This will tell the LUSID engine how to interpret the transaction and correctly update the holdings. LUSID comes with a set of transaction types you can use out of the box, or you can configure your own set(s) of transactions. For more details see the [LUSID Getting Started Guide for transaction configuration.](https://support.lusid.com/configuring-transaction-types) | Field|Type|Description | | - --|- --|- -- | | TransactionId|string|The unique identifier for the transaction. | | Type|string|The type of the transaction e.g. 'Buy', 'Sell'. The transaction type should have been pre-configured via the System Configuration API endpoint. If it hasn't been pre-configured the transaction will still be updated or inserted however you will be unable to generate the resultant holdings for the portfolio that contains this transaction as LUSID does not know how to process it. | | InstrumentIdentifiers|map|A set of instrument identifiers to use to resolve the transaction to a unique instrument. | | TransactionDate|dateorcutlabel|The date of the transaction. | | SettlementDate|dateorcutlabel|The settlement date of the transaction. | | Units|decimal|The number of units transacted in the associated instrument. | | TransactionPrice|transactionprice|The price for each unit of the transacted instrument in the transaction currency. | | TotalConsideration|currencyandamount|The total value of the transaction in the settlement currency. | | ExchangeRate|decimal|The exchange rate between the transaction and settlement currency. For example if the transaction currency is in USD and the settlement currency is in GBP this this the USD/GBP rate. | | TransactionCurrency|currency|The transaction currency. | | Properties|map|Set of unique transaction properties and associated values to store with the transaction. Each property must be from the 'Transaction' domain. | | CounterpartyId|string|The identifier for the counterparty of the transaction. | | Source|string|The source of the transaction. This is used to look up the appropriate transaction group set in the transaction type configuration. | From these fields, the following values can be calculated * **Transaction value in Transaction currency**: TotalConsideration / ExchangeRate * **Transaction value in Portfolio currency**: Transaction value in Transaction currency * TradeToPortfolioRate ### Example Transactions #### A Common Purchase Example Three example transactions are shown in the table below. They represent a purchase of USD denominated IBM shares within a Sterling denominated portfolio. * The first two transactions are for separate buy and fx trades * Buying 500 IBM shares for $71,480.00 * A foreign exchange conversion to fund the IBM purchase. (Buy $71,480.00 for &#163;54,846.60) * The third transaction is an alternate version of the above trades. Buying 500 IBM shares and settling directly in Sterling. | Column | Buy Trade | Fx Trade | Buy Trade with foreign Settlement | | - -- -- | - -- -- | - -- -- | - -- -- | | TransactionId | FBN00001 | FBN00002 | FBN00003 | | Type | Buy | FxBuy | Buy | | InstrumentIdentifiers | { \"figi\", \"BBG000BLNNH6\" } | { \"CCY\", \"CCY_USD\" } | { \"figi\", \"BBG000BLNNH6\" } | | TransactionDate | 2018-08-02 | 2018-08-02 | 2018-08-02 | | SettlementDate | 2018-08-06 | 2018-08-06 | 2018-08-06 | | Units | 500 | 71480 | 500 | | TransactionPrice | 142.96 | 1 | 142.96 | | TradeCurrency | USD | USD | USD | | ExchangeRate | 1 | 0.7673 | 0.7673 | | TotalConsideration.Amount | 71480.00 | 54846.60 | 54846.60 | | TotalConsideration.Currency | USD | GBP | GBP | | Trade/default/TradeToPortfolioRate&ast; | 0.7673 | 0.7673 | 0.7673 | [&ast; This is a property field] #### A Forward FX Example LUSID has a flexible transaction modelling system, and there are a number of different ways of modelling forward fx trades. The default LUSID transaction types are FwdFxBuy and FwdFxSell. Other types and behaviours can be configured as required. Using these transaction types, the holdings query will report two forward positions. One in each currency. Since an FX trade is an exchange of one currency for another, the following two 6 month forward transactions are equivalent: | Column | Forward 'Sell' Trade | Forward 'Buy' Trade | | - -- -- | - -- -- | - -- -- | | TransactionId | FBN00004 | FBN00005 | | Type | FwdFxSell | FwdFxBuy | | InstrumentIdentifiers | { \"CCY\", \"CCY_GBP\" } | { \"CCY\", \"CCY_USD\" } | | TransactionDate | 2018-08-02 | 2018-08-02 | | SettlementDate | 2019-02-06 | 2019-02-06 | | Units | 10000.00 | 13142.00 | | TransactionPrice |1 | 1 | | TradeCurrency | GBP | USD | | ExchangeRate | 1.3142 | 0.760919 | | TotalConsideration.Amount | 13142.00 | 10000.00 | | TotalConsideration.Currency | USD | GBP | | Trade/default/TradeToPortfolioRate | 1.0 | 0.760919 | ## Holdings A holding represents a position in a instrument or cash on a given date. | Field|Type|Description | | - --|- --|- -- | | InstrumentUid|string|The unqiue Lusid Instrument Id (LUID) of the instrument that the holding is in. | | SubHoldingKeys|map|The sub-holding properties which identify the holding. Each property will be from the 'Transaction' domain. These are configured when a transaction portfolio is created. | | Properties|map|The properties which have been requested to be decorated onto the holding. These will be from the 'Instrument' or 'Holding' domain. | | HoldingType|string|The type of the holding e.g. Position, Balance, CashCommitment, Receivable, ForwardFX etc. | | Units|decimal|The total number of units of the holding. | | SettledUnits|decimal|The total number of settled units of the holding. | | Cost|currencyandamount|The total cost of the holding in the transaction currency. | | CostPortfolioCcy|currencyandamount|The total cost of the holding in the portfolio currency. | | Transaction|transaction|The transaction associated with an unsettled holding. | ## Corporate Actions Corporate actions are represented within LUSID in terms of a set of instrument-specific 'transitions'. These transitions are used to specify the participants of the corporate action, and the effect that the corporate action will have on holdings in those participants. ### Corporate Action | Field|Type|Description | | - --|- --|- -- | | CorporateActionCode|code|The unique identifier of this corporate action | | Description|string| | | AnnouncementDate|datetimeoffset|The announcement date of the corporate action | | ExDate|datetimeoffset|The ex date of the corporate action | | RecordDate|datetimeoffset|The record date of the corporate action | | PaymentDate|datetimeoffset|The payment date of the corporate action | | Transitions|corporateactiontransition[]|The transitions that result from this corporate action | ### Transition | Field|Type|Description | | - --|- --|- -- | | InputTransition|corporateactiontransitioncomponent|Indicating the basis of the corporate action - which security and how many units | | OutputTransitions|corporateactiontransitioncomponent[]|What will be generated relative to the input transition | ### Example Corporate Action Transitions #### A Dividend Action Transition In this example, for each share of IBM, 0.20 units (or 20 pence) of GBP are generated. | Column | Input Transition | Output Transition | | - -- -- | - -- -- | - -- -- | | Instrument Identifiers | { \"figi\" : \"BBG000BLNNH6\" } | { \"ccy\" : \"CCY_GBP\" } | | Units Factor | 1 | 0.20 | | Cost Factor | 1 | 0 | #### A Split Action Transition In this example, for each share of IBM, we end up with 2 units (2 shares) of IBM, with total value unchanged. | Column | Input Transition | Output Transition | | - -- -- | - -- -- | - -- -- | | Instrument Identifiers | { \"figi\" : \"BBG000BLNNH6\" } | { \"figi\" : \"BBG000BLNNH6\" } | | Units Factor | 1 | 2 | | Cost Factor | 1 | 1 | #### A Spinoff Action Transition In this example, for each share of IBM, we end up with 1 unit (1 share) of IBM and 3 units (3 shares) of Celestica, with 85% of the value remaining on the IBM share, and 5% in each Celestica share (15% total). | Column | Input Transition | Output Transition 1 | Output Transition 2 | | - -- -- | - -- -- | - -- -- | - -- -- | | Instrument Identifiers | { \"figi\" : \"BBG000BLNNH6\" } | { \"figi\" : \"BBG000BLNNH6\" } | { \"figi\" : \"BBG000HBGRF3\" } | | Units Factor | 1 | 1 | 3 | | Cost Factor | 1 | 0.85 | 0.15 | ## Property Properties are key-value pairs that can be applied to any entity within a domain (where a domain is `trade`, `portfolio`, `security` etc). Properties must be defined before use with a `PropertyDefinition` and can then subsequently be added to entities. # Schemas The following headers are returned on all responses from LUSID | Name | Purpose | | - -- | - -- | | lusid-meta-duration | Duration of the request | | lusid-meta-success | Whether or not LUSID considered the request to be successful | | lusid-meta-requestId | The unique identifier for the request | | lusid-schema-url | Url of the schema for the data being returned | | lusid-property-schema-url | Url of the schema for any properties | # Error Codes | Code|Name|Description | | - --|- --|- -- | | <a name=\"102\">102</a>|VersionNotFound| | | <a name=\"104\">104</a>|InstrumentNotFound| | | <a name=\"105\">105</a>|PropertyNotFound| | | <a name=\"106\">106</a>|PortfolioRecursionDepth| | | <a name=\"108\">108</a>|GroupNotFound| | | <a name=\"109\">109</a>|PortfolioNotFound| | | <a name=\"110\">110</a>|PropertySchemaNotFound| | | <a name=\"111\">111</a>|PortfolioAncestryNotFound| | | <a name=\"112\">112</a>|PortfolioWithIdAlreadyExists| | | <a name=\"113\">113</a>|OrphanedPortfolio| | | <a name=\"119\">119</a>|MissingBaseClaims| | | <a name=\"121\">121</a>|PropertyNotDefined| | | <a name=\"122\">122</a>|CannotDeleteSystemProperty| | | <a name=\"123\">123</a>|CannotModifyImmutablePropertyField| | | <a name=\"124\">124</a>|PropertyAlreadyExists| | | <a name=\"125\">125</a>|InvalidPropertyLifeTime| | | <a name=\"127\">127</a>|CannotModifyDefaultDataType| | | <a name=\"128\">128</a>|GroupAlreadyExists| | | <a name=\"129\">129</a>|NoSuchDataType| | | <a name=\"132\">132</a>|ValidationError| | | <a name=\"133\">133</a>|LoopDetectedInGroupHierarchy| | | <a name=\"135\">135</a>|SubGroupAlreadyExists| | | <a name=\"138\">138</a>|PriceSourceNotFound| | | <a name=\"139\">139</a>|AnalyticStoreNotFound| | | <a name=\"141\">141</a>|AnalyticStoreAlreadyExists| | | <a name=\"143\">143</a>|ClientInstrumentAlreadyExists| | | <a name=\"144\">144</a>|DuplicateInParameterSet| | | <a name=\"147\">147</a>|ResultsNotFound| | | <a name=\"148\">148</a>|OrderFieldNotInResultSet| | | <a name=\"149\">149</a>|OperationFailed| | | <a name=\"150\">150</a>|ElasticSearchError| | | <a name=\"151\">151</a>|InvalidParameterValue| | | <a name=\"153\">153</a>|CommandProcessingFailure| | | <a name=\"154\">154</a>|EntityStateConstructionFailure| | | <a name=\"155\">155</a>|EntityTimelineDoesNotExist| | | <a name=\"156\">156</a>|EventPublishFailure| | | <a name=\"157\">157</a>|InvalidRequestFailure| | | <a name=\"158\">158</a>|EventPublishUnknown| | | <a name=\"159\">159</a>|EventQueryFailure| | | <a name=\"160\">160</a>|BlobDidNotExistFailure| | | <a name=\"162\">162</a>|SubSystemRequestFailure| | | <a name=\"163\">163</a>|SubSystemConfigurationFailure| | | <a name=\"165\">165</a>|FailedToDelete| | | <a name=\"166\">166</a>|UpsertClientInstrumentFailure| | | <a name=\"167\">167</a>|IllegalAsAtInterval| | | <a name=\"168\">168</a>|IllegalBitemporalQuery| | | <a name=\"169\">169</a>|InvalidAlternateId| | | <a name=\"170\">170</a>|CannotAddSourcePortfolioPropertyExplicitly| | | <a name=\"171\">171</a>|EntityAlreadyExistsInGroup| | | <a name=\"173\">173</a>|EntityWithIdAlreadyExists| | | <a name=\"174\">174</a>|DerivedPortfolioDetailsDoNotExist| | | <a name=\"176\">176</a>|PortfolioWithNameAlreadyExists| | | <a name=\"177\">177</a>|InvalidTransactions| | | <a name=\"178\">178</a>|ReferencePortfolioNotFound| | | <a name=\"179\">179</a>|DuplicateIdFailure| | | <a name=\"180\">180</a>|CommandRetrievalFailure| | | <a name=\"181\">181</a>|DataFilterApplicationFailure| | | <a name=\"182\">182</a>|SearchFailed| | | <a name=\"183\">183</a>|MovementsEngineConfigurationKeyFailure| | | <a name=\"184\">184</a>|FxRateSourceNotFound| | | <a name=\"185\">185</a>|AccrualSourceNotFound| | | <a name=\"186\">186</a>|AccessDenied| | | <a name=\"187\">187</a>|InvalidIdentityToken| | | <a name=\"188\">188</a>|InvalidRequestHeaders| | | <a name=\"189\">189</a>|PriceNotFound| | | <a name=\"190\">190</a>|InvalidSubHoldingKeysProvided| | | <a name=\"191\">191</a>|DuplicateSubHoldingKeysProvided| | | <a name=\"192\">192</a>|CutDefinitionNotFound| | | <a name=\"193\">193</a>|CutDefinitionInvalid| | | <a name=\"194\">194</a>|TimeVariantPropertyDeletionDateUnspecified| | | <a name=\"195\">195</a>|PerpetualPropertyDeletionDateSpecified| | | <a name=\"200\">200</a>|InvalidUnitForDataType| | | <a name=\"201\">201</a>|InvalidTypeForDataType| | | <a name=\"202\">202</a>|InvalidValueForDataType| | | <a name=\"203\">203</a>|UnitNotDefinedForDataType| | | <a name=\"204\">204</a>|UnitsNotSupportedOnDataType| | | <a name=\"205\">205</a>|CannotSpecifyUnitsOnDataType| | | <a name=\"206\">206</a>|UnitSchemaInconsistentWithDataType| | | <a name=\"207\">207</a>|UnitDefinitionNotSpecified| | | <a name=\"208\">208</a>|DuplicateUnitDefinitionsSpecified| | | <a name=\"209\">209</a>|InvalidUnitsDefinition| | | <a name=\"210\">210</a>|InvalidInstrumentIdentifierUnit| | | <a name=\"211\">211</a>|HoldingsAdjustmentDoesNotExist| | | <a name=\"212\">212</a>|CouldNotBuildExcelUrl| | | <a name=\"213\">213</a>|CouldNotGetExcelVersion| | | <a name=\"214\">214</a>|InstrumentByCodeNotFound| | | <a name=\"215\">215</a>|EntitySchemaDoesNotExist| | | <a name=\"216\">216</a>|FeatureNotSupportedOnPortfolioType| | | <a name=\"217\">217</a>|QuoteNotFoundFailure| | | <a name=\"218\">218</a>|InvalidQuoteIdentifierFailure| | | <a name=\"219\">219</a>|InvalidInstrumentDefinition| | | <a name=\"221\">221</a>|InstrumentUpsertFailure| | | <a name=\"222\">222</a>|ReferencePortfolioRequestNotSupported| | | <a name=\"223\">223</a>|TransactionPortfolioRequestNotSupported| | | <a name=\"224\">224</a>|InvalidPropertyValueAssignment| | | <a name=\"230\">230</a>|TransactionTypeNotFound| | | <a name=\"231\">231</a>|TransactionTypeDuplication| | | <a name=\"232\">232</a>|PortfolioDoesNotExistAtGivenDate| | | <a name=\"233\">233</a>|QueryParserFailure| | | <a name=\"234\">234</a>|DuplicateConstituentFailure| | | <a name=\"235\">235</a>|UnresolvedInstrumentConstituentFailure| | | <a name=\"236\">236</a>|UnresolvedInstrumentInTransitionFailure| | | <a name=\"300\">300</a>|MissingRecipeFailure| | | <a name=\"301\">301</a>|DependenciesFailure| | | <a name=\"304\">304</a>|PortfolioPreprocessFailure| | | <a name=\"310\">310</a>|ValuationEngineFailure| | | <a name=\"311\">311</a>|TaskFactoryFailure| | | <a name=\"312\">312</a>|TaskEvaluationFailure| | | <a name=\"350\">350</a>|InstrumentFailure| | | <a name=\"351\">351</a>|CashFlowsFailure| | | <a name=\"360\">360</a>|AggregationFailure| | | <a name=\"370\">370</a>|ResultRetrievalFailure| | | <a name=\"371\">371</a>|ResultProcessingFailure| | | <a name=\"371\">371</a>|ResultProcessingFailure| | | <a name=\"372\">372</a>|VendorResultProcessingFailure| | | <a name=\"373\">373</a>|VendorResultMappingFailure| | | <a name=\"374\">374</a>|VendorLibraryUnauthorisedFailure| | | <a name=\"390\">390</a>|AttemptToUpsertDuplicateQuotes| | | <a name=\"391\">391</a>|CorporateActionSourceDoesNotExist| | | <a name=\"392\">392</a>|CorporateActionSourceAlreadyExists| | | <a name=\"393\">393</a>|InstrumentIdentifierAlreadyInUse| | | <a name=\"394\">394</a>|PropertiesNotFound| | | <a name=\"395\">395</a>|BatchOperationAborted| | | <a name=\"400\">400</a>|InvalidIso4217CurrencyCodeFailure| | | <a name=\"410\">410</a>|IndexDoesNotExist| | | <a name=\"411\">411</a>|SortFieldDoesNotExist| | | <a name=\"413\">413</a>|NegativePaginationParameters| | | <a name=\"414\">414</a>|InvalidSearchSyntax| | | <a name=\"-10\">-10</a>|ServerConfigurationError| | | <a name=\"-1\">-1</a>|Unknown error| | * * The version of the OpenAPI document: 0.10.730 * Contact: info@finbourne.com * Generated by: https://github.com/openapitools/openapi-generator.git */ using System; using System.Linq; using System.IO; using System.Text; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using OpenAPIDateConverter = Lusid.Sdk.Client.OpenAPIDateConverter; namespace Lusid.Sdk.Model { /// <summary> /// A reconciliation break /// </summary> [DataContract] public partial class ReconciliationBreak : IEquatable<ReconciliationBreak> { /// <summary> /// Initializes a new instance of the <see cref="ReconciliationBreak" /> class. /// </summary> [JsonConstructorAttribute] protected ReconciliationBreak() { } /// <summary> /// Initializes a new instance of the <see cref="ReconciliationBreak" /> class. /// </summary> /// <param name="instrumentUid">Unique instrument identifier (required).</param> /// <param name="subHoldingKeys">Any other properties that comprise the Sub-Holding Key (required).</param> /// <param name="leftUnits">Units from the left hand side (required).</param> /// <param name="rightUnits">Units from the right hand side (required).</param> /// <param name="differenceUnits">Difference in units (required).</param> /// <param name="leftCost">leftCost (required).</param> /// <param name="rightCost">rightCost (required).</param> /// <param name="differenceCost">differenceCost (required).</param> /// <param name="instrumentProperties">Additional features relating to the instrument (required).</param> public ReconciliationBreak(string instrumentUid = default(string), Dictionary<string, PerpetualProperty> subHoldingKeys = default(Dictionary<string, PerpetualProperty>), double? leftUnits = default(double?), double? rightUnits = default(double?), double? differenceUnits = default(double?), CurrencyAndAmount leftCost = default(CurrencyAndAmount), CurrencyAndAmount rightCost = default(CurrencyAndAmount), CurrencyAndAmount differenceCost = default(CurrencyAndAmount), List<Property> instrumentProperties = default(List<Property>)) { // to ensure "instrumentUid" is required (not null) if (instrumentUid == null) { throw new InvalidDataException("instrumentUid is a required property for ReconciliationBreak and cannot be null"); } else { this.InstrumentUid = instrumentUid; } // to ensure "subHoldingKeys" is required (not null) if (subHoldingKeys == null) { throw new InvalidDataException("subHoldingKeys is a required property for ReconciliationBreak and cannot be null"); } else { this.SubHoldingKeys = subHoldingKeys; } // to ensure "leftUnits" is required (not null) if (leftUnits == null) { throw new InvalidDataException("leftUnits is a required property for ReconciliationBreak and cannot be null"); } else { this.LeftUnits = leftUnits; } // to ensure "rightUnits" is required (not null) if (rightUnits == null) { throw new InvalidDataException("rightUnits is a required property for ReconciliationBreak and cannot be null"); } else { this.RightUnits = rightUnits; } // to ensure "differenceUnits" is required (not null) if (differenceUnits == null) { throw new InvalidDataException("differenceUnits is a required property for ReconciliationBreak and cannot be null"); } else { this.DifferenceUnits = differenceUnits; } // to ensure "leftCost" is required (not null) if (leftCost == null) { throw new InvalidDataException("leftCost is a required property for ReconciliationBreak and cannot be null"); } else { this.LeftCost = leftCost; } // to ensure "rightCost" is required (not null) if (rightCost == null) { throw new InvalidDataException("rightCost is a required property for ReconciliationBreak and cannot be null"); } else { this.RightCost = rightCost; } // to ensure "differenceCost" is required (not null) if (differenceCost == null) { throw new InvalidDataException("differenceCost is a required property for ReconciliationBreak and cannot be null"); } else { this.DifferenceCost = differenceCost; } // to ensure "instrumentProperties" is required (not null) if (instrumentProperties == null) { throw new InvalidDataException("instrumentProperties is a required property for ReconciliationBreak and cannot be null"); } else { this.InstrumentProperties = instrumentProperties; } } /// <summary> /// Unique instrument identifier /// </summary> /// <value>Unique instrument identifier</value> [DataMember(Name="instrumentUid", EmitDefaultValue=false)] public string InstrumentUid { get; set; } /// <summary> /// Any other properties that comprise the Sub-Holding Key /// </summary> /// <value>Any other properties that comprise the Sub-Holding Key</value> [DataMember(Name="subHoldingKeys", EmitDefaultValue=false)] public Dictionary<string, PerpetualProperty> SubHoldingKeys { get; set; } /// <summary> /// Units from the left hand side /// </summary> /// <value>Units from the left hand side</value> [DataMember(Name="leftUnits", EmitDefaultValue=false)] public double? LeftUnits { get; set; } /// <summary> /// Units from the right hand side /// </summary> /// <value>Units from the right hand side</value> [DataMember(Name="rightUnits", EmitDefaultValue=false)] public double? RightUnits { get; set; } /// <summary> /// Difference in units /// </summary> /// <value>Difference in units</value> [DataMember(Name="differenceUnits", EmitDefaultValue=false)] public double? DifferenceUnits { get; set; } /// <summary> /// Gets or Sets LeftCost /// </summary> [DataMember(Name="leftCost", EmitDefaultValue=false)] public CurrencyAndAmount LeftCost { get; set; } /// <summary> /// Gets or Sets RightCost /// </summary> [DataMember(Name="rightCost", EmitDefaultValue=false)] public CurrencyAndAmount RightCost { get; set; } /// <summary> /// Gets or Sets DifferenceCost /// </summary> [DataMember(Name="differenceCost", EmitDefaultValue=false)] public CurrencyAndAmount DifferenceCost { get; set; } /// <summary> /// Additional features relating to the instrument /// </summary> /// <value>Additional features relating to the instrument</value> [DataMember(Name="instrumentProperties", EmitDefaultValue=false)] public List<Property> InstrumentProperties { 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 ReconciliationBreak {\n"); sb.Append(" InstrumentUid: ").Append(InstrumentUid).Append("\n"); sb.Append(" SubHoldingKeys: ").Append(SubHoldingKeys).Append("\n"); sb.Append(" LeftUnits: ").Append(LeftUnits).Append("\n"); sb.Append(" RightUnits: ").Append(RightUnits).Append("\n"); sb.Append(" DifferenceUnits: ").Append(DifferenceUnits).Append("\n"); sb.Append(" LeftCost: ").Append(LeftCost).Append("\n"); sb.Append(" RightCost: ").Append(RightCost).Append("\n"); sb.Append(" DifferenceCost: ").Append(DifferenceCost).Append("\n"); sb.Append(" InstrumentProperties: ").Append(InstrumentProperties).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 virtual 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 ReconciliationBreak); } /// <summary> /// Returns true if ReconciliationBreak instances are equal /// </summary> /// <param name="input">Instance of ReconciliationBreak to be compared</param> /// <returns>Boolean</returns> public bool Equals(ReconciliationBreak input) { if (input == null) return false; return ( this.InstrumentUid == input.InstrumentUid || (this.InstrumentUid != null && this.InstrumentUid.Equals(input.InstrumentUid)) ) && ( this.SubHoldingKeys == input.SubHoldingKeys || this.SubHoldingKeys != null && input.SubHoldingKeys != null && this.SubHoldingKeys.SequenceEqual(input.SubHoldingKeys) ) && ( this.LeftUnits == input.LeftUnits || (this.LeftUnits != null && this.LeftUnits.Equals(input.LeftUnits)) ) && ( this.RightUnits == input.RightUnits || (this.RightUnits != null && this.RightUnits.Equals(input.RightUnits)) ) && ( this.DifferenceUnits == input.DifferenceUnits || (this.DifferenceUnits != null && this.DifferenceUnits.Equals(input.DifferenceUnits)) ) && ( this.LeftCost == input.LeftCost || (this.LeftCost != null && this.LeftCost.Equals(input.LeftCost)) ) && ( this.RightCost == input.RightCost || (this.RightCost != null && this.RightCost.Equals(input.RightCost)) ) && ( this.DifferenceCost == input.DifferenceCost || (this.DifferenceCost != null && this.DifferenceCost.Equals(input.DifferenceCost)) ) && ( this.InstrumentProperties == input.InstrumentProperties || this.InstrumentProperties != null && input.InstrumentProperties != null && this.InstrumentProperties.SequenceEqual(input.InstrumentProperties) ); } /// <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.InstrumentUid != null) hashCode = hashCode * 59 + this.InstrumentUid.GetHashCode(); if (this.SubHoldingKeys != null) hashCode = hashCode * 59 + this.SubHoldingKeys.GetHashCode(); if (this.LeftUnits != null) hashCode = hashCode * 59 + this.LeftUnits.GetHashCode(); if (this.RightUnits != null) hashCode = hashCode * 59 + this.RightUnits.GetHashCode(); if (this.DifferenceUnits != null) hashCode = hashCode * 59 + this.DifferenceUnits.GetHashCode(); if (this.LeftCost != null) hashCode = hashCode * 59 + this.LeftCost.GetHashCode(); if (this.RightCost != null) hashCode = hashCode * 59 + this.RightCost.GetHashCode(); if (this.DifferenceCost != null) hashCode = hashCode * 59 + this.DifferenceCost.GetHashCode(); if (this.InstrumentProperties != null) hashCode = hashCode * 59 + this.InstrumentProperties.GetHashCode(); return hashCode; } } } }
112.143284
23,815
0.660961
[ "MIT" ]
timbarrass/lusid-sdk-csharp
sdk/Lusid.Sdk/Model/ReconciliationBreak.cs
37,568
C#
using System; using System.Collections.Generic; using JustSaying.AwsTools; using JustSaying.AwsTools.QueueCreation; using JustSaying.Messaging.Channels.SubscriptionGroups; using JustSaying.Models; using Microsoft.Extensions.Logging; namespace JustSaying.Fluent { /// <summary> /// A class representing a builder for subscriptions. This class cannot be inherited. /// </summary> public sealed class SubscriptionsBuilder { /// <summary> /// Initializes a new instance of the <see cref="SubscriptionsBuilder"/> class. /// </summary> /// <param name="parent">The <see cref="MessagingBusBuilder"/> that owns this instance.</param> internal SubscriptionsBuilder(MessagingBusBuilder parent) { Parent = parent; } /// <summary> /// Gets the parent of this builder. /// </summary> internal MessagingBusBuilder Parent { get; } internal SubscriptionGroupSettingsBuilder Defaults = new SubscriptionGroupSettingsBuilder(); /// <summary> /// Gets the configured subscription builders. /// </summary> private IList<ISubscriptionBuilder<Message>> Subscriptions { get; } = new List<ISubscriptionBuilder<Message>>(); private IDictionary<string, SubscriptionGroupConfigBuilder> SubscriptionGroupSettings { get; } = new Dictionary<string, SubscriptionGroupConfigBuilder>(); /// <summary> /// Configure the default settings for all subscription groups. /// </summary> /// <param name="configure">A delegate that configures the default settings.</param> /// <returns> /// The current <see cref="SubscriptionsBuilder"/>. /// </returns> /// <exception cref="ArgumentNullException"> /// <paramref name="configure"/> is <see langword="null"/>. /// </exception> public SubscriptionsBuilder WithDefaults(Action<SubscriptionGroupSettingsBuilder> configure) { if (configure == null) throw new ArgumentNullException(nameof(configure)); configure(Defaults); return this; } /// <summary> /// Configures a queue subscription for the default queue. /// </summary> /// <typeparam name="T">The type of the message to subscribe to.</typeparam> /// <returns> /// The current <see cref="SubscriptionsBuilder"/>. /// </returns> public SubscriptionsBuilder ForQueue<T>() where T : Message { return ForQueue<T>((p) => p.WithDefaultQueue()); } /// <summary> /// Configures a queue subscription. /// </summary> /// <typeparam name="T">The type of the message to subscribe to.</typeparam> /// <param name="configure">A delegate to a method to use to configure a queue subscription.</param> /// <returns> /// The current <see cref="SubscriptionsBuilder"/>. /// </returns> /// <exception cref="ArgumentNullException"> /// <paramref name="configure"/> is <see langword="null"/>. /// </exception> public SubscriptionsBuilder ForQueue<T>(Action<QueueSubscriptionBuilder<T>> configure) where T : Message { if (configure == null) throw new ArgumentNullException(nameof(configure)); var builder = new QueueSubscriptionBuilder<T>(); configure(builder); Subscriptions.Add(builder); return this; } /// <summary> /// Configures a queue subscription for a pre-existing queue. /// </summary> /// <param name="queueArn">The ARN of the queue to subscribe to.</param> /// <param name="configure">An optional delegate to configure a queue subscription.</param> /// <typeparam name="T">The type of the message to subscribe to.</typeparam> /// <returns>The current <see cref="SubscriptionsBuilder"/>.</returns> public SubscriptionsBuilder ForQueueArn<T>(string queueArn, Action<QueueAddressSubscriptionBuilder<T>> configure = null) where T : Message { if (queueArn == null) throw new ArgumentNullException(nameof(queueArn)); var queueAddress = QueueAddress.FromArn(queueArn); var builder = new QueueAddressSubscriptionBuilder<T>(queueAddress); configure?.Invoke(builder); Subscriptions.Add(builder); return this; } /// <summary> /// Configures a queue subscription for a pre-existing queue. /// </summary> /// <param name="queueUrl">The URL of the queue to subscribe to.</param> /// <param name="regionName">The AWS region the queue is in.</param> /// <param name="configure">An optional delegate to configure a queue subscription.</param> /// <typeparam name="T">The type of the message to subscribe to.</typeparam> /// <returns>The current <see cref="SubscriptionsBuilder"/>.</returns> public SubscriptionsBuilder ForQueueUrl<T>(string queueUrl, string regionName = null, Action<QueueAddressSubscriptionBuilder<T>> configure = null) where T : Message { if (queueUrl == null) throw new ArgumentNullException(nameof(queueUrl)); var queueAddress = QueueAddress.FromUrl(queueUrl, regionName); var builder = new QueueAddressSubscriptionBuilder<T>(queueAddress); configure?.Invoke(builder); Subscriptions.Add(builder); return this; } /// <summary> /// Configures a queue subscription for a pre-existing queue. /// </summary> /// <param name="queueUrl">The URL of the queue to subscribe to.</param> /// <param name="regionName">The AWS region the queue is in.</param> /// <param name="configure">An optional delegate to configure a queue subscription.</param> /// <typeparam name="T">The type of the message to subscribe to.</typeparam> /// <returns>The current <see cref="SubscriptionsBuilder"/>.</returns> public SubscriptionsBuilder ForQueueUri<T>(Uri queueUrl, string regionName = null, Action<QueueAddressSubscriptionBuilder<T>> configure = null) where T : Message { if (queueUrl == null) throw new ArgumentNullException(nameof(queueUrl)); var queueAddress = QueueAddress.FromUri(queueUrl, regionName); var builder = new QueueAddressSubscriptionBuilder<T>(queueAddress); configure?.Invoke(builder); Subscriptions.Add(builder); return this; } /// <summary> /// Configures a topic subscription for the default topic name. /// </summary> /// <typeparam name="T">The type of the message to subscribe to.</typeparam> /// <returns> /// The current <see cref="SubscriptionsBuilder"/>. /// </returns> public SubscriptionsBuilder ForTopic<T>() where T : Message { return ForTopic<T>((p) => p.IntoDefaultTopic()); } /// <summary> /// Configures a topic subscription. /// </summary> /// <typeparam name="T">The type of the message to subscribe to.</typeparam> /// <param name="configure">A delegate to a method to use to configure a topic subscription.</param> /// <returns> /// The current <see cref="SubscriptionsBuilder"/>. /// </returns> /// <exception cref="ArgumentNullException"> /// <paramref name="configure"/> is <see langword="null"/>. /// </exception> public SubscriptionsBuilder ForTopic<T>(Action<TopicSubscriptionBuilder<T>> configure) where T : Message { if (configure == null) throw new ArgumentNullException(nameof(configure)); var builder = new TopicSubscriptionBuilder<T>(); configure(builder); Subscriptions.Add(builder); return this; } /// <summary> /// Configures the subscriptions for the <see cref="JustSayingBus"/>. /// </summary> /// <param name="bus">The <see cref="JustSayingBus"/> to configure subscriptions for.</param> /// <param name="serviceResolver">The <see cref="IServiceResolver"/> to use to resolve middleware with</param> /// <param name="creator">The <see cref="IVerifyAmazonQueues"/>to use to create queues with.</param> /// <param name="awsClientFactoryProxy">The <see cref="IAwsClientFactoryProxy"/> to use to create SQS/SNS clients with.</param> /// <param name="loggerFactory">The <see cref="ILoggerFactory"/>logger factory to use.</param> /// <exception cref="InvalidOperationException"> /// No instance of <see cref="IHandlerResolver"/> could be resolved. /// </exception> internal void Configure( JustSayingBus bus, IServiceResolver serviceResolver, IVerifyAmazonQueues creator, IAwsClientFactoryProxy awsClientFactoryProxy, ILoggerFactory loggerFactory) { var resolver = Parent.ServicesBuilder?.HandlerResolver?.Invoke() ?? Parent.ServiceResolver.ResolveService<IHandlerResolver>(); if (resolver == null) { throw new InvalidOperationException($"No {nameof(IHandlerResolver)} is registered."); } Defaults.Validate(); bus.SetGroupSettings(Defaults, SubscriptionGroupSettings); foreach (ISubscriptionBuilder<Message> builder in Subscriptions) { builder.Configure(bus, resolver, serviceResolver, creator, awsClientFactoryProxy, loggerFactory); } } /// <summary> /// Adds or updates SubscriptionGroup configuration. /// </summary> /// <param name="groupName">The name of the group to update.</param> /// <param name="action">The update action to apply to the configuration.</param> /// <returns> /// The current <see cref="SubscriptionsBuilder"/>. /// </returns> public SubscriptionsBuilder WithSubscriptionGroup( string groupName, Action<SubscriptionGroupConfigBuilder> action) { if (string.IsNullOrEmpty(groupName)) throw new ArgumentException("Cannot be null or empty.", nameof(groupName)); if (action == null) throw new ArgumentNullException(nameof(action)); if (SubscriptionGroupSettings.TryGetValue(groupName, out var settings)) { action.Invoke(settings); } else { var newSettings = new SubscriptionGroupConfigBuilder(groupName); action.Invoke(newSettings); SubscriptionGroupSettings.Add(groupName, newSettings); } return this; } } }
41.605263
154
0.612994
[ "Apache-2.0" ]
afrazhm/JustSaying
src/JustSaying/Fluent/SubscriptionsBuilder.cs
11,067
C#
using Sharpen; namespace org.apache.http.client.protocol { [Sharpen.NakedStub] public interface ClientContext { } [Sharpen.NakedStub] public abstract class ClientContextClass { } }
12.733333
41
0.759162
[ "Apache-2.0" ]
Conceptengineai/XobotOS
android/naked-stubs/org/apache/http/client/protocol/ClientContext.cs
191
C#
using cqhttp.WebSocketReverse.NETCore.Interface; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Text.Json.Serialization; using System.Threading.Tasks; namespace cqhttp.WebSocketReverse.NETCore.Model.Params { /// <summary> /// 群组全员禁言 /// </summary> internal class SetGroupWholeBanParams : IParams { /// <summary> /// 群号 /// </summary> [JsonPropertyName("group_id")] public long GroupId { get; set; } /// <summary> /// 是否禁言 /// </summary> [JsonPropertyName("enable")] public bool Enable { get; set; } } }
22.827586
54
0.613293
[ "MIT" ]
cqbef/cqhttp.WebSocketReverse.NETCore
src/Model/Param/SetGroupWholeBanParams.cs
688
C#
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Threading.Tasks; using RoleBasedMenu.Data; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; namespace RoleBasedMenu.Controllers { public class ProfileController : Controller { private readonly UserManager<ApplicationUser> _userManager; private readonly SignInManager<ApplicationUser> _signInManager; private readonly ILogger<ProfileController> _logger; public ProfileController(UserManager<ApplicationUser> userManager, SignInManager<ApplicationUser> signInManager, ILogger<ProfileController> logger) { _userManager = userManager; _signInManager = signInManager; _logger = logger; } private ApplicationUser _currentUser; public ApplicationUser CurrentUser { get { if (_currentUser == null) { var user = _userManager.GetUserAsync(User); if (user == null) { throw new ApplicationException($"Unable to load user with ID '{_userManager.GetUserId(User)}'."); } _currentUser = user.Result; } return _currentUser; } } public bool IsEmailConfirmed { get { return _userManager.IsEmailConfirmedAsync(CurrentUser).Result; } } public bool IsHasPassword { get { return _userManager.HasPasswordAsync(CurrentUser).Result; } } public class ChangePasswordInput { [Required] [DataType(DataType.Password)] [Display(Name = "Current password")] public string OldPassword { get; set; } [Required] [StringLength(100, ErrorMessage = "The {0} must be at least {2} and at max {1} characters long.", MinimumLength = 6)] [DataType(DataType.Password)] [Display(Name = "New password")] public string NewPassword { get; set; } [DataType(DataType.Password)] [Display(Name = "Confirm new password")] [Compare("NewPassword", ErrorMessage = "The new password and confirmation password do not match.")] public string ConfirmPassword { get; set; } } [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> ChangePassword(ChangePasswordInput model) { if (!ModelState.IsValid) { return BadRequest(ModelState); } var changePasswordResult = await _userManager.ChangePasswordAsync(CurrentUser, model.OldPassword, model.NewPassword); if (!changePasswordResult.Succeeded) { foreach (var error in changePasswordResult.Errors) { ModelState.AddModelError(string.Empty, error.Description); } return BadRequest(ModelState); } await _signInManager.SignInAsync(CurrentUser, isPersistent: false); _logger.LogInformation("User changed their password successfully."); return Ok("Your password has been changed."); } public class SetPasswordInput { [Required] [StringLength(100, ErrorMessage = "The {0} must be at least {2} and at max {1} characters long.", MinimumLength = 6)] [DataType(DataType.Password)] [Display(Name = "New password")] public string NewPassword { get; set; } [DataType(DataType.Password)] [Display(Name = "Confirm new password")] [Compare("NewPassword", ErrorMessage = "The new password and confirmation password do not match.")] public string ConfirmPassword { get; set; } } [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> SetPassword(SetPasswordInput model) { if (!ModelState.IsValid) { return BadRequest(ModelState); } var addPasswordResult = await _userManager.AddPasswordAsync(CurrentUser, model.NewPassword); if (!addPasswordResult.Succeeded) { foreach (var error in addPasswordResult.Errors) { ModelState.AddModelError(string.Empty, error.Description); } return BadRequest(ModelState); } await _signInManager.SignInAsync(CurrentUser, isPersistent: false); _logger.LogInformation("User set password successfully."); return Ok("Your password has been set."); } } }
34.616438
155
0.581717
[ "MIT" ]
SyedMdKamruzzaman/AdminLTE-dynamic-Menu-from-Database
src/Controllers/ProfileController.cs
5,056
C#
// Python Tools for Visual Studio // Copyright(c) Microsoft Corporation // All rights reserved. // // Licensed under the Apache License, Version 2.0 (the License); you may not use // this file except in compliance with the License. You may obtain a copy of the // License at http://www.apache.org/licenses/LICENSE-2.0 // // THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS // OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY // IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, // MERCHANTABLITY OR NON-INFRINGEMENT. // // See the Apache Version 2.0 License for specific language governing // permissions and limitations under the License. using System; using System.Windows.Forms; using Microsoft.PythonTools.Parsing; namespace Microsoft.PythonTools.Options { public partial class PythonGeneralOptionsControl : UserControl { private const int ErrorIndex = 0; private const int WarningIndex = 1; private const int DontIndex = 2; public PythonGeneralOptionsControl() { InitializeComponent(); } internal Severity IndentationInconsistencySeverity { get { switch (_indentationInconsistentCombo.SelectedIndex) { case ErrorIndex: return Severity.Error; case WarningIndex: return Severity.Warning; case DontIndex: return Severity.Ignore; default: return Severity.Ignore; } } set { switch (value) { case Severity.Error: _indentationInconsistentCombo.SelectedIndex = ErrorIndex; break; case Severity.Warning: _indentationInconsistentCombo.SelectedIndex = WarningIndex; break; default: _indentationInconsistentCombo.SelectedIndex = DontIndex; break; } } } internal void SyncControlWithPageSettings(PythonToolsService pyService) { _showOutputWindowForVirtualEnvCreate.Checked = pyService.GeneralOptions.ShowOutputWindowForVirtualEnvCreate; _showOutputWindowForPackageInstallation.Checked = pyService.GeneralOptions.ShowOutputWindowForPackageInstallation; _elevatePip.Checked = pyService.GeneralOptions.ElevatePip; _updateSearchPathsForLinkedFiles.Checked = pyService.GeneralOptions.UpdateSearchPathsWhenAddingLinkedFiles; _unresolvedImportWarning.Checked = pyService.GeneralOptions.UnresolvedImportWarning; _invalidEncodingWarning.Checked = pyService.GeneralOptions.InvalidEncodingWarning; _clearGlobalPythonPath.Checked = pyService.GeneralOptions.ClearGlobalPythonPath; IndentationInconsistencySeverity = pyService.GeneralOptions.IndentationInconsistencySeverity; } internal void SyncPageWithControlSettings(PythonToolsService pyService) { pyService.GeneralOptions.ShowOutputWindowForVirtualEnvCreate = _showOutputWindowForVirtualEnvCreate.Checked; pyService.GeneralOptions.ShowOutputWindowForPackageInstallation = _showOutputWindowForPackageInstallation.Checked; pyService.GeneralOptions.ElevatePip = _elevatePip.Checked; pyService.GeneralOptions.UpdateSearchPathsWhenAddingLinkedFiles = _updateSearchPathsForLinkedFiles.Checked; pyService.GeneralOptions.IndentationInconsistencySeverity = IndentationInconsistencySeverity; pyService.GeneralOptions.UnresolvedImportWarning = _unresolvedImportWarning.Checked; pyService.GeneralOptions.InvalidEncodingWarning = _invalidEncodingWarning.Checked; pyService.GeneralOptions.ClearGlobalPythonPath = _clearGlobalPythonPath.Checked; } private void _resetSuppressDialog_Click(object sender, EventArgs e) { System.Diagnostics.Debug.Assert(ResetSuppressDialog != null, "No listener for ResetSuppressDialog event"); ResetSuppressDialog?.Invoke(this, EventArgs.Empty); } public event EventHandler ResetSuppressDialog; } }
49.258427
126
0.684535
[ "Apache-2.0" ]
113771169/PTVS
Python/Product/PythonTools/PythonTools/Options/PythonGeneralOptionsControl.cs
4,384
C#
using System; using System.Xml.Serialization; using System.ComponentModel.DataAnnotations; using BroadWorksConnector.Ocip.Validation; using System.Collections.Generic; namespace BroadWorksConnector.Ocip.Models { /// <summary> /// This is the configuration parameters for Speed Dial 8 service /// </summary> [Serializable] [XmlRoot(Namespace = "")] [Groups(@"[{""__type"":""Sequence:#BroadWorksConnector.Ocip.Validation"",""id"":""53d18cc797d03d802cbc411ad821f1d4:4385""}]")] public class ProfileAndServiceSpeedDial8Info { private List<BroadWorksConnector.Ocip.Models.SpeedDial8Entry> _speedDialEntry = new List<BroadWorksConnector.Ocip.Models.SpeedDial8Entry>(); [XmlElement(ElementName = "speedDialEntry", IsNullable = false, Namespace = "")] [Optional] [Group(@"53d18cc797d03d802cbc411ad821f1d4:4385")] public List<BroadWorksConnector.Ocip.Models.SpeedDial8Entry> SpeedDialEntry { get => _speedDialEntry; set { SpeedDialEntrySpecified = true; _speedDialEntry = value; } } [XmlIgnore] protected bool SpeedDialEntrySpecified { get; set; } } }
31.717949
148
0.667745
[ "MIT" ]
JTOne123/broadworks-connector-net
BroadworksConnector/Ocip/Models/ProfileAndServiceSpeedDial8Info.cs
1,237
C#
using System; namespace csharptest { class Program { static void Main(string[] args) { Console.WriteLine("Hello World!"); Console.WriteLine("perfect world"); Console.WriteLine("Just an inicial comment"); } } }
19.866667
58
0.52349
[ "MIT" ]
vglarra/csharptest
Program.cs
300
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Cinema { class Program { static void Main(string[] args) { var type = Console.ReadLine().ToLower(); int r = int.Parse(Console.ReadLine()); int c = int.Parse(Console.ReadLine()); switch(type) { case "premiere": Console.WriteLine("{0:f2}" + "leva", r*c*12.00); break; case "normal": Console.WriteLine("{0:f2}" + "leva", r * c * 7.50); break; case "discount": Console.WriteLine("{0:f2}" + "leva", r * c * 5.00); break; } } } }
28.32
91
0.526836
[ "MIT" ]
CaptainUltra/IT-Career-Course
Year 1/Module 1 - Programming Fundamentals/IFovi/Cinema/Program.cs
710
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. namespace Microsoft.Graph { using System; using System.Collections.Generic; using System.IO; using System.Net.Http; using System.Threading; /// <summary> /// The interface IWorkbookFunctionsTbillEqRequest. /// </summary> public partial interface IWorkbookFunctionsTbillEqRequest : IBaseRequest { /// <summary> /// Gets the request body. /// </summary> WorkbookFunctionsTbillEqRequestBody RequestBody { get; } /// <summary> /// Issues the POST request. /// </summary> System.Threading.Tasks.Task<WorkbookFunctionResult> PostAsync(); /// <summary> /// Issues the POST request. /// </summary> /// <param name=""cancellationToken"">The <see cref=""CancellationToken""/> for the request.</param> /// <returns>The task to await for async call.</returns> System.Threading.Tasks.Task<WorkbookFunctionResult> PostAsync( CancellationToken cancellationToken); /// <summary> /// Adds the specified expand value to the request. /// </summary> /// <param name="value">The expand value.</param> /// <returns>The request object to send.</returns> IWorkbookFunctionsTbillEqRequest Expand(string value); /// <summary> /// Adds the specified select value to the request. /// </summary> /// <param name="value">The select value.</param> /// <returns>The request object to send.</returns> IWorkbookFunctionsTbillEqRequest Select(string value); } }
33.032787
153
0.578164
[ "MIT" ]
twsouthwick/msgraph-sdk-dotnet
src/Microsoft.Graph/Requests/Generated/IWorkbookFunctionsTbillEqRequest.cs
2,015
C#
using System.Reflection; using System.Runtime.InteropServices; [assembly: AssemblyTitle("Velyo.Web.Extensions")] [assembly: AssemblyDescription("Extension methods for some System.Web classes.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Velio Ivanov http://velyo.net")] [assembly: AssemblyProduct(".NET Extension Methods")] [assembly: AssemblyCopyright("Copyright © Velyo 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] [assembly: Guid("e33d76b7-9557-40cf-bad3-7758271ee683")] [assembly: AssemblyVersion("1.0.*")]
33.277778
81
0.766277
[ "MIT" ]
velio/dotnet-extensions
src/Velyo.Web.Extensions/Properties/AssemblyInfo.cs
602
C#
using System.Collections.Generic; using UnityEngine; namespace ReginaGameDev.Models { [System.Serializable] public class RandomWordStorage { public List<string> Adjectives; public List<string> Nouns; public string GetRandomAdjective() { return Adjectives[Random.Range(0, Adjectives.Count)]; } public string GetRandomNoun() { return Nouns[Random.Range(0, Nouns.Count)]; } } }
21.909091
65
0.616183
[ "Apache-2.0" ]
Othaur/Project-1
Tomatoes/Assets/Scripts/Models/RandomWordStorage.cs
484
C#
using System.IO; using ProtoBuf; namespace ExpertFunicular.Common.Serializers { public class FunicularProtobufSerializer : IFunicularSerializer { public byte[] Serialize<TMessage>(TMessage message) where TMessage : class { using var memoryStream = new MemoryStream(); Serializer.Serialize(memoryStream, message); return memoryStream.ToArray(); } public byte[] Serialize(object message) { using var memoryStream = new MemoryStream(); Serializer.Serialize(memoryStream, message); return memoryStream.ToArray(); } } }
29.454545
82
0.637346
[ "MIT" ]
aroman35/expert-funicular
ExpertFunicular.Common/Serializers/FunicularProtobufSerializer.cs
648
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.Compute.V20190301.Outputs { [OutputType] public sealed class TargetRegionResponse { /// <summary> /// The name of the region. /// </summary> public readonly string Name; /// <summary> /// The number of replicas of the Image Version to be created per region. This property is updatable. /// </summary> public readonly int? RegionalReplicaCount; /// <summary> /// Specifies the storage account type to be used to store the image. This property is not updatable. /// </summary> public readonly string? StorageAccountType; [OutputConstructor] private TargetRegionResponse( string name, int? regionalReplicaCount, string? storageAccountType) { Name = name; RegionalReplicaCount = regionalReplicaCount; StorageAccountType = storageAccountType; } } }
30.046512
109
0.636997
[ "Apache-2.0" ]
pulumi-bot/pulumi-azure-native
sdk/dotnet/Compute/V20190301/Outputs/TargetRegionResponse.cs
1,292
C#
namespace PCMarket.Data.Interfaces { public interface INewsUnitOfWork : IUnitOfWork { ISoftwareNewRepository SoftwareNews { get; } IHardwareNewRepository HardwareNews { get; } } }
23.222222
52
0.698565
[ "MIT" ]
kraskoo/PCMarket
PCMarket/PCMarket.Data/Interfaces/INewsUnitOfWork.cs
211
C#
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Threading.Tasks; namespace DapperDino.Models.ManageViewModels { public class IndexViewModel { public string Username { get; set; } public bool IsEmailConfirmed { get; set; } [Required] [EmailAddress] public string Email { get; set; } [Phone] [Display(Name = "Phone number")] public string PhoneNumber { get; set; } public string StatusMessage { get; set; } public string DiscordId { get; set; } public string DiscordUsername { get; set; } public int Level { get; set; } public int Xp { get; set; } public bool IsDiscordConfirmed { get; set; } [Display(Name ="Discord Connect Code")] public Guid DiscordRegistrationCode { get; internal set; } } }
26.257143
66
0.632209
[ "MIT" ]
DapperCoding/DapperDino-Website
DapperDino.Web/Models/ManageViewModels/IndexViewModel.cs
921
C#
using Newtonsoft.Json; namespace Magicodes.Wx.PublicAccount.Sdk.Apis.Guide.Dtos { public class GetGuideMassendJobInput { /// <summary> /// 任务id /// </summary> [JsonProperty("task_id")] public int TaskId { get; set; } } }
21.076923
56
0.583942
[ "MIT" ]
xin-lai/Magicodes.Wx.Sdk
src/Magicodes.Wx.PublicAccount.Sdk/Apis/Guide/Dtos/GetGuideMassendJobInput.cs
280
C#
using System; namespace JenkinsTryOut.Authentication.External { public class ExternalLoginProviderInfo { public string Name { get; set; } public string ClientId { get; set; } public string ClientSecret { get; set; } public Type ProviderApiType { get; set; } public ExternalLoginProviderInfo(string name, string clientId, string clientSecret, Type providerApiType) { Name = name; ClientId = clientId; ClientSecret = clientSecret; ProviderApiType = providerApiType; } } }
24.666667
113
0.625
[ "MIT" ]
kgamab/jenkins-demo
aspnet-core/src/JenkinsTryOut.Web.Core/Authentication/External/ExternalLoginProviderInfo.cs
594
C#
/// <summary> /// The MIT License (MIT) /// /// Copyright (c) 2014-2016 Marc de Verdelhan & respective authors (see AUTHORS) /// /// 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. /// </summary> using TA4N.Test.FixtureData; namespace TA4N.Test.Indicators.Oscillators { using NUnit.Framework; using TA4N.Indicators.Simple; using TA4N.Indicators.Oscillators; public sealed class CmoIndicatorTest { private TimeSeries _series; [SetUp] public void SetUp() { _series = GenerateTimeSeries.From(21.27, 22.19, 22.08, 22.47, 22.48, 22.53, 22.23, 21.43, 21.24, 21.29, 22.15, 22.39, 22.38, 22.61, 23.36, 24.05, 24.75, 24.83, 23.95, 23.63, 23.82, 23.87, 23.15, 23.19, 23.10, 22.65, 22.48, 22.87, 22.93, 22.91); } [Test] public void Dpo() { var cmo = new CmoIndicator(new ClosePriceIndicator(_series), 9); TaTestsUtils.AssertDecimalEquals(cmo.GetValue(5), 85.1351); TaTestsUtils.AssertDecimalEquals(cmo.GetValue(6), 53.9326); TaTestsUtils.AssertDecimalEquals(cmo.GetValue(7), 6.2016); TaTestsUtils.AssertDecimalEquals(cmo.GetValue(8), -1.083); TaTestsUtils.AssertDecimalEquals(cmo.GetValue(9), 0.7092); TaTestsUtils.AssertDecimalEquals(cmo.GetValue(10), -1.4493); TaTestsUtils.AssertDecimalEquals(cmo.GetValue(11), 10.7266); TaTestsUtils.AssertDecimalEquals(cmo.GetValue(12), -3.5857); TaTestsUtils.AssertDecimalEquals(cmo.GetValue(13), 4.7619); TaTestsUtils.AssertDecimalEquals(cmo.GetValue(14), 24.1983); TaTestsUtils.AssertDecimalEquals(cmo.GetValue(15), 47.644); } } }
43.416667
247
0.722841
[ "MIT" ]
chrisw000/TA4N
TA4N.Test/Indicators/Oscillators/CMOIndicatorTest.cs
2,607
C#
using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Migrations; using System; using System.Collections.Generic; namespace Lab3.Migrations { public partial class Initial : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.CreateTable( name: "Airplanes", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("MySql:ValueGenerationStrategy", MySqlValueGenerationStrategy.IdentityColumn), LastCheckUp = table.Column<DateTime>(nullable: false), Model = table.Column<string>(nullable: true), Seats = table.Column<int>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_Airplanes", x => x.Id); }); migrationBuilder.CreateTable( name: "Airports", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("MySql:ValueGenerationStrategy", MySqlValueGenerationStrategy.IdentityColumn), City = table.Column<string>(nullable: true), Country = table.Column<string>(nullable: true), Name = table.Column<string>(nullable: true) }, constraints: table => { table.PrimaryKey("PK_Airports", x => x.Id); }); migrationBuilder.CreateTable( name: "AviaCompanies", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("MySql:ValueGenerationStrategy", MySqlValueGenerationStrategy.IdentityColumn), CompanyName = table.Column<string>(nullable: true), Country = table.Column<string>(nullable: true) }, constraints: table => { table.PrimaryKey("PK_AviaCompanies", x => x.Id); }); migrationBuilder.CreateTable( name: "BackUpFlights", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("MySql:ValueGenerationStrategy", MySqlValueGenerationStrategy.IdentityColumn), AirplaneId = table.Column<int>(nullable: false), Arrival = table.Column<DateTime>(nullable: false), AviaCompanyId = table.Column<int>(nullable: false), Departure = table.Column<DateTime>(nullable: false), DestinationAirportId = table.Column<int>(nullable: false), HomeAirportId = table.Column<int>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_BackUpFlights", x => x.Id); table.ForeignKey( name: "FK_BackUpFlights_Airplanes_AirplaneId", column: x => x.AirplaneId, principalTable: "Airplanes", principalColumn: "Id", onDelete: ReferentialAction.Cascade); table.ForeignKey( name: "FK_BackUpFlights_AviaCompanies_AviaCompanyId", column: x => x.AviaCompanyId, principalTable: "AviaCompanies", principalColumn: "Id", onDelete: ReferentialAction.Cascade); table.ForeignKey( name: "FK_BackUpFlights_Airports_DestinationAirportId", column: x => x.DestinationAirportId, principalTable: "Airports", principalColumn: "Id", onDelete: ReferentialAction.Cascade); table.ForeignKey( name: "FK_BackUpFlights_Airports_HomeAirportId", column: x => x.HomeAirportId, principalTable: "Airports", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "Flights", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("MySql:ValueGenerationStrategy", MySqlValueGenerationStrategy.IdentityColumn), AirplaneId = table.Column<int>(nullable: false), Arrival = table.Column<DateTime>(nullable: false), AviaCompanyId = table.Column<int>(nullable: false), Departure = table.Column<DateTime>(nullable: false), DestinationAirportId = table.Column<int>(nullable: false), HomeAirportId = table.Column<int>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_Flights", x => x.Id); table.ForeignKey( name: "FK_Flights_Airplanes_AirplaneId", column: x => x.AirplaneId, principalTable: "Airplanes", principalColumn: "Id", onDelete: ReferentialAction.Cascade); table.ForeignKey( name: "FK_Flights_AviaCompanies_AviaCompanyId", column: x => x.AviaCompanyId, principalTable: "AviaCompanies", principalColumn: "Id", onDelete: ReferentialAction.Cascade); table.ForeignKey( name: "FK_Flights_Airports_DestinationAirportId", column: x => x.DestinationAirportId, principalTable: "Airports", principalColumn: "Id", onDelete: ReferentialAction.Cascade); table.ForeignKey( name: "FK_Flights_Airports_HomeAirportId", column: x => x.HomeAirportId, principalTable: "Airports", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateIndex( name: "IX_BackUpFlights_AirplaneId", table: "BackUpFlights", column: "AirplaneId"); migrationBuilder.CreateIndex( name: "IX_BackUpFlights_AviaCompanyId", table: "BackUpFlights", column: "AviaCompanyId"); migrationBuilder.CreateIndex( name: "IX_BackUpFlights_DestinationAirportId", table: "BackUpFlights", column: "DestinationAirportId"); migrationBuilder.CreateIndex( name: "IX_BackUpFlights_HomeAirportId", table: "BackUpFlights", column: "HomeAirportId"); migrationBuilder.CreateIndex( name: "IX_Flights_AirplaneId", table: "Flights", column: "AirplaneId"); migrationBuilder.CreateIndex( name: "IX_Flights_AviaCompanyId", table: "Flights", column: "AviaCompanyId"); migrationBuilder.CreateIndex( name: "IX_Flights_DestinationAirportId", table: "Flights", column: "DestinationAirportId"); migrationBuilder.CreateIndex( name: "IX_Flights_HomeAirportId", table: "Flights", column: "HomeAirportId"); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropTable( name: "BackUpFlights"); migrationBuilder.DropTable( name: "Flights"); migrationBuilder.DropTable( name: "Airplanes"); migrationBuilder.DropTable( name: "AviaCompanies"); migrationBuilder.DropTable( name: "Airports"); } } }
43.035
114
0.499129
[ "MIT" ]
IvanenkoAnton/LabsDataBase
Lab3/Migrations/20171203222729_Initial.cs
8,609
C#
/* THIS IS A GENERATED FILE. DO NOT EDIT. */ using Dullahan; using System; using System.Collections.Concurrent; using System.IO; using System.Text; namespace TestGame { partial class World { partial class Entity { public sealed partial class ConsoleBufferComponent : TestGame.IConsoleBufferComponent { public readonly Entity entity; public readonly int constructionTick; public int disposalTick { get; private set; } public ConsoleBufferComponent(Entity entity) { this.entity = entity; constructionTick = entity.world.currentTick; disposalTick = int.MaxValue; entity.consoleBufferComponent = this; if (((VisualizationSystem_Implementation)entity.world.visualizationSystem).consoleBuffer_entity != null) { throw new InvalidOperationException("Multiple consoleBuffer singletons for TestGame.VisualizationSystem!"); } ((VisualizationSystem_Implementation)entity.world.visualizationSystem).consoleBuffer_entity = entity; } private class Snapshot_consoleBuffer { public static readonly ConcurrentBag<Snapshot_consoleBuffer> pool = new ConcurrentBag<Snapshot_consoleBuffer>(); public static readonly Dullahan.Rank2BufferDiffer differ = new Dullahan.Rank2BufferDiffer(); // diffTicks and diffEnds form an associative array public readonly Ring<int> diffTicks = new Ring<int>(); public readonly Ring<(int, int)> diffSpans = new Ring<(int, int)>(); public readonly BinaryWriter diffWriter = new BinaryWriter(new MemoryStream(), Encoding.UTF8, leaveOpen: true); public System.Byte[,] state = default; } // consoleBuffer_ticks and consoleBuffer_snapshots form an associative array private readonly Ring<int> consoleBuffer_ticks = new Ring<int> { 0 }; private readonly Ring<Snapshot_consoleBuffer> consoleBuffer_snapshots = new Ring<Snapshot_consoleBuffer> {new Snapshot_consoleBuffer() }; public System.Byte[,] consoleBuffer { get { if (consoleBuffer_ticks.Count == 0) { return default; } int index = consoleBuffer_ticks.BinarySearch(entity.world.currentTick); if (index < 0) { return consoleBuffer_snapshots[~index - 1].state; } else { return consoleBuffer_snapshots[index].state; } } set { Snapshot_consoleBuffer snapshot; int tick = entity.world.currentTick; int index = consoleBuffer_ticks.BinarySearch(tick); if (index < 0) { if (!Snapshot_consoleBuffer.pool.TryTake(out snapshot)) { snapshot = new Snapshot_consoleBuffer(); } } else { snapshot = consoleBuffer_snapshots[index]; consoleBuffer_snapshots.RemoveAt(index); consoleBuffer_ticks.RemoveAt(index); } snapshot.diffTicks.Clear(); snapshot.diffSpans.Clear(); snapshot.diffWriter.SetOffset(0); snapshot.state = value; if (index < 0) { index = ~index; } // iterate backwards because we might terminate on finding no diffs w.r.t. the immediately preceding tick int start = index - 1; for (int i = start; i >= consoleBuffer_ticks.Start; --i) { int savedOffset = snapshot.diffWriter.GetOffset(); if (!Snapshot_consoleBuffer.differ.Diff(consoleBuffer_snapshots[i].state, snapshot.state, snapshot.diffWriter)) { if (i == start) { // value didn't change Snapshot_consoleBuffer.pool.Add(snapshot); return; } snapshot.diffWriter.SetOffset(savedOffset); } snapshot.diffTicks.PushEnd(tick - consoleBuffer_ticks[i]); snapshot.diffSpans.PushEnd((savedOffset, snapshot.diffWriter.GetOffset() - savedOffset)); } consoleBuffer_ticks.Insert(index, tick); consoleBuffer_snapshots.Insert(index, snapshot); // now that we have a new or modified snapshot, later snapshots need to diff with it for (int i = index + 1; i < consoleBuffer_ticks.End; ++i) { int savedOffset = consoleBuffer_snapshots[i].diffWriter.GetOffset(); if (!Snapshot_consoleBuffer.differ.Diff(snapshot.state, consoleBuffer_snapshots[i].state, consoleBuffer_snapshots[i].diffWriter)) { consoleBuffer_snapshots[i].diffWriter.SetOffset(savedOffset); } int diffTick = consoleBuffer_ticks[i] - tick; var diffSpan = (savedOffset, consoleBuffer_snapshots[i].diffWriter.GetOffset() - savedOffset); int diffIndex = consoleBuffer_snapshots[i].diffTicks.BinarySearch(diffTick); if (diffIndex < 0) { consoleBuffer_snapshots[i].diffTicks.Insert(~diffIndex, diffTick); consoleBuffer_snapshots[i].diffSpans.Insert(~diffIndex, diffSpan); } else { //consoleBuffer_snapshots[i].diffTick[diffIndex] = diffTick; // diffTick was found; no need to change it consoleBuffer_snapshots[i].diffSpans[diffIndex] = diffSpan; } } } } private void Dispose(bool disposing) { if (disposalTick == int.MaxValue) { if (disposing) { ((VisualizationSystem_Implementation)entity.world.visualizationSystem).consoleBuffer_entity = null; } entity.consoleBufferComponent = null; disposalTick = entity.world.currentTick; } } public void Dispose() { // Do not change this code. Put cleanup code in 'Dispose(bool disposing)' method Dispose(disposing: true); System.GC.SuppressFinalize(this); } } } } }
50.868966
159
0.510168
[ "BSD-3-Clause" ]
niuk/Dullahan
TestServer/Generated/ConsoleBufferComponent.cs
7,376
C#
////----------------------------------------------------------------------- //// <copyright> //// //// Copyright (c) TU Chemnitz, Prof. Technische Thermodynamik //// Written by Noah Pflugradt. //// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: //// //// Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. //// Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer //// in the documentation and/or other materials provided with the distribution. //// All advertising materials mentioning features or use of this software must display the following acknowledgement: //// “This product includes software developed by the TU Chemnitz, Prof. Technische Thermodynamik and its contributors.” //// Neither the name of the University nor the names of its contributors may be used to endorse or promote products //// derived from this software without specific prior written permission. //// //// THIS SOFTWARE IS PROVIDED BY THE UNIVERSITY 'AS IS' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, //// BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE //// DISCLAIMED. IN NO EVENT SHALL THE UNIVERSITY OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, S //// PECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; L //// OSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, //// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF //// ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. //// </copyright> ////----------------------------------------------------------------------- //#region //using System.Collections.Generic; //using System.Collections.ObjectModel; //using System.Linq; //using Common; //using Common.Enums; //using Database; //using Database.Tables.BasicHouseholds; //using Database.Tables.ModularHouseholds; //using JetBrains.Annotations; //using LoadProfileGenerator.Presenters.BasicElements; //using LoadProfileGenerator.Views.Households; //#endregion //namespace LoadProfileGenerator.Presenters.Households { // public class TemplatePersonPresenter : PresenterBaseDBBase<TemplatePersonView> { // [JetBrains.Annotations.NotNull] private readonly TemplatePerson _thisTemplate; // private TraitPriority _selectedPriority; // public TemplatePersonPresenter([JetBrains.Annotations.NotNull] ApplicationPresenter applicationPresenter, [JetBrains.Annotations.NotNull] TemplatePersonView view, // [JetBrains.Annotations.NotNull] TemplatePerson template) : base(view, "ThisTemplate.HeaderString", template, applicationPresenter) // { // _thisTemplate = template; // RefreshTree(TraitPrios, Sim, template); // } // [ItemNotNull] // [JetBrains.Annotations.NotNull] // [UsedImplicitly] // public ObservableCollection<HouseholdTrait> FilteredTraits { get; } = // new ObservableCollection<HouseholdTrait>(); // [JetBrains.Annotations.NotNull] // [UsedImplicitly] // public Dictionary<PermittedGender, string> Genders => GenderHelper.GenderEnumDictionary; // [ItemNotNull] // [JetBrains.Annotations.NotNull] // [UsedImplicitly] // public ObservableCollection<ModularHousehold> ModularHouseholds // => Sim.ModularHouseholds.Items; // [ItemNotNull] // [JetBrains.Annotations.NotNull] // [UsedImplicitly] // public ObservableCollection<Person> Persons => Sim.Persons.Items; // [JetBrains.Annotations.NotNull] // [UsedImplicitly] // public Dictionary<TraitPriority, string> Priorities => TraitPriorityHelper // .TraitPriorityDictionaryEnumDictionaryWithAll; // [UsedImplicitly] // public PermittedGender SelectedGender { // get => _thisTemplate.Gender; // set { // _thisTemplate.Gender = value; // OnPropertyChanged(nameof(SelectedGender)); // } // } // [CanBeNull] // [UsedImplicitly] // public object SelectedItem { get; set; } // [UsedImplicitly] // public TraitPriority SelectedPriority { // get => _selectedPriority; // set { // _selectedPriority = value; // FilterTraits(); // } // } // [JetBrains.Annotations.NotNull] // public TemplatePerson ThisTemplate => _thisTemplate; // [ItemNotNull] // [JetBrains.Annotations.NotNull] // [UsedImplicitly] // public ObservableCollection<TraitPrio> TraitPrios { get; } = new ObservableCollection<TraitPrio>(); // public override void Close(bool saveToDB, bool removeLast = false) // { // if (saveToDB) { // _thisTemplate.SaveToDB(); // } // ApplicationPresenter.CloseTab(this, removeLast); // } // public void Delete() // { // Sim.TemplatePersons.DeleteItem(_thisTemplate); // Close(false); // } // public override bool Equals(object obj) // { // var presenter = obj as TemplatePersonPresenter; // return presenter?.ThisTemplate.Equals(_thisTemplate) == true; // } // private void FilterTraits() // { // List<HouseholdTrait> traits; // if (_selectedPriority == TraitPriority.All) { // traits = Sim.HouseholdTraits.Items.ToList(); // } // else { // traits = // Sim.HouseholdTraits.Items.Where( // x => x.Tags.Any(y => y.Tag.TraitPriority == _selectedPriority)).ToList(); // } // FilteredTraits.SynchronizeWithList(traits); // } // public override int GetHashCode() // { // unchecked // Overflow is fine, just wrap // { // int hash = 17; // // Suitable nullity checks etc, of course :) // hash = hash * 23 + TabHeaderPath.GetHashCode(); // return hash; // } // } // public void RefreshTree() // { // RefreshTree(TraitPrios, Sim, _thisTemplate); // } // public static void RefreshTree([ItemNotNull] [JetBrains.Annotations.NotNull] ObservableCollection<TraitPrio> traitPrios, [JetBrains.Annotations.NotNull] Simulator sim, // [JetBrains.Annotations.NotNull] TemplatePerson thisTemplate) // { // traitPrios.Clear(); // var prios = sim.TraitTags.Items.Select(x => x.TraitPriority).Distinct().ToList(); // foreach (var traitPriority in prios) { // var traitPrio = // new TraitPrio(TraitPriorityHelper.TraitPriorityDictionaryEnumDictionaryComplete[traitPriority]); // traitPrios.Add(traitPrio); // var traitTags = sim.TraitTags.Items.Where(x => x.TraitPriority == traitPriority).ToList(); // foreach (var traitTag in traitTags) { // var traitCat = new TraitCategory(traitTag.Name); // var traits = // thisTemplate.Traits.Where(x => x.Trait.Tags.Any(y => y.Tag == traitTag)).ToList(); // if (traits.Count > 0) { // foreach (var trait in traits) { // traitCat.Traits.Add(trait); // } // traitPrio.TraitCategories.Add(traitCat); // } // } // } // } // public class TraitCategory { // public TraitCategory([JetBrains.Annotations.NotNull] string name) => Name = name; // [JetBrains.Annotations.NotNull] // public string Name { get; set; } // [ItemNotNull] // [JetBrains.Annotations.NotNull] // public ObservableCollection<TemplatePersonTrait> Traits { get; } = // new ObservableCollection<TemplatePersonTrait>(); // } // public class TraitPrio { // public TraitPrio([JetBrains.Annotations.NotNull] string name) => Name = name; // [JetBrains.Annotations.NotNull] // public string Name { get; set; } // [ItemNotNull] // [JetBrains.Annotations.NotNull] // [UsedImplicitly] // public ObservableCollection<TraitCategory> TraitCategories { get; } = // new ObservableCollection<TraitCategory>(); // } // } //}
42.292453
177
0.607183
[ "MIT" ]
kyleniemeyer/LoadProfileGenerator
WpfApplication1/Presenters/Households/TemplatePersonPresenter.cs
8,972
C#
/**************************************************************************** * SequenceP2TestCases.cs * * This file contains the Sequence P2 test case validation. * ******************************************************************************/ using System; using System.Text; using System.Collections.Generic; using System.Linq; using Microsoft.VisualStudio.TestTools.UnitTesting; using Bio.TestAutomation.Util; using Bio.Util.Logging; namespace Bio.TestAutomation { /// <summary> /// Test Automation code for Bio Sequence P2 level validations.. /// </summary> [TestClass] public class SequenceP2TestCases { #region Global Variables Utility utilityObj = new Utility(@"TestUtils\TestsConfig.xml"); #endregion Global Variables #region Constructor /// <summary> /// Static constructor to open log and make other settings needed for test /// </summary> static SequenceP2TestCases() { Trace.Set(Trace.SeqWarnings); if (!ApplicationLog.Ready) { ApplicationLog.Open("bio.automation.log"); } } #endregion #region P2 Test Cases /// <summary> /// Invalidates CopyTo /// </summary> [TestMethod] [Priority(2)] [TestCategory("Priority2")] public void InvalidateCopyTo() { // Get input and expected values from xml string expectedSequence = utilityObj.xmlUtil.GetTextValue(Constants.RnaDerivedSequenceNode, Constants.ExpectedSequence); string alphabetName = utilityObj.xmlUtil.GetTextValue(Constants.RnaDerivedSequenceNode, Constants.AlphabetNameNode); IAlphabet alphabet = Utility.GetAlphabet(alphabetName); // Create a Sequence object. ISequence iseqObj = new Sequence(alphabet, expectedSequence); Sequence seqObj = new Sequence(iseqObj); //check with null array byte[] array = null; try { seqObj.CopyTo(array, 10, 20); Assert.Fail(); } catch (ArgumentNullException anex) { ApplicationLog.WriteLine("Successfully caught ArgumentNullException : " + anex.Message); } //check with more than available length array = new byte[expectedSequence.Length]; try { seqObj.CopyTo(array, 0, expectedSequence.Length + 100); Assert.Fail(); } catch (ArgumentException aex) { ApplicationLog.WriteLine("Successfully caught ArgumentException : " + aex.Message); } //check with negative start array = new byte[expectedSequence.Length]; try { seqObj.CopyTo(array, -5, expectedSequence.Length); Assert.Fail(); } catch (ArgumentException aex) { ApplicationLog.WriteLine("Successfully caught ArgumentException : " + aex.Message); } //check with negative count array = new byte[expectedSequence.Length]; try { seqObj.CopyTo(array, 0, -5); Assert.Fail(); } catch (ArgumentException aex) { ApplicationLog.WriteLine("Successfully caught ArgumentException : " + aex.Message); } } #endregion P2 Test Cases } }
30.890756
104
0.530196
[ "Apache-2.0" ]
jdm7dv/Microsoft-Biology-Foundation
archive/Changesets/mbf/Tests/Bio.TestAutomation/SequenceP2TestCases.cs
3,678
C#
//------------------------------------------------------------------------------ // <auto-generated> // Dieser Code wurde von einem Tool generiert. // Laufzeitversion:4.0.30319.42000 // // Änderungen an dieser Datei können falsches Verhalten verursachen und gehen verloren, wenn // der Code erneut generiert wird. // </auto-generated> //------------------------------------------------------------------------------ using NMFExamples.Identifier; using NMFExamples.Pcm.Core.Composition; using NMFExamples.Pcm.Repository; using NMFExamples.Pcm.Resourcetype; using NMF.Collections.Generic; using NMF.Collections.ObjectModel; using NMF.Expressions; using NMF.Expressions.Linq; using NMF.Models; using NMF.Models.Collections; using NMF.Models.Expressions; using NMF.Models.Meta; using NMF.Models.Repository; using NMF.Serialization; using NMF.Utilities; using System; using global::System.Collections; using global::System.Collections.Generic; using global::System.Collections.ObjectModel; using global::System.Collections.Specialized; using System.ComponentModel; using System.Diagnostics; using System.Linq; namespace NMFExamples.Pcm.Core.Entity { public class InterfaceProvidingEntityProvidedRoles_InterfaceProvidingEntityCollection : ObservableOppositeList<IInterfaceProvidingEntity, IProvidedRole> { public InterfaceProvidingEntityProvidedRoles_InterfaceProvidingEntityCollection(IInterfaceProvidingEntity parent) : base(parent) { } private void OnItemParentChanged(object sender, ValueChangedEventArgs e) { if ((e.NewValue != this.Parent)) { this.Remove(((IProvidedRole)(sender))); } } protected override void SetOpposite(IProvidedRole item, IInterfaceProvidingEntity parent) { if ((parent != null)) { item.ParentChanged += this.OnItemParentChanged; item.ProvidingEntity_ProvidedRole = parent; } else { item.ParentChanged -= this.OnItemParentChanged; if ((item.ProvidingEntity_ProvidedRole == this.Parent)) { item.ProvidingEntity_ProvidedRole = parent; } } } } }
31.905405
156
0.623888
[ "BSD-3-Clause" ]
NMFCode/NMF
IntegrationTests/ComponentBasedSoftwareArchitectures/Pcm/Core/Entity/InterfaceProvidingEntityProvidedRoles_InterfaceProvidingEntityCollection.cs
2,363
C#
using System; using System.Reflection; namespace Chat.Areas.HelpPage.ModelDescriptions { public interface IModelDocumentationProvider { string GetDocumentation(MemberInfo member); string GetDocumentation(Type type); } }
20.75
51
0.742972
[ "MIT" ]
xto3na/chat
Chat/Areas/HelpPage/ModelDescriptions/IModelDocumentationProvider.cs
249
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.VFX; public class VFXTimeOfDayBinder : MonoBehaviour { public VisualEffect system; void FixedUpdate() { //Color c = color.Evaluate(time.Get01FullCycle()); //ParticleSystem.MainModule main = system.main; //main.startColor = c; system.SetFloat("TimeOfDay", DayNightCycle.instance.time01); } }
29.866667
69
0.685268
[ "CC0-1.0" ]
JonaMazu/KoboldKare
Assets/KoboldKare/Scripts/VFXTimeOfDayBinder.cs
450
C#
using UnityEditor; using UnityEngine; using ActiveObjects.Triggers; // RecipeItemDrawer [CustomPropertyDrawer(typeof(ButtonTrigger))] public class ButtonTriggerDrawer : PropertyDrawer { // Draw the property inside the given rect public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) { // Using BeginProperty / EndProperty on the parent property means that // prefab override logic works on the entire property. EditorGUI.BeginProperty(position, label, property); EditorGUI.PropertyField(position, property.FindPropertyRelative("Message"), label); //EditorGUI.LabelField(position, new GUIContent("", tooltip)); EditorGUI.EndProperty(); } }
34.227273
92
0.7251
[ "MIT" ]
Sumrix/DAZVillage
Assets/Editor/ButtonTriggerDrawer.cs
755
C#