content
stringlengths
5
1.04M
avg_line_length
float64
1.75
12.9k
max_line_length
int64
2
244k
alphanum_fraction
float64
0
0.98
licenses
list
repository_name
stringlengths
7
92
path
stringlengths
3
249
size
int64
5
1.04M
lang
stringclasses
2 values
using System; //library namespace TutorialCSharp //namespace { class Program //class { static void Main(string[] args) //method special, automatic run program on this Main method and call a statement { var user = Enum.GetNames(typeof(User)); string userFind = Enum.GetName(typeof(User), 1); Console.WriteLine(userFind); Console.WriteLine("\nUser constant names:"); foreach (string str in user) Console.WriteLine(str); } enum User { Fauzi, Galih, } } }
24.6
120
0.549593
[ "MIT" ]
fauzigalih/TutorialCSharp
data/088 Enum.cs
615
C#
// ************************************************************* // project: graphql-aspnet // -- // repo: https://github.com/graphql-aspnet // docs: https://graphql-aspnet.github.io // -- // License: MIT // ************************************************************* namespace GraphQL.AspNet.Configuration { using GraphQL.AspNet.Common; using GraphQL.AspNet.Execution.Contexts; using GraphQL.AspNet.Interfaces.Configuration; using GraphQL.AspNet.Interfaces.Middleware; using GraphQL.AspNet.Interfaces.TypeSystem; /// <summary> /// A builder for constructing hte individual pipelines the schema will use when executing a query. /// </summary> /// <typeparam name="TSchema">The type of the schema this builder exists for.</typeparam> public partial class SchemaBuilder<TSchema> : ISchemaBuilder<TSchema> where TSchema : class, ISchema { /// <summary> /// Initializes a new instance of the <see cref="SchemaBuilder{TSchema}" /> class. /// </summary> /// <param name="options">The primary options for configuring the schema.</param> public SchemaBuilder(SchemaOptions options) { Validation.ThrowIfNull(options, nameof(options)); this.FieldExecutionPipeline = new SchemaPipelineBuilder<TSchema, IGraphFieldExecutionMiddleware, GraphFieldExecutionContext>(options, Constants.Pipelines.FIELD_EXECUTION_PIPELINE); this.FieldAuthorizationPipeline = new SchemaPipelineBuilder<TSchema, IGraphFieldSecurityMiddleware, GraphFieldSecurityContext>(options, Constants.Pipelines.FIELD_AUTHORIZATION_PIPELINE); this.QueryExecutionPipeline = new SchemaPipelineBuilder<TSchema, IQueryExecutionMiddleware, GraphQueryExecutionContext>(options, Constants.Pipelines.QUERY_PIPELINE); this.Options = options; } /// <summary> /// Gets a builder to construct the field execution pipeline. This pipeline is invoked per field resolution request to generate a /// piece of data in the process of fulfilling the primary query. /// </summary> /// <value>The field execution pipeline.</value> public SchemaPipelineBuilder<TSchema, IGraphFieldExecutionMiddleware, GraphFieldExecutionContext> FieldExecutionPipeline { get; } /// <summary> /// Gets a builder to construct the field authorization pipeline. This pipeline is invoked per field resolution request to authorize /// the user to the field allowing or denying them access to it. /// </summary> /// <value>The field authorization pipeline.</value> public SchemaPipelineBuilder<TSchema, IGraphFieldSecurityMiddleware, GraphFieldSecurityContext> FieldAuthorizationPipeline { get; } /// <summary> /// Gets a builder to construct the primary query pipeline. This pipeline oversees the processing of a query and is invoked /// directly by the http handler. /// </summary> /// <value>The query execution pipeline.</value> public SchemaPipelineBuilder<TSchema, IQueryExecutionMiddleware, GraphQueryExecutionContext> QueryExecutionPipeline { get; } /// <summary> /// Gets a builder to construct the field execution pipeline. This pipeline is invoked per field resolution request to generate a /// piece of data in the process of fulfilling the primary query. /// </summary> /// <value>The field execution pipeline.</value> ISchemaPipelineBuilder<TSchema, IGraphFieldExecutionMiddleware, GraphFieldExecutionContext> ISchemaBuilder<TSchema>.FieldExecutionPipeline => this.FieldExecutionPipeline; /// <summary> /// Gets a builder to construct the field authorization pipeline. This pipeline is invoked per field resolution request to authorize /// the user to the field allowing or denying them access to it. /// </summary> /// <value>The field authorization pipeline.</value> ISchemaPipelineBuilder<TSchema, IGraphFieldSecurityMiddleware, GraphFieldSecurityContext> ISchemaBuilder<TSchema>.FieldAuthorizationPipeline => this.FieldAuthorizationPipeline; /// <summary> /// Gets a builder to construct the primary query pipeline. This pipeline oversees the processing of a query and is invoked /// directly by the http handler. /// </summary> /// <value>The query execution pipeline.</value> ISchemaPipelineBuilder<TSchema, IQueryExecutionMiddleware, GraphQueryExecutionContext> ISchemaBuilder<TSchema>.QueryExecutionPipeline => this.QueryExecutionPipeline; /// <summary> /// Gets the completed options used to configure this schema. /// </summary> /// <value>The options.</value> public SchemaOptions Options { get; } } }
55.079545
198
0.689911
[ "MIT" ]
NET1211/aspnet-archive-tools
src/graphql-aspnet/Configuration/SchemaBuilder.cs
4,849
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; namespace Microsoft.ML.AutoML.Test { internal static class MLNetUtils { public static bool[] BuildArray(int length, IEnumerable<DataViewSchema.Column> columnsNeeded) { var result = new bool[length]; foreach (var col in columnsNeeded) { if (col.Index < result.Length) result[col.Index] = true; } return result; } } }
28.708333
101
0.616836
[ "MIT" ]
1Crazymoney/machinelearning
test/Microsoft.ML.AutoML.Tests/Utils/MLNetUtils/MLNetUtils.cs
691
C#
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Collections.Specialized; using System.ComponentModel; using System.Threading.Tasks; using Microsoft.Maui.Controls.Internals; namespace Microsoft.Maui.Controls { // Don't add IElementConfiguration<Cell> because it kills performance on UWP structures that use Cells /// <include file="../../../docs/Microsoft.Maui.Controls/Cell.xml" path="Type[@FullName='Microsoft.Maui.Controls.Cell']/Docs" /> public abstract class Cell : Element, ICellController, IFlowDirectionController, IPropertyPropagationController, IVisualController, IWindowController { /// <include file="../../../docs/Microsoft.Maui.Controls/Cell.xml" path="//Member[@MemberName='DefaultCellHeight']/Docs" /> public const int DefaultCellHeight = 40; /// <include file="../../../docs/Microsoft.Maui.Controls/Cell.xml" path="//Member[@MemberName='IsEnabledProperty']/Docs" /> public static readonly BindableProperty IsEnabledProperty = BindableProperty.Create("IsEnabled", typeof(bool), typeof(Cell), true, propertyChanged: OnIsEnabledPropertyChanged); ObservableCollection<MenuItem> _contextActions; readonly Lazy<ElementConfiguration> _elementConfiguration; double _height = -1; bool _nextCallToForceUpdateSizeQueued; /// <include file="../../../docs/Microsoft.Maui.Controls/Cell.xml" path="//Member[@MemberName='.ctor']/Docs" /> public Cell() { _elementConfiguration = new Lazy<ElementConfiguration>(() => new ElementConfiguration(this)); } EffectiveFlowDirection _effectiveFlowDirection = default(EffectiveFlowDirection); EffectiveFlowDirection IFlowDirectionController.EffectiveFlowDirection { get { return _effectiveFlowDirection; } set { if (value == _effectiveFlowDirection) return; _effectiveFlowDirection = value; var ve = (Parent as VisualElement); ve?.InvalidateMeasureInternal(InvalidationTrigger.Undefined); OnPropertyChanged(VisualElement.FlowDirectionProperty.PropertyName); } } IVisual _effectiveVisual = Microsoft.Maui.Controls.VisualMarker.Default; IVisual IVisualController.EffectiveVisual { get { return _effectiveVisual; } set { if (value == _effectiveVisual) return; _effectiveVisual = value; OnPropertyChanged(VisualElement.VisualProperty.PropertyName); } } IVisual IVisualController.Visual => Microsoft.Maui.Controls.VisualMarker.MatchParent; bool IFlowDirectionController.ApplyEffectiveFlowDirectionToChildContainer => true; IFlowDirectionController FlowController => this; IPropertyPropagationController PropertyPropagationController => this; Window _window; Window IWindowController.Window { get => _window; set { if (value == _window) return; _window = value; OnPropertyChanged(VisualElement.WindowProperty.PropertyName); } } /// <include file="../../../docs/Microsoft.Maui.Controls/Cell.xml" path="//Member[@MemberName='ContextActions']/Docs" /> public IList<MenuItem> ContextActions { get { if (_contextActions == null) { _contextActions = new ObservableCollection<MenuItem>(); _contextActions.CollectionChanged += OnContextActionsChanged; } return _contextActions; } } /// <include file="../../../docs/Microsoft.Maui.Controls/Cell.xml" path="//Member[@MemberName='HasContextActions']/Docs" /> public bool HasContextActions { get { return _contextActions != null && _contextActions.Count > 0 && IsEnabled; } } /// <include file="../../../docs/Microsoft.Maui.Controls/Cell.xml" path="//Member[@MemberName='IsContextActionsLegacyModeEnabled']/Docs" /> public bool IsContextActionsLegacyModeEnabled { get; set; } = false; /// <include file="../../../docs/Microsoft.Maui.Controls/Cell.xml" path="//Member[@MemberName='Height']/Docs" /> public double Height { get { return _height; } set { if (_height == value) return; OnPropertyChanging("Height"); OnPropertyChanging("RenderHeight"); _height = value; OnPropertyChanged("Height"); OnPropertyChanged("RenderHeight"); } } /// <include file="../../../docs/Microsoft.Maui.Controls/Cell.xml" path="//Member[@MemberName='IsEnabled']/Docs" /> public bool IsEnabled { get { return (bool)GetValue(IsEnabledProperty); } set { SetValue(IsEnabledProperty, value); } } /// <include file="../../../docs/Microsoft.Maui.Controls/Cell.xml" path="//Member[@MemberName='RenderHeight']/Docs" /> public double RenderHeight { get { var table = RealParent as TableView; if (table != null) return table.HasUnevenRows && Height > 0 ? Height : table.RowHeight; var list = RealParent as ListView; if (list != null) return list.HasUnevenRows && Height > 0 ? Height : list.RowHeight; return DefaultCellHeight; } } double IFlowDirectionController.Width => (Parent as VisualElement)?.Width ?? 0; public event EventHandler Appearing; public event EventHandler Disappearing; [EditorBrowsable(EditorBrowsableState.Never)] public event EventHandler ForceUpdateSizeRequested; /// <include file="../../../docs/Microsoft.Maui.Controls/Cell.xml" path="//Member[@MemberName='ForceUpdateSize']/Docs" /> public void ForceUpdateSize() { if (_nextCallToForceUpdateSizeQueued) return; if ((Parent as ListView)?.HasUnevenRows == true || (Parent as TableView)?.HasUnevenRows == true) { _nextCallToForceUpdateSizeQueued = true; OnForceUpdateSizeRequested(); } } public event EventHandler Tapped; protected internal virtual void OnTapped() => Tapped?.Invoke(this, EventArgs.Empty); protected virtual void OnAppearing() => Appearing?.Invoke(this, EventArgs.Empty); protected override void OnBindingContextChanged() { base.OnBindingContextChanged(); if (HasContextActions) { for (var i = 0; i < _contextActions.Count; i++) SetInheritedBindingContext(_contextActions[i], BindingContext); } } protected virtual void OnDisappearing() => Disappearing?.Invoke(this, EventArgs.Empty); protected override void OnParentSet() { if (RealParent != null) { RealParent.PropertyChanged += OnParentPropertyChanged; RealParent.PropertyChanging += OnParentPropertyChanging; } base.OnParentSet(); PropertyPropagationController.PropagatePropertyChanged(null); } protected override void OnPropertyChanging(string propertyName = null) { if (propertyName == "Parent") { if (RealParent != null) { RealParent.PropertyChanged -= OnParentPropertyChanged; RealParent.PropertyChanging -= OnParentPropertyChanging; } PropertyPropagationController.PropagatePropertyChanged(null); } base.OnPropertyChanging(propertyName); } /// <include file="../../../docs/Microsoft.Maui.Controls/Cell.xml" path="//Member[@MemberName='SendAppearing']/Docs" /> [EditorBrowsable(EditorBrowsableState.Never)] public void SendAppearing() { OnAppearing(); var container = RealParent as ListView; if (container != null) container.SendCellAppearing(this); } /// <include file="../../../docs/Microsoft.Maui.Controls/Cell.xml" path="//Member[@MemberName='SendDisappearing']/Docs" /> [EditorBrowsable(EditorBrowsableState.Never)] public void SendDisappearing() { OnDisappearing(); var container = RealParent as ListView; if (container != null) container.SendCellDisappearing(this); } void IPropertyPropagationController.PropagatePropertyChanged(string propertyName) { PropertyPropagationExtensions.PropagatePropertyChanged(propertyName, this, ((IElementController)this).LogicalChildren); } void OnContextActionsChanged(object sender, NotifyCollectionChangedEventArgs e) { for (var i = 0; i < _contextActions.Count; i++) SetInheritedBindingContext(_contextActions[i], BindingContext); OnPropertyChanged("HasContextActions"); } async void OnForceUpdateSizeRequested() { // don't run more than once per 16 milliseconds await Task.Delay(TimeSpan.FromMilliseconds(16)); ForceUpdateSizeRequested?.Invoke(this, null); _nextCallToForceUpdateSizeQueued = false; } static void OnIsEnabledPropertyChanged(BindableObject bindable, object oldvalue, object newvalue) { (bindable as Cell).OnPropertyChanged("HasContextActions"); } void OnParentPropertyChanged(object sender, PropertyChangedEventArgs e) { // Technically we might be raising this even if it didn't change, but I'm taking the bet that // its uncommon enough that we don't want to take the penalty of N GetValue calls to verify. if (e.PropertyName == "RowHeight") OnPropertyChanged("RenderHeight"); else if (e.PropertyName == VisualElement.FlowDirectionProperty.PropertyName || e.PropertyName == VisualElement.VisualProperty.PropertyName) PropertyPropagationController.PropagatePropertyChanged(e.PropertyName); } void OnParentPropertyChanging(object sender, PropertyChangingEventArgs e) { if (e.PropertyName == "RowHeight") OnPropertyChanging("RenderHeight"); } #if ANDROID // This is used by ListView to pass data to the GetCell call // Ideally we can pass these as arguments to ToHandler // But we'll do that in a different smaller more targeted PR internal Android.Views.View ConvertView { get; set; } #elif IOS internal UIKit.UITableViewCell ReusableCell { get; set; } internal UIKit.UITableView TableView { get; set; } #endif #region Nested IElementConfiguration<Cell> Implementation // This creates a nested class to keep track of IElementConfiguration<Cell> because adding // IElementConfiguration<Cell> to the Cell itself tanks performance on UWP ListViews // Issue has been logged with UWP /// <include file="../../../docs/Microsoft.Maui.Controls/Cell.xml" path="//Member[@MemberName='On']/Docs" /> public IPlatformElementConfiguration<T, Cell> On<T>() where T : IConfigPlatform { return GetElementConfiguration().On<T>(); } IElementConfiguration<Cell> GetElementConfiguration() { return _elementConfiguration.Value; } class ElementConfiguration : IElementConfiguration<Cell> { readonly Lazy<PlatformConfigurationRegistry<Cell>> _platformConfigurationRegistry; public ElementConfiguration(Cell cell) { _platformConfigurationRegistry = new Lazy<PlatformConfigurationRegistry<Cell>>(() => new PlatformConfigurationRegistry<Cell>(cell)); } public IPlatformElementConfiguration<T, Cell> On<T>() where T : IConfigPlatform { return _platformConfigurationRegistry.Value.On<T>(); } internal PlatformConfigurationRegistry<Cell> Registry => _platformConfigurationRegistry.Value; } #endregion } }
32.267267
178
0.730479
[ "MIT" ]
AlexanderSemenyak/maui
src/Controls/src/Core/Cells/Cell.cs
10,745
C#
// ----------------------------------------------------------------------- // <copyright file="PartnerServiceRequestOperations.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> // ----------------------------------------------------------------------- namespace Microsoft.Store.PartnerCenter.ServiceRequests { using System; using System.Globalization; using System.Threading; using System.Threading.Tasks; using Extensions; using Models.ServiceRequests; /// <summary> /// Implements operations that can be performed on a single partner's service requests. /// </summary> internal class PartnerServiceRequestOperations : BasePartnerComponent<Tuple<string, string>>, IServiceRequest { /// <summary> /// Initializes a new instance of the <see cref="PartnerServiceRequestOperations" /> class. /// </summary> /// <param name="rootPartnerOperations">The root partner operations instance.</param> /// <param name="serviceRequestId">The service request identifier.</param> public PartnerServiceRequestOperations(IPartner rootPartnerOperations, string serviceRequestId) : base(rootPartnerOperations, new Tuple<string, string>(serviceRequestId, string.Empty)) { serviceRequestId.AssertNotEmpty(nameof(serviceRequestId)); } /// <summary> /// Get the specified service request. /// </summary> /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> /// <returns>The requested service request.</returns> public ServiceRequest Get(CancellationToken cancellationToken = default(CancellationToken)) { return PartnerService.SynchronousExecute(() => GetAsync(cancellationToken)); } /// <summary> /// Get the specified service request. /// </summary> /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> /// <returns>The requested service request.</returns> public async Task<ServiceRequest> GetAsync(CancellationToken cancellationToken = default(CancellationToken)) { return await Partner.ServiceClient.GetAsync<ServiceRequest>( new Uri( string.Format( CultureInfo.InvariantCulture, $"/{PartnerService.Instance.ApiVersion}/{PartnerService.Instance.Configuration.Apis.GetServiceRequestPartner.Path}", Context.Item1), UriKind.Relative), cancellationToken).ConfigureAwait(false); } /// <summary> /// Updates the service request. /// </summary> /// <param name="entity">The service request to be updated.</param> /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> /// <returns>The service request that was just updated.</returns> public ServiceRequest Patch(ServiceRequest entity, CancellationToken cancellationToken = default(CancellationToken)) { return PartnerService.SynchronousExecute(() => PatchAsync(entity, cancellationToken)); } /// <summary> /// Updates the service request. /// </summary> /// <param name="entity">The service request to be updated.</param> /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> /// <returns>The service request that was just updated.</returns> public async Task<ServiceRequest> PatchAsync(ServiceRequest entity, CancellationToken cancellationToken = default(CancellationToken)) { entity.AssertNotNull(nameof(entity)); return await Partner.ServiceClient.PatchAsync<ServiceRequest, ServiceRequest>( new Uri( string.Format( CultureInfo.InvariantCulture, $"/{PartnerService.Instance.ApiVersion}/{PartnerService.Instance.Configuration.Apis.UpdateServiceRequestPartner.Path}", Context.Item1), UriKind.Relative), entity, cancellationToken).ConfigureAwait(false); } } }
50.362637
152
0.630373
[ "MIT" ]
vijayraavi/Partner-Center-PowerShell
src/PartnerCenter/ServiceRequests/PartnerServiceRequestOperations.cs
4,585
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:2.0.50727.1433 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace onenet_chatroom.Properties { [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "9.0.0.0")] internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase { private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings()))); public static Settings Default { get { return defaultInstance; } } } }
34.451613
150
0.582397
[ "BSD-2-Clause" ]
limao777/chatroom-based-onenet
onenet_chatroom/Properties/Settings.Designer.cs
1,070
C#
using System; using System.Collections.Generic; using System.Linq; using UnityEngine; using System.Reflection; using Unity.Collections; namespace Unity.Netcode { /// <summary> /// The base class to override to write network code. Inherits MonoBehaviour /// </summary> public abstract class NetworkBehaviour : MonoBehaviour { #pragma warning disable IDE1006 // disable naming rule violation check // RuntimeAccessModifiersILPP will make this `protected` internal enum __RpcExecStage { None = 0, Server = 1, Client = 2 } // NetworkBehaviourILPP will override this in derived classes to return the name of the concrete type internal virtual string __getTypeName() => nameof(NetworkBehaviour); [NonSerialized] // RuntimeAccessModifiersILPP will make this `protected` internal __RpcExecStage __rpc_exec_stage = __RpcExecStage.None; #pragma warning restore IDE1006 // restore naming rule violation check private const int k_RpcMessageDefaultSize = 1024; // 1k private const int k_RpcMessageMaximumSize = 1024 * 64; // 64k #pragma warning disable IDE1006 // disable naming rule violation check // RuntimeAccessModifiersILPP will make this `protected` internal FastBufferWriter __beginSendServerRpc(uint rpcMethodId, ServerRpcParams serverRpcParams, RpcDelivery rpcDelivery) #pragma warning restore IDE1006 // restore naming rule violation check { return new FastBufferWriter(k_RpcMessageDefaultSize, Allocator.Temp, k_RpcMessageMaximumSize); } #pragma warning disable IDE1006 // disable naming rule violation check // RuntimeAccessModifiersILPP will make this `protected` internal void __endSendServerRpc(ref FastBufferWriter bufferWriter, uint rpcMethodId, ServerRpcParams serverRpcParams, RpcDelivery rpcDelivery) #pragma warning restore IDE1006 // restore naming rule violation check { var serverRpcMessage = new ServerRpcMessage { Metadata = new RpcMetadata { NetworkObjectId = NetworkObjectId, NetworkBehaviourId = NetworkBehaviourId, NetworkRpcMethodId = rpcMethodId, }, WriteBuffer = bufferWriter }; NetworkDelivery networkDelivery; switch (rpcDelivery) { default: case RpcDelivery.Reliable: networkDelivery = NetworkDelivery.ReliableFragmentedSequenced; break; case RpcDelivery.Unreliable: if (bufferWriter.Length > MessagingSystem.NON_FRAGMENTED_MESSAGE_MAX_SIZE) { throw new OverflowException("RPC parameters are too large for unreliable delivery."); } networkDelivery = NetworkDelivery.Unreliable; break; } var rpcWriteSize = 0; // If we are a server/host then we just no op and send to ourself if (IsHost || IsServer) { using var tempBuffer = new FastBufferReader(bufferWriter, Allocator.Temp); var context = new NetworkContext { SenderId = NetworkManager.ServerClientId, Timestamp = Time.realtimeSinceStartup, SystemOwner = NetworkManager, // header information isn't valid since it's not a real message. // RpcMessage doesn't access this stuff so it's just left empty. Header = new MessageHeader(), SerializedHeaderSize = 0, MessageSize = 0 }; serverRpcMessage.ReadBuffer = tempBuffer; serverRpcMessage.Handle(ref context); rpcWriteSize = tempBuffer.Length; } else { rpcWriteSize = NetworkManager.SendMessage(ref serverRpcMessage, networkDelivery, NetworkManager.ServerClientId); } bufferWriter.Dispose(); #if DEVELOPMENT_BUILD || UNITY_EDITOR if (NetworkManager.__rpc_name_table.TryGetValue(rpcMethodId, out var rpcMethodName)) { NetworkManager.NetworkMetrics.TrackRpcSent( NetworkManager.ServerClientId, NetworkObject, rpcMethodName, __getTypeName(), rpcWriteSize); } #endif } #pragma warning disable IDE1006 // disable naming rule violation check // RuntimeAccessModifiersILPP will make this `protected` internal FastBufferWriter __beginSendClientRpc(uint rpcMethodId, ClientRpcParams clientRpcParams, RpcDelivery rpcDelivery) #pragma warning restore IDE1006 // restore naming rule violation check { return new FastBufferWriter(k_RpcMessageDefaultSize, Allocator.Temp, k_RpcMessageMaximumSize); } #pragma warning disable IDE1006 // disable naming rule violation check // RuntimeAccessModifiersILPP will make this `protected` internal void __endSendClientRpc(ref FastBufferWriter bufferWriter, uint rpcMethodId, ClientRpcParams clientRpcParams, RpcDelivery rpcDelivery) #pragma warning restore IDE1006 // restore naming rule violation check { var clientRpcMessage = new ClientRpcMessage { Metadata = new RpcMetadata { NetworkObjectId = NetworkObjectId, NetworkBehaviourId = NetworkBehaviourId, NetworkRpcMethodId = rpcMethodId, }, WriteBuffer = bufferWriter }; NetworkDelivery networkDelivery; switch (rpcDelivery) { default: case RpcDelivery.Reliable: networkDelivery = NetworkDelivery.ReliableFragmentedSequenced; break; case RpcDelivery.Unreliable: if (bufferWriter.Length > MessagingSystem.NON_FRAGMENTED_MESSAGE_MAX_SIZE) { throw new OverflowException("RPC parameters are too large for unreliable delivery."); } networkDelivery = NetworkDelivery.Unreliable; break; } var rpcWriteSize = 0; // We check to see if we need to shortcut for the case where we are the host/server and we can send a clientRPC // to ourself. Sadly we have to figure that out from the list of clientIds :( bool shouldSendToHost = false; if (clientRpcParams.Send.TargetClientIds != null) { foreach (var targetClientId in clientRpcParams.Send.TargetClientIds) { if (targetClientId == NetworkManager.ServerClientId) { shouldSendToHost = true; break; } // Check to make sure we are sending to only observers, if not log an error. if (NetworkManager.LogLevel >= LogLevel.Error && !NetworkObject.Observers.Contains(targetClientId)) { NetworkLog.LogError(GenerateObserverErrorMessage(clientRpcParams, targetClientId)); } } rpcWriteSize = NetworkManager.SendMessage(ref clientRpcMessage, networkDelivery, in clientRpcParams.Send.TargetClientIds); } else if (clientRpcParams.Send.TargetClientIdsNativeArray != null) { foreach (var targetClientId in clientRpcParams.Send.TargetClientIdsNativeArray) { if (targetClientId == NetworkManager.ServerClientId) { shouldSendToHost = true; break; } // Check to make sure we are sending to only observers, if not log an error. if (NetworkManager.LogLevel >= LogLevel.Error && !NetworkObject.Observers.Contains(targetClientId)) { NetworkLog.LogError(GenerateObserverErrorMessage(clientRpcParams, targetClientId)); } } rpcWriteSize = NetworkManager.SendMessage(ref clientRpcMessage, networkDelivery, clientRpcParams.Send.TargetClientIdsNativeArray.Value); } else { var observerEnumerator = NetworkObject.Observers.GetEnumerator(); while (observerEnumerator.MoveNext()) { // Skip over the host if (IsHost && observerEnumerator.Current == NetworkManager.LocalClientId) { shouldSendToHost = true; continue; } rpcWriteSize = NetworkManager.MessagingSystem.SendMessage(ref clientRpcMessage, networkDelivery, observerEnumerator.Current); } } // If we are a server/host then we just no op and send to ourself if (shouldSendToHost) { using var tempBuffer = new FastBufferReader(bufferWriter, Allocator.Temp); var context = new NetworkContext { SenderId = NetworkManager.ServerClientId, Timestamp = Time.realtimeSinceStartup, SystemOwner = NetworkManager, // header information isn't valid since it's not a real message. // RpcMessage doesn't access this stuff so it's just left empty. Header = new MessageHeader(), SerializedHeaderSize = 0, MessageSize = 0 }; clientRpcMessage.ReadBuffer = tempBuffer; clientRpcMessage.Handle(ref context); } bufferWriter.Dispose(); #if DEVELOPMENT_BUILD || UNITY_EDITOR if (NetworkManager.__rpc_name_table.TryGetValue(rpcMethodId, out var rpcMethodName)) { foreach (var client in NetworkManager.ConnectedClients) { NetworkManager.NetworkMetrics.TrackRpcSent( client.Key, NetworkObject, rpcMethodName, __getTypeName(), rpcWriteSize); } } #endif } internal string GenerateObserverErrorMessage(ClientRpcParams clientRpcParams, ulong targetClientId) { var containerNameHoldingId = clientRpcParams.Send.TargetClientIds != null ? nameof(ClientRpcParams.Send.TargetClientIds) : nameof(ClientRpcParams.Send.TargetClientIdsNativeArray); return $"Sending ClientRpc to non-observer! {containerNameHoldingId} contains clientId {targetClientId} that is not an observer!"; } /// <summary> /// Gets the NetworkManager that owns this NetworkBehaviour instance /// See note around `NetworkObject` for how there is a chicken / egg problem when we are not initialized /// </summary> public NetworkManager NetworkManager => NetworkObject.NetworkManager; /// <summary> /// If a NetworkObject is assigned, it will return whether or not this NetworkObject /// is the local player object. If no NetworkObject is assigned it will always return false. /// </summary> public bool IsLocalPlayer { get; private set; } /// <summary> /// Gets if the object is owned by the local player or if the object is the local player object /// </summary> public bool IsOwner { get; internal set; } /// <summary> /// Gets if we are executing as server /// </summary> protected bool IsServer { get; private set; } /// <summary> /// Gets if we are executing as client /// </summary> protected bool IsClient { get; private set; } /// <summary> /// Gets if we are executing as Host, I.E Server and Client /// </summary> protected bool IsHost { get; private set; } /// <summary> /// Gets Whether or not the object has a owner /// </summary> public bool IsOwnedByServer { get; internal set; } /// <summary> /// Used to determine if it is safe to access NetworkObject and NetworkManager from within a NetworkBehaviour component /// Primarily useful when checking NetworkObject/NetworkManager properties within FixedUpate /// </summary> public bool IsSpawned { get; internal set; } internal bool IsBehaviourEditable() { // Only server can MODIFY. So allow modification if network is either not running or we are server return !m_NetworkObject || m_NetworkObject.NetworkManager == null || m_NetworkObject.NetworkManager.IsListening == false || m_NetworkObject.NetworkManager.IsServer; } /// <summary> /// Gets the NetworkObject that owns this NetworkBehaviour instance /// TODO: this needs an overhaul. It's expensive, it's ja little naive in how it looks for networkObject in /// its parent and worst, it creates a puzzle if you are a NetworkBehaviour wanting to see if you're live or not /// (e.g. editor code). All you want to do is find out if NetworkManager is null, but to do that you /// need NetworkObject, but if you try and grab NetworkObject and NetworkManager isn't up you'll get /// the warning below. This is why IsBehaviourEditable had to be created. Matt was going to re-do /// how NetworkObject works but it was close to the release and too risky to change /// /// </summary> public NetworkObject NetworkObject { get { if (m_NetworkObject == null) { m_NetworkObject = GetComponentInParent<NetworkObject>(); } // ShutdownInProgress check: // This prevents an edge case scenario where the NetworkManager is shutting down but user code // in Update and/or in FixedUpdate could still be checking NetworkBehaviour.NetworkObject directly (i.e. does it exist?) // or NetworkBehaviour.IsSpawned (i.e. to early exit if not spawned) which, in turn, could generate several Warning messages // per spawned NetworkObject. Checking for ShutdownInProgress prevents these unnecessary LogWarning messages. if (m_NetworkObject == null && (NetworkManager.Singleton == null || !NetworkManager.Singleton.ShutdownInProgress)) { if (NetworkLog.CurrentLogLevel <= LogLevel.Normal) { NetworkLog.LogWarning($"Could not get {nameof(NetworkObject)} for the {nameof(NetworkBehaviour)}. Are you missing a {nameof(NetworkObject)} component?"); } } return m_NetworkObject; } } /// <summary> /// Gets whether or not this NetworkBehaviour instance has a NetworkObject owner. /// </summary> public bool HasNetworkObject => NetworkObject != null; private NetworkObject m_NetworkObject = null; /// <summary> /// Gets the NetworkId of the NetworkObject that owns this NetworkBehaviour /// </summary> public ulong NetworkObjectId { get; internal set; } /// <summary> /// Gets NetworkId for this NetworkBehaviour from the owner NetworkObject /// </summary> public ushort NetworkBehaviourId { get; internal set; } /// <summary> /// Internally caches the Id of this behaviour in a NetworkObject. Makes look-up faster /// </summary> internal ushort NetworkBehaviourIdCache = 0; /// <summary> /// Returns a the NetworkBehaviour with a given BehaviourId for the current NetworkObject /// </summary> /// <param name="behaviourId">The behaviourId to return</param> /// <returns>Returns NetworkBehaviour with given behaviourId</returns> protected NetworkBehaviour GetNetworkBehaviour(ushort behaviourId) { return NetworkObject.GetNetworkBehaviourAtOrderIndex(behaviourId); } /// <summary> /// Gets the ClientId that owns the NetworkObject /// </summary> public ulong OwnerClientId { get; internal set; } /// <summary> /// Updates properties with network session related /// dependencies such as a NetworkObject's spawned /// state or NetworkManager's session state. /// </summary> internal void UpdateNetworkProperties() { // Set NetworkObject dependent properties if (NetworkObject != null) { // Set identification related properties NetworkObjectId = NetworkObject.NetworkObjectId; IsLocalPlayer = NetworkObject.IsLocalPlayer; // This is "OK" because GetNetworkBehaviourOrderIndex uses the order of // NetworkObject.ChildNetworkBehaviours which is set once when first // accessed. NetworkBehaviourId = NetworkObject.GetNetworkBehaviourOrderIndex(this); // Set ownership related properties IsOwnedByServer = NetworkObject.IsOwnedByServer; IsOwner = NetworkObject.IsOwner; OwnerClientId = NetworkObject.OwnerClientId; // Set NetworkManager dependent properties if (NetworkManager != null) { IsHost = NetworkManager.IsListening && NetworkManager.IsHost; IsClient = NetworkManager.IsListening && NetworkManager.IsClient; IsServer = NetworkManager.IsListening && NetworkManager.IsServer; } } else // Shouldn't happen, but if so then set the properties to their default value; { OwnerClientId = NetworkObjectId = default; IsOwnedByServer = IsOwner = IsHost = IsClient = IsServer = default; NetworkBehaviourId = default; } } /// <summary> /// Gets called when the <see cref="NetworkObject"/> gets spawned, message handlers are ready to be registered and the network is setup. /// </summary> public virtual void OnNetworkSpawn() { } /// <summary> /// Gets called when the <see cref="NetworkObject"/> gets despawned. Is called both on the server and clients. /// </summary> public virtual void OnNetworkDespawn() { } internal void InternalOnNetworkSpawn() { IsSpawned = true; InitializeVariables(); UpdateNetworkProperties(); OnNetworkSpawn(); } internal void InternalOnNetworkDespawn() { IsSpawned = false; UpdateNetworkProperties(); OnNetworkDespawn(); } /// <summary> /// Gets called when the local client gains ownership of this object /// </summary> public virtual void OnGainedOwnership() { } internal void InternalOnGainedOwnership() { UpdateNetworkProperties(); OnGainedOwnership(); } /// <summary> /// Gets called when we loose ownership of this object /// </summary> public virtual void OnLostOwnership() { } internal void InternalOnLostOwnership() { UpdateNetworkProperties(); OnLostOwnership(); } /// <summary> /// Gets called when the parent NetworkObject of this NetworkBehaviour's NetworkObject has changed /// </summary> public virtual void OnNetworkObjectParentChanged(NetworkObject parentNetworkObject) { } private bool m_VarInit = false; private readonly List<HashSet<int>> m_DeliveryMappedNetworkVariableIndices = new List<HashSet<int>>(); private readonly List<NetworkDelivery> m_DeliveryTypesForNetworkVariableGroups = new List<NetworkDelivery>(); internal readonly List<NetworkVariableBase> NetworkVariableFields = new List<NetworkVariableBase>(); private static Dictionary<Type, FieldInfo[]> s_FieldTypes = new Dictionary<Type, FieldInfo[]>(); private static FieldInfo[] GetFieldInfoForType(Type type) { if (!s_FieldTypes.ContainsKey(type)) { s_FieldTypes.Add(type, GetFieldInfoForTypeRecursive(type)); } return s_FieldTypes[type]; } private static FieldInfo[] GetFieldInfoForTypeRecursive(Type type, List<FieldInfo> list = null) { if (list == null) { list = new List<FieldInfo>(); list.AddRange(type.GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance)); } else { list.AddRange(type.GetFields(BindingFlags.NonPublic | BindingFlags.Instance)); } if (type.BaseType != null && type.BaseType != typeof(NetworkBehaviour)) { return GetFieldInfoForTypeRecursive(type.BaseType, list); } return list.OrderBy(x => x.Name, StringComparer.Ordinal).ToArray(); } internal void InitializeVariables() { if (m_VarInit) { return; } m_VarInit = true; var sortedFields = GetFieldInfoForType(GetType()); for (int i = 0; i < sortedFields.Length; i++) { var fieldType = sortedFields[i].FieldType; if (fieldType.IsSubclassOf(typeof(NetworkVariableBase))) { var instance = (NetworkVariableBase)sortedFields[i].GetValue(this); if (instance == null) { throw new Exception($"{GetType().FullName}.{sortedFields[i].Name} cannot be null. All {nameof(NetworkVariableBase)} instances must be initialized."); } instance.Initialize(this); var instanceNameProperty = fieldType.GetProperty(nameof(NetworkVariableBase.Name)); var sanitizedVariableName = sortedFields[i].Name.Replace("<", string.Empty).Replace(">k__BackingField", string.Empty); instanceNameProperty?.SetValue(instance, sanitizedVariableName); NetworkVariableFields.Add(instance); } } { // Create index map for delivery types var firstLevelIndex = new Dictionary<NetworkDelivery, int>(); int secondLevelCounter = 0; for (int i = 0; i < NetworkVariableFields.Count; i++) { var networkDelivery = NetworkVariableBase.Delivery; if (!firstLevelIndex.ContainsKey(networkDelivery)) { firstLevelIndex.Add(networkDelivery, secondLevelCounter); m_DeliveryTypesForNetworkVariableGroups.Add(networkDelivery); secondLevelCounter++; } if (firstLevelIndex[networkDelivery] >= m_DeliveryMappedNetworkVariableIndices.Count) { m_DeliveryMappedNetworkVariableIndices.Add(new HashSet<int>()); } m_DeliveryMappedNetworkVariableIndices[firstLevelIndex[networkDelivery]].Add(i); } } } internal void PreNetworkVariableWrite() { // reset our "which variables got written" data NetworkVariableIndexesToReset.Clear(); NetworkVariableIndexesToResetSet.Clear(); } internal void PostNetworkVariableWrite() { // mark any variables we wrote as no longer dirty for (int i = 0; i < NetworkVariableIndexesToReset.Count; i++) { NetworkVariableFields[NetworkVariableIndexesToReset[i]].ResetDirty(); } } internal void VariableUpdate(ulong targetClientId) { if (!m_VarInit) { InitializeVariables(); } PreNetworkVariableWrite(); NetworkVariableUpdate(targetClientId, NetworkBehaviourId); } internal readonly List<int> NetworkVariableIndexesToReset = new List<int>(); internal readonly HashSet<int> NetworkVariableIndexesToResetSet = new HashSet<int>(); private void NetworkVariableUpdate(ulong targetClientId, int behaviourIndex) { if (!CouldHaveDirtyNetworkVariables()) { return; } if (NetworkManager.NetworkConfig.UseSnapshotDelta) { for (int k = 0; k < NetworkVariableFields.Count; k++) { NetworkManager.SnapshotSystem.Store(NetworkObjectId, behaviourIndex, k, NetworkVariableFields[k]); } } if (!NetworkManager.NetworkConfig.UseSnapshotDelta) { for (int j = 0; j < m_DeliveryMappedNetworkVariableIndices.Count; j++) { var shouldSend = false; for (int k = 0; k < NetworkVariableFields.Count; k++) { var networkVariable = NetworkVariableFields[k]; if (networkVariable.IsDirty() && networkVariable.CanClientRead(targetClientId)) { shouldSend = true; break; } } if (shouldSend) { var message = new NetworkVariableDeltaMessage { NetworkObjectId = NetworkObjectId, NetworkBehaviourIndex = NetworkObject.GetNetworkBehaviourOrderIndex(this), NetworkBehaviour = this, TargetClientId = targetClientId, DeliveryMappedNetworkVariableIndex = m_DeliveryMappedNetworkVariableIndices[j] }; // TODO: Serialization is where the IsDirty flag gets changed. // Messages don't get sent from the server to itself, so if we're host and sending to ourselves, // we still have to actually serialize the message even though we're not sending it, otherwise // the dirty flag doesn't change properly. These two pieces should be decoupled at some point // so we don't have to do this serialization work if we're not going to use the result. if (IsServer && targetClientId == NetworkManager.ServerClientId) { var tmpWriter = new FastBufferWriter(MessagingSystem.NON_FRAGMENTED_MESSAGE_MAX_SIZE, Allocator.Temp, MessagingSystem.FRAGMENTED_MESSAGE_MAX_SIZE); using (tmpWriter) { message.Serialize(tmpWriter); } } else { NetworkManager.SendMessage(ref message, m_DeliveryTypesForNetworkVariableGroups[j], targetClientId); } } } } } private bool CouldHaveDirtyNetworkVariables() { // TODO: There should be a better way by reading one dirty variable vs. 'n' for (int i = 0; i < NetworkVariableFields.Count; i++) { if (NetworkVariableFields[i].IsDirty()) { return true; } } return false; } internal void MarkVariablesDirty() { for (int j = 0; j < NetworkVariableFields.Count; j++) { NetworkVariableFields[j].SetDirty(true); } } internal void WriteNetworkVariableData(FastBufferWriter writer, ulong targetClientId) { if (NetworkVariableFields.Count == 0) { return; } for (int j = 0; j < NetworkVariableFields.Count; j++) { bool canClientRead = NetworkVariableFields[j].CanClientRead(targetClientId); if (canClientRead) { var writePos = writer.Position; writer.WriteValueSafe((ushort)0); var startPos = writer.Position; NetworkVariableFields[j].WriteField(writer); var size = writer.Position - startPos; writer.Seek(writePos); writer.WriteValueSafe((ushort)size); writer.Seek(startPos + size); } else { writer.WriteValueSafe((ushort)0); } } } internal void SetNetworkVariableData(FastBufferReader reader) { if (NetworkVariableFields.Count == 0) { return; } for (int j = 0; j < NetworkVariableFields.Count; j++) { reader.ReadValueSafe(out ushort varSize); if (varSize == 0) { continue; } var readStartPos = reader.Position; NetworkVariableFields[j].ReadField(reader); if (NetworkManager.NetworkConfig.EnsureNetworkVariableLengthSafety) { if (reader.Position > (readStartPos + varSize)) { if (NetworkLog.CurrentLogLevel <= LogLevel.Normal) { NetworkLog.LogWarning($"Var data read too far. {reader.Position - (readStartPos + varSize)} bytes."); } reader.Seek(readStartPos + varSize); } else if (reader.Position < (readStartPos + varSize)) { if (NetworkLog.CurrentLogLevel <= LogLevel.Normal) { NetworkLog.LogWarning($"Var data read too little. {(readStartPos + varSize) - reader.Position} bytes."); } reader.Seek(readStartPos + varSize); } } } } /// <summary> /// Gets the local instance of a object with a given NetworkId /// </summary> /// <param name="networkId"></param> /// <returns></returns> protected NetworkObject GetNetworkObject(ulong networkId) { return NetworkManager.SpawnManager.SpawnedObjects.TryGetValue(networkId, out NetworkObject networkObject) ? networkObject : null; } public virtual void OnDestroy() { // this seems odd to do here, but in fact especially in tests we can find ourselves // here without having called InitializedVariables, which causes problems if any // of those variables use native containers (e.g. NetworkList) as they won't be // registered here and therefore won't be cleaned up. // // we should study to understand the initialization patterns if (!m_VarInit) { InitializeVariables(); } for (int i = 0; i < NetworkVariableFields.Count; i++) { NetworkVariableFields[i].Dispose(); } } } }
41.884076
191
0.563247
[ "MIT" ]
wackoisgod/com.unity.netcode.gameobjects
com.unity.netcode.gameobjects/Runtime/Core/NetworkBehaviour.cs
32,879
C#
using Microsoft.EntityFrameworkCore; using Abp.Zero.EntityFrameworkCore; using LinXiDecorate.Authorization.Roles; using LinXiDecorate.Authorization.Users; using LinXiDecorate.MultiTenancy; using LinXiDecorate.Persons; namespace LinXiDecorate.EntityFrameworkCore { public class LinXiDecorateDbContext : AbpZeroDbContext<Tenant, Role, User, LinXiDecorateDbContext> { /* Define a DbSet for each entity of the application */ public LinXiDecorateDbContext(DbContextOptions<LinXiDecorateDbContext> options) : base(options) { } public DbSet<Person> People { get; set; } } }
29.227273
102
0.732504
[ "MIT" ]
FayneLi/LinXiDecorate
aspnet-core/src/LinXiDecorate.EntityFrameworkCore/EntityFrameworkCore/LinXiDecorateDbContext.cs
645
C#
using MovieMeter.Repository.Contracts; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using MovieMeter.Model; using MovieMeter.Data.Context; using AutoMapper; using System.Data.Entity; using MovieMeter.WebHarvester.Harvester; using MovieMeter.WebHarvester.Parsers; using System.Linq.Expressions; namespace MovieMeter.Repository.Repositories { public class MovieMeterEFRepository : IMovieMeterRepository { private MovieMeterContext _context; private IMapper _mapper; private const string VotesSeparator = ","; public MovieMeterEFRepository(MovieMeterContext context, IMapper mapper) { _context = context; _mapper = mapper; } public Task<Program> AddOrUpdateProgram(Program program) { throw new NotImplementedException(); } public async Task AddOrUpdateProgramUserData(ProgramUserData programUserData) { var existing = await _context.ProgramUserData.FirstOrDefaultAsync(elem => elem.ProgramId == programUserData.ProgramId && elem.UserId == programUserData.UserId); if(existing == null) { var newDbEntity = _mapper.Map<MovieMeter.Data.Model.ProgramUserData>(programUserData); _context.ProgramUserData.Add(newDbEntity); } else { existing.UserRating = programUserData.UserRating; existing.Watched = programUserData.Watched; } await _context.SaveChangesAsync(); } public async Task AddUpdate(Update update, List<Program> programs, string sourceId) { var updateDbEntity = _mapper.Map<MovieMeter.Data.Model.Update>(update); var sourceDbEntity = await _context.Sources.FirstAsync(elem => elem.Id == sourceId); sourceDbEntity.Updates.Add(updateDbEntity); _context.Updates.Add(updateDbEntity); for (int index = 0; index < programs.Count; index++) { var program = programs[index]; var programDbEntity = await _context.Programs.FirstOrDefaultAsync(elem => elem.ImdbId == program.ImdbId); if (programDbEntity == null) { program.Id = Guid.NewGuid().ToString(); programDbEntity = _mapper.Map<MovieMeter.Data.Model.Program>(program); sourceDbEntity.Programs.Add(programDbEntity); //_context.Programs.Add(programDbEntity); } else { programDbEntity.ImdbRating = program.ImdbRating; programDbEntity.ImdbVotes = program.ImdbVotes; } //programDbEntity.Source = sourceDbEntity; programDbEntity.Update = updateDbEntity; } try { await _context.SaveChangesAsync(); } catch (System.Data.Entity.Validation.DbEntityValidationException ex) { // Retrieve the error messages as a list of strings. var errorMessages = ex.EntityValidationErrors .SelectMany(x => x.ValidationErrors) .Select(x => x.ErrorMessage); // Join the list to a single string. var fullErrorMessage = string.Join("; ", errorMessages); // Combine the original exception message with the new one. var exceptionMessage = string.Concat(ex.Message, " The validation errors are: ", fullErrorMessage); // Throw a new DbEntityValidationException with the improved exception message. throw new System.Data.Entity.Validation.DbEntityValidationException(exceptionMessage, ex.EntityValidationErrors); } } public async Task<List<Program>> GetAllPrograms() { var query = await _context.Programs.ToListAsync(); var programs = query.Select(elem => _mapper.Map<Program>(elem)).ToList(); return programs; } public async Task<List<Program>> GetAllPrograms(ProgramQuery query, int count) { var programs = new List<Program>(); var updates = await GetLatestUpdates(); try { programs = await _context.Programs.Where(elem => updates.Contains(elem.Update.Id) && (!string.IsNullOrEmpty(query.Actor) ? elem.Actors.Contains(query.Actor) : true) && (!string.IsNullOrEmpty(query.Director) ? elem.Director.Contains(query.Director) : true) && (!string.IsNullOrEmpty(query.Genre) ? elem.Genre.Contains(query.Genre) : true) && (!string.IsNullOrEmpty(query.Language) ? elem.Language.Contains(query.Language) : true) && (query.MinRating.HasValue ? elem.ImdbRating >= query.MinRating : true) && (query.MaxRating.HasValue ? elem.ImdbRating <= query.MaxRating : true) && (query.Year.HasValue ? elem.Year >= query.Year : true)) .OrderByDescending(elem => elem.ImdbRating) .ProjectToListAsync<Program>(_mapper.ConfigurationProvider); programs = programs.Where(elem => query.MinVotes.HasValue ? ConvertToNumber(elem.ImdbVotes, VotesSeparator) >= query.MinVotes : true) .Take(count) .ToList(); } catch { } return programs; } public async Task<List<Source>> GetAllSources() { var query = await _context.Sources.ToListAsync(); var sources = query.Select(elem => _mapper.Map<Source>(elem)).ToList(); return sources; } public async Task<List<Update>> GetAllUpdates() { var query = await _context.Updates.ToListAsync(); var updates = query.Select(elem => _mapper.Map<Update>(elem)).ToList(); return updates; } public async Task<Update> GetLatestUpdateForSource(string sourceId) { var query = await _context.Updates.Where(elem => elem.SourceId == sourceId).OrderBy(elem => elem.UpdatedOn).FirstOrDefaultAsync(); var update = _mapper.Map<Update>(query); return update; } public async Task<Program> GetProgram(string programId) { var userId = Guid.Empty.ToString(); var program = await _context.Programs.Select(prog => new { Program = prog, ProgramUserData = prog.ProgramUserData.Where(elem => elem.UserId == userId) }) .Where(elem => elem.Program.ImdbId == programId) .Select(x => x.Program) .ProjectToSingleAsync<Program>(_mapper.ConfigurationProvider); return program; } public async Task<int> GetActiveProgramCount() { List<string> updates = await GetLatestUpdates(); var count = await _context.Programs.Where(elem => !string.IsNullOrEmpty(elem.ImdbId) && updates.Contains(elem.Update.Id)).CountAsync(); return count; } private async Task<List<string>> GetLatestUpdates() { var sources = await _context.Sources.ToListAsync(); var updates = new List<string>(); foreach (var source in sources) { var update = await _context.Updates.Where(elem => elem.SourceId == source.Id).OrderByDescending(elem => elem.UpdatedOn).FirstOrDefaultAsync(); if (update != null) updates.Add(update.Id); } return updates; } public async Task<Source> GetSource(string sourceId) { Source source = null; try { source = await _context.Sources.Where(elem => elem.Id == sourceId).ProjectToSingleAsync<Source>(_mapper.ConfigurationProvider); //source = _mapper.Map<Source>(query); } catch(Exception ex) { } return source; } public async Task<List<Update>> GetUpdatesForSource(string sourceId) { var query = await _context.Updates.Where(elem => elem.SourceId == sourceId).OrderBy(elem => elem.UpdatedOn).ToListAsync(); var updates = query.Select(elem => _mapper.Map<Update>(elem)).ToList(); return updates; } public async Task UpdateProgram(Program program) { if (program == null || string.IsNullOrEmpty(program.Id)) throw new ArgumentException("Unable to update", nameof(program)); var programData = await _context.Programs.FirstAsync(elem => elem.Id == program.Id); programData.ImdbRating = program.ImdbRating; programData.ImdbVotes = program.ImdbVotes; } private uint ConvertToNumber(string value, string separator) { uint result = 0; if (string.IsNullOrEmpty(value) == false) { var baseValue = value.Replace(separator, string.Empty); UInt32.TryParse(baseValue, out result); } return result; } } }
39.63745
173
0.557242
[ "MIT" ]
brugi82/MovieMeter
MovieMeter/MovieMeter.Repository/Repositories/MovieMeterEFRepository.cs
9,951
C#
using System.Reflection; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("MSSQLReplicationMonitorService")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Devcorner.nl")] [assembly: AssemblyProduct("MSSQLReplicationMonitorService")] [assembly: AssemblyCopyright("Copyright © Devcorner.nl 2014")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("5813c5c9-a967-447b-8651-2145fa3ed6cc")] // 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")]
39.388889
84
0.751058
[ "MIT" ]
RobThree/NMSSQLReplication
MSSQLReplicationMonitorService/Properties/AssemblyInfo.cs
1,421
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class BillboardTie : MonoBehaviour { public HackingGame hackingGame; public GameObject billboard; public Material newTexture; // Use this for initialization void Start () { } // Update is called once per frame void Update () { if (hackingGame.triggerBillboard) { billboard.GetComponent<MeshRenderer> ().material = newTexture; } } }
19.304348
65
0.740991
[ "MIT" ]
wickedlyethan/GGJ-18
Global-Game-Jam-2018/Assets/WebPlayerTemplates/BillboardTie.cs
446
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("BACnet.Tagging.Tests")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("BACnet.Tagging.Tests")] [assembly: AssemblyCopyright("Copyright © 2014")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("460aea63-3b79-45e5-a6ec-caed0d48e856")] // 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.189189
84
0.745223
[ "MIT" ]
LorenVS/bacstack
BACnet.Tagging.Tests/Properties/AssemblyInfo.cs
1,416
C#
#if NETFX_CORE using System; using System.Threading.Tasks; using Windows.Foundation; using Windows.UI.Xaml.Controls; namespace WinRTXamlToolkit.AwaitableUI { /// <summary> /// Extension methods for WebView class. /// </summary> public static class WebViewExtensions { /// <summary> /// Navigates to the given source URI and waits for the loading to complete or fail. /// </summary> public static async Task NavigateAsync(this WebView webView, Uri source) { var tcs = new TaskCompletionSource<object>(); TypedEventHandler<WebView, WebViewNavigationCompletedEventArgs> nceh = null; nceh = (s, e) => { webView.NavigationCompleted -= nceh; tcs.SetResult(null); }; webView.NavigationCompleted += nceh; webView.Navigate(source); await tcs.Task; } } } #endif
25.918919
92
0.597497
[ "MIT" ]
hermz365/WODTimer
WODTimer/WinRTXamlToolkit/AwaitableUI/WebViewExtensions 8.1.cs
961
C#
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ using System.Collections.Generic; using Aliyun.Acs.Core; using Aliyun.Acs.Core.Http; using Aliyun.Acs.Core.Transform; using Aliyun.Acs.Core.Utils; using Aliyun.Acs.live.Transform; using Aliyun.Acs.live.Transform.V20161101; namespace Aliyun.Acs.live.Model.V20161101 { public class StopCasterSceneRequest : RpcAcsRequest<StopCasterSceneResponse> { public StopCasterSceneRequest() : base("live", "2016-11-01", "StopCasterScene", "live", "openAPI") { } private string casterId; private string sceneId; private long? ownerId; public string CasterId { get { return casterId; } set { casterId = value; DictionaryUtil.Add(QueryParameters, "CasterId", value); } } public string SceneId { get { return sceneId; } set { sceneId = value; DictionaryUtil.Add(QueryParameters, "SceneId", value); } } public long? OwnerId { get { return ownerId; } set { ownerId = value; DictionaryUtil.Add(QueryParameters, "OwnerId", value.ToString()); } } public override StopCasterSceneResponse GetResponse(UnmarshallerContext unmarshallerContext) { return StopCasterSceneResponseUnmarshaller.Unmarshall(unmarshallerContext); } } }
24.625
100
0.678819
[ "Apache-2.0" ]
xueandfeng/aliyun-openapi-net-sdk
aliyun-net-sdk-live/Live/Model/V20161101/StopCasterSceneRequest.cs
2,167
C#
using System; using System.IO; using System.Text; using NUnit.Framework; // Most CSV test data came from csv-spectrum: https://github.com/maxogden/csv-spectrum namespace ExcelDataReader.Tests { [TestFixture] public class ExcelCsvReaderTest { [Test] public void CsvCommaInQuotes() { using (var excelReader = ExcelReaderFactory.CreateCsvReader(Configuration.GetTestWorkbook("csv\\comma_in_quotes.csv"))) { var ds = excelReader.AsDataSet(); Assert.AreEqual("first", ds.Tables[0].Rows[0][0]); Assert.AreEqual("last", ds.Tables[0].Rows[0][1]); Assert.AreEqual("address", ds.Tables[0].Rows[0][2]); Assert.AreEqual("city", ds.Tables[0].Rows[0][3]); Assert.AreEqual("zip", ds.Tables[0].Rows[0][4]); Assert.AreEqual("John", ds.Tables[0].Rows[1][0]); Assert.AreEqual("Doe", ds.Tables[0].Rows[1][1]); Assert.AreEqual("120 any st.", ds.Tables[0].Rows[1][2]); Assert.AreEqual("Anytown, WW", ds.Tables[0].Rows[1][3]); Assert.AreEqual("08123", ds.Tables[0].Rows[1][4]); } } [Test] public void CsvEscapedQuotes() { using (var excelReader = ExcelReaderFactory.CreateCsvReader(Configuration.GetTestWorkbook("csv\\escaped_quotes.csv"))) { var ds = excelReader.AsDataSet(); Assert.AreEqual("a", ds.Tables[0].Rows[0][0]); Assert.AreEqual("b", ds.Tables[0].Rows[0][1]); Assert.AreEqual("1", ds.Tables[0].Rows[1][0]); Assert.AreEqual("ha \"ha\" ha", ds.Tables[0].Rows[1][1]); Assert.AreEqual("3", ds.Tables[0].Rows[2][0]); Assert.AreEqual("4", ds.Tables[0].Rows[2][1]); } } [Test] public void CsvQuotesAndNewlines() { using (var stream = new MemoryStream()) { using (var writer = new StreamWriter(stream, Encoding.UTF8)) { writer.NewLine = "\n"; writer.WriteLine("a,b"); writer.WriteLine("1,\"ha "); writer.WriteLine("\"\"ha\"\" "); writer.WriteLine("ha\""); writer.WriteLine("3,4"); writer.Flush(); using (var excelReader = ExcelReaderFactory.CreateCsvReader(stream)) { var ds = excelReader.AsDataSet(); Assert.AreEqual("a", ds.Tables[0].Rows[0][0]); Assert.AreEqual("b", ds.Tables[0].Rows[0][1]); Assert.AreEqual("1", ds.Tables[0].Rows[1][0]); Assert.AreEqual("ha \n\"ha\" \nha", ds.Tables[0].Rows[1][1]); Assert.AreEqual("3", ds.Tables[0].Rows[2][0]); Assert.AreEqual("4", ds.Tables[0].Rows[2][1]); } } } } [Test] public void CsvEmpty() { // empty.csv // empty_crlf.csv TestEmpty("\n"); TestEmpty("\r\n"); } private static void TestEmpty(string newLine) { using (var stream = new MemoryStream()) { using (var writer = new StreamWriter(stream, Encoding.UTF8)) { writer.NewLine = newLine; writer.WriteLine("a,b,c"); writer.WriteLine("1,\"\",\"\""); writer.WriteLine("2,3,4"); writer.Flush(); using (var excelReader = ExcelReaderFactory.CreateCsvReader(stream)) { var ds = excelReader.AsDataSet(); Assert.AreEqual("a", ds.Tables[0].Rows[0][0]); Assert.AreEqual("b", ds.Tables[0].Rows[0][1]); Assert.AreEqual("c", ds.Tables[0].Rows[0][2]); Assert.AreEqual("1", ds.Tables[0].Rows[1][0]); Assert.AreEqual("", ds.Tables[0].Rows[1][1]); Assert.AreEqual("", ds.Tables[0].Rows[1][2]); Assert.AreEqual("2", ds.Tables[0].Rows[2][0]); Assert.AreEqual("3", ds.Tables[0].Rows[2][1]); Assert.AreEqual("4", ds.Tables[0].Rows[2][2]); } } } } [Test] public void CsvNewlines() { // newlines.csv // newlines_crlf.csv TestNewlines("\n"); TestNewlines("\r\n"); } private static void TestNewlines(string newLine) { using (var stream = new MemoryStream()) { using (var writer = new StreamWriter(stream, Encoding.UTF8)) { writer.NewLine = newLine; writer.WriteLine("a,b,c"); writer.WriteLine("1,2,3"); writer.WriteLine("\"Once upon "); writer.WriteLine("a time\",5,6"); writer.WriteLine("7,8,9"); writer.Flush(); using (var excelReader = ExcelReaderFactory.CreateCsvReader(stream)) { var ds = excelReader.AsDataSet(); Assert.AreEqual("a", ds.Tables[0].Rows[0][0]); Assert.AreEqual("b", ds.Tables[0].Rows[0][1]); Assert.AreEqual("c", ds.Tables[0].Rows[0][2]); Assert.AreEqual("1", ds.Tables[0].Rows[1][0]); Assert.AreEqual("2", ds.Tables[0].Rows[1][1]); Assert.AreEqual("3", ds.Tables[0].Rows[1][2]); Assert.AreEqual("Once upon " + newLine + "a time", ds.Tables[0].Rows[2][0]); Assert.AreEqual("5", ds.Tables[0].Rows[2][1]); Assert.AreEqual("6", ds.Tables[0].Rows[2][2]); Assert.AreEqual("7", ds.Tables[0].Rows[3][0]); Assert.AreEqual("8", ds.Tables[0].Rows[3][1]); Assert.AreEqual("9", ds.Tables[0].Rows[3][2]); } } } } [Test] public void CsvWhitespaceNull() { using (var excelReader = ExcelReaderFactory.CreateCsvReader(Configuration.GetTestWorkbook("csv\\simple_whitespace_null.csv"))) { var ds = excelReader.AsDataSet(); Assert.AreEqual("a", ds.Tables[0].Rows[0][0]); // ignore spaces Assert.AreEqual("\0b\0", ds.Tables[0].Rows[0][1]); Assert.AreEqual("c", ds.Tables[0].Rows[0][2]); // ignore tabs Assert.AreEqual("1", ds.Tables[0].Rows[1][0]); Assert.AreEqual("2", ds.Tables[0].Rows[1][1]); Assert.AreEqual("3", ds.Tables[0].Rows[1][2]); } } [Test] public void CsvEncoding() { TestEncoding("csv\\utf8.csv", "ʤ"); TestEncoding("csv\\utf8_bom.csv", "ʤ"); TestEncoding("csv\\utf16le_bom.csv", "ʤ"); TestEncoding("csv\\utf16be_bom.csv", "ʤ"); TestEncoding("csv\\cp1252.csv", "æøå"); } private static void TestEncoding(string workbook, string specialString) { using (var excelReader = ExcelReaderFactory.CreateCsvReader(Configuration.GetTestWorkbook(workbook))) { var ds = excelReader.AsDataSet(); Assert.AreEqual("a", ds.Tables[0].Rows[0][0], workbook); Assert.AreEqual("b", ds.Tables[0].Rows[0][1], workbook); Assert.AreEqual("c", ds.Tables[0].Rows[0][2], workbook); Assert.AreEqual("1", ds.Tables[0].Rows[1][0], workbook); Assert.AreEqual("2", ds.Tables[0].Rows[1][1], workbook); Assert.AreEqual("3", ds.Tables[0].Rows[1][2], workbook); Assert.AreEqual("4", ds.Tables[0].Rows[2][0], workbook); Assert.AreEqual("5", ds.Tables[0].Rows[2][1], workbook); Assert.AreEqual(specialString, ds.Tables[0].Rows[2][2], workbook); } } [Test] public void CsvWrongEncoding() { Assert.Throws(typeof(DecoderFallbackException), () => { var configuration = new ExcelReaderConfiguration() { FallbackEncoding = Encoding.UTF8 }; using (var _ = ExcelReaderFactory.CreateCsvReader(Configuration.GetTestWorkbook("csv\\cp1252.csv"), configuration)) { } }); } [Test] public void CsvBigSheet() { using (var excelReader = ExcelReaderFactory.CreateCsvReader(Configuration.GetTestWorkbook("csv\\MOCK_DATA.csv"))) { var ds = excelReader.AsDataSet(); Assert.AreEqual("id", ds.Tables[0].Rows[0][0]); Assert.AreEqual("111.4.88.155", ds.Tables[0].Rows[1000][5]); // Check value at 1024 byte buffer boundary: // 17,Christoper,Blanning,cblanningg@so-net.ne.jp,Male,76.108.72.165 Assert.AreEqual("cblanningg@so-net.ne.jp", ds.Tables[0].Rows[17][3]); Assert.AreEqual(6, ds.Tables[0].Columns.Count); Assert.AreEqual(1001, ds.Tables[0].Rows.Count); } } [Test] public void CsvNoSeparator() { TestNoSeparator(null); } [Test] public void CsvMissingSeparator() { TestNoSeparator(new ExcelReaderConfiguration() { AutodetectSeparators = new char[0] }); TestNoSeparator(new ExcelReaderConfiguration() { AutodetectSeparators = null }); } public void TestNoSeparator(ExcelReaderConfiguration configuration) { using (var stream = new MemoryStream()) { using (var writer = new StreamWriter(stream, Encoding.UTF8)) { writer.WriteLine("This"); writer.WriteLine("is"); writer.WriteLine("a"); writer.Write("test"); writer.Flush(); using (var excelReader = ExcelReaderFactory.CreateCsvReader(stream, configuration)) { var ds = excelReader.AsDataSet(); Assert.AreEqual("This", ds.Tables[0].Rows[0][0]); Assert.AreEqual("is", ds.Tables[0].Rows[1][0]); Assert.AreEqual("a", ds.Tables[0].Rows[2][0]); Assert.AreEqual("test", ds.Tables[0].Rows[3][0]); } } } } [Test] public void GitIssue323DoubleClose() { using (var reader = ExcelReaderFactory.CreateCsvReader(Configuration.GetTestWorkbook("csv\\MOCK_DATA.csv"))) { reader.Read(); reader.Close(); } } [Test] public void GitIssue333EanQuotes() { using (var reader = ExcelReaderFactory.CreateCsvReader(Configuration.GetTestWorkbook("csv\\ean.txt"))) { reader.Read(); Assert.AreEqual(2, reader.RowCount); Assert.AreEqual(24, reader.FieldCount); } } [Test] public void GitIssue351LastLineWithoutLineFeed() { using (var stream = new MemoryStream()) { using (var writer = new StreamWriter(stream, Encoding.UTF8)) { writer.NewLine = "\n"; writer.WriteLine("5;6;1;Test"); writer.Write("Test;;;"); writer.Flush(); using (var reader = ExcelReaderFactory.CreateCsvReader(stream)) { var ds = reader.AsDataSet(); Assert.AreEqual(2, ds.Tables[0].Rows.Count); Assert.AreEqual(4, reader.FieldCount); } } } } [Test] public void ColumnWidthsTest() { using (var reader = ExcelReaderFactory.CreateCsvReader(Configuration.GetTestWorkbook("csv\\column_widths_test.csv"))) { reader.Read(); Assert.AreEqual(8.43, reader.GetColumnWidth(0)); Assert.AreEqual(8.43, reader.GetColumnWidth(1)); Assert.AreEqual(8.43, reader.GetColumnWidth(2)); Assert.AreEqual(8.43, reader.GetColumnWidth(3)); Assert.AreEqual(8.43, reader.GetColumnWidth(4)); var expectedException = typeof(ArgumentException); var exception = Assert.Throws(expectedException, () => { reader.GetColumnWidth(5); }); Assert.AreEqual($"Column at index 5 does not exist.{Environment.NewLine}Parameter name: i", exception.Message); } } [Test] public void CsvDisposed() { // Verify the file stream is closed and disposed by the reader { var stream = Configuration.GetTestWorkbook("csv\\MOCK_DATA.csv"); using (IExcelDataReader excelReader = ExcelReaderFactory.CreateCsvReader(stream)) { var _ = excelReader.AsDataSet(); } Assert.Throws<ObjectDisposedException>(() => stream.ReadByte()); } } [Test] public void CsvLeaveOpen() { // Verify the file stream is not disposed by the reader { var stream = Configuration.GetTestWorkbook("csv\\MOCK_DATA.csv"); using (IExcelDataReader excelReader = ExcelReaderFactory.CreateCsvReader(stream, new ExcelReaderConfiguration() { LeaveOpen = true })) { var _ = excelReader.AsDataSet(); } stream.Seek(0, SeekOrigin.Begin); stream.ReadByte(); stream.Dispose(); } } [Test] public void CsvRowCountAnalyzeRowsThrows() { { var stream = Configuration.GetTestWorkbook("csv\\MOCK_DATA.csv"); using (IExcelDataReader reader = ExcelReaderFactory.CreateCsvReader(stream, new ExcelReaderConfiguration() { AnalyzeInitialCsvRows = 100 })) { Assert.Throws(typeof(InvalidOperationException), () => { var _ = reader.RowCount; }); } } } } }
37.830882
138
0.475154
[ "MIT" ]
60071jimmy/ExcelDataReader
test/ExcelDataReader.Tests/ExcelCsvReaderTest.cs
15,444
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.ComponentModel; using Pulumi; namespace Pulumi.AzureNative.CognitiveServices.V20160201Preview { /// <summary> /// Required. Indicates the type of cognitive service account. /// </summary> [EnumType] public readonly struct Kind : IEquatable<Kind> { private readonly string _value; private Kind(string value) { _value = value ?? throw new ArgumentNullException(nameof(value)); } public static Kind Academic { get; } = new Kind("Academic"); public static Kind Bing_Autosuggest { get; } = new Kind("Bing.Autosuggest"); public static Kind Bing_Search { get; } = new Kind("Bing.Search"); public static Kind Bing_Speech { get; } = new Kind("Bing.Speech"); public static Kind Bing_SpellCheck { get; } = new Kind("Bing.SpellCheck"); public static Kind ComputerVision { get; } = new Kind("ComputerVision"); public static Kind ContentModerator { get; } = new Kind("ContentModerator"); public static Kind Emotion { get; } = new Kind("Emotion"); public static Kind Face { get; } = new Kind("Face"); public static Kind LUIS { get; } = new Kind("LUIS"); public static Kind Recommendations { get; } = new Kind("Recommendations"); public static Kind SpeakerRecognition { get; } = new Kind("SpeakerRecognition"); public static Kind Speech { get; } = new Kind("Speech"); public static Kind SpeechTranslation { get; } = new Kind("SpeechTranslation"); public static Kind TextAnalytics { get; } = new Kind("TextAnalytics"); public static Kind TextTranslation { get; } = new Kind("TextTranslation"); public static Kind WebLM { get; } = new Kind("WebLM"); public static bool operator ==(Kind left, Kind right) => left.Equals(right); public static bool operator !=(Kind left, Kind right) => !left.Equals(right); public static explicit operator string(Kind value) => value._value; [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object? obj) => obj is Kind other && Equals(other); public bool Equals(Kind other) => string.Equals(_value, other._value, StringComparison.Ordinal); [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() => _value?.GetHashCode() ?? 0; public override string ToString() => _value; } /// <summary> /// Gets or sets the sku name. Required for account creation, optional for update. /// </summary> [EnumType] public readonly struct SkuName : IEquatable<SkuName> { private readonly string _value; private SkuName(string value) { _value = value ?? throw new ArgumentNullException(nameof(value)); } public static SkuName F0 { get; } = new SkuName("F0"); public static SkuName P0 { get; } = new SkuName("P0"); public static SkuName P1 { get; } = new SkuName("P1"); public static SkuName P2 { get; } = new SkuName("P2"); public static SkuName S0 { get; } = new SkuName("S0"); public static SkuName S1 { get; } = new SkuName("S1"); public static SkuName S2 { get; } = new SkuName("S2"); public static SkuName S3 { get; } = new SkuName("S3"); public static SkuName S4 { get; } = new SkuName("S4"); public static SkuName S5 { get; } = new SkuName("S5"); public static SkuName S6 { get; } = new SkuName("S6"); public static bool operator ==(SkuName left, SkuName right) => left.Equals(right); public static bool operator !=(SkuName left, SkuName right) => !left.Equals(right); public static explicit operator string(SkuName value) => value._value; [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object? obj) => obj is SkuName other && Equals(other); public bool Equals(SkuName other) => string.Equals(_value, other._value, StringComparison.Ordinal); [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() => _value?.GetHashCode() ?? 0; public override string ToString() => _value; } }
45.71875
107
0.642288
[ "Apache-2.0" ]
polivbr/pulumi-azure-native
sdk/dotnet/CognitiveServices/V20160201Preview/Enums.cs
4,389
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ // Generation date: 11/28/2021 8:55:09 PM namespace Microsoft.Dynamics.DataEntities { /// <summary> /// There are no comments for PayrollArrearLimitMethod in the schema. /// </summary> public enum PayrollArrearLimitMethod { AllOrNothing = 0, Partial = 1 } }
30.26087
81
0.5
[ "MIT" ]
NathanClouseAX/AAXDataEntityPerfTest
Projects/AAXDataEntityPerfTest/ODataUtility/Connected Services/D365/PayrollArrearLimitMethod.cs
698
C#
namespace Xamarin.Forms.GoogleMaps { public enum MapType { Street, Satellite, Hybrid, Terrain, None } }
14.181818
35
0.512821
[ "MIT" ]
Bhekinkosi12/Xamarin.Forms.GoogleMaps
Xamarin.Forms.GoogleMaps/Xamarin.Forms.GoogleMaps/MapType.cs
158
C#
using System.Threading.Tasks; using Microsoft.AspNetCore.Components.WebAssembly.Hosting; namespace Bamboo.Attendance.Blazor.Host { public class Program { public static async Task Main(string[] args) { var builder = WebAssemblyHostBuilder.CreateDefault(args); var application = builder.AddApplication<AttendanceBlazorHostModule>(options => { options.UseAutofac(); }); var host = builder.Build(); await application.InitializeAsync(host.Services); await host.RunAsync(); } } }
24.6
91
0.614634
[ "MIT" ]
BlazorHub/bamboomodules
Bamboo.Attendance/host/Bamboo.Attendance.Blazor.Host/Program.cs
615
C#
using System; using Newtonsoft.Json; namespace TrackApartments.Auth { public class AuthenticationModel { [JsonProperty("access_token", NullValueHandling = NullValueHandling.Ignore)] public string AccessToken { get; set; } [JsonProperty("provider_name", NullValueHandling = NullValueHandling.Ignore)] public string ProviderName { get; set; } [JsonProperty("user_id", NullValueHandling = NullValueHandling.Ignore)] public string UserId { get; set; } [JsonProperty("user_claims", NullValueHandling = NullValueHandling.Ignore)] public AuthenticationClaim[] UserClaims { get; set; } [JsonProperty("access_token_secret", NullValueHandling = NullValueHandling.Ignore)] public string AccessTokenSecret { get; set; } [JsonProperty("authentication_token", NullValueHandling = NullValueHandling.Ignore)] public string AuthenticationToken { get; set; } [JsonProperty("expires_on", NullValueHandling = NullValueHandling.Ignore)] public string ExpiresOn { get; set; } [JsonProperty("id_token", NullValueHandling = NullValueHandling.Ignore)] public string IdToken { get; set; } [JsonProperty("refresh_token", NullValueHandling = NullValueHandling.Ignore)] public string RefreshToken { get; set; } } }
37.555556
92
0.700444
[ "MIT" ]
EvilAvenger/TrackApartmentsApp
TrackApartments.Auth/AuthenticationModel.cs
1,354
C#
// Copyright 2020 The Tilt Brush Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using UnityEngine; using System; namespace TiltBrush { public class Clock : MonoBehaviour { [SerializeField] private TMPro.TextMeshPro m_Text; void Update() { if (DemoManager.m_Instance.ShouldUseCountdownTimer) { m_Text.text = DemoManager.m_Instance.TimeRemaining + " Remaining"; } else { DateTime time = DateTime.Now; if (time.Second % 2 == 0) { m_Text.text = time.ToString("h mmtt"); } else { m_Text.text = time.ToString("h:mmtt"); } } } } } // namespace TiltBrush
30.702703
75
0.696303
[ "Apache-2.0" ]
Babouchot/open-brush
Assets/Scripts/Clock.cs
1,138
C#
namespace ShoppingWebCrawler.Cef.Core { using System; using System.Collections.Generic; using System.Diagnostics; using System.Runtime.InteropServices; using ShoppingWebCrawler.Cef.Core.Interop; /// <summary> /// Callback interface for asynchronous continuation of print job requests. /// </summary> public sealed unsafe partial class CefPrintJobCallback { /// <summary> /// Indicate completion of the print job. /// </summary> public void Continue() { cef_print_job_callback_t.cont(_self); } } }
26.217391
79
0.641791
[ "Apache-2.0" ]
dongshengfengniaowu/ShoppingWebCrawler
ShoppingWebCrawler.Cef.Core/Classes.Proxies/CefPrintJobCallback.cs
605
C#
using System.Reflection; using Jasper; using Microsoft.AspNetCore.Hosting; using Shouldly; using TestingSupport; using Xunit; namespace HttpTests.AspNetCoreIntegration { public class integration_with_hosting_environment { public class FakeSettings { public string Environment { get; set; } } public class MySpecialRegistry : JasperRegistry { public MySpecialRegistry() { Handlers.DisableConventionalDiscovery(); ServiceName = "MySpecialApp"; } } [Fact] public void hosting_environment_app_name_is_application_assembly_name() { using (var runtime = JasperHost.For<MySpecialRegistry>()) { // This is important for the MVC and ASP.Net Core integration to work correctly runtime.Get<IHostingEnvironment>().ApplicationName.ShouldBe(Assembly.GetExecutingAssembly().FullName); } } [Fact] public void hosting_environment_uses_config() { var registry = new JasperRegistry(); registry.Handlers.DisableConventionalDiscovery(); registry.Hosting(x => x.UseEnvironment("Fake")); using (var runtime = JasperHost.For(registry)) { runtime.Get<IHostingEnvironment>() .EnvironmentName.ShouldBe("Fake"); } } [Fact] public void hosting_environment_uses_config_2() { var registry = new JasperRegistry(); registry.Handlers.DisableConventionalDiscovery(); registry.Hosting(x => x.UseEnvironment("Fake2")); using (var runtime = JasperHost.For(registry)) { runtime.Get<IHostingEnvironment>() .EnvironmentName.ShouldBe("Fake2"); } } } }
29.378788
118
0.580712
[ "MIT" ]
JasperFx/JasperHttp
src/HttpTests/AspNetCoreIntegration/integration_with_hosting_environment.cs
1,941
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 Microsoft.ML.Runtime; using Microsoft.ML.Runtime.CommandLine; using Microsoft.ML.Runtime.Data; using Microsoft.ML.Runtime.EntryPoints; using Microsoft.ML.Runtime.Internal.Utilities; using Microsoft.ML.Transforms.Categorical; using Microsoft.ML.Transforms.Conversions; using Microsoft.ML.Transforms.Text; using System.Collections.Generic; using System.Linq; using System.Text; [assembly: LoadableClass(WordHashBagTransform.Summary, typeof(IDataTransform), typeof(WordHashBagTransform), typeof(WordHashBagTransform.Arguments), typeof(SignatureDataTransform), "Word Hash Bag Transform", "WordHashBagTransform", "WordHashBag")] [assembly: LoadableClass(NgramHashExtractorTransform.Summary, typeof(INgramExtractorFactory), typeof(NgramHashExtractorTransform), typeof(NgramHashExtractorTransform.NgramHashExtractorArguments), typeof(SignatureNgramExtractorFactory), "Ngram Hash Extractor Transform", "NgramHashExtractorTransform", "NgramHash", NgramHashExtractorTransform.LoaderSignature)] [assembly: EntryPointModule(typeof(NgramHashExtractorTransform.NgramHashExtractorArguments))] namespace Microsoft.ML.Transforms.Text { public static class WordHashBagTransform { public sealed class Column : NgramHashExtractorTransform.ColumnBase { public static Column Parse(string str) { Contracts.AssertNonEmpty(str); var res = new Column(); if (res.TryParse(str)) return res; return null; } protected override bool TryParse(string str) { Contracts.AssertNonEmpty(str); // We accept N:B:S where N is the new column name, B is the number of bits, // and S is source column names. string extra; if (!base.TryParse(str, out extra)) return false; if (extra == null) return true; int bits; if (!int.TryParse(extra, out bits)) return false; HashBits = bits; return true; } public bool TryUnparse(StringBuilder sb) { Contracts.AssertValue(sb); if (NgramLength != null || SkipLength != null || Seed != null || Ordered != null || InvertHash != null) { return false; } if (HashBits == null) return TryUnparseCore(sb); string extra = HashBits.Value.ToString(); return TryUnparseCore(sb, extra); } } public sealed class Arguments : NgramHashExtractorTransform.ArgumentsBase { [Argument(ArgumentType.Multiple | ArgumentType.Required, HelpText = "New column definition(s) (optional form: name:hashBits:srcs)", ShortName = "col", SortOrder = 1)] public Column[] Column; } private const string RegistrationName = "WordHashBagTransform"; internal const string Summary = "Produces a bag of counts of ngrams (sequences of consecutive words of length 1-n) in a given text. " + "It does so by hashing each ngram and using the hash value as the index in the bag."; public static IDataTransform Create(IHostEnvironment env, Arguments args, IDataView input) { Contracts.CheckValue(env, nameof(env)); var h = env.Register(RegistrationName); h.CheckValue(args, nameof(args)); h.CheckValue(input, nameof(input)); h.CheckUserArg(Utils.Size(args.Column) > 0, nameof(args.Column), "Columns must be specified"); // To each input column to the WordHashBagTransform, a tokenize transform is applied, // followed by applying WordHashVectorizeTransform. // Since WordHashBagTransform is a many-to-one column transform, for each // WordHashBagTransform.Column we may need to define multiple tokenize transform columns. // NgramHashExtractorTransform may need to define an identical number of HashTransform.Columns. // The intermediate columns are dropped at the end of using a DropColumnsTransform. IDataView view = input; var uniqueSourceNames = NgramExtractionUtils.GenerateUniqueSourceNames(h, args.Column, view.Schema); Contracts.Assert(uniqueSourceNames.Length == args.Column.Length); var tokenizeColumns = new List<WordTokenizeTransform.ColumnInfo>(); var extractorCols = new NgramHashExtractorTransform.Column[args.Column.Length]; var colCount = args.Column.Length; List<string> tmpColNames = new List<string>(); for (int iinfo = 0; iinfo < colCount; iinfo++) { var column = args.Column[iinfo]; int srcCount = column.Source.Length; var curTmpNames = new string[srcCount]; Contracts.Assert(uniqueSourceNames[iinfo].Length == args.Column[iinfo].Source.Length); for (int isrc = 0; isrc < srcCount; isrc++) tokenizeColumns.Add(new WordTokenizeTransform.ColumnInfo(args.Column[iinfo].Source[isrc], curTmpNames[isrc] = uniqueSourceNames[iinfo][isrc])); tmpColNames.AddRange(curTmpNames); extractorCols[iinfo] = new NgramHashExtractorTransform.Column { Name = column.Name, Source = curTmpNames, HashBits = column.HashBits, NgramLength = column.NgramLength, Seed = column.Seed, SkipLength = column.SkipLength, Ordered = column.Ordered, InvertHash = column.InvertHash, FriendlyNames = args.Column[iinfo].Source, AllLengths = column.AllLengths }; } view = new WordTokenizingEstimator(env, tokenizeColumns.ToArray()).Fit(view).Transform(view); var featurizeArgs = new NgramHashExtractorTransform.Arguments { AllLengths = args.AllLengths, HashBits = args.HashBits, NgramLength = args.NgramLength, SkipLength = args.SkipLength, Ordered = args.Ordered, Seed = args.Seed, Column = extractorCols.ToArray(), InvertHash = args.InvertHash }; view = NgramHashExtractorTransform.Create(h, featurizeArgs, view); // Since we added columns with new names, we need to explicitly drop them before we return the IDataTransform. return SelectColumnsTransform.CreateDrop(h, view, tmpColNames.ToArray()); } } /// <summary> /// A transform that turns a collection of tokenized text (vector of ReadOnlyMemory) into numerical feature vectors /// using the hashing trick. /// </summary> public static class NgramHashExtractorTransform { public abstract class ColumnBase : ManyToOneColumn { [Argument(ArgumentType.AtMostOnce, HelpText = "Ngram length (stores all lengths up to the specified Ngram length)", ShortName = "ngram")] public int? NgramLength; [Argument(ArgumentType.AtMostOnce, HelpText = "Maximum number of tokens to skip when constructing an ngram", ShortName = "skips")] public int? SkipLength; [Argument(ArgumentType.AtMostOnce, HelpText = "Number of bits to hash into. Must be between 1 and 30, inclusive.", ShortName = "bits")] public int? HashBits; [Argument(ArgumentType.AtMostOnce, HelpText = "Hashing seed")] public uint? Seed; [Argument(ArgumentType.AtMostOnce, HelpText = "Whether the position of each source column should be included in the hash (when there are multiple source columns).", ShortName = "ord")] public bool? Ordered; [Argument(ArgumentType.AtMostOnce, HelpText = "Limit the number of keys used to generate the slot name to this many. 0 means no invert hashing, -1 means no limit.", ShortName = "ih")] public int? InvertHash; [Argument(ArgumentType.AtMostOnce, HelpText = "Whether to include all ngram lengths up to " + nameof(NgramLength) + " or only " + nameof(NgramLength), ShortName = "all", SortOrder = 4)] public bool? AllLengths; } public sealed class Column : ColumnBase { // For all source columns, use these friendly names for the source // column names instead of the real column names. public string[] FriendlyNames; public static Column Parse(string str) { Contracts.AssertNonEmpty(str); var res = new Column(); if (res.TryParse(str)) return res; return null; } protected override bool TryParse(string str) { Contracts.AssertNonEmpty(str); // We accept N:B:S where N is the new column name, B is the number of bits, // and S is source column names. string extra; if (!base.TryParse(str, out extra)) return false; if (extra == null) return true; int bits; if (!int.TryParse(extra, out bits)) return false; HashBits = bits; return true; } public bool TryUnparse(StringBuilder sb) { Contracts.AssertValue(sb); if (NgramLength != null || SkipLength != null || Seed != null || Ordered != null || InvertHash != null) { return false; } if (HashBits == null) return TryUnparseCore(sb); string extra = HashBits.Value.ToString(); return TryUnparseCore(sb, extra); } } /// <summary> /// This class is a merger of <see cref="HashTransformer.Arguments"/> and /// <see cref="NgramHashTransform.Arguments"/>, with the ordered option, /// the rehashUnigrams option and the allLength option removed. /// </summary> public abstract class ArgumentsBase { [Argument(ArgumentType.AtMostOnce, HelpText = "Ngram length", ShortName = "ngram", SortOrder = 3)] public int NgramLength = 1; [Argument(ArgumentType.AtMostOnce, HelpText = "Maximum number of tokens to skip when constructing an ngram", ShortName = "skips", SortOrder = 4)] public int SkipLength = 0; [Argument(ArgumentType.AtMostOnce, HelpText = "Number of bits to hash into. Must be between 1 and 30, inclusive.", ShortName = "bits", SortOrder = 2)] public int HashBits = 16; [Argument(ArgumentType.AtMostOnce, HelpText = "Hashing seed")] public uint Seed = 314489979; [Argument(ArgumentType.AtMostOnce, HelpText = "Whether the position of each source column should be included in the hash (when there are multiple source columns).", ShortName = "ord")] public bool Ordered = true; [Argument(ArgumentType.AtMostOnce, HelpText = "Limit the number of keys used to generate the slot name to this many. 0 means no invert hashing, -1 means no limit.", ShortName = "ih")] public int InvertHash; [Argument(ArgumentType.AtMostOnce, HelpText = "Whether to include all ngram lengths up to ngramLength or only ngramLength", ShortName = "all", SortOrder = 4)] public bool AllLengths = true; } [TlcModule.Component(Name = "NGramHash", FriendlyName = "NGram Hash Extractor Transform", Alias = "NGramHashExtractorTransform,NGramHashExtractor", Desc = "Extracts NGrams from text and convert them to vector using hashing trick.")] public sealed class NgramHashExtractorArguments : ArgumentsBase, INgramExtractorFactoryFactory { public INgramExtractorFactory CreateComponent(IHostEnvironment env, TermLoaderArguments loaderArgs) { return Create(env, this, loaderArgs); } } public sealed class Arguments : ArgumentsBase { [Argument(ArgumentType.Multiple, HelpText = "New column definition(s) (optional form: name:srcs)", ShortName = "col", SortOrder = 1)] public Column[] Column; } internal const string Summary = "A transform that turns a collection of tokenized text (vector of ReadOnlyMemory) into numerical feature vectors using the hashing trick."; internal const string LoaderSignature = "NgramHashExtractor"; public static IDataTransform Create(IHostEnvironment env, Arguments args, IDataView input, TermLoaderArguments termLoaderArgs = null) { Contracts.CheckValue(env, nameof(env)); var h = env.Register(LoaderSignature); h.CheckValue(args, nameof(args)); h.CheckValue(input, nameof(input)); h.CheckUserArg(Utils.Size(args.Column) > 0, nameof(args.Column), "Columns must be specified"); // To each input column to the NgramHashExtractorArguments, a HashTransform using 31 // bits (to minimize collisions) is applied first, followed by an NgramHashTransform. IDataView view = input; List<TermTransform.Column> termCols = null; if (termLoaderArgs != null) termCols = new List<TermTransform.Column>(); var hashColumns = new List<HashTransformer.Column>(); var ngramHashColumns = new NgramHashTransform.Column[args.Column.Length]; var colCount = args.Column.Length; // The NGramHashExtractor has a ManyToOne column type. To avoid stepping over the source // column name when a 'name' destination column name was specified, we use temporary column names. string[][] tmpColNames = new string[colCount][]; for (int iinfo = 0; iinfo < colCount; iinfo++) { var column = args.Column[iinfo]; h.CheckUserArg(!string.IsNullOrWhiteSpace(column.Name), nameof(column.Name)); h.CheckUserArg(Utils.Size(column.Source) > 0 && column.Source.All(src => !string.IsNullOrWhiteSpace(src)), nameof(column.Source)); int srcCount = column.Source.Length; tmpColNames[iinfo] = new string[srcCount]; for (int isrc = 0; isrc < srcCount; isrc++) { var tmpName = input.Schema.GetTempColumnName(column.Source[isrc]); tmpColNames[iinfo][isrc] = tmpName; if (termLoaderArgs != null) { termCols.Add( new TermTransform.Column { Name = tmpName, Source = column.Source[isrc] }); } hashColumns.Add( new HashTransformer.Column { Name = tmpName, Source = termLoaderArgs == null ? column.Source[isrc] : tmpName, HashBits = 30, Seed = column.Seed, Ordered = false, InvertHash = column.InvertHash }); } ngramHashColumns[iinfo] = new NgramHashTransform.Column { Name = column.Name, Source = tmpColNames[iinfo], AllLengths = column.AllLengths, HashBits = column.HashBits, NgramLength = column.NgramLength, RehashUnigrams = false, Seed = column.Seed, SkipLength = column.SkipLength, Ordered = column.Ordered, InvertHash = column.InvertHash, // REVIEW: This is an ugly internal hack to get around // the problem that we want the *original* source names surfacing // in the descriptions where appropriate, rather than _tmp000 and // what have you. The alternative is we do something elaborate // with metadata or something but I'm not sure that's better. FriendlyNames = column.FriendlyNames }; } if (termLoaderArgs != null) { h.Assert(Utils.Size(termCols) == hashColumns.Count); var termArgs = new TermTransform.Arguments() { MaxNumTerms = int.MaxValue, Terms = termLoaderArgs.Terms, Term = termLoaderArgs.Term, DataFile = termLoaderArgs.DataFile, Loader = termLoaderArgs.Loader, TermsColumn = termLoaderArgs.TermsColumn, Sort = termLoaderArgs.Sort, Column = termCols.ToArray() }; view = TermTransform.Create(h, termArgs, view); if (termLoaderArgs.DropUnknowns) { var naDropArgs = new MissingValueDroppingTransformer.Arguments { Column = new MissingValueDroppingTransformer.Column[termCols.Count] }; for (int iinfo = 0; iinfo < termCols.Count; iinfo++) { naDropArgs.Column[iinfo] = new MissingValueDroppingTransformer.Column { Name = termCols[iinfo].Name, Source = termCols[iinfo].Name }; } view = new MissingValueDroppingTransformer(h, naDropArgs, view); } } // Args for the Hash function with multiple columns var hashArgs = new HashTransformer.Arguments { HashBits = 31, Seed = args.Seed, Ordered = false, Column = hashColumns.ToArray(), InvertHash = args.InvertHash }; view = HashTransformer.Create(h, hashArgs, view); // creating the NgramHash function var ngramHashArgs = new NgramHashTransform.Arguments { AllLengths = args.AllLengths, HashBits = args.HashBits, NgramLength = args.NgramLength, SkipLength = args.SkipLength, RehashUnigrams = false, Ordered = args.Ordered, Seed = args.Seed, Column = ngramHashColumns, InvertHash = args.InvertHash }; view = new NgramHashTransform(h, ngramHashArgs, view); return SelectColumnsTransform.CreateDrop(h, view, tmpColNames.SelectMany(cols => cols).ToArray()); } public static IDataTransform Create(NgramHashExtractorArguments extractorArgs, IHostEnvironment env, IDataView input, ExtractorColumn[] cols, TermLoaderArguments termLoaderArgs = null) { Contracts.CheckValue(env, nameof(env)); var h = env.Register(LoaderSignature); h.CheckValue(extractorArgs, nameof(extractorArgs)); h.CheckValue(input, nameof(input)); h.CheckUserArg(extractorArgs.SkipLength < extractorArgs.NgramLength, nameof(extractorArgs.SkipLength), "Should be less than " + nameof(extractorArgs.NgramLength)); h.CheckUserArg(Utils.Size(cols) > 0, nameof(Arguments.Column), "Must be specified"); h.AssertValueOrNull(termLoaderArgs); var extractorCols = new Column[cols.Length]; for (int i = 0; i < cols.Length; i++) { extractorCols[i] = new Column { Name = cols[i].Name, Source = cols[i].Source, FriendlyNames = cols[i].FriendlyNames }; } var args = new Arguments { Column = extractorCols, NgramLength = extractorArgs.NgramLength, SkipLength = extractorArgs.SkipLength, HashBits = extractorArgs.HashBits, InvertHash = extractorArgs.InvertHash, Ordered = extractorArgs.Ordered, Seed = extractorArgs.Seed, AllLengths = extractorArgs.AllLengths }; return Create(h, args, input, termLoaderArgs); } public static INgramExtractorFactory Create(IHostEnvironment env, NgramHashExtractorArguments extractorArgs, TermLoaderArguments termLoaderArgs) { Contracts.CheckValue(env, nameof(env)); var h = env.Register(LoaderSignature); h.CheckValue(extractorArgs, nameof(extractorArgs)); h.CheckValueOrNull(termLoaderArgs); return new NgramHashExtractorFactory(extractorArgs, termLoaderArgs); } } }
45.444668
196
0.561056
[ "MIT" ]
Caraul/machinelearning
src/Microsoft.ML.Transforms/Text/WordHashBagTransform.cs
22,588
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using MvvmCross.Forms.Presenters.Attributes; using MvvmCross.Forms.Views; using MvxFormsTemp.Core.ViewModels.Home; using Xamarin.Forms; using Xamarin.Forms.Xaml; namespace MvxFormsTemp.UI.Pages { [XamlCompilation(XamlCompilationOptions.Compile)] [MvxContentPagePresentation(WrapInNavigationPage = true)] public partial class HomePage : MvxContentPage<HomeViewModel> { public HomePage() { InitializeComponent(); } protected override void OnAppearing() { base.OnAppearing(); if (Application.Current.MainPage is NavigationPage navigationPage) { navigationPage.BarTextColor = Color.White; navigationPage.BarBackgroundColor = (Color)Application.Current.Resources["PrimaryColor"]; } } } }
27.485714
105
0.681913
[ "MIT" ]
3factr/3factr-scaffolding
src/Templates/MvxForms/Blank/src/MvxFormsTemp.UI/Pages/HomePage.xaml.cs
962
C#
namespace buildeR.Common.DTO { public class UserLetterDTO { public string UserName { get; set; } public string UserEmail { get; set; } public string Subject { get; set; } public string Description { get; set; } public int Rating { get; set; } public bool IsRespond { get; set; } } }
28.5
47
0.590643
[ "MIT" ]
yermolenko-d/bsa-2020-buildeR
backend/buildeR.Common/DTO/UserLetterDTO.cs
342
C#
namespace JoinRpg.Web.Models.FieldSetup { /// <summary> /// Navigation in fields area /// </summary> public class FieldNavigationModel : IProjectIdAware { /// <see cref="FieldNavigationPage"/> public FieldNavigationPage Page { get; set; } /// <inheritdoc /> public int ProjectId { get; set; } /// <summary> /// Can current user edit fields /// </summary> public bool CanEditFields { get; set; } } /// <summary> /// Chosen page /// </summary> public enum FieldNavigationPage { /// <summary> /// Some unknown page of this area /// </summary> Unknown = 0, /// <summary> /// All active fields /// </summary> ActiveFieldsList = 1, /// <summary> /// All deleted fields /// </summary> DeletedFieldsList = 2, /// <summary> /// Field settings /// </summary> FieldSettings = 3, /// <summary> /// Adding field /// </summary> AddField = 4, /// <summary> /// Editing field /// </summary> EditField = 5, } }
23.54902
55
0.486261
[ "MIT" ]
HeyLaurelTestOrg/joinrpg-net
src/JoinRpg.WebPortal.Models/FieldSetup/FieldNavigationModel.cs
1,201
C#
// <auto-generated> // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. // </auto-generated> namespace Microsoft.Azure.Management.RecoveryServices.SiteRecovery.Models { using Newtonsoft.Json; using System.Linq; /// <summary> /// Contains the localized display information for this particular /// operation / action. These value will be used by several clients for (1) /// custom role definitions for RBAC; (2) complex query filters for the /// event service; and (3) audit history / records for management /// operations. /// </summary> public partial class Display { /// <summary> /// Initializes a new instance of the Display class. /// </summary> public Display() { CustomInit(); } /// <summary> /// Initializes a new instance of the Display class. /// </summary> /// <param name="provider">The provider. The localized friendly form of /// the resource provider name – it is expected to also include the /// publisher/company responsible. It should use Title Casing and begin /// with "Microsoft" for 1st party services. e.g. "Microsoft Monitoring /// Insights" or "Microsoft Compute."</param> /// <param name="resource">The resource. The localized friendly form of /// the resource related to this action/operation – it should match the /// public documentation for the resource provider. It should use Title /// Casing. This value should be unique for a particular URL type (e.g. /// nested types should *not* reuse their parent’s display.resource /// field). e.g. "Virtual Machines" or "Scheduler Job Collections", or /// "Virtual Machine VM Sizes" or "Scheduler Jobs"</param> /// <param name="operation">The operation. The localized friendly name /// for the operation, as it should be shown to the user. It should be /// concise (to fit in drop downs) but clear (i.e. self-documenting). /// It should use Title Casing. Prescriptive guidance: Read Create or /// Update Delete 'ActionName'</param> /// <param name="description">The description. The localized friendly /// description for the operation, as it should be shown to the user. /// It should be thorough, yet concise – it will be used in tool tips /// and detailed views. Prescriptive guidance for namespaces: Read any /// 'display.provider' resource Create or Update any 'display.provider' /// resource Delete any 'display.provider' resource Perform any other /// action on any 'display.provider' resource Prescriptive guidance for /// namespaces: Read any 'display.resource' Create or Update any /// 'display.resource' Delete any 'display.resource' 'ActionName' any /// 'display.resources'</param> public Display(string provider = default(string), string resource = default(string), string operation = default(string), string description = default(string)) { Provider = provider; Resource = resource; Operation = operation; Description = description; CustomInit(); } /// <summary> /// An initialization method that performs custom operations like setting defaults /// </summary> partial void CustomInit(); /// <summary> /// Gets or sets the provider. The localized friendly form of the /// resource provider name – it is expected to also include the /// publisher/company responsible. It should use Title Casing and begin /// with "Microsoft" for 1st party services. e.g. "Microsoft Monitoring /// Insights" or "Microsoft Compute." /// </summary> [JsonProperty(PropertyName = "provider")] public string Provider { get; set; } /// <summary> /// Gets or sets the resource. The localized friendly form of the /// resource related to this action/operation – it should match the /// public documentation for the resource provider. It should use Title /// Casing. This value should be unique for a particular URL type (e.g. /// nested types should *not* reuse their parent’s display.resource /// field). e.g. "Virtual Machines" or "Scheduler Job Collections", or /// "Virtual Machine VM Sizes" or "Scheduler Jobs" /// </summary> [JsonProperty(PropertyName = "resource")] public string Resource { get; set; } /// <summary> /// Gets or sets the operation. The localized friendly name for the /// operation, as it should be shown to the user. It should be concise /// (to fit in drop downs) but clear (i.e. self-documenting). It should /// use Title Casing. Prescriptive guidance: Read Create or Update /// Delete 'ActionName' /// </summary> [JsonProperty(PropertyName = "operation")] public string Operation { get; set; } /// <summary> /// Gets or sets the description. The localized friendly description /// for the operation, as it should be shown to the user. It should be /// thorough, yet concise – it will be used in tool tips and detailed /// views. Prescriptive guidance for namespaces: Read any /// 'display.provider' resource Create or Update any 'display.provider' /// resource Delete any 'display.provider' resource Perform any other /// action on any 'display.provider' resource Prescriptive guidance for /// namespaces: Read any 'display.resource' Create or Update any /// 'display.resource' Delete any 'display.resource' 'ActionName' any /// 'display.resources' /// </summary> [JsonProperty(PropertyName = "description")] public string Description { get; set; } } }
49.34127
166
0.64211
[ "MIT" ]
0rland0Wats0n/azure-sdk-for-net
sdk/recoveryservices-siterecovery/Microsoft.Azure.Management.RecoveryServices.SiteRecovery/src/Generated/Models/Display.cs
6,233
C#
// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information. // Ported from um/Uxtheme.h in the Windows SDK for Windows 10.0.22000.0 // Original source is Copyright © Microsoft. All rights reserved. namespace TerraFX.Interop.Windows; /// <include file='TA_TIMINGFUNCTION.xml' path='doc/member[@name="TA_TIMINGFUNCTION"]/*' /> public partial struct TA_TIMINGFUNCTION { /// <include file='TA_TIMINGFUNCTION.xml' path='doc/member[@name="TA_TIMINGFUNCTION.eTimingFunctionType"]/*' /> public TA_TIMINGFUNCTION_TYPE eTimingFunctionType; }
44.928571
145
0.766296
[ "MIT" ]
reflectronic/terrafx.interop.windows
sources/Interop/Windows/Windows/um/Uxtheme/TA_TIMINGFUNCTION.cs
631
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, // MERCHANTABILITY OR NON-INFRINGEMENT. // // See the Apache Version 2.0 License for specific language governing // permissions and limitations under the License. using System.IO; #if DEV16_OR_LATER using Microsoft.WebTools.Languages.Html.Artifacts; using Microsoft.WebTools.Languages.Shared.Text; #else using Microsoft.Html.Core.Artifacts; using Microsoft.Web.Core.Text; #endif namespace Microsoft.PythonTools.Django.TemplateParsing { /// <summary> /// Produces the <see cref="TemplateArtifactCollection"/> for a given text document. /// </summary> internal class TemplateArtifactProcessor : IArtifactProcessor { private class TextProviderReader : TextReader { private readonly ITextProvider _text; private int _pos; public TextProviderReader(ITextProvider text) { _text = text; } public override int Read() { if (_pos >= _text.Length) { return -1; } return _text[_pos++]; } } public void GetArtifacts(ITextProvider text, ArtifactCollection artifactCollection) { var reader = new TextProviderReader(text); var tokenizer = new TemplateTokenizer(reader); foreach (var token in tokenizer.GetTokens()) { if (token.Kind != TemplateTokenKind.Text) { var range = TextRange.FromBounds(token.Start, token.End + 1); var artifact = TemplateArtifact.Create(token.Kind, range, token.IsClosed); artifactCollection.Add(artifact); } } } public ArtifactCollection CreateArtifactCollection() { return new TemplateArtifactCollection(); } public bool IsReady { get { return true; } } public string LeftSeparator { get { return ""; } } public string RightSeparator { get { return ""; } } public string LeftCommentSeparator { get { return "{#"; } } public string RightCommentSeparator { get { return "#}"; } } } }
32.682353
94
0.62059
[ "Apache-2.0" ]
awesome-archive/PTVS
Python/Product/Django/TemplateParsing/TemplateArtifactProcessor.cs
2,778
C#
// <auto-generated> /* * OpenAPI Petstore * * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://github.com/openapitools/openapi-generator.git */ #nullable enable using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; namespace Org.OpenAPITools.Model { /// <summary> /// Foo /// </summary> public partial class Foo : IEquatable<Foo>, IValidatableObject { /// <summary> /// Initializes a new instance of the <see cref="Foo" /> class. /// </summary> /// <param name="bar">bar (default to &quot;bar&quot;)</param> public Foo(string? bar = "bar") { Bar = bar; } /// <summary> /// Gets or Sets Bar /// </summary> [JsonPropertyName("bar")] public string? Bar { get; set; } /// <summary> /// Gets or Sets additional properties /// </summary> [JsonExtensionData] public Dictionary<string, JsonElement> AdditionalProperties { get; set; } = new Dictionary<string, JsonElement>(); /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { StringBuilder sb = new StringBuilder(); sb.Append("class Foo {\n"); sb.Append(" Bar: ").Append(Bar).Append("\n"); sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <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 OpenAPIClientUtils.compareLogic.Compare(this, input as Foo).AreEqual; } /// <summary> /// Returns true if Foo instances are equal /// </summary> /// <param name="input">Instance of Foo to be compared</param> /// <returns>Boolean</returns> public bool Equals(Foo? input) { return OpenAPIClientUtils.compareLogic.Compare(this, input).AreEqual; } /// <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.Bar != null) { hashCode = (hashCode * 59) + this.Bar.GetHashCode(); } if (this.AdditionalProperties != null) { hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); } return hashCode; } } /// <summary> /// To validate all properties of the instance /// </summary> /// <param name="validationContext">Validation context</param> /// <returns>Validation Result</returns> public IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> Validate(ValidationContext validationContext) { yield break; } } }
31.852459
159
0.576171
[ "Apache-2.0" ]
1inker/openapi-generator
samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/Foo.cs
3,886
C#
// -------------------------------------------------------------------------------------------------------------------- // <summary> // The widget. // </summary> // -------------------------------------------------------------------------------------------------------------------- namespace Widgets.VisitorInfo { using System; using System.Collections.Generic; using App_Code.Controls; using BlogEngine.Core; /// <summary> /// The widget. /// </summary> public partial class Widget : WidgetBase { #region Constants and Fields /// <summary> /// The number of comments. /// </summary> private int numberOfComments; #endregion #region Properties /// <summary> /// Gets a value indicating whether IsEditable. /// </summary> public override bool IsEditable { get { return false; } } /// <summary> /// Gets Name. /// </summary> public override string Name { get { return "Visitor info"; } } #endregion #region Public Methods /// <summary> /// This method works as a substitute for Page_Load. You should use this method for /// data binding etc. instead of Page_Load. /// </summary> public override void LoadWidget() { Visible = false; var cookie = Request.Cookies["comment"]; if (cookie == null) { return; } var name = cookie.Values["name"]; var email = cookie.Values["email"]; var website = cookie.Values["url"]; if (name == null) { return; } name = name.Replace("+", " "); WriteHtml(name, email, website); Uri url; if (Request.QueryString["apml"] == null && Uri.TryCreate(website, UriKind.Absolute, out url)) { phScript.Visible = true; // ltWebsite.Text = url.ToString(); } Visible = true; } #endregion #region Methods /// <summary> /// Gets the commented posts. /// </summary> /// <param name="email">The email.</param> /// <param name="website">The website.</param> /// <returns>A list of Post</returns> private List<Post> GetCommentedPosts(string email, string website) { var list = new List<Post>(); foreach (var post in Post.Posts) { var comments = post.Comments.FindAll( c => email.Equals(c.Email, StringComparison.OrdinalIgnoreCase) || (c.Website != null && c.Website.ToString().Equals(website, StringComparison.OrdinalIgnoreCase))); if (comments.Count <= 0) { continue; } numberOfComments += comments.Count; var index = post.Comments.IndexOf(comments[comments.Count - 1]); if (index < post.Comments.Count - 1 && post.Comments[post.Comments.Count - 1].DateCreated > DateTime.Now.AddDays(-7)) { list.Add(post); } } return list; } /// <summary> /// Writes the HTML. /// </summary> /// <param name="name">The name to write.</param> /// <param name="email">The email.</param> /// <param name="website">The website.</param> private void WriteHtml(string name, string email, string website) { if (name.Contains(" ")) { name = name.Substring(0, name.IndexOf(" ")); } var avatar = Avatar.GetAvatar(16, email, null, null, name); var avatarLink = avatar == null || avatar.Url == null ? string.Empty : avatar.Url.ToString(); Title = string.Format( String.Concat("<img src=\"{0}\" alt=\"{1}\" align=\"top\" /> ", Resources.labels.visitorHi, " {1}"), avatarLink, Server.HtmlEncode(name)); pName.InnerHtml = "<strong>" + Resources.labels.welcomeBack + "</strong>"; var list = GetCommentedPosts(email, website); if (list.Count > 0) { var link = string.Format( "<a href=\"{0}\">{1}</a>", list[0].RelativeLink, Server.HtmlEncode(list[0].Title)); pComment.InnerHtml = string.Format(Resources.labels.commentsAddedSince, link); } if (numberOfComments > 0) { pComment.InnerHtml += string.Format(Resources.labels.writtenCommentsTotal, numberOfComments); } } #endregion } }
30.071856
154
0.459578
[ "MIT" ]
blee-usa/BlogEngine28
widgets/Visitor info/widget.ascx.cs
5,024
C#
using System; using System.Threading.Tasks; namespace Pop3.IO { internal interface INetworkOperations : IDisposable { #region Methods #if FULL void Open(string hostName, int port); void Open(string hostName, int port, bool useSsl); void Open(string hostName, int port, bool useSsl, bool checkCertificate); string Read(); void Write(string data); #endif void Close(); #endregion #region Async Methods #if !NET40 Task OpenAsync(string hostName, int port); Task OpenAsync(string hostName, int port, bool useSsl); Task<string> ReadAsync(); Task WriteAsync(string data); #endif #endregion } }
18.15
81
0.626722
[ "MIT" ]
rfinochi/pop3dotnet
LibraryCore/IO/INetworkOperations.cs
728
C#
/* Copyright (C) 2013-present The DataCentric Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using System; using System.Collections.Generic; using DataCentric; using Xunit; namespace DataCentric.Test { /// <summary>Unit tests for XmlTreeReader.</summary> public class XmlReaderTest { /// <summary>Test for reading XML with attributes.</summary> [Fact] public void Attributes() { using (var context = new UnitTestContext(this)) { string eol = StringUtil.Eol; string xmlText = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" + eol + "<firstElement attributeOfFirstElement1=\"AttributeValue1\" attributeOfFirstElement2=\"AttributeValue2\">" + eol + " <secondElement>" + eol + " <valueElement1>TestValue1</valueElement1>" + eol + " <valueElement2 attributeOfValueElement=\"AttributeValue\">TestValue2</valueElement2>" + eol + " </secondElement>" + eol + "</firstElement>" + eol; // Create XML reader ITreeReader reader = new XmlTreeReader(xmlText); // Read root element with two attributes ITreeReader firstElement = reader.ReadElement("firstElement"); context.Log.Verify($"attributeOfFirstElement1={firstElement.ReadAttribute("attributeOfFirstElement1")}"); context.Log.Verify($"attributeOfFirstElement2={firstElement.ReadAttribute("attributeOfFirstElement2")}"); // Read embedded element ITreeReader secondElement = firstElement.ReadElement("secondElement"); // Read value element using a single method call string valueElement1 = secondElement.ReadValueElement("valueElement1"); context.Log.Verify($"valueElement1={valueElement1}"); // Add value element with two attributes by creating element explicitly ITreeReader valueElementNode2 = secondElement.ReadElement("valueElement2"); string valueElement2 = valueElementNode2.ReadValue(); context.Log.Verify($"attributeOfValueElement={valueElementNode2.ReadAttribute("attributeOfValueElement")}"); context.Log.Verify($"valueElement2={valueElement2}"); } } } }
43.323529
128
0.636117
[ "Apache-2.0" ]
datacentricorg/datacentric-cs
cs/src/DataCentric.Test/Serialization/Xml/XmlTreeReaderTest.cs
2,946
C#
//////////////////////////////////////////////////////////////////////////////// //NUnit tests for "EF Core Provider for LCPI OLE DB" // IBProvider and Contributors. 26.03.2021. using System; using System.Data; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using Microsoft.EntityFrameworkCore; using NUnit.Framework; using xdb=lcpi.data.oledb; namespace EFCore_LcpiOleDb_Tests.General.Work.DBMS.Firebird.V03_0_0.D3.Query.Operators.SET_002__AS_STR.Add.Complete.Double.Double{ //////////////////////////////////////////////////////////////////////////////// using T_DATA1 =System.Double; using T_DATA2 =System.Double; //////////////////////////////////////////////////////////////////////////////// //class TestSet_R504AAB004__param____NV public static class TestSet_R504AAB004__param____NV { private const string c_NameOf__TABLE ="DUAL"; private sealed class MyContext:TestBaseDbContext { [Table(c_NameOf__TABLE)] public sealed class TEST_RECORD { [Key] [Column("ID")] public System.Int32? TEST_ID { get; set; } };//class TEST_RECORD //---------------------------------------------------------------------- public DbSet<TEST_RECORD> testTable { get; set; } //---------------------------------------------------------------------- public MyContext(xdb.OleDbTransaction tr) :base(tr) { }//MyContext };//class MyContext //----------------------------------------------------------------------- [Test] public static void Test_001() { using(var cn=LocalCnHelper.CreateCn()) { cn.Open(); using(var tr=cn.BeginTransaction()) { //insert new record in external transaction using(var db=new MyContext(tr)) { string vv1=null; string vv2="12"; var recs=db.testTable.Where(r => (string)(object)(((T_DATA1)vv1.Length)+((T_DATA1)vv1.Length)+((T_DATA2)vv2.Length))==null); int nRecs=0; foreach(var r in recs) { Assert.AreEqual (0, nRecs); ++nRecs; Assert.IsTrue (r.TEST_ID.HasValue); Assert.AreEqual (1, r.TEST_ID.Value); }//foreach r db.CheckTextOfLastExecutedCommand (new TestSqlTemplate() .T("SELECT ").N("d","ID").EOL() .T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("d").EOL() .T("WHERE ").P_BOOL("__Exec_V_V_0")); Assert.AreEqual (1, nRecs); }//using db tr.Commit(); }//using tr }//using cn }//Test_001 //----------------------------------------------------------------------- [Test] public static void Test_002() { using(var cn=LocalCnHelper.CreateCn()) { cn.Open(); using(var tr=cn.BeginTransaction()) { //insert new record in external transaction using(var db=new MyContext(tr)) { string vv1=null; string vv2="12"; var recs=db.testTable.Where(r => (string)(object)((((T_DATA1)vv1.Length)+((T_DATA1)vv1.Length))+((T_DATA2)vv2.Length))==null); int nRecs=0; foreach(var r in recs) { Assert.AreEqual (0, nRecs); ++nRecs; Assert.IsTrue (r.TEST_ID.HasValue); Assert.AreEqual (1, r.TEST_ID.Value); }//foreach r db.CheckTextOfLastExecutedCommand (new TestSqlTemplate() .T("SELECT ").N("d","ID").EOL() .T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("d").EOL() .T("WHERE ").P_BOOL("__Exec_V_V_0")); Assert.AreEqual (1, nRecs); }//using db tr.Commit(); }//using tr }//using cn }//Test_002 //----------------------------------------------------------------------- [Test] public static void Test_003() { using(var cn=LocalCnHelper.CreateCn()) { cn.Open(); using(var tr=cn.BeginTransaction()) { //insert new record in external transaction using(var db=new MyContext(tr)) { string vv1=null; string vv2="12"; var recs=db.testTable.Where(r => (string)(object)(((T_DATA1)vv1.Length)+(((T_DATA1)vv1.Length)+((T_DATA2)vv2.Length)))==null); int nRecs=0; foreach(var r in recs) { Assert.AreEqual (0, nRecs); ++nRecs; Assert.IsTrue (r.TEST_ID.HasValue); Assert.AreEqual (1, r.TEST_ID.Value); }//foreach r db.CheckTextOfLastExecutedCommand (new TestSqlTemplate() .T("SELECT ").N("d","ID").EOL() .T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("d").EOL() .T("WHERE ").P_BOOL("__Exec_V_V_0")); Assert.AreEqual (1, nRecs); }//using db tr.Commit(); }//using tr }//using cn }//Test_003 };//class TestSet_R504AAB004__param____NV //////////////////////////////////////////////////////////////////////////////// }//namespace EFCore_LcpiOleDb_Tests.General.Work.DBMS.Firebird.V03_0_0.D3.Query.Operators.SET_002__AS_STR.Add.Complete.Double.Double
24.150485
132
0.526633
[ "MIT" ]
ibprovider/Lcpi.EFCore.LcpiOleDb
Tests/General/Source/Work/DBMS/Firebird/V03_0_0/D3/Query/Operators/SET_002__AS_STR/Add/Complete/Double/Double/TestSet_R504AAB004__param____NV.cs
4,977
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.Data.Common; using System.Data.SqlTypes; using System.Diagnostics; using System.Runtime.CompilerServices; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Xml; using Microsoft.SqlServer.Server; namespace System.Data.SqlClient { public sealed class SqlCommand : DbCommand { private string _commandText; private CommandType _commandType; private int _commandTimeout = ADP.DefaultCommandTimeout; private readonly static DiagnosticListener _diagnosticListener = new DiagnosticListener(SqlClientDiagnosticListenerExtensions.DiagnosticListenerName); private bool _parentOperationStarted = false; // Prepare // Against 7.0 Serve a prepare/unprepare requires an extra roundtrip to the server. // // From 8.0 and above the preparation can be done as part of the command execution. private enum EXECTYPE { UNPREPARED, // execute unprepared commands, all server versions (results in sp_execsql call) PREPAREPENDING, // prepare and execute command, 8.0 and above only (results in sp_prepexec call) PREPARED, // execute prepared commands, all server versions (results in sp_exec call) } // _hiddenPrepare // On 8.0 and above the Prepared state cannot be left. Once a command is prepared it will always be prepared. // A change in parameters, commandtext etc (IsDirty) automatically causes a hidden prepare // // _inPrepare will be set immediately before the actual prepare is done. // The OnReturnValue function will test this flag to determine whether the returned value is a _prepareHandle or something else. // // _prepareHandle - the handle of a prepared command. Apparently there can be multiple prepared commands at a time - a feature that we do not support yet. private bool _inPrepare = false; private int _prepareHandle = -1; private bool _hiddenPrepare = false; private int _preparedConnectionCloseCount = -1; private int _preparedConnectionReconnectCount = -1; private SqlParameterCollection _parameters; private SqlConnection _activeConnection; private bool _dirty = false; // true if the user changes the commandtext or number of parameters after the command is already prepared private EXECTYPE _execType = EXECTYPE.UNPREPARED; // by default, assume the user is not sharing a connection so the command has not been prepared // cut down on object creation and cache all these // cached metadata private _SqlMetaDataSet _cachedMetaData; // Last TaskCompletionSource for reconnect task - use for cancellation only private TaskCompletionSource<object> _reconnectionCompletionSource = null; #if DEBUG static internal int DebugForceAsyncWriteDelay { get; set; } #endif // Cached info for async executions private class CachedAsyncState { private int _cachedAsyncCloseCount = -1; // value of the connection's CloseCount property when the asyncResult was set; tracks when connections are closed after an async operation private TaskCompletionSource<object> _cachedAsyncResult = null; private SqlConnection _cachedAsyncConnection = null; // Used to validate that the connection hasn't changed when end the connection; private SqlDataReader _cachedAsyncReader = null; private RunBehavior _cachedRunBehavior = RunBehavior.ReturnImmediately; private string _cachedEndMethod = null; internal CachedAsyncState() { } internal SqlDataReader CachedAsyncReader { get { return _cachedAsyncReader; } } internal RunBehavior CachedRunBehavior { get { return _cachedRunBehavior; } } internal bool PendingAsyncOperation { get { return (null != _cachedAsyncResult); } } internal string EndMethodName { get { return _cachedEndMethod; } } internal bool IsActiveConnectionValid(SqlConnection activeConnection) { return (_cachedAsyncConnection == activeConnection && _cachedAsyncCloseCount == activeConnection.CloseCount); } internal void ResetAsyncState() { _cachedAsyncCloseCount = -1; _cachedAsyncResult = null; if (_cachedAsyncConnection != null) { _cachedAsyncConnection.AsyncCommandInProgress = false; _cachedAsyncConnection = null; } _cachedAsyncReader = null; _cachedRunBehavior = RunBehavior.ReturnImmediately; _cachedEndMethod = null; } internal void SetActiveConnectionAndResult(TaskCompletionSource<object> completion, string endMethod, SqlConnection activeConnection) { Debug.Assert(activeConnection != null, "Unexpected null connection argument on SetActiveConnectionAndResult!"); TdsParser parser = activeConnection.TryGetParser(); if ((parser == null) || (parser.State == TdsParserState.Closed) || (parser.State == TdsParserState.Broken)) { throw ADP.ClosedConnectionError(); } _cachedAsyncCloseCount = activeConnection.CloseCount; _cachedAsyncResult = completion; if (null != activeConnection && !parser.MARSOn) { if (activeConnection.AsyncCommandInProgress) throw SQL.MARSUnspportedOnConnection(); } _cachedAsyncConnection = activeConnection; // Should only be needed for non-MARS, but set anyways. _cachedAsyncConnection.AsyncCommandInProgress = true; _cachedEndMethod = endMethod; } internal void SetAsyncReaderState(SqlDataReader ds, RunBehavior runBehavior) { _cachedAsyncReader = ds; _cachedRunBehavior = runBehavior; } } private CachedAsyncState _cachedAsyncState = null; private CachedAsyncState cachedAsyncState { get { if (_cachedAsyncState == null) { _cachedAsyncState = new CachedAsyncState(); } return _cachedAsyncState; } } // sql reader will pull this value out for each NextResult call. It is not cumulative // _rowsAffected is cumulative for ExecuteNonQuery across all rpc batches internal int _rowsAffected = -1; // rows affected by the command // transaction support private SqlTransaction _transaction; private StatementCompletedEventHandler _statementCompletedEventHandler; private TdsParserStateObject _stateObj; // this is the TDS session we're using. // Volatile bool used to synchronize with cancel thread the state change of an executing // command going from pre-processing to obtaining a stateObject. The cancel synchronization // we require in the command is only from entering an Execute* API to obtaining a // stateObj. Once a stateObj is successfully obtained, cancel synchronization is handled // by the stateObject. private volatile bool _pendingCancel; public SqlCommand() : base() { GC.SuppressFinalize(this); } public SqlCommand(string cmdText) : this() { CommandText = cmdText; } public SqlCommand(string cmdText, SqlConnection connection) : this() { CommandText = cmdText; Connection = connection; } public SqlCommand(string cmdText, SqlConnection connection, SqlTransaction transaction) : this() { CommandText = cmdText; Connection = connection; Transaction = transaction; } new public SqlConnection Connection { get { return _activeConnection; } set { // Don't allow the connection to be changed while in a async operation. if (_activeConnection != value && _activeConnection != null) { // If new value... if (cachedAsyncState.PendingAsyncOperation) { // If in pending async state, throw. throw SQL.CannotModifyPropertyAsyncOperationInProgress(); } } // Check to see if the currently set transaction has completed. If so, // null out our local reference. if (null != _transaction && _transaction.Connection == null) { _transaction = null; } // Command is no longer prepared on new connection, cleanup prepare status if (IsPrepared) { if (_activeConnection != value && _activeConnection != null) { try { // cleanup Unprepare(); } catch (Exception) { // we do not really care about errors in unprepare (may be the old connection went bad) } finally { // clean prepare status (even successful Unprepare does not do that) _prepareHandle = -1; _execType = EXECTYPE.UNPREPARED; } } } _activeConnection = value; } } override protected DbConnection DbConnection { get { return Connection; } set { Connection = (SqlConnection)value; } } internal SqlStatistics Statistics { get { if (null != _activeConnection) { if (_activeConnection.StatisticsEnabled || _diagnosticListener.IsEnabled(SqlClientDiagnosticListenerExtensions.SqlAfterExecuteCommand)) { return _activeConnection.Statistics; } } return null; } } new public SqlTransaction Transaction { get { // if the transaction object has been zombied, just return null if ((null != _transaction) && (null == _transaction.Connection)) { _transaction = null; } return _transaction; } set { // Don't allow the transaction to be changed while in a async operation. if (_transaction != value && _activeConnection != null) { // If new value... if (cachedAsyncState.PendingAsyncOperation) { // If in pending async state, throw throw SQL.CannotModifyPropertyAsyncOperationInProgress(); } } _transaction = value; } } override protected DbTransaction DbTransaction { get { return Transaction; } set { Transaction = (SqlTransaction)value; } } override public string CommandText { get { string value = _commandText; return ((null != value) ? value : ADP.StrEmpty); } set { if (_commandText != value) { PropertyChanging(); _commandText = value; } } } override public int CommandTimeout { get { return _commandTimeout; } set { if (value < 0) { throw ADP.InvalidCommandTimeout(value); } if (value != _commandTimeout) { PropertyChanging(); _commandTimeout = value; } } } public void ResetCommandTimeout() { if (ADP.DefaultCommandTimeout != _commandTimeout) { PropertyChanging(); _commandTimeout = ADP.DefaultCommandTimeout; } } override public CommandType CommandType { get { CommandType cmdType = _commandType; return ((0 != cmdType) ? cmdType : CommandType.Text); } set { if (_commandType != value) { switch (value) { case CommandType.Text: case CommandType.StoredProcedure: PropertyChanging(); _commandType = value; break; case System.Data.CommandType.TableDirect: throw SQL.NotSupportedCommandType(value); default: throw ADP.InvalidCommandType(value); } } } } // @devnote: By default, the cmd object is visible on the design surface (i.e. VS7 Server Tray) // to limit the number of components that clutter the design surface, // when the DataAdapter design wizard generates the insert/update/delete commands it will // set the DesignTimeVisible property to false so that cmds won't appear as individual objects public override bool DesignTimeVisible { get { return true; } set { } } new public SqlParameterCollection Parameters { get { if (null == _parameters) { // delay the creation of the SqlParameterCollection // until user actually uses the Parameters property _parameters = new SqlParameterCollection(); } return _parameters; } } override protected DbParameterCollection DbParameterCollection { get { return Parameters; } } override public UpdateRowSource UpdatedRowSource { get { return UpdateRowSource.None; } set { } } public event StatementCompletedEventHandler StatementCompleted { add { _statementCompletedEventHandler += value; } remove { _statementCompletedEventHandler -= value; } } internal void OnStatementCompleted(int recordCount) { if (0 <= recordCount) { StatementCompletedEventHandler handler = _statementCompletedEventHandler; if (null != handler) { try { handler(this, new StatementCompletedEventArgs(recordCount)); } catch (Exception e) { if (!ADP.IsCatchableOrSecurityExceptionType(e)) { throw; } } } } } private void PropertyChanging() { // also called from SqlParameterCollection this.IsDirty = true; } override public void Prepare() { // Reset _pendingCancel upon entry into any Execute - used to synchronize state // between entry into Execute* API and the thread obtaining the stateObject. _pendingCancel = false; SqlStatistics statistics = null; statistics = SqlStatistics.StartTimer(Statistics); // only prepare if batch with parameters if ( this.IsPrepared && !this.IsDirty || (this.CommandType == CommandType.StoredProcedure) || ( (System.Data.CommandType.Text == this.CommandType) && (0 == GetParameterCount(_parameters)) ) ) { if (null != Statistics) { Statistics.SafeIncrement(ref Statistics._prepares); } _hiddenPrepare = false; } else { // Validate the command outside of the try\catch to avoid putting the _stateObj on error ValidateCommand(async: false); bool processFinallyBlock = true; try { // NOTE: The state object isn't actually needed for this, but it is still here for back-compat (since it does a bunch of checks) GetStateObject(); // Loop through parameters ensuring that we do not have unspecified types, sizes, scales, or precisions if (null != _parameters) { int count = _parameters.Count; for (int i = 0; i < count; ++i) { _parameters[i].Prepare(this); } } InternalPrepare(); } catch (Exception e) { processFinallyBlock = ADP.IsCatchableExceptionType(e); throw; } finally { if (processFinallyBlock) { _hiddenPrepare = false; // The command is now officially prepared ReliablePutStateObject(); } } } SqlStatistics.StopTimer(statistics); } private void InternalPrepare() { if (this.IsDirty) { Debug.Assert(_cachedMetaData == null || !_dirty, "dirty query should not have cached metadata!"); // can have cached metadata if dirty because of parameters // // someone changed the command text or the parameter schema so we must unprepare the command // this.Unprepare(); this.IsDirty = false; } Debug.Assert(_execType != EXECTYPE.PREPARED, "Invalid attempt to Prepare already Prepared command!"); Debug.Assert(_activeConnection != null, "must have an open connection to Prepare"); Debug.Assert(null != _stateObj, "TdsParserStateObject should not be null"); Debug.Assert(null != _stateObj.Parser, "TdsParser class should not be null in Command.Execute!"); Debug.Assert(_stateObj.Parser == _activeConnection.Parser, "stateobject parser not same as connection parser"); Debug.Assert(false == _inPrepare, "Already in Prepare cycle, this.inPrepare should be false!"); // remember that the user wants to do a prepare but don't actually do an rpc _execType = EXECTYPE.PREPAREPENDING; // Note the current close count of the connection - this will tell us if the connection has been closed between calls to Prepare() and Execute _preparedConnectionCloseCount = _activeConnection.CloseCount; _preparedConnectionReconnectCount = _activeConnection.ReconnectCount; if (null != Statistics) { Statistics.SafeIncrement(ref Statistics._prepares); } } // SqlInternalConnectionTds needs to be able to unprepare a statement internal void Unprepare() { Debug.Assert(true == IsPrepared, "Invalid attempt to Unprepare a non-prepared command!"); Debug.Assert(_activeConnection != null, "must have an open connection to UnPrepare"); Debug.Assert(false == _inPrepare, "_inPrepare should be false!"); _execType = EXECTYPE.PREPAREPENDING; // Don't zero out the handle because we'll pass it in to sp_prepexec on the next prepare // Unless the close count isn't the same as when we last prepared if ((_activeConnection.CloseCount != _preparedConnectionCloseCount) || (_activeConnection.ReconnectCount != _preparedConnectionReconnectCount)) { // reset our handle _prepareHandle = -1; } _cachedMetaData = null; } // Cancel is supposed to be multi-thread safe. // It doesn't make sense to verify the connection exists or that it is open during cancel // because immediately after checkin the connection can be closed or removed via another thread. // override public void Cancel() { SqlStatistics statistics = null; try { statistics = SqlStatistics.StartTimer(Statistics); // If we are in reconnect phase simply cancel the waiting task var reconnectCompletionSource = _reconnectionCompletionSource; if (reconnectCompletionSource != null) { if (reconnectCompletionSource.TrySetCanceled()) { return; } } // the pending data flag means that we are awaiting a response or are in the middle of processing a response // if we have no pending data, then there is nothing to cancel // if we have pending data, but it is not a result of this command, then we don't cancel either. Note that // this model is implementable because we only allow one active command at any one time. This code // will have to change we allow multiple outstanding batches if (null == _activeConnection) { return; } SqlInternalConnectionTds connection = (_activeConnection.InnerConnection as SqlInternalConnectionTds); if (null == connection) { // Fail with out locking return; } // The lock here is to protect against the command.cancel / connection.close race condition // The SqlInternalConnectionTds is set to OpenBusy during close, once this happens the cast below will fail and // the command will no longer be cancelable. It might be desirable to be able to cancel the close operation, but this is // outside of the scope of Whidbey RTM. See (SqlConnection::Close) for other lock. lock (connection) { if (connection != (_activeConnection.InnerConnection as SqlInternalConnectionTds)) { // make sure the connection held on the active connection is what we have stored in our temp connection variable, if not between getting "connection" and taking the lock, the connection has been closed return; } TdsParser parser = connection.Parser; if (null == parser) { return; } if (!_pendingCancel) { // Do nothing if already pending. // Before attempting actual cancel, set the _pendingCancel flag to false. // This denotes to other thread before obtaining stateObject from the // session pool that there is another thread wishing to cancel. // The period in question is between entering the ExecuteAPI and obtaining // a stateObject. _pendingCancel = true; TdsParserStateObject stateObj = _stateObj; if (null != stateObj) { stateObj.Cancel(this); } else { SqlDataReader reader = connection.FindLiveReader(this); if (reader != null) { reader.Cancel(this); } } } } } finally { SqlStatistics.StopTimer(statistics); } } new public SqlParameter CreateParameter() { return new SqlParameter(); } override protected DbParameter CreateDbParameter() { return CreateParameter(); } override protected void Dispose(bool disposing) { if (disposing) { // release managed objects _cachedMetaData = null; } // release unmanaged objects base.Dispose(disposing); } override public object ExecuteScalar() { // Reset _pendingCancel upon entry into any Execute - used to synchronize state // between entry into Execute* API and the thread obtaining the stateObject. _pendingCancel = false; Guid operationId = _diagnosticListener.WriteCommandBefore(this); SqlStatistics statistics = null; Exception e = null; try { statistics = SqlStatistics.StartTimer(Statistics); SqlDataReader ds; ds = RunExecuteReader(0, RunBehavior.ReturnImmediately, returnStream: true); return CompleteExecuteScalar(ds, false); } catch (Exception ex) { e = ex; throw; } finally { SqlStatistics.StopTimer(statistics); if (e != null) { _diagnosticListener.WriteCommandError(operationId, this, e); } else { _diagnosticListener.WriteCommandAfter(operationId, this); } } } private object CompleteExecuteScalar(SqlDataReader ds, bool returnSqlValue) { object retResult = null; try { if (ds.Read()) { if (ds.FieldCount > 0) { if (returnSqlValue) { retResult = ds.GetSqlValue(0); } else { retResult = ds.GetValue(0); } } } } finally { // clean off the wire ds.Close(); } return retResult; } override public int ExecuteNonQuery() { // Reset _pendingCancel upon entry into any Execute - used to synchronize state // between entry into Execute* API and the thread obtaining the stateObject. _pendingCancel = false; Guid operationId = _diagnosticListener.WriteCommandBefore(this); SqlStatistics statistics = null; Exception e = null; try { statistics = SqlStatistics.StartTimer(Statistics); InternalExecuteNonQuery(completion: null, sendToPipe: false, timeout: CommandTimeout); return _rowsAffected; } catch (Exception ex) { e = ex; throw; } finally { SqlStatistics.StopTimer(statistics); if (e != null) { _diagnosticListener.WriteCommandError(operationId, this, e); } else { _diagnosticListener.WriteCommandAfter(operationId, this); } } } private IAsyncResult BeginExecuteNonQuery(AsyncCallback callback, object stateObject) { // Reset _pendingCancel upon entry into any Execute - used to synchronize state // between entry into Execute* API and the thread obtaining the stateObject. _pendingCancel = false; ValidateAsyncCommand(); // Special case - done outside of try/catches to prevent putting a stateObj // back into pool when we should not. SqlStatistics statistics = null; try { statistics = SqlStatistics.StartTimer(Statistics); TaskCompletionSource<object> completion = new TaskCompletionSource<object>(stateObject); try { // InternalExecuteNonQuery already has reliability block, but if failure will not put stateObj back into pool. Task execNQ = InternalExecuteNonQuery(completion, false, CommandTimeout, asyncWrite: true); // must finish caching information before ReadSni which can activate the callback before returning cachedAsyncState.SetActiveConnectionAndResult(completion, nameof(EndExecuteNonQuery), _activeConnection); if (execNQ != null) { AsyncHelper.ContinueTask(execNQ, completion, () => BeginExecuteNonQueryInternalReadStage(completion)); } else { BeginExecuteNonQueryInternalReadStage(completion); } } catch (Exception e) { if (!ADP.IsCatchableOrSecurityExceptionType(e)) { // If not catchable - the connection has already been caught and doomed in RunExecuteReader. throw; } // For async, RunExecuteReader will never put the stateObj back into the pool, so do so now. ReliablePutStateObject(); throw; } // Add callback after work is done to avoid overlapping Begin\End methods if (callback != null) { completion.Task.ContinueWith((t) => callback(t), TaskScheduler.Default); } return completion.Task; } finally { SqlStatistics.StopTimer(statistics); } } private void BeginExecuteNonQueryInternalReadStage(TaskCompletionSource<object> completion) { // Read SNI does not have catches for async exceptions, handle here. try { _stateObj.ReadSni(completion); } catch (Exception) { // Similarly, if an exception occurs put the stateObj back into the pool. // and reset async cache information to allow a second async execute if (null != _cachedAsyncState) { _cachedAsyncState.ResetAsyncState(); } ReliablePutStateObject(); throw; } } private void VerifyEndExecuteState(Task completionTask, String endMethod) { Debug.Assert(completionTask != null); if (completionTask.IsCanceled) { if (_stateObj != null) { _stateObj.Parser.State = TdsParserState.Broken; // We failed to respond to attention, we have to quit! _stateObj.Parser.Connection.BreakConnection(); _stateObj.Parser.ThrowExceptionAndWarning(_stateObj); } else { Debug.Assert(_reconnectionCompletionSource == null || _reconnectionCompletionSource.Task.IsCanceled, "ReconnectCompletionSource should be null or cancelled"); throw SQL.CR_ReconnectionCancelled(); } } else if (completionTask.IsFaulted) { throw completionTask.Exception.InnerException; } if (cachedAsyncState.EndMethodName == null) { throw ADP.MethodCalledTwice(endMethod); } if (endMethod != cachedAsyncState.EndMethodName) { throw ADP.MismatchedAsyncResult(cachedAsyncState.EndMethodName, endMethod); } if ((_activeConnection.State != ConnectionState.Open) || (!cachedAsyncState.IsActiveConnectionValid(_activeConnection))) { // If the connection is not 'valid' then it was closed while we were executing throw ADP.ClosedConnectionError(); } } private void WaitForAsyncResults(IAsyncResult asyncResult) { Task completionTask = (Task)asyncResult; if (!asyncResult.IsCompleted) { asyncResult.AsyncWaitHandle.WaitOne(); } _stateObj._networkPacketTaskSource = null; _activeConnection.GetOpenTdsConnection().DecrementAsyncCount(); } private void ThrowIfReconnectionHasBeenCanceled() { if (_stateObj == null) { var reconnectionCompletionSource = _reconnectionCompletionSource; if (reconnectionCompletionSource != null && reconnectionCompletionSource.Task.IsCanceled) { throw SQL.CR_ReconnectionCancelled(); } } } private int EndExecuteNonQuery(IAsyncResult asyncResult) { Exception asyncException = ((Task)asyncResult).Exception; if (asyncException != null) { // Leftover exception from the Begin...InternalReadStage ReliablePutStateObject(); throw asyncException.InnerException; } else { ThrowIfReconnectionHasBeenCanceled(); // lock on _stateObj prevents races with close/cancel. lock (_stateObj) { return EndExecuteNonQueryInternal(asyncResult); } } } private int EndExecuteNonQueryInternal(IAsyncResult asyncResult) { SqlStatistics statistics = null; try { statistics = SqlStatistics.StartTimer(Statistics); VerifyEndExecuteState((Task)asyncResult, nameof(EndExecuteNonQuery)); WaitForAsyncResults(asyncResult); bool processFinallyBlock = true; try { CheckThrowSNIException(); // only send over SQL Batch command if we are not a stored proc and have no parameters if ((System.Data.CommandType.Text == this.CommandType) && (0 == GetParameterCount(_parameters))) { try { bool dataReady; Debug.Assert(_stateObj._syncOverAsync, "Should not attempt pends in a synchronous call"); bool result = _stateObj.Parser.TryRun(RunBehavior.UntilDone, this, null, null, _stateObj, out dataReady); if (!result) { throw SQL.SynchronousCallMayNotPend(); } } finally { cachedAsyncState.ResetAsyncState(); } } else { // otherwise, use a full-fledged execute that can handle params and stored procs SqlDataReader reader = CompleteAsyncExecuteReader(); if (null != reader) { reader.Close(); } } } catch (Exception e) { processFinallyBlock = ADP.IsCatchableExceptionType(e); throw; } finally { if (processFinallyBlock) { PutStateObject(); } } Debug.Assert(null == _stateObj, "non-null state object in EndExecuteNonQuery"); return _rowsAffected; } catch (Exception e) { if (cachedAsyncState != null) { cachedAsyncState.ResetAsyncState(); }; if (ADP.IsCatchableExceptionType(e)) { ReliablePutStateObject(); }; throw; } finally { SqlStatistics.StopTimer(statistics); } } private Task InternalExecuteNonQuery(TaskCompletionSource<object> completion, bool sendToPipe, int timeout, bool asyncWrite = false, [CallerMemberName] string methodName = "") { bool async = (null != completion); SqlStatistics statistics = Statistics; _rowsAffected = -1; // this function may throw for an invalid connection // returns false for empty command text ValidateCommand(async, methodName); Task task = null; // only send over SQL Batch command if we are not a stored proc and have no parameters and not in batch RPC mode if ((System.Data.CommandType.Text == this.CommandType) && (0 == GetParameterCount(_parameters))) { Debug.Assert(!sendToPipe, "trying to send non-context command to pipe"); if (null != statistics) { if (!this.IsDirty && this.IsPrepared) { statistics.SafeIncrement(ref statistics._preparedExecs); } else { statistics.SafeIncrement(ref statistics._unpreparedExecs); } } task = RunExecuteNonQueryTds(methodName, async, timeout, asyncWrite); } else { // otherwise, use a full-fledged execute that can handle params and stored procs Debug.Assert(!sendToPipe, "trying to send non-context command to pipe"); SqlDataReader reader = RunExecuteReader(0, RunBehavior.UntilDone, false, completion, timeout, out task, asyncWrite, methodName); if (null != reader) { if (task != null) { task = AsyncHelper.CreateContinuationTask(task, () => reader.Close()); } else { reader.Close(); } } } Debug.Assert(async || null == _stateObj, "non-null state object in InternalExecuteNonQuery"); return task; } public XmlReader ExecuteXmlReader() { // Reset _pendingCancel upon entry into any Execute - used to synchronize state // between entry into Execute* API and the thread obtaining the stateObject. _pendingCancel = false; Guid operationId = _diagnosticListener.WriteCommandBefore(this); SqlStatistics statistics = null; Exception e = null; try { statistics = SqlStatistics.StartTimer(Statistics); // use the reader to consume metadata SqlDataReader ds; ds = RunExecuteReader(CommandBehavior.SequentialAccess, RunBehavior.ReturnImmediately, returnStream: true); return CompleteXmlReader(ds); } catch (Exception ex) { e = ex; throw; } finally { SqlStatistics.StopTimer(statistics); if (e != null) { _diagnosticListener.WriteCommandError(operationId, this, e); } else { _diagnosticListener.WriteCommandAfter(operationId, this); } } } private IAsyncResult BeginExecuteXmlReader(AsyncCallback callback, object stateObject) { // Reset _pendingCancel upon entry into any Execute - used to synchronize state // between entry into Execute* API and the thread obtaining the stateObject. _pendingCancel = false; ValidateAsyncCommand(); // Special case - done outside of try/catches to prevent putting a stateObj // back into pool when we should not. SqlStatistics statistics = null; try { statistics = SqlStatistics.StartTimer(Statistics); TaskCompletionSource<object> completion = new TaskCompletionSource<object>(stateObject); Task writeTask; try { // InternalExecuteNonQuery already has reliability block, but if failure will not put stateObj back into pool. RunExecuteReader(CommandBehavior.SequentialAccess, RunBehavior.ReturnImmediately, true, completion, CommandTimeout, out writeTask, asyncWrite: true); } catch (Exception e) { if (!ADP.IsCatchableOrSecurityExceptionType(e)) { // If not catchable - the connection has already been caught and doomed in RunExecuteReader. throw; } // For async, RunExecuteReader will never put the stateObj back into the pool, so do so now. ReliablePutStateObject(); throw; } // must finish caching information before ReadSni which can activate the callback before returning cachedAsyncState.SetActiveConnectionAndResult(completion, nameof(EndExecuteXmlReader), _activeConnection); if (writeTask != null) { AsyncHelper.ContinueTask(writeTask, completion, () => BeginExecuteXmlReaderInternalReadStage(completion)); } else { BeginExecuteXmlReaderInternalReadStage(completion); } // Add callback after work is done to avoid overlapping Begin\End methods if (callback != null) { completion.Task.ContinueWith((t) => callback(t), TaskScheduler.Default); } return completion.Task; } finally { SqlStatistics.StopTimer(statistics); } } private void BeginExecuteXmlReaderInternalReadStage(TaskCompletionSource<object> completion) { Debug.Assert(completion != null, "Completion source should not be null"); // Read SNI does not have catches for async exceptions, handle here. try { _stateObj.ReadSni(completion); } catch (Exception e) { // Similarly, if an exception occurs put the stateObj back into the pool. // and reset async cache information to allow a second async execute if (null != _cachedAsyncState) { _cachedAsyncState.ResetAsyncState(); } ReliablePutStateObject(); completion.TrySetException(e); } } private XmlReader EndExecuteXmlReader(IAsyncResult asyncResult) { Exception asyncException = ((Task)asyncResult).Exception; if (asyncException != null) { // Leftover exception from the Begin...InternalReadStage ReliablePutStateObject(); throw asyncException.InnerException; } else { ThrowIfReconnectionHasBeenCanceled(); // lock on _stateObj prevents races with close/cancel. lock (_stateObj) { return EndExecuteXmlReaderInternal(asyncResult); } } } private XmlReader EndExecuteXmlReaderInternal(IAsyncResult asyncResult) { try { return CompleteXmlReader(InternalEndExecuteReader(asyncResult, nameof(EndExecuteXmlReader)), async: true); } catch (Exception e) { if (cachedAsyncState != null) { cachedAsyncState.ResetAsyncState(); }; if (ADP.IsCatchableExceptionType(e)) { ReliablePutStateObject(); }; throw; } } private XmlReader CompleteXmlReader(SqlDataReader ds, bool async = false) { XmlReader xr = null; SmiExtendedMetaData[] md = ds.GetInternalSmiMetaData(); bool isXmlCapable = (null != md && md.Length == 1 && (md[0].SqlDbType == SqlDbType.NText || md[0].SqlDbType == SqlDbType.NVarChar || md[0].SqlDbType == SqlDbType.Xml)); if (isXmlCapable) { try { SqlStream sqlBuf = new SqlStream(ds, true /*addByteOrderMark*/, (md[0].SqlDbType == SqlDbType.Xml) ? false : true /*process all rows*/); xr = sqlBuf.ToXmlReader(async); } catch (Exception e) { if (ADP.IsCatchableExceptionType(e)) { ds.Close(); } throw; } } if (xr == null) { ds.Close(); throw SQL.NonXmlResult(); } return xr; } override protected DbDataReader ExecuteDbDataReader(CommandBehavior behavior) { return ExecuteReader(behavior); } new public SqlDataReader ExecuteReader() { SqlStatistics statistics = null; try { statistics = SqlStatistics.StartTimer(Statistics); return ExecuteReader(CommandBehavior.Default); } finally { SqlStatistics.StopTimer(statistics); } } new public SqlDataReader ExecuteReader(CommandBehavior behavior) { // Reset _pendingCancel upon entry into any Execute - used to synchronize state // between entry into Execute* API and the thread obtaining the stateObject. _pendingCancel = false; Guid operationId = _diagnosticListener.WriteCommandBefore(this); SqlStatistics statistics = null; Exception e = null; try { statistics = SqlStatistics.StartTimer(Statistics); return RunExecuteReader(behavior, RunBehavior.ReturnImmediately, returnStream: true); } catch (Exception ex) { e = ex; throw; } finally { SqlStatistics.StopTimer(statistics); if (e != null) { _diagnosticListener.WriteCommandError(operationId, this, e); } else { _diagnosticListener.WriteCommandAfter(operationId, this); } } } private SqlDataReader EndExecuteReader(IAsyncResult asyncResult) { Exception asyncException = ((Task)asyncResult).Exception; if (asyncException != null) { // Leftover exception from the Begin...InternalReadStage ReliablePutStateObject(); throw asyncException.InnerException; } else { ThrowIfReconnectionHasBeenCanceled(); // lock on _stateObj prevents races with close/cancel. lock (_stateObj) { return EndExecuteReaderInternal(asyncResult); } } } private SqlDataReader EndExecuteReaderInternal(IAsyncResult asyncResult) { SqlStatistics statistics = null; try { statistics = SqlStatistics.StartTimer(Statistics); return InternalEndExecuteReader(asyncResult, nameof(EndExecuteReader)); } catch (Exception e) { if (cachedAsyncState != null) { cachedAsyncState.ResetAsyncState(); }; if (ADP.IsCatchableExceptionType(e)) { ReliablePutStateObject(); }; throw; } finally { SqlStatistics.StopTimer(statistics); } } private IAsyncResult BeginExecuteReader(CommandBehavior behavior, AsyncCallback callback, object stateObject) { // Reset _pendingCancel upon entry into any Execute - used to synchronize state // between entry into Execute* API and the thread obtaining the stateObject. _pendingCancel = false; SqlStatistics statistics = null; try { statistics = SqlStatistics.StartTimer(Statistics); TaskCompletionSource<object> completion = new TaskCompletionSource<object>(stateObject); ValidateAsyncCommand(); // Special case - done outside of try/catches to prevent putting a stateObj // back into pool when we should not. Task writeTask = null; try { // InternalExecuteNonQuery already has reliability block, but if failure will not put stateObj back into pool. RunExecuteReader(behavior, RunBehavior.ReturnImmediately, true, completion, CommandTimeout, out writeTask, asyncWrite: true); } catch (Exception e) { if (!ADP.IsCatchableOrSecurityExceptionType(e)) { // If not catchable - the connection has already been caught and doomed in RunExecuteReader. throw; } // For async, RunExecuteReader will never put the stateObj back into the pool, so do so now. ReliablePutStateObject(); throw; } // must finish caching information before ReadSni which can activate the callback before returning cachedAsyncState.SetActiveConnectionAndResult(completion, nameof(EndExecuteReader), _activeConnection); if (writeTask != null) { AsyncHelper.ContinueTask(writeTask, completion, () => BeginExecuteReaderInternalReadStage(completion)); } else { BeginExecuteReaderInternalReadStage(completion); } // Add callback after work is done to avoid overlapping Begin\End methods if (callback != null) { completion.Task.ContinueWith((t) => callback(t), TaskScheduler.Default); } return completion.Task; } finally { SqlStatistics.StopTimer(statistics); } } private void BeginExecuteReaderInternalReadStage(TaskCompletionSource<object> completion) { Debug.Assert(completion != null, "CompletionSource should not be null"); // Read SNI does not have catches for async exceptions, handle here. try { _stateObj.ReadSni(completion); } catch (Exception e) { // Similarly, if an exception occurs put the stateObj back into the pool. // and reset async cache information to allow a second async execute if (null != _cachedAsyncState) { _cachedAsyncState.ResetAsyncState(); } ReliablePutStateObject(); completion.TrySetException(e); } } private SqlDataReader InternalEndExecuteReader(IAsyncResult asyncResult, string endMethod) { VerifyEndExecuteState((Task)asyncResult, endMethod); WaitForAsyncResults(asyncResult); CheckThrowSNIException(); SqlDataReader reader = CompleteAsyncExecuteReader(); Debug.Assert(null == _stateObj, "non-null state object in InternalEndExecuteReader"); return reader; } public override Task<int> ExecuteNonQueryAsync(CancellationToken cancellationToken) { Guid operationId = _diagnosticListener.WriteCommandBefore(this); TaskCompletionSource<int> source = new TaskCompletionSource<int>(); CancellationTokenRegistration registration = new CancellationTokenRegistration(); if (cancellationToken.CanBeCanceled) { if (cancellationToken.IsCancellationRequested) { source.SetCanceled(); return source.Task; } registration = cancellationToken.Register(s => ((SqlCommand)s).CancelIgnoreFailure(), this); } Task<int> returnedTask = source.Task; try { RegisterForConnectionCloseNotification(ref returnedTask); Task<int>.Factory.FromAsync(BeginExecuteNonQuery, EndExecuteNonQuery, null).ContinueWith((t) => { registration.Dispose(); if (t.IsFaulted) { Exception e = t.Exception.InnerException; _diagnosticListener.WriteCommandError(operationId, this, e); source.SetException(e); } else { if (t.IsCanceled) { source.SetCanceled(); } else { source.SetResult(t.Result); } _diagnosticListener.WriteCommandAfter(operationId, this); } }, TaskScheduler.Default); } catch (Exception e) { _diagnosticListener.WriteCommandError(operationId, this, e); source.SetException(e); } return returnedTask; } protected override Task<DbDataReader> ExecuteDbDataReaderAsync(CommandBehavior behavior, CancellationToken cancellationToken) { return ExecuteReaderAsync(behavior, cancellationToken).ContinueWith<DbDataReader>((result) => { if (result.IsFaulted) { throw result.Exception.InnerException; } return result.Result; }, CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously | TaskContinuationOptions.NotOnCanceled, TaskScheduler.Default); } new public Task<SqlDataReader> ExecuteReaderAsync() { return ExecuteReaderAsync(CommandBehavior.Default, CancellationToken.None); } new public Task<SqlDataReader> ExecuteReaderAsync(CommandBehavior behavior) { return ExecuteReaderAsync(behavior, CancellationToken.None); } new public Task<SqlDataReader> ExecuteReaderAsync(CancellationToken cancellationToken) { return ExecuteReaderAsync(CommandBehavior.Default, cancellationToken); } new public Task<SqlDataReader> ExecuteReaderAsync(CommandBehavior behavior, CancellationToken cancellationToken) { Guid operationId; if (!_parentOperationStarted) operationId = _diagnosticListener.WriteCommandBefore(this); TaskCompletionSource<SqlDataReader> source = new TaskCompletionSource<SqlDataReader>(); CancellationTokenRegistration registration = new CancellationTokenRegistration(); if (cancellationToken.CanBeCanceled) { if (cancellationToken.IsCancellationRequested) { source.SetCanceled(); return source.Task; } registration = cancellationToken.Register(s => ((SqlCommand)s).CancelIgnoreFailure(), this); } Task<SqlDataReader> returnedTask = source.Task; try { RegisterForConnectionCloseNotification(ref returnedTask); Task<SqlDataReader>.Factory.FromAsync(BeginExecuteReader, EndExecuteReader, behavior, null).ContinueWith((t) => { registration.Dispose(); if (t.IsFaulted) { Exception e = t.Exception.InnerException; if (!_parentOperationStarted) _diagnosticListener.WriteCommandError(operationId, this, e); source.SetException(e); } else { if (t.IsCanceled) { source.SetCanceled(); } else { source.SetResult(t.Result); } if (!_parentOperationStarted) _diagnosticListener.WriteCommandAfter(operationId, this); } }, TaskScheduler.Default); } catch (Exception e) { if (!_parentOperationStarted) _diagnosticListener.WriteCommandError(operationId, this, e); source.SetException(e); } return returnedTask; } public override Task<object> ExecuteScalarAsync(CancellationToken cancellationToken) { _parentOperationStarted = true; Guid operationId = _diagnosticListener.WriteCommandBefore(this); return ExecuteReaderAsync(cancellationToken).ContinueWith((executeTask) => { TaskCompletionSource<object> source = new TaskCompletionSource<object>(); if (executeTask.IsCanceled) { source.SetCanceled(); } else if (executeTask.IsFaulted) { _diagnosticListener.WriteCommandError(operationId, this, executeTask.Exception.InnerException); source.SetException(executeTask.Exception.InnerException); } else { SqlDataReader reader = executeTask.Result; reader.ReadAsync(cancellationToken).ContinueWith((readTask) => { try { if (readTask.IsCanceled) { reader.Dispose(); source.SetCanceled(); } else if (readTask.IsFaulted) { reader.Dispose(); _diagnosticListener.WriteCommandError(operationId, this, readTask.Exception.InnerException); source.SetException(readTask.Exception.InnerException); } else { Exception exception = null; object result = null; try { bool more = readTask.Result; if (more && reader.FieldCount > 0) { try { result = reader.GetValue(0); } catch (Exception e) { exception = e; } } } finally { reader.Dispose(); } if (exception != null) { _diagnosticListener.WriteCommandError(operationId, this, exception); source.SetException(exception); } else { _diagnosticListener.WriteCommandAfter(operationId, this); source.SetResult(result); } } } catch (Exception e) { // exception thrown by Dispose... source.SetException(e); } }, TaskScheduler.Default); } _parentOperationStarted = false; return source.Task; }, TaskScheduler.Default).Unwrap(); } public Task<XmlReader> ExecuteXmlReaderAsync() { return ExecuteXmlReaderAsync(CancellationToken.None); } public Task<XmlReader> ExecuteXmlReaderAsync(CancellationToken cancellationToken) { Guid operationId = _diagnosticListener.WriteCommandBefore(this); TaskCompletionSource<XmlReader> source = new TaskCompletionSource<XmlReader>(); CancellationTokenRegistration registration = new CancellationTokenRegistration(); if (cancellationToken.CanBeCanceled) { if (cancellationToken.IsCancellationRequested) { source.SetCanceled(); return source.Task; } registration = cancellationToken.Register(s => ((SqlCommand)s).CancelIgnoreFailure(), this); } Task<XmlReader> returnedTask = source.Task; try { RegisterForConnectionCloseNotification(ref returnedTask); Task<XmlReader>.Factory.FromAsync(BeginExecuteXmlReader, EndExecuteXmlReader, null).ContinueWith((t) => { registration.Dispose(); if (t.IsFaulted) { Exception e = t.Exception.InnerException; _diagnosticListener.WriteCommandError(operationId, this, e); source.SetException(e); } else { if (t.IsCanceled) { source.SetCanceled(); } else { source.SetResult(t.Result); } _diagnosticListener.WriteCommandAfter(operationId, this); } }, TaskScheduler.Default); } catch (Exception e) { _diagnosticListener.WriteCommandError(operationId, this, e); source.SetException(e); } return returnedTask; } // get cached metadata internal _SqlMetaDataSet MetaData { get { return _cachedMetaData; } } // Tds-specific logic for ExecuteNonQuery run handling private Task RunExecuteNonQueryTds(string methodName, bool async, int timeout, bool asyncWrite) { Debug.Assert(!asyncWrite || async, "AsyncWrite should be always accompanied by Async"); bool processFinallyBlock = true; try { Task reconnectTask = _activeConnection.ValidateAndReconnect(null, timeout); if (reconnectTask != null) { long reconnectionStart = ADP.TimerCurrent(); if (async) { TaskCompletionSource<object> completion = new TaskCompletionSource<object>(); _activeConnection.RegisterWaitingForReconnect(completion.Task); _reconnectionCompletionSource = completion; CancellationTokenSource timeoutCTS = new CancellationTokenSource(); AsyncHelper.SetTimeoutException(completion, timeout, SQL.CR_ReconnectTimeout, timeoutCTS.Token); AsyncHelper.ContinueTask(reconnectTask, completion, () => { if (completion.Task.IsCompleted) { return; } Interlocked.CompareExchange(ref _reconnectionCompletionSource, null, completion); timeoutCTS.Cancel(); Task subTask = RunExecuteNonQueryTds(methodName, async, TdsParserStaticMethods.GetRemainingTimeout(timeout, reconnectionStart), asyncWrite); if (subTask == null) { completion.SetResult(null); } else { AsyncHelper.ContinueTask(subTask, completion, () => completion.SetResult(null)); } }, connectionToAbort: _activeConnection); return completion.Task; } else { AsyncHelper.WaitForCompletion(reconnectTask, timeout, () => { throw SQL.CR_ReconnectTimeout(); }); timeout = TdsParserStaticMethods.GetRemainingTimeout(timeout, reconnectionStart); } } if (asyncWrite) { _activeConnection.AddWeakReference(this, SqlReferenceCollection.CommandTag); } GetStateObject(); // we just send over the raw text with no annotation // no parameters are sent over // no data reader is returned // use this overload for "batch SQL" tds token type Task executeTask = _stateObj.Parser.TdsExecuteSQLBatch(this.CommandText, timeout, _stateObj, sync: true); Debug.Assert(executeTask == null, "Shouldn't get a task when doing sync writes"); if (async) { _activeConnection.GetOpenTdsConnection(methodName).IncrementAsyncCount(); } else { bool dataReady; Debug.Assert(_stateObj._syncOverAsync, "Should not attempt pends in a synchronous call"); bool result = _stateObj.Parser.TryRun(RunBehavior.UntilDone, this, null, null, _stateObj, out dataReady); if (!result) { throw SQL.SynchronousCallMayNotPend(); } } } catch (Exception e) { processFinallyBlock = ADP.IsCatchableExceptionType(e); throw; } finally { if (processFinallyBlock && !async) { // When executing Async, we need to keep the _stateObj alive... PutStateObject(); } } return null; } internal SqlDataReader RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, bool returnStream, [CallerMemberName] string method = "") { Task unused; // sync execution SqlDataReader reader = RunExecuteReader(cmdBehavior, runBehavior, returnStream, completion: null, timeout: CommandTimeout, task: out unused, method: method); Debug.Assert(unused == null, "returned task during synchronous execution"); return reader; } // task is created in case of pending asynchronous write, returned SqlDataReader should not be utilized until that task is complete internal SqlDataReader RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, bool returnStream, TaskCompletionSource<object> completion, int timeout, out Task task, bool asyncWrite = false, [CallerMemberName] string method = "") { bool async = (null != completion); task = null; _rowsAffected = -1; if (0 != (CommandBehavior.SingleRow & cmdBehavior)) { // CommandBehavior.SingleRow implies CommandBehavior.SingleResult cmdBehavior |= CommandBehavior.SingleResult; } // this function may throw for an invalid connection // returns false for empty command text ValidateCommand(async, method); SqlStatistics statistics = Statistics; if (null != statistics) { if ((!this.IsDirty && this.IsPrepared && !_hiddenPrepare) || (this.IsPrepared && _execType == EXECTYPE.PREPAREPENDING)) { statistics.SafeIncrement(ref statistics._preparedExecs); } else { statistics.SafeIncrement(ref statistics._unpreparedExecs); } } { return RunExecuteReaderTds(cmdBehavior, runBehavior, returnStream, async, timeout, out task, asyncWrite && async); } } private SqlDataReader RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, bool returnStream, bool async, int timeout, out Task task, bool asyncWrite, SqlDataReader ds = null) { Debug.Assert(!asyncWrite || async, "AsyncWrite should be always accompanied by Async"); if (ds == null && returnStream) { ds = new SqlDataReader(this, cmdBehavior); } Task reconnectTask = _activeConnection.ValidateAndReconnect(null, timeout); if (reconnectTask != null) { long reconnectionStart = ADP.TimerCurrent(); if (async) { TaskCompletionSource<object> completion = new TaskCompletionSource<object>(); _activeConnection.RegisterWaitingForReconnect(completion.Task); _reconnectionCompletionSource = completion; CancellationTokenSource timeoutCTS = new CancellationTokenSource(); AsyncHelper.SetTimeoutException(completion, timeout, SQL.CR_ReconnectTimeout, timeoutCTS.Token); AsyncHelper.ContinueTask(reconnectTask, completion, () => { if (completion.Task.IsCompleted) { return; } Interlocked.CompareExchange(ref _reconnectionCompletionSource, null, completion); timeoutCTS.Cancel(); Task subTask; RunExecuteReaderTds(cmdBehavior, runBehavior, returnStream, async, TdsParserStaticMethods.GetRemainingTimeout(timeout, reconnectionStart), out subTask, asyncWrite, ds); if (subTask == null) { completion.SetResult(null); } else { AsyncHelper.ContinueTask(subTask, completion, () => completion.SetResult(null)); } }, connectionToAbort: _activeConnection); task = completion.Task; return ds; } else { AsyncHelper.WaitForCompletion(reconnectTask, timeout, () => { throw SQL.CR_ReconnectTimeout(); }); timeout = TdsParserStaticMethods.GetRemainingTimeout(timeout, reconnectionStart); } } // prepare the command // execute bool inSchema = (0 != (cmdBehavior & CommandBehavior.SchemaOnly)); task = null; string optionSettings = null; bool processFinallyBlock = true; bool decrementAsyncCountOnFailure = false; if (async) { _activeConnection.GetOpenTdsConnection().IncrementAsyncCount(); decrementAsyncCountOnFailure = true; } try { if (asyncWrite) { _activeConnection.AddWeakReference(this, SqlReferenceCollection.CommandTag); } GetStateObject(); Task writeTask = null; if ((System.Data.CommandType.Text == this.CommandType) && (0 == GetParameterCount(_parameters))) { // Send over SQL Batch command if we are not a stored proc and have no parameters Debug.Assert(!IsUserPrepared, "CommandType.Text with no params should not be prepared!"); string text = GetCommandText(cmdBehavior) + GetResetOptionsString(cmdBehavior); writeTask = _stateObj.Parser.TdsExecuteSQLBatch(text, timeout, _stateObj, sync: !asyncWrite); } else if (System.Data.CommandType.Text == this.CommandType) { if (this.IsDirty) { Debug.Assert(_cachedMetaData == null || !_dirty, "dirty query should not have cached metadata!"); // can have cached metadata if dirty because of parameters // // someone changed the command text or the parameter schema so we must unprepare the command // // remember that IsDirty includes test for IsPrepared! if (_execType == EXECTYPE.PREPARED) { _hiddenPrepare = true; } Unprepare(); IsDirty = false; } _SqlRPC rpc; if (_execType == EXECTYPE.PREPARED) { Debug.Assert(this.IsPrepared && (_prepareHandle != -1), "invalid attempt to call sp_execute without a handle!"); rpc = BuildExecute(inSchema); } else if (_execType == EXECTYPE.PREPAREPENDING) { rpc = BuildPrepExec(cmdBehavior); // next time through, only do an exec _execType = EXECTYPE.PREPARED; _preparedConnectionCloseCount = _activeConnection.CloseCount; _preparedConnectionReconnectCount = _activeConnection.ReconnectCount; // mark ourselves as preparing the command _inPrepare = true; } else { Debug.Assert(_execType == EXECTYPE.UNPREPARED, "Invalid execType!"); rpc = BuildExecuteSql(cmdBehavior, null, _parameters); } // if shiloh, then set NOMETADATA_UNLESSCHANGED flag rpc.options = TdsEnums.RPC_NOMETADATA; writeTask = _stateObj.Parser.TdsExecuteRPC(rpc, timeout, inSchema, _stateObj, CommandType.StoredProcedure == CommandType, sync: !asyncWrite); } else { Debug.Assert(this.CommandType == System.Data.CommandType.StoredProcedure, "unknown command type!"); _SqlRPC rpc = BuildRPC(inSchema, _parameters); // if we need to augment the command because a user has changed the command behavior (e.g. FillSchema) // then batch sql them over. This is inefficient (3 round trips) but the only way we can get metadata only from // a stored proc optionSettings = GetSetOptionsString(cmdBehavior); // turn set options ON if (null != optionSettings) { Task executeTask = _stateObj.Parser.TdsExecuteSQLBatch(optionSettings, timeout, _stateObj, sync: true); Debug.Assert(executeTask == null, "Shouldn't get a task when doing sync writes"); bool dataReady; Debug.Assert(_stateObj._syncOverAsync, "Should not attempt pends in a synchronous call"); bool result = _stateObj.Parser.TryRun(RunBehavior.UntilDone, this, null, null, _stateObj, out dataReady); if (!result) { throw SQL.SynchronousCallMayNotPend(); } // and turn OFF when the ds exhausts the stream on Close() optionSettings = GetResetOptionsString(cmdBehavior); } // execute sp writeTask = _stateObj.Parser.TdsExecuteRPC(rpc, timeout, inSchema, _stateObj, CommandType.StoredProcedure == CommandType, sync: !asyncWrite); } Debug.Assert(writeTask == null || async, "Returned task in sync mode"); if (async) { decrementAsyncCountOnFailure = false; if (writeTask != null) { task = AsyncHelper.CreateContinuationTask(writeTask, () => { _activeConnection.GetOpenTdsConnection(); // it will throw if connection is closed cachedAsyncState.SetAsyncReaderState(ds, runBehavior); }, onFailure: (exc) => { _activeConnection.GetOpenTdsConnection().DecrementAsyncCount(); }); } else { cachedAsyncState.SetAsyncReaderState(ds, runBehavior); } } else { // Always execute - even if no reader! FinishExecuteReader(ds, runBehavior); } } catch (Exception e) { processFinallyBlock = ADP.IsCatchableExceptionType(e); if (decrementAsyncCountOnFailure) { SqlInternalConnectionTds innerConnectionTds = (_activeConnection.InnerConnection as SqlInternalConnectionTds); if (null != innerConnectionTds) { // it may be closed innerConnectionTds.DecrementAsyncCount(); } } throw; } finally { if (processFinallyBlock && !async) { // When executing async, we need to keep the _stateObj alive... PutStateObject(); } } Debug.Assert(async || null == _stateObj, "non-null state object in RunExecuteReader"); return ds; } private SqlDataReader CompleteAsyncExecuteReader() { SqlDataReader ds = cachedAsyncState.CachedAsyncReader; // should not be null bool processFinallyBlock = true; try { FinishExecuteReader(ds, cachedAsyncState.CachedRunBehavior); } catch (Exception e) { processFinallyBlock = ADP.IsCatchableExceptionType(e); throw; } finally { if (processFinallyBlock) { cachedAsyncState.ResetAsyncState(); PutStateObject(); } } return ds; } private void FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior) { // always wrap with a try { FinishExecuteReader(...) } finally { PutStateObject(); } if (runBehavior == RunBehavior.UntilDone) { try { bool dataReady; Debug.Assert(_stateObj._syncOverAsync, "Should not attempt pends in a synchronous call"); bool result = _stateObj.Parser.TryRun(RunBehavior.UntilDone, this, ds, null, _stateObj, out dataReady); if (!result) { throw SQL.SynchronousCallMayNotPend(); } } catch (Exception e) { if (ADP.IsCatchableExceptionType(e)) { if (_inPrepare) { // The flag is expected to be reset by OnReturnValue. We should receive // the handle unless command execution failed. If fail, move back to pending // state. _inPrepare = false; // reset the flag IsDirty = true; // mark command as dirty so it will be prepared next time we're coming through _execType = EXECTYPE.PREPAREPENDING; // reset execution type to pending } if (null != ds) { try { ds.Close(); } catch(Exception exClose) { Debug.WriteLine("Received this exception from SqlDataReader.Close() while in another catch block: " + exClose.ToString()); } } } throw; } } // bind the parser to the reader if we get this far if (ds != null) { ds.Bind(_stateObj); _stateObj = null; // the reader now owns this... // bind this reader to this connection now _activeConnection.AddWeakReference(ds, SqlReferenceCollection.DataReaderTag); // force this command to start reading data off the wire. // this will cause an error to be reported at Execute() time instead of Read() time // if the command is not set. try { _cachedMetaData = ds.MetaData; ds.IsInitialized = true; } catch (Exception e) { if (ADP.IsCatchableExceptionType(e)) { if (_inPrepare) { // The flag is expected to be reset by OnReturnValue. We should receive // the handle unless command execution failed. If fail, move back to pending // state. _inPrepare = false; // reset the flag IsDirty = true; // mark command as dirty so it will be prepared next time we're coming through _execType = EXECTYPE.PREPAREPENDING; // reset execution type to pending } try { ds.Close(); } catch (Exception exClose) { Debug.WriteLine("Received this exception from SqlDataReader.Close() while in another catch block: " + exClose.ToString()); } } throw; } } } private void RegisterForConnectionCloseNotification<T>(ref Task<T> outerTask) { SqlConnection connection = _activeConnection; if (connection == null) { // No connection throw ADP.ClosedConnectionError(); } connection.RegisterForConnectionCloseNotification<T>(ref outerTask, this, SqlReferenceCollection.CommandTag); } // validates that a command has commandText and a non-busy open connection // throws exception for error case, returns false if the commandText is empty private void ValidateCommand(bool async, [CallerMemberName] string method = "") { if (null == _activeConnection) { throw ADP.ConnectionRequired(method); } // Ensure that the connection is open and that the Parser is in the correct state SqlInternalConnectionTds tdsConnection = _activeConnection.InnerConnection as SqlInternalConnectionTds; if (tdsConnection != null) { var parser = tdsConnection.Parser; if ((parser == null) || (parser.State == TdsParserState.Closed)) { throw ADP.OpenConnectionRequired(method, ConnectionState.Closed); } else if (parser.State != TdsParserState.OpenLoggedIn) { throw ADP.OpenConnectionRequired(method, ConnectionState.Broken); } } else if (_activeConnection.State == ConnectionState.Closed) { throw ADP.OpenConnectionRequired(method, ConnectionState.Closed); } else if (_activeConnection.State == ConnectionState.Broken) { throw ADP.OpenConnectionRequired(method, ConnectionState.Broken); } ValidateAsyncCommand(); // close any non MARS dead readers, if applicable, and then throw if still busy. // Throw if we have a live reader on this command _activeConnection.ValidateConnectionForExecute(method, this); // Check to see if the currently set transaction has completed. If so, // null out our local reference. if (null != _transaction && _transaction.Connection == null) _transaction = null; // throw if the connection is in a transaction but there is no // locally assigned transaction object if (_activeConnection.HasLocalTransactionFromAPI && (null == _transaction)) throw ADP.TransactionRequired(method); // if we have a transaction, check to ensure that the active // connection property matches the connection associated with // the transaction if (null != _transaction && _activeConnection != _transaction.Connection) throw ADP.TransactionConnectionMismatch(); if (string.IsNullOrEmpty(this.CommandText)) throw ADP.CommandTextRequired(method); } private void ValidateAsyncCommand() { if (cachedAsyncState.PendingAsyncOperation) { // Enforce only one pending async execute at a time. if (cachedAsyncState.IsActiveConnectionValid(_activeConnection)) { throw SQL.PendingBeginXXXExists(); } else { _stateObj = null; // Session was re-claimed by session pool upon connection close. cachedAsyncState.ResetAsyncState(); } } } private void GetStateObject(TdsParser parser = null) { Debug.Assert(null == _stateObj, "StateObject not null on GetStateObject"); Debug.Assert(null != _activeConnection, "no active connection?"); if (_pendingCancel) { _pendingCancel = false; // Not really needed, but we'll reset anyways. // If a pendingCancel exists on the object, we must have had a Cancel() call // between the point that we entered an Execute* API and the point in Execute* that // we proceeded to call this function and obtain a stateObject. In that case, // we now throw a cancelled error. throw SQL.OperationCancelled(); } if (parser == null) { parser = _activeConnection.TryGetParser(); if ((parser == null) || (parser.State == TdsParserState.Broken) || (parser.State == TdsParserState.Closed)) { // Connection's parser is null as well, therefore we must be closed throw ADP.ClosedConnectionError(); } } TdsParserStateObject stateObj = parser.GetSession(this); _stateObj = stateObj; if (_pendingCancel) { _pendingCancel = false; // Not really needed, but we'll reset anyways. // If a pendingCancel exists on the object, we must have had a Cancel() call // between the point that we entered this function and the point where we obtained // and actually assigned the stateObject to the local member. It is possible // that the flag is set as well as a call to stateObj.Cancel - though that would // be a no-op. So - throw. throw SQL.OperationCancelled(); } } private void ReliablePutStateObject() { PutStateObject(); } private void PutStateObject() { TdsParserStateObject stateObj = _stateObj; _stateObj = null; if (null != stateObj) { stateObj.CloseSession(); } } internal void OnReturnStatus(int status) { if (_inPrepare) return; SqlParameterCollection parameters = _parameters; // see if a return value is bound int count = GetParameterCount(parameters); for (int i = 0; i < count; i++) { SqlParameter parameter = parameters[i]; if (parameter.Direction == ParameterDirection.ReturnValue) { object v = parameter.Value; // if the user bound a sqlint32 (the only valid one for status, use it) if ((null != v) && (v.GetType() == typeof(SqlInt32))) { parameter.Value = new SqlInt32(status); // value type } else { parameter.Value = status; } break; } } } // // Move the return value to the corresponding output parameter. // Return parameters are sent in the order in which they were defined in the procedure. // If named, match the parameter name, otherwise fill in based on ordinal position. // If the parameter is not bound, then ignore the return value. // internal void OnReturnValue(SqlReturnValue rec) { if (_inPrepare) { if (!rec.value.IsNull) { _prepareHandle = rec.value.Int32; } _inPrepare = false; return; } SqlParameterCollection parameters = _parameters; int count = GetParameterCount(parameters); SqlParameter thisParam = GetParameterForOutputValueExtraction(parameters, rec.parameter, count); if (null != thisParam) { // copy over data // if the value user has supplied a SqlType class, then just copy over the SqlType, otherwise convert // to the com type object val = thisParam.Value; //set the UDT value as typed object rather than bytes if (SqlDbType.Udt == thisParam.SqlDbType) { throw ADP.DbTypeNotSupported(SqlDbType.Udt.ToString()); } else { thisParam.SetSqlBuffer(rec.value); } MetaType mt = MetaType.GetMetaTypeFromSqlDbType(rec.type, false); if (rec.type == SqlDbType.Decimal) { thisParam.ScaleInternal = rec.scale; thisParam.PrecisionInternal = rec.precision; } else if (mt.IsVarTime) { thisParam.ScaleInternal = rec.scale; } else if (rec.type == SqlDbType.Xml) { SqlCachedBuffer cachedBuffer = (thisParam.Value as SqlCachedBuffer); if (null != cachedBuffer) { thisParam.Value = cachedBuffer.ToString(); } } if (rec.collation != null) { Debug.Assert(mt.IsCharType, "Invalid collation structure for non-char type"); thisParam.Collation = rec.collation; } } return; } private SqlParameter GetParameterForOutputValueExtraction(SqlParameterCollection parameters, string paramName, int paramCount) { SqlParameter thisParam = null; bool foundParam = false; if (null == paramName) { // rec.parameter should only be null for a return value from a function for (int i = 0; i < paramCount; i++) { thisParam = parameters[i]; // searching for ReturnValue if (thisParam.Direction == ParameterDirection.ReturnValue) { foundParam = true; break; // found it } } } else { for (int i = 0; i < paramCount; i++) { thisParam = parameters[i]; // searching for Output or InputOutput or ReturnValue with matching name if (thisParam.Direction != ParameterDirection.Input && thisParam.Direction != ParameterDirection.ReturnValue && paramName == thisParam.ParameterNameFixed) { foundParam = true; break; // found it } } } if (foundParam) return thisParam; else return null; } private void SetUpRPCParameters(_SqlRPC rpc, int startCount, bool inSchema, SqlParameterCollection parameters) { int ii; int paramCount = GetParameterCount(parameters); int j = startCount; TdsParser parser = _activeConnection.Parser; for (ii = 0; ii < paramCount; ii++) { SqlParameter parameter = parameters[ii]; parameter.Validate(ii, CommandType.StoredProcedure == CommandType); // func will change type to that with a 4 byte length if the type has a two // byte length and a parameter length > than that expressible in 2 bytes if ((!parameter.ValidateTypeLengths().IsPlp) && (parameter.Direction != ParameterDirection.Output)) { parameter.FixStreamDataForNonPLP(); } if (ShouldSendParameter(parameter)) { rpc.parameters[j] = parameter; // set output bit if (parameter.Direction == ParameterDirection.InputOutput || parameter.Direction == ParameterDirection.Output) rpc.paramoptions[j] = TdsEnums.RPC_PARAM_BYREF; // set default value bit if (parameter.Direction != ParameterDirection.Output) { // remember that null == Convert.IsEmpty, DBNull.Value is a database null! // Don't assume a default value exists for parameters in the case when // the user is simply requesting schema. // TVPs use DEFAULT and do not allow NULL, even for schema only. if (null == parameter.Value && (!inSchema || SqlDbType.Structured == parameter.SqlDbType)) { rpc.paramoptions[j] |= TdsEnums.RPC_PARAM_DEFAULT; } } // Must set parameter option bit for LOB_COOKIE if unfilled LazyMat blob j++; } } } private _SqlRPC BuildPrepExec(CommandBehavior behavior) { Debug.Assert(System.Data.CommandType.Text == this.CommandType, "invalid use of sp_prepexec for stored proc invocation!"); SqlParameter sqlParam; int j = 3; int count = CountSendableParameters(_parameters); _SqlRPC rpc = new _SqlRPC(count + j) { ProcID = TdsEnums.RPC_PROCID_PREPEXEC, rpcName = TdsEnums.SP_PREPEXEC }; //@handle sqlParam = new SqlParameter(null, SqlDbType.Int); sqlParam.Direction = ParameterDirection.InputOutput; sqlParam.Value = _prepareHandle; rpc.parameters[0] = sqlParam; rpc.paramoptions[0] = TdsEnums.RPC_PARAM_BYREF; //@batch_params string paramList = BuildParamList(_stateObj.Parser, _parameters); sqlParam = new SqlParameter(null, ((paramList.Length << 1) <= TdsEnums.TYPE_SIZE_LIMIT) ? SqlDbType.NVarChar : SqlDbType.NText, paramList.Length); sqlParam.Value = paramList; rpc.parameters[1] = sqlParam; //@batch_text string text = GetCommandText(behavior); sqlParam = new SqlParameter(null, ((text.Length << 1) <= TdsEnums.TYPE_SIZE_LIMIT) ? SqlDbType.NVarChar : SqlDbType.NText, text.Length); sqlParam.Value = text; rpc.parameters[2] = sqlParam; SetUpRPCParameters(rpc, j, false, _parameters); return rpc; } // // returns true if the parameter is not a return value // and it's value is not DBNull (for a nullable parameter) // private static bool ShouldSendParameter(SqlParameter p) { switch (p.Direction) { case ParameterDirection.ReturnValue: // return value parameters are never sent return false; case ParameterDirection.Output: case ParameterDirection.InputOutput: case ParameterDirection.Input: // InputOutput/Output parameters are aways sent return true; default: Debug.Assert(false, "Invalid ParameterDirection!"); return false; } } private int CountSendableParameters(SqlParameterCollection parameters) { int cParams = 0; if (parameters != null) { int count = parameters.Count; for (int i = 0; i < count; i++) { if (ShouldSendParameter(parameters[i])) cParams++; } } return cParams; } // Returns total number of parameters private int GetParameterCount(SqlParameterCollection parameters) { return ((null != parameters) ? parameters.Count : 0); } // // build the RPC record header for this stored proc and add parameters // private _SqlRPC BuildRPC(bool inSchema, SqlParameterCollection parameters) { Debug.Assert(this.CommandType == System.Data.CommandType.StoredProcedure, "Command must be a stored proc to execute an RPC"); int count = CountSendableParameters(parameters); _SqlRPC rpc = new _SqlRPC(count) { rpcName = this.CommandText // just get the raw command text }; SetUpRPCParameters(rpc, 0, inSchema, parameters); return rpc; } // // build the RPC record header for sp_unprepare // // prototype for sp_unprepare is: // sp_unprepare(@handle) // build the RPC record header for sp_execute // // prototype for sp_execute is: // sp_execute(@handle int,param1value,param2value...) private _SqlRPC BuildExecute(bool inSchema) { Debug.Assert(_prepareHandle != -1, "Invalid call to sp_execute without a valid handle!"); int j = 1; int count = CountSendableParameters(_parameters); _SqlRPC rpc = new _SqlRPC(count + j) { ProcID = TdsEnums.RPC_PROCID_EXECUTE, rpcName = TdsEnums.SP_EXECUTE }; //@handle SqlParameter sqlParam = new SqlParameter(null, SqlDbType.Int); sqlParam.Value = _prepareHandle; rpc.parameters[0] = sqlParam; SetUpRPCParameters(rpc, j, inSchema, _parameters); return rpc; } // // build the RPC record header for sp_executesql and add the parameters // // prototype for sp_executesql is: // sp_executesql(@batch_text nvarchar(4000),@batch_params nvarchar(4000), param1,.. paramN) private _SqlRPC BuildExecuteSql(CommandBehavior behavior, string commandText, SqlParameterCollection parameters) { Debug.Assert(_prepareHandle == -1, "This command has an existing handle, use sp_execute!"); Debug.Assert(System.Data.CommandType.Text == this.CommandType, "invalid use of sp_executesql for stored proc invocation!"); int j; SqlParameter sqlParam; int cParams = CountSendableParameters(parameters); if (cParams > 0) { j = 2; } else { j = 1; } _SqlRPC rpc = new _SqlRPC(cParams + j) { ProcID = TdsEnums.RPC_PROCID_EXECUTESQL, rpcName = TdsEnums.SP_EXECUTESQL }; // @sql if (commandText == null) { commandText = GetCommandText(behavior); } sqlParam = new SqlParameter(null, ((commandText.Length << 1) <= TdsEnums.TYPE_SIZE_LIMIT) ? SqlDbType.NVarChar : SqlDbType.NText, commandText.Length); sqlParam.Value = commandText; rpc.parameters[0] = sqlParam; if (cParams > 0) { string paramList = BuildParamList(_stateObj.Parser, _parameters); sqlParam = new SqlParameter(null, ((paramList.Length << 1) <= TdsEnums.TYPE_SIZE_LIMIT) ? SqlDbType.NVarChar : SqlDbType.NText, paramList.Length); sqlParam.Value = paramList; rpc.parameters[1] = sqlParam; bool inSchema = (0 != (behavior & CommandBehavior.SchemaOnly)); SetUpRPCParameters(rpc, j, inSchema, parameters); } return rpc; } // paramList parameter for sp_executesql, sp_prepare, and sp_prepexec internal string BuildParamList(TdsParser parser, SqlParameterCollection parameters) { StringBuilder paramList = new StringBuilder(); bool fAddSeperator = false; int count = 0; count = parameters.Count; for (int i = 0; i < count; i++) { SqlParameter sqlParam = parameters[i]; sqlParam.Validate(i, CommandType.StoredProcedure == CommandType); // skip ReturnValue parameters; we never send them to the server if (!ShouldSendParameter(sqlParam)) continue; // add our separator for the ith parameter if (fAddSeperator) paramList.Append(','); paramList.Append(sqlParam.ParameterNameFixed); MetaType mt = sqlParam.InternalMetaType; //for UDTs, get the actual type name. Get only the typename, omit catalog and schema names. //in TSQL you should only specify the unqualified type name // paragraph above doesn't seem to be correct. Server won't find the type // if we don't provide a fully qualified name paramList.Append(" "); if (mt.SqlDbType == SqlDbType.Udt) { throw ADP.DbTypeNotSupported(SqlDbType.Udt.ToString()); } else if (mt.SqlDbType == SqlDbType.Structured) { string typeName = sqlParam.TypeName; if (string.IsNullOrEmpty(typeName)) { throw SQL.MustSetTypeNameForParam(mt.TypeName, sqlParam.ParameterNameFixed); } paramList.Append(ParseAndQuoteIdentifier(typeName)); // TVPs currently are the only Structured type and must be read only, so add that keyword paramList.Append(" READONLY"); } else { // func will change type to that with a 4 byte length if the type has a two // byte length and a parameter length > than that expressible in 2 bytes mt = sqlParam.ValidateTypeLengths(); if ((!mt.IsPlp) && (sqlParam.Direction != ParameterDirection.Output)) { sqlParam.FixStreamDataForNonPLP(); } paramList.Append(mt.TypeName); } fAddSeperator = true; if (mt.SqlDbType == SqlDbType.Decimal) { byte precision = sqlParam.GetActualPrecision(); byte scale = sqlParam.GetActualScale(); paramList.Append('('); if (0 == precision) { precision = TdsEnums.DEFAULT_NUMERIC_PRECISION; } paramList.Append(precision); paramList.Append(','); paramList.Append(scale); paramList.Append(')'); } else if (mt.IsVarTime) { byte scale = sqlParam.GetActualScale(); paramList.Append('('); paramList.Append(scale); paramList.Append(')'); } else if (false == mt.IsFixed && false == mt.IsLong && mt.SqlDbType != SqlDbType.Timestamp && mt.SqlDbType != SqlDbType.Udt && SqlDbType.Structured != mt.SqlDbType) { int size = sqlParam.Size; paramList.Append('('); // if using non unicode types, obtain the actual byte length from the parser, with it's associated code page if (mt.IsAnsiType) { object val = sqlParam.GetCoercedValue(); string s = null; // deal with the sql types if ((null != val) && (DBNull.Value != val)) { s = (val as string); if (null == s) { SqlString sval = val is SqlString ? (SqlString)val : SqlString.Null; if (!sval.IsNull) { s = sval.Value; } } } if (null != s) { int actualBytes = parser.GetEncodingCharLength(s, sqlParam.GetActualSize(), sqlParam.Offset, null); // if actual number of bytes is greater than the user given number of chars, use actual bytes if (actualBytes > size) size = actualBytes; } } // If the user specifies a 0-sized parameter for a variable len field // pass over max size (8000 bytes or 4000 characters for wide types) if (0 == size) size = mt.IsSizeInCharacters ? (TdsEnums.MAXSIZE >> 1) : TdsEnums.MAXSIZE; paramList.Append(size); paramList.Append(')'); } else if (mt.IsPlp && (mt.SqlDbType != SqlDbType.Xml) && (mt.SqlDbType != SqlDbType.Udt)) { paramList.Append("(max) "); } // set the output bit for Output or InputOutput parameters if (sqlParam.Direction != ParameterDirection.Input) paramList.Append(" " + TdsEnums.PARAM_OUTPUT); } return paramList.ToString(); } // Adds quotes to each part of a SQL identifier that may be multi-part, while leaving // the result as a single composite name. private string ParseAndQuoteIdentifier(string identifier) { string[] strings = SqlParameter.ParseTypeName(identifier); StringBuilder bld = new StringBuilder(); // Stitching back together is a little tricky. Assume we want to build a full multi-part name // with all parts except trimming separators for leading empty names (null or empty strings, // but not whitespace). Separators in the middle should be added, even if the name part is // null/empty, to maintain proper location of the parts. for (int i = 0; i < strings.Length; i++) { if (0 < bld.Length) { bld.Append('.'); } if (null != strings[i] && 0 != strings[i].Length) { bld.Append(ADP.BuildQuotedString("[", "]", strings[i])); } } return bld.ToString(); } // returns set option text to turn on format only and key info on and off // When we are executing as a text command, then we never need // to turn off the options since they command text is executed in the scope of sp_executesql. // For a stored proc command, however, we must send over batch sql and then turn off // the set options after we read the data. See the code in Command.Execute() private string GetSetOptionsString(CommandBehavior behavior) { string s = null; if ((System.Data.CommandBehavior.SchemaOnly == (behavior & CommandBehavior.SchemaOnly)) || (System.Data.CommandBehavior.KeyInfo == (behavior & CommandBehavior.KeyInfo))) { // SET FMTONLY ON will cause the server to ignore other SET OPTIONS, so turn // it off before we ask for browse mode metadata s = TdsEnums.FMTONLY_OFF; if (System.Data.CommandBehavior.KeyInfo == (behavior & CommandBehavior.KeyInfo)) { s = s + TdsEnums.BROWSE_ON; } if (System.Data.CommandBehavior.SchemaOnly == (behavior & CommandBehavior.SchemaOnly)) { s = s + TdsEnums.FMTONLY_ON; } } return s; } internal static string GetResetOptionsString(CommandBehavior behavior) { string s = null; // SET FMTONLY ON OFF if (CommandBehavior.SchemaOnly == (behavior & CommandBehavior.SchemaOnly)) { s = s + TdsEnums.FMTONLY_OFF; } // SET NO_BROWSETABLE OFF if (CommandBehavior.KeyInfo == (behavior & CommandBehavior.KeyInfo)) { s = s + TdsEnums.BROWSE_OFF; } return s; } private String GetCommandText(CommandBehavior behavior) { // build the batch string we send over, since we execute within a stored proc (sp_executesql), the SET options never need to be // turned off since they are scoped to the sproc Debug.Assert(System.Data.CommandType.Text == this.CommandType, "invalid call to GetCommandText for stored proc!"); return GetSetOptionsString(behavior) + this.CommandText; } internal void CheckThrowSNIException() { var stateObj = _stateObj; if (stateObj != null) { stateObj.CheckThrowSNIException(); } } // We're being notified that the underlying connection has closed internal void OnConnectionClosed() { var stateObj = _stateObj; if (stateObj != null) { stateObj.OnConnectionClosed(); } } internal TdsParserStateObject StateObject { get { return _stateObj; } } private bool IsPrepared { get { return (_execType != EXECTYPE.UNPREPARED); } } private bool IsUserPrepared { get { return IsPrepared && !_hiddenPrepare && !IsDirty; } } internal bool IsDirty { get { // only dirty if prepared var activeConnection = _activeConnection; return (IsPrepared && (_dirty || ((_parameters != null) && (_parameters.IsDirty)) || ((activeConnection != null) && ((activeConnection.CloseCount != _preparedConnectionCloseCount) || (activeConnection.ReconnectCount != _preparedConnectionReconnectCount))))); } set { // only mark the command as dirty if it is already prepared // but always clear the value if it we are clearing the dirty flag _dirty = value ? IsPrepared : false; if (null != _parameters) { _parameters.IsDirty = _dirty; } _cachedMetaData = null; } } internal int InternalRecordsAffected { get { return _rowsAffected; } set { if (-1 == _rowsAffected) { _rowsAffected = value; } else if (0 < value) { _rowsAffected += value; } } } #if DEBUG internal void CompletePendingReadWithSuccess(bool resetForcePendingReadsToWait) { var stateObj = _stateObj; if (stateObj != null) { stateObj.CompletePendingReadWithSuccess(resetForcePendingReadsToWait); } else { var tempCachedAsyncState = cachedAsyncState; if (tempCachedAsyncState != null) { var reader = tempCachedAsyncState.CachedAsyncReader; if (reader != null) { reader.CompletePendingReadWithSuccess(resetForcePendingReadsToWait); } } } } internal void CompletePendingReadWithFailure(int errorCode, bool resetForcePendingReadsToWait) { var stateObj = _stateObj; if (stateObj != null) { stateObj.CompletePendingReadWithFailure(errorCode, resetForcePendingReadsToWait); } else { var tempCachedAsyncState = _cachedAsyncState; if (tempCachedAsyncState != null) { var reader = tempCachedAsyncState.CachedAsyncReader; if (reader != null) { reader.CompletePendingReadWithFailure(errorCode, resetForcePendingReadsToWait); } } } } #endif internal void CancelIgnoreFailure() { // This method is used to route CancellationTokens to the Cancel method. // Cancellation is a suggestion, and exceptions should be ignored // rather than allowed to be unhandled, as there is no way to route // them to the caller. It would be expected that the error will be // observed anyway from the regular method. An example is canceling // an operation on a closed connection. try { Cancel(); } catch (Exception) { } } } }
39.588292
253
0.504347
[ "MIT" ]
dpaoliello/SqlClientSlim
src/SqlClientSlim/System/Data/SqlClient/SqlCommand.cs
123,080
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; namespace Translator { public static class StatusReporter { private static TextWriter writer = null; // Progress step variables private static string stepMsg = string.Empty; private static string nodeMsg = string.Empty; private static int nodeCnt = 0; private static int stepCnt = 0; // Summary status variables private static Statement inputQueries = null; private static int numInQueries = 0; private static Statement outputQueries = null; private static int numOutQueries = 0; //private static int numConversions = 0; //private static int numCaseFixing = 0; public static int InputQueriesCount { get { return numInQueries; } } public static int OutputQueriesCount { get { return numOutQueries; } } public static Statement InputQueries { get { return inputQueries; } } public static Statement OutputQueries { get { return outputQueries; } } public static void Initialize(TextWriter textWriter) { writer = textWriter; } public static int Finish() { writer = null; return nodeCnt; } public static int GetCount() { return nodeCnt; } public static bool IsInitialized() { return writer != null; } public static void SetStage(string stageName, string stepMessage) { if (IsInitialized()) { writer.WriteLine(stageName); nodeMsg = stepMessage; stepMsg = string.Empty; nodeCnt = 0; stepCnt = 0; } } public static void SetStage(string stepMessage) { if (IsInitialized()) { stepMsg = stepMessage; nodeMsg = string.Empty; nodeCnt = 0; stepCnt = 0; } } public static void ReportProgress() { if (IsInitialized() ) { ++stepCnt; ProgressPrint(stepMsg, stepCnt); } } public static void ReportProgress(GrammarNode node) { if (IsInitialized() && IsNodeCountable(node)) { ++nodeCnt; ProgressPrint(nodeMsg, nodeCnt); } } private static void ProgressPrint(string msg, int value) { if (msg != string.Empty) { if ((value % 10) == 0 || value == 1) { writer.WriteLine(); string padStr = (value < 10) ? " " : " "; if (value >= 100) { padStr = ""; } writer.Write(" {0} {1}{2}", msg, padStr, value); } else { writer.Write(" {0}", value % 10); } } } public static void Message(string msg) { if (IsInitialized()) { writer.WriteLine(msg); } } private static bool IsNodeCountable(GrammarNode node) { if (node == null || !(node is Statement) || node is BlockStatement || node is SqlStartStatement) { return false; } if (node is BreakStatement || node is GoStatement || node is ContinueStatement) { return false; } //Console.WriteLine("Node type = " + node.GetType().Name); return true; } public static void SetInputQueries(Statement rootStatement) { inputQueries = rootStatement; Scanner sc = new Scanner(); sc.Scan(inputQueries); numInQueries = StatusReporter.GetCount(); //First statement can be StartSQLStatement if (numInQueries > 1) { --numInQueries; } } public static void SetOutputQueries(Statement rootStatement, int queriesCount) { outputQueries = rootStatement; numOutQueries = queriesCount; } } }
26.982955
108
0.464308
[ "MIT" ]
B1SA/HanaTranslator-Src
Translator/StatusReporter.cs
4,751
C#
using System; using System.Collections.Generic; using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; using ISTS.Domain.PostalCodes; using ISTS.Infrastructure.Model; namespace ISTS.Infrastructure.Repository { public class PostalCodeRepository : IPostalCodeRepository { private readonly IstsContext _context; public PostalCodeRepository( IstsContext context) { _context = context; } public async Task<IEnumerable<PostalCode>> GetAsync() { var entities = await _context.PostalCodes .ToListAsync(); return entities; } public async Task<PostalCode> GetAsync(string postalCode) { var entity = await _context.PostalCodes .SingleOrDefaultAsync(c => c.Code == postalCode); return entity; } public async Task<IEnumerable<PostalCodeDistance>> GetPostalCodesWithinDistance(string postalCode, decimal distance) { var entities = _context.PostalCodeDistances.FromSql( "[dbo].[usp_GetPostalCodesWithinMiles] @p0, @p1", postalCode, distance); return await entities.ToListAsync(); } } }
27.891304
124
0.623539
[ "MIT" ]
meutley/ISTS
src/Infrastructure/Repository/PostalCodeRepository.cs
1,283
C#
namespace FileTypeChecker.Types { using FileTypeChecker.Abstracts; public class PortableNetworkGraphic : FileType, IFileType { private const string name = "Portable Network Graphic"; private const string extension = FileExtension.Png; private static readonly byte[] magicBytes = new byte[] { 0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A }; public PortableNetworkGraphic() : base(name, extension, magicBytes) { } } }
30.3125
114
0.668041
[ "MIT" ]
Adelzu/AyncFileTypeChecker
FileTypeChecker/Types/PortableNetworkGraphic.cs
487
C#
namespace Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Models.Api20171201 { using Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Runtime.PowerShell; /// <summary> /// A PowerShell PSTypeConverter to support converting to an instance of <see cref="ServerPrivateEndpointConnection" /> /// </summary> public partial class ServerPrivateEndpointConnectionTypeConverter : global::System.Management.Automation.PSTypeConverter { /// <summary> /// Determines if the converter can convert the <see cref="sourceValue"/> parameter to the <see cref="destinationType" /> /// parameter. /// </summary> /// <param name="sourceValue">the <see cref="System.Object"/> to convert from</param> /// <param name="destinationType">the <see cref="System.Type" /> to convert to</param> /// <returns> /// <c>true</c> if the converter can convert the <see cref="sourceValue"/> parameter to the <see cref="destinationType" /> /// parameter, otherwise <c>false</c>. /// </returns> public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); /// <summary> /// Determines if the converter can convert the <see cref="sourceValue"/> parameter to the <see cref="destinationType" /> /// parameter. /// </summary> /// <param name="sourceValue">the <see cref="System.Object" /> instance to check if it can be converted to the <see cref="ServerPrivateEndpointConnection" /// /> type.</param> /// <returns> /// <c>true</c> if the instance could be converted to a <see cref="ServerPrivateEndpointConnection" /> type, otherwise <c>false</c> /// </returns> public static bool CanConvertFrom(dynamic sourceValue) { if (null == sourceValue) { return true; } global::System.Type type = sourceValue.GetType(); if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) { // we say yest to PSObjects return true; } if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) { // we say yest to Hashtables/dictionaries return true; } try { if (null != sourceValue.ToJsonString()) { return true; } } catch { // Not one of our objects } try { string text = sourceValue.ToString()?.Trim(); return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Runtime.Json.JsonType.Object; } catch { // Doesn't look like it can be treated as JSON } return false; } /// <summary> /// Determines if the <see cref="sourceValue" /> parameter can be converted to the <see cref="destinationType" /> parameter /// </summary> /// <param name="sourceValue">the <see cref="System.Object"/> to convert from</param> /// <param name="destinationType">the <see cref="System.Type" /> to convert to</param> /// <returns> /// <c>true</c> if the converter can convert the <see cref="sourceValue" /> parameter to the <see cref="destinationType" /> /// parameter, otherwise <c>false</c> /// </returns> public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; /// <summary> /// Converts the <see cref="sourceValue" /> parameter to the <see cref="destinationType" /> parameter using <see cref="formatProvider" /// /> and <see cref="ignoreCase" /> /// </summary> /// <param name="sourceValue">the <see cref="System.Object"/> to convert from</param> /// <param name="destinationType">the <see cref="System.Type" /> to convert to</param> /// <param name="formatProvider">not used by this TypeConverter.</param> /// <param name="ignoreCase">when set to <c>true</c>, will ignore the case when converting.</param> /// <returns> /// an instance of <see cref="ServerPrivateEndpointConnection" />, or <c>null</c> if there is no suitable conversion. /// </returns> public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); /// <summary> /// Converts the <see cref="sourceValue" /> parameter to the <see cref="destinationType" /> parameter using <see cref="formatProvider" /// /> and <see cref="ignoreCase" /> /// </summary> /// <param name="sourceValue">the value to convert into an instance of <see cref="ServerPrivateEndpointConnection" />.</param> /// <returns> /// an instance of <see cref="ServerPrivateEndpointConnection" />, or <c>null</c> if there is no suitable conversion. /// </returns> public static Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Models.Api20171201.IServerPrivateEndpointConnection ConvertFrom(dynamic sourceValue) { if (null == sourceValue) { return null; } global::System.Type type = sourceValue.GetType(); if (typeof(Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Models.Api20171201.IServerPrivateEndpointConnection).IsAssignableFrom(type)) { return sourceValue; } try { return ServerPrivateEndpointConnection.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; } catch { // Unable to use JSON pattern } if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) { return ServerPrivateEndpointConnection.DeserializeFromPSObject(sourceValue); } if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) { return ServerPrivateEndpointConnection.DeserializeFromDictionary(sourceValue); } return null; } /// <summary>NotImplemented -- this will return <c>null</c></summary> /// <param name="sourceValue">the <see cref="System.Object"/> to convert from</param> /// <param name="destinationType">the <see cref="System.Type" /> to convert to</param> /// <param name="formatProvider">not used by this TypeConverter.</param> /// <param name="ignoreCase">when set to <c>true</c>, will ignore the case when converting.</param> /// <returns>will always return <c>null</c>.</returns> public override object ConvertTo(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => null; } }
52.71831
251
0.592706
[ "MIT" ]
3quanfeng/azure-powershell
src/PostgreSql/generated/api/Models/Api20171201/ServerPrivateEndpointConnection.TypeConverter.cs
7,345
C#
using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Reflection; namespace Newtonsoft.Json.Utilities { // Token: 0x0200006C RID: 108 internal static class EnumUtils { // Token: 0x060005AE RID: 1454 RVA: 0x00014376 File Offset: 0x00012576 public static T Parse<T>(string enumMemberName) where T : struct { return EnumUtils.Parse<T>(enumMemberName, false); } // Token: 0x060005AF RID: 1455 RVA: 0x0001437F File Offset: 0x0001257F public static T Parse<T>(string enumMemberName, bool ignoreCase) where T : struct { ValidationUtils.ArgumentTypeIsEnum(typeof(T), "T"); return (T)((object)Enum.Parse(typeof(T), enumMemberName, ignoreCase)); } // Token: 0x060005B0 RID: 1456 RVA: 0x000143C8 File Offset: 0x000125C8 public static bool TryParse<T>(string enumMemberName, bool ignoreCase, out T value) where T : struct { ValidationUtils.ArgumentTypeIsEnum(typeof(T), "T"); return MiscellaneousUtils.TryAction<T>(() => EnumUtils.Parse<T>(enumMemberName, ignoreCase), out value); } // Token: 0x060005B1 RID: 1457 RVA: 0x0001441C File Offset: 0x0001261C public static IList<T> GetFlagsValues<T>(T value) where T : struct { Type typeFromHandle = typeof(T); if (!typeFromHandle.IsDefined(typeof(FlagsAttribute), false)) { throw new Exception("Enum type {0} is not a set of flags.".FormatWith(CultureInfo.InvariantCulture, new object[] { typeFromHandle })); } Type underlyingType = Enum.GetUnderlyingType(value.GetType()); ulong num = Convert.ToUInt64(value, CultureInfo.InvariantCulture); EnumValues<ulong> namesAndValues = EnumUtils.GetNamesAndValues<T>(); IList<T> list = new List<T>(); foreach (EnumValue<ulong> enumValue in namesAndValues) { if ((num & enumValue.Value) == enumValue.Value && enumValue.Value != 0UL) { list.Add((T)((object)Convert.ChangeType(enumValue.Value, underlyingType, CultureInfo.CurrentCulture))); } } if (list.Count == 0 && Enumerable.SingleOrDefault<EnumValue<ulong>>(namesAndValues, (EnumValue<ulong> v) => v.Value == 0UL) != null) { list.Add(default(T)); } return list; } // Token: 0x060005B2 RID: 1458 RVA: 0x00014548 File Offset: 0x00012748 public static EnumValues<ulong> GetNamesAndValues<T>() where T : struct { return EnumUtils.GetNamesAndValues<ulong>(typeof(T)); } // Token: 0x060005B3 RID: 1459 RVA: 0x00014559 File Offset: 0x00012759 public static EnumValues<TUnderlyingType> GetNamesAndValues<TEnum, TUnderlyingType>() where TEnum : struct where TUnderlyingType : struct { return EnumUtils.GetNamesAndValues<TUnderlyingType>(typeof(TEnum)); } // Token: 0x060005B4 RID: 1460 RVA: 0x0001456C File Offset: 0x0001276C public static EnumValues<TUnderlyingType> GetNamesAndValues<TUnderlyingType>(Type enumType) where TUnderlyingType : struct { if (enumType == null) { throw new ArgumentNullException("enumType"); } ValidationUtils.ArgumentTypeIsEnum(enumType, "enumType"); IList<object> values = EnumUtils.GetValues(enumType); IList<string> names = EnumUtils.GetNames(enumType); EnumValues<TUnderlyingType> enumValues = new EnumValues<TUnderlyingType>(); for (int i = 0; i < values.Count; i++) { try { enumValues.Add(new EnumValue<TUnderlyingType>(names[i], (TUnderlyingType)((object)Convert.ChangeType(values[i], typeof(TUnderlyingType), CultureInfo.CurrentCulture)))); } catch (OverflowException ex) { throw new Exception(string.Format(CultureInfo.InvariantCulture, "Value from enum with the underlying type of {0} cannot be added to dictionary with a value type of {1}. Value was too large: {2}", new object[] { Enum.GetUnderlyingType(enumType), typeof(TUnderlyingType), Convert.ToUInt64(values[i], CultureInfo.InvariantCulture) }), ex); } } return enumValues; } // Token: 0x060005B5 RID: 1461 RVA: 0x00014658 File Offset: 0x00012858 public static IList<T> GetValues<T>() { return Enumerable.ToList<T>(Enumerable.Cast<T>(EnumUtils.GetValues(typeof(T)))); } // Token: 0x060005B6 RID: 1462 RVA: 0x0001467C File Offset: 0x0001287C public static IList<object> GetValues(Type enumType) { if (!enumType.IsEnum) { throw new ArgumentException("Type '" + enumType.Name + "' is not an enum."); } List<object> list = new List<object>(); IEnumerable<FieldInfo> enumerable = Enumerable.Where<FieldInfo>(enumType.GetFields(), (FieldInfo field) => field.IsLiteral); foreach (FieldInfo fieldInfo in enumerable) { object value = fieldInfo.GetValue(enumType); list.Add(value); } return list; } // Token: 0x060005B7 RID: 1463 RVA: 0x00014724 File Offset: 0x00012924 public static IList<string> GetNames<T>() { return EnumUtils.GetNames(typeof(T)); } // Token: 0x060005B8 RID: 1464 RVA: 0x00014740 File Offset: 0x00012940 public static IList<string> GetNames(Type enumType) { if (!enumType.IsEnum) { throw new ArgumentException("Type '" + enumType.Name + "' is not an enum."); } List<string> list = new List<string>(); IEnumerable<FieldInfo> enumerable = Enumerable.Where<FieldInfo>(enumType.GetFields(), (FieldInfo field) => field.IsLiteral); foreach (FieldInfo fieldInfo in enumerable) { list.Add(fieldInfo.Name); } return list; } // Token: 0x060005B9 RID: 1465 RVA: 0x000147E0 File Offset: 0x000129E0 public static TEnumType GetMaximumValue<TEnumType>(Type enumType) where TEnumType : IConvertible, IComparable<TEnumType> { if (enumType == null) { throw new ArgumentNullException("enumType"); } Type underlyingType = Enum.GetUnderlyingType(enumType); if (!typeof(TEnumType).IsAssignableFrom(underlyingType)) { throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, "TEnumType is not assignable from the enum's underlying type of {0}.", new object[] { underlyingType.Name })); } ulong num = 0UL; IList<object> values = EnumUtils.GetValues(enumType); if (enumType.IsDefined(typeof(FlagsAttribute), false)) { using (IEnumerator<object> enumerator = values.GetEnumerator()) { while (enumerator.MoveNext()) { object obj = enumerator.Current; TEnumType tenumType = (TEnumType)((object)obj); num |= tenumType.ToUInt64(CultureInfo.InvariantCulture); } goto IL_102; } } foreach (object obj2 in values) { TEnumType tenumType2 = (TEnumType)((object)obj2); ulong num2 = tenumType2.ToUInt64(CultureInfo.InvariantCulture); if (num.CompareTo(num2) == -1) { num = num2; } } IL_102: return (TEnumType)((object)Convert.ChangeType(num, typeof(TEnumType), CultureInfo.InvariantCulture)); } } }
35.40625
213
0.705502
[ "MIT" ]
zcfsky/Newtonsoft.Json.Compact
Newtonsoft.Json.Compact/Newtonsoft/Json/Utilities/EnumUtils.cs
6,800
C#
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace DotNetty.Codecs.Http.Tests.WebSockets { using System; using DotNetty.Codecs.Http.WebSockets; using DotNetty.Common.Utilities; public class WebSocketClientHandshaker00Test : WebSocketClientHandshakerTest { protected override WebSocketClientHandshaker NewHandshaker(Uri uri, string subprotocol, HttpHeaders headers, bool absoluteUpgradeUrl) => new WebSocketClientHandshaker00(uri, WebSocketVersion.V00, subprotocol, headers, 1024, 10000, absoluteUpgradeUrl); protected override AsciiString GetOriginHeaderName() => HttpHeaderNames.Origin; protected override AsciiString GetProtocolHeaderName() { return HttpHeaderNames.SecWebsocketProtocol; } protected override AsciiString[] GetHandshakeRequiredHeaderNames() { return new AsciiString[] { HttpHeaderNames.Connection, HttpHeaderNames.Upgrade, HttpHeaderNames.Host, HttpHeaderNames.SecWebsocketKey1, HttpHeaderNames.SecWebsocketKey2, }; } } }
36.714286
144
0.686381
[ "MIT" ]
cuteant/SpanNetty
test/DotNetty.Codecs.Http.Tests/WebSockets/WebSocketClientHandshaker00Test.cs
1,287
C#
using McMaster.Extensions.CommandLineUtils; using StrawberryShake.Tools.OAuth; namespace StrawberryShake.Tools { public static class UpdateCommand { public static void Build(CommandLineApplication update) { update.Description = "Update local schema"; CommandOption pathArg = update.Option( "-p|--Path", "The directory where the client shall be located.", CommandOptionType.SingleValue); CommandOption urlArg = update.Option( "-u|--uri", "The URL to the GraphQL endpoint.", CommandOptionType.SingleValue); CommandOption jsonArg = update.Option( "-j|--json", "Console output as JSON.", CommandOptionType.NoValue); CommandOption headersArg = update.Option( "-x|--headers", "Custom headers used in request to Graph QL server." + "Can be used mulitple times. Example: --headers key1=value1 --headers key2=value2", CommandOptionType.MultipleValue); AuthArguments authArguments = update.AddAuthArguments(); update.OnExecuteAsync(cancellationToken => { var arguments = new UpdateCommandArguments( urlArg, pathArg, authArguments, headersArg); UpdateCommandHandler handler = CommandTools.CreateHandler<UpdateCommandHandler>(jsonArg); return handler.ExecuteAsync(arguments, cancellationToken); }); } } }
35
105
0.565476
[ "MIT" ]
johan-lindqvist/hotchocolate
src/StrawberryShake/Tooling/src/dotnet-graphql/UpdateCommand.cs
1,680
C#
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Utilities; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Simplification; namespace Microsoft.CodeAnalysis.CSharp.Simplification { internal partial class CSharpSimplificationService { private class Expander : CSharpSyntaxRewriter { private static readonly SyntaxTrivia s_oneWhitespaceSeparator = SyntaxFactory.SyntaxTrivia(SyntaxKind.WhitespaceTrivia, " "); private static readonly SymbolDisplayFormat s_typeNameFormatWithGenerics = new SymbolDisplayFormat( globalNamespaceStyle: SymbolDisplayGlobalNamespaceStyle.Included, genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters, memberOptions: SymbolDisplayMemberOptions.IncludeContainingType, localOptions: SymbolDisplayLocalOptions.IncludeType, miscellaneousOptions: SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers | SymbolDisplayMiscellaneousOptions.ExpandNullable, typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces); private static readonly SymbolDisplayFormat s_typeNameFormatWithoutGenerics = new SymbolDisplayFormat( globalNamespaceStyle: SymbolDisplayGlobalNamespaceStyle.Included, genericsOptions: SymbolDisplayGenericsOptions.None, memberOptions: SymbolDisplayMemberOptions.IncludeContainingType, localOptions: SymbolDisplayLocalOptions.IncludeType, miscellaneousOptions: SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers | SymbolDisplayMiscellaneousOptions.ExpandNullable, typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces); private readonly SemanticModel _semanticModel; private readonly Func<SyntaxNode, bool> _expandInsideNode; private readonly CancellationToken _cancellationToken; private readonly SyntaxAnnotation _annotationForReplacedAliasIdentifier; private readonly bool _expandParameter; public Expander( SemanticModel semanticModel, Func<SyntaxNode, bool> expandInsideNode, bool expandParameter, CancellationToken cancellationToken, SyntaxAnnotation annotationForReplacedAliasIdentifier = null) { _semanticModel = semanticModel; _expandInsideNode = expandInsideNode; _expandParameter = expandParameter; _cancellationToken = cancellationToken; _annotationForReplacedAliasIdentifier = annotationForReplacedAliasIdentifier; } public override SyntaxNode Visit(SyntaxNode node) { if (_expandInsideNode == null || _expandInsideNode(node)) { return base.Visit(node); } return node; } private bool IsPassedToDelegateCreationExpression(ArgumentSyntax argument, ITypeSymbol type) { if (type.IsDelegateType() && argument.IsParentKind(SyntaxKind.ArgumentList) && argument.Parent.IsParentKind(SyntaxKind.ObjectCreationExpression)) { var objectCreationExpression = (ObjectCreationExpressionSyntax)argument.Parent.Parent; var objectCreationType = _semanticModel.GetTypeInfo(objectCreationExpression).Type; if (objectCreationType.Equals(type)) { return true; } } return false; } private SpeculationAnalyzer GetSpeculationAnalyzer(ExpressionSyntax expression, ExpressionSyntax newExpression) { return new SpeculationAnalyzer(expression, newExpression, _semanticModel, _cancellationToken); } private bool TryCastTo(ITypeSymbol targetType, ExpressionSyntax expression, ExpressionSyntax newExpression, out ExpressionSyntax newExpressionWithCast) { var speculativeAnalyzer = GetSpeculationAnalyzer(expression, newExpression); var speculativeSemanticModel = speculativeAnalyzer.SpeculativeSemanticModel; var speculatedExpression = speculativeAnalyzer.ReplacedExpression; var result = speculatedExpression.CastIfPossible(targetType, speculatedExpression.SpanStart, speculativeSemanticModel); if (result != speculatedExpression) { newExpressionWithCast = result; return true; } newExpressionWithCast = null; return false; } private bool TryGetLambdaExpressionBodyWithCast(LambdaExpressionSyntax lambdaExpression, LambdaExpressionSyntax newLambdaExpression, out ExpressionSyntax newLambdaExpressionBodyWithCast) { if (newLambdaExpression.Body is ExpressionSyntax) { var body = (ExpressionSyntax)lambdaExpression.Body; var newBody = (ExpressionSyntax)newLambdaExpression.Body; var returnType = (_semanticModel.GetSymbolInfo(lambdaExpression).Symbol as IMethodSymbol)?.ReturnType; if (returnType != null) { return TryCastTo(returnType, body, newBody, out newLambdaExpressionBodyWithCast); } } newLambdaExpressionBodyWithCast = null; return false; } public override SyntaxNode VisitReturnStatement(ReturnStatementSyntax node) { var newNode = base.VisitReturnStatement(node); if (newNode is ReturnStatementSyntax) { var newReturnStatement = (ReturnStatementSyntax)newNode; if (newReturnStatement.Expression != null) { var parentLambda = node.FirstAncestorOrSelf<LambdaExpressionSyntax>(); if (parentLambda != null) { var returnType = (_semanticModel.GetSymbolInfo(parentLambda).Symbol as IMethodSymbol)?.ReturnType; if (returnType != null) { ExpressionSyntax newExpressionWithCast; if (TryCastTo(returnType, node.Expression, newReturnStatement.Expression, out newExpressionWithCast)) { newNode = newReturnStatement.WithExpression(newExpressionWithCast); } } } } } return newNode; } public override SyntaxNode VisitParenthesizedLambdaExpression(ParenthesizedLambdaExpressionSyntax node) { var newNode = base.VisitParenthesizedLambdaExpression(node); if (newNode is ParenthesizedLambdaExpressionSyntax) { var parenthesizedLambda = (ParenthesizedLambdaExpressionSyntax)newNode; // First, try to add a cast to the lambda. ExpressionSyntax newLambdaExpressionBodyWithCast; if (TryGetLambdaExpressionBodyWithCast(node, parenthesizedLambda, out newLambdaExpressionBodyWithCast)) { parenthesizedLambda = parenthesizedLambda.WithBody(newLambdaExpressionBodyWithCast); } // Next, try to add a types to the lambda parameters if (_expandParameter && parenthesizedLambda.ParameterList != null) { var parameterList = parenthesizedLambda.ParameterList; var parameters = parameterList.Parameters.ToArray(); if (parameters.Length > 0 && parameters.Any(p => p.Type == null)) { var parameterSymbols = node.ParameterList.Parameters .Select(p => _semanticModel.GetDeclaredSymbol(p, _cancellationToken)) .ToArray(); if (parameterSymbols.All(p => p.Type?.ContainsAnonymousType() == false)) { var newParameters = parameterList.Parameters; for (int i = 0; i < parameterSymbols.Length; i++) { var typeSyntax = parameterSymbols[i].Type.GenerateTypeSyntax().WithTrailingTrivia(s_oneWhitespaceSeparator); var newParameter = parameters[i].WithType(typeSyntax).WithAdditionalAnnotations(Simplifier.Annotation); var currentParameter = newParameters[i]; newParameters = newParameters.Replace(currentParameter, newParameter); } var newParameterList = parameterList.WithParameters(newParameters); var newParenthesizedLambda = parenthesizedLambda.WithParameterList(newParameterList); return SimplificationHelpers.CopyAnnotations(from: parenthesizedLambda, to: newParenthesizedLambda); } } } return parenthesizedLambda; } return newNode; } public override SyntaxNode VisitSimpleLambdaExpression(SimpleLambdaExpressionSyntax node) { var newNode = base.VisitSimpleLambdaExpression(node); if (newNode is SimpleLambdaExpressionSyntax) { var simpleLambda = (SimpleLambdaExpressionSyntax)newNode; // First, try to add a cast to the lambda. ExpressionSyntax newLambdaExpressionBodyWithCast; if (TryGetLambdaExpressionBodyWithCast(node, simpleLambda, out newLambdaExpressionBodyWithCast)) { simpleLambda = simpleLambda.WithBody(newLambdaExpressionBodyWithCast); } // Next, try to add a type to the lambda parameter if (_expandParameter) { var parameterSymbol = _semanticModel.GetDeclaredSymbol(node.Parameter); if (parameterSymbol?.Type?.ContainsAnonymousType() == false) { var typeSyntax = parameterSymbol.Type.GenerateTypeSyntax().WithTrailingTrivia(s_oneWhitespaceSeparator); var newSimpleLambdaParameter = simpleLambda.Parameter.WithType(typeSyntax).WithoutTrailingTrivia(); var parenthesizedLambda = SyntaxFactory.ParenthesizedLambdaExpression( simpleLambda.AsyncKeyword, SyntaxFactory.ParameterList(SyntaxFactory.SingletonSeparatedList(newSimpleLambdaParameter)) .WithTrailingTrivia(simpleLambda.Parameter.GetTrailingTrivia()) .WithLeadingTrivia(simpleLambda.Parameter.GetLeadingTrivia()), simpleLambda.ArrowToken, simpleLambda.RefKeyword, simpleLambda.Body).WithAdditionalAnnotations(Simplifier.Annotation); return SimplificationHelpers.CopyAnnotations(from: simpleLambda, to: parenthesizedLambda); } } return simpleLambda; } return newNode; } public override SyntaxNode VisitArgument(ArgumentSyntax node) { _cancellationToken.ThrowIfCancellationRequested(); var newArgument = (ArgumentSyntax)base.VisitArgument(node); var argumentType = _semanticModel.GetTypeInfo(node.Expression).ConvertedType; if (argumentType != null && !IsPassedToDelegateCreationExpression(node, argumentType)) { ExpressionSyntax newArgumentExpressionWithCast; if (TryCastTo(argumentType, node.Expression, newArgument.Expression, out newArgumentExpressionWithCast)) { return newArgument.WithExpression(newArgumentExpressionWithCast); } } return newArgument; } public override SyntaxNode VisitBinaryExpression(BinaryExpressionSyntax node) { _cancellationToken.ThrowIfCancellationRequested(); // Special case: We parenthesize to avoid a situation where inlining an // expression can cause code to parse differently. The canonical case is... // // var x = 0; // var y = (1 + 2); // var z = new[] { x < x, x > y }; // // Inlining 'y' in the code above will produce code that parses differently // (i.e. as a generic method invocation). // // var z = new[] { x < x, x > (1 + 2) }; var result = (BinaryExpressionSyntax)base.VisitBinaryExpression(node); if ((node.Kind() == SyntaxKind.GreaterThanExpression || node.Kind() == SyntaxKind.RightShiftExpression) && !node.IsParentKind(SyntaxKind.ParenthesizedExpression)) { return result.Parenthesize(); } return result; } public override SyntaxNode VisitInterpolation(InterpolationSyntax node) { var result = (InterpolationSyntax)base.VisitInterpolation(node); if (result.Expression != null && !result.Expression.IsKind(SyntaxKind.ParenthesizedExpression)) { result = result.WithExpression(result.Expression.Parenthesize()); } return result; } public override SyntaxNode VisitXmlNameAttribute(XmlNameAttributeSyntax node) { _cancellationToken.ThrowIfCancellationRequested(); var newNode = (XmlNameAttributeSyntax)base.VisitXmlNameAttribute(node); return node.CopyAnnotationsTo(newNode); } public override SyntaxNode VisitNameMemberCref(NameMemberCrefSyntax node) { _cancellationToken.ThrowIfCancellationRequested(); var rewrittenname = (TypeSyntax)this.Visit(node.Name); var parameters = (CrefParameterListSyntax)this.Visit(node.Parameters); if (rewrittenname.Kind() == SyntaxKind.QualifiedName) { return node.CopyAnnotationsTo(SyntaxFactory.QualifiedCref( ((QualifiedNameSyntax)rewrittenname).Left .WithAdditionalAnnotations(Simplifier.Annotation), SyntaxFactory.NameMemberCref(((QualifiedNameSyntax)rewrittenname).Right, parameters) .WithLeadingTrivia(SyntaxTriviaList.Empty)) .WithLeadingTrivia(node.GetLeadingTrivia()) .WithTrailingTrivia(node.GetTrailingTrivia())) .WithAdditionalAnnotations(Simplifier.Annotation); } else if (rewrittenname.Kind() == SyntaxKind.AliasQualifiedName) { return node.CopyAnnotationsTo(SyntaxFactory.TypeCref( rewrittenname).WithLeadingTrivia(node.GetLeadingTrivia()) .WithTrailingTrivia(node.GetTrailingTrivia())) .WithAdditionalAnnotations(Simplifier.Annotation); } return node.Update(rewrittenname, parameters); } public override SyntaxNode VisitGenericName(GenericNameSyntax node) { _cancellationToken.ThrowIfCancellationRequested(); var newNode = (SimpleNameSyntax)base.VisitGenericName(node); return VisitSimpleName(newNode, node); } public override SyntaxNode VisitIdentifierName(IdentifierNameSyntax node) { _cancellationToken.ThrowIfCancellationRequested(); var identifier = node.Identifier; var newNode = (SimpleNameSyntax)base.VisitIdentifierName(node); return VisitSimpleName(newNode, node); } private ExpressionSyntax VisitSimpleName(SimpleNameSyntax rewrittenSimpleName, SimpleNameSyntax originalSimpleName) { _cancellationToken.ThrowIfCancellationRequested(); // if this is "var", then do not process further if (originalSimpleName.IsVar) { return rewrittenSimpleName; } var identifier = rewrittenSimpleName.Identifier; ExpressionSyntax newNode = rewrittenSimpleName; var isInsideCref = originalSimpleName.AncestorsAndSelf(ascendOutOfTrivia: true).Any(n => n is CrefSyntax); //// //// 1. if this identifier is an alias, we'll expand it here and replace the node completely. //// if (!SyntaxFacts.IsAliasQualifier(originalSimpleName)) { var aliasInfo = _semanticModel.GetAliasInfo(originalSimpleName, _cancellationToken); if (aliasInfo != null) { var aliasTarget = aliasInfo.Target; if (aliasTarget.IsNamespace() && ((INamespaceSymbol)aliasTarget).IsGlobalNamespace) { return rewrittenSimpleName; } // if the enclosing expression is a typeof expression that already contains open type we cannot // we need to insert an open type as well. var typeOfExpression = originalSimpleName.GetAncestor<TypeOfExpressionSyntax>(); if (typeOfExpression != null && IsTypeOfUnboundGenericType(_semanticModel, typeOfExpression)) { aliasTarget = ((INamedTypeSymbol)aliasTarget).ConstructUnboundGenericType(); } // the expanded form replaces the current identifier name. var replacement = FullyQualifyIdentifierName( aliasTarget, newNode, originalSimpleName, replaceNode: true, isInsideCref: isInsideCref, omitLeftHandSide: false) .WithAdditionalAnnotations(Simplifier.Annotation); // We replace the simple name completely, so we can't continue and rename the token // with a RenameLocationAnnotation. // There's also no way of removing annotations, so we just add a DoNotRenameAnnotation. if (replacement.Kind() == SyntaxKind.AliasQualifiedName) { var qualifiedReplacement = (AliasQualifiedNameSyntax)replacement; var newIdentifier = identifier.CopyAnnotationsTo(qualifiedReplacement.Name.Identifier); if (_annotationForReplacedAliasIdentifier != null) { newIdentifier = newIdentifier.WithAdditionalAnnotations(_annotationForReplacedAliasIdentifier); } var aliasAnnotationInfo = AliasAnnotation.Create(aliasInfo.Name); newIdentifier = newIdentifier.WithAdditionalAnnotations(aliasAnnotationInfo); replacement = replacement.ReplaceNode( qualifiedReplacement.Name, qualifiedReplacement.Name.WithIdentifier(newIdentifier)); replacement = newNode.CopyAnnotationsTo(replacement); var firstReplacementToken = replacement.GetFirstToken(true, false, true, true); var firstOriginalToken = originalSimpleName.GetFirstToken(true, false, true, true); SyntaxToken tokenWithLeadingWhitespace; if (TryAddLeadingElasticTriviaIfNecessary(firstReplacementToken, firstOriginalToken, out tokenWithLeadingWhitespace)) { replacement = replacement.ReplaceToken(firstOriginalToken, tokenWithLeadingWhitespace); } replacement = AppendElasticTriviaIfNecessary(replacement, originalSimpleName); return replacement; } if (replacement.Kind() == SyntaxKind.QualifiedName) { var qualifiedReplacement = (QualifiedNameSyntax)replacement; var newIdentifier = identifier.CopyAnnotationsTo(qualifiedReplacement.Right.Identifier); if (_annotationForReplacedAliasIdentifier != null) { newIdentifier = newIdentifier.WithAdditionalAnnotations(_annotationForReplacedAliasIdentifier); } var aliasAnnotationInfo = AliasAnnotation.Create(aliasInfo.Name); newIdentifier = newIdentifier.WithAdditionalAnnotations(aliasAnnotationInfo); replacement = replacement.ReplaceNode( qualifiedReplacement.Right, qualifiedReplacement.Right.WithIdentifier(newIdentifier)); replacement = newNode.CopyAnnotationsTo(replacement); replacement = AppendElasticTriviaIfNecessary(replacement, originalSimpleName); return replacement; } if (replacement.IsKind(SyntaxKind.IdentifierName)) { var identifierReplacement = (IdentifierNameSyntax)replacement; var newIdentifier = identifier.CopyAnnotationsTo(identifierReplacement.Identifier); if (_annotationForReplacedAliasIdentifier != null) { newIdentifier = newIdentifier.WithAdditionalAnnotations(_annotationForReplacedAliasIdentifier); } var aliasAnnotationInfo = AliasAnnotation.Create(aliasInfo.Name); newIdentifier = newIdentifier.WithAdditionalAnnotations(aliasAnnotationInfo); replacement = replacement.ReplaceToken(identifier, newIdentifier); replacement = newNode.CopyAnnotationsTo(replacement); replacement = AppendElasticTriviaIfNecessary(replacement, originalSimpleName); return replacement; } throw new NotImplementedException(); } } var symbol = _semanticModel.GetSymbolInfo(originalSimpleName.Identifier).Symbol; if (symbol == null) { return newNode; } var typeArgumentSymbols = TypeArgumentSymbolsPresentInName(originalSimpleName); var omitLeftSideOfExpression = false; // Check to see if the type Arguments in the resultant Symbol is recursively defined. if (IsTypeArgumentDefinedRecursive(symbol, typeArgumentSymbols, enterContainingSymbol: true)) { if (symbol.ContainingSymbol.Equals(symbol.OriginalDefinition.ContainingSymbol) && symbol.Kind == SymbolKind.Method && ((IMethodSymbol)symbol).IsStatic) { if (IsTypeArgumentDefinedRecursive(symbol, typeArgumentSymbols, enterContainingSymbol: false)) { return newNode; } else { omitLeftSideOfExpression = true; } } else { return newNode; } } if (IsInvocationWithDynamicArguments(originalSimpleName, _semanticModel)) { return newNode; } //// //// 2. If it's an attribute, make sure the identifier matches the attribute's class name. //// if (originalSimpleName.GetAncestor<AttributeSyntax>() != null) { if (symbol.IsConstructor() && symbol.ContainingType?.IsAttribute() == true) { symbol = symbol.ContainingType; var name = symbol.Name; Debug.Assert(name.StartsWith(originalSimpleName.Identifier.ValueText, StringComparison.Ordinal)); // if the user already used the Attribute suffix in the attribute, we'll maintain it. if (identifier.ValueText == name && name.EndsWith("Attribute", StringComparison.Ordinal)) { identifier = identifier.WithAdditionalAnnotations(SimplificationHelpers.DontSimplifyAnnotation); } identifier = identifier.CopyAnnotationsTo(SyntaxFactory.VerbatimIdentifier(identifier.LeadingTrivia, name, name, identifier.TrailingTrivia)); } } //// //// 3. Always try to escape keyword identifiers //// identifier = TryEscapeIdentifierToken(identifier, originalSimpleName, _semanticModel).WithAdditionalAnnotations(Simplifier.Annotation); if (identifier != rewrittenSimpleName.Identifier) { switch (newNode.Kind()) { case SyntaxKind.IdentifierName: case SyntaxKind.GenericName: newNode = ((SimpleNameSyntax)newNode).WithIdentifier(identifier); break; default: throw new NotImplementedException(); } } var parent = originalSimpleName.Parent; // do not complexify further for location where only simple names are allowed if (parent is MemberDeclarationSyntax || parent is MemberBindingExpressionSyntax || originalSimpleName.GetAncestor<NameEqualsSyntax>() != null || (parent is MemberAccessExpressionSyntax && parent.Kind() != SyntaxKind.SimpleMemberAccessExpression) || ((parent.Kind() == SyntaxKind.SimpleMemberAccessExpression || parent.Kind() == SyntaxKind.NameMemberCref) && originalSimpleName.IsRightSideOfDot()) || (parent.Kind() == SyntaxKind.QualifiedName && originalSimpleName.IsRightSideOfQualifiedName()) || (parent.Kind() == SyntaxKind.AliasQualifiedName)) { return TryAddTypeArgumentToIdentifierName(newNode, symbol); } //// //// 4. If this is a standalone identifier or the left side of a qualified name or member access try to fully qualify it //// // we need to treat the constructor as type name, so just get the containing type. if (symbol.IsConstructor() && (parent.Kind() == SyntaxKind.ObjectCreationExpression || parent.Kind() == SyntaxKind.NameMemberCref)) { symbol = symbol.ContainingType; } // if it's a namespace or type name, fully qualify it. if (symbol.Kind == SymbolKind.NamedType || symbol.Kind == SymbolKind.Namespace) { var replacement = FullyQualifyIdentifierName( (INamespaceOrTypeSymbol)symbol, newNode, originalSimpleName, replaceNode: false, isInsideCref: isInsideCref, omitLeftHandSide: omitLeftSideOfExpression) .WithAdditionalAnnotations(Simplifier.Annotation); replacement = AppendElasticTriviaIfNecessary(replacement, originalSimpleName); return replacement; } // if it's a member access, we're fully qualifying the left side and make it a member access. if (symbol.Kind == SymbolKind.Method || symbol.Kind == SymbolKind.Field || symbol.Kind == SymbolKind.Property) { if (symbol.IsStatic || originalSimpleName.IsParentKind(SyntaxKind.NameMemberCref) || _semanticModel.SyntaxTree.IsNameOfContext(originalSimpleName.SpanStart, _semanticModel, _cancellationToken)) { newNode = FullyQualifyIdentifierName( symbol, newNode, originalSimpleName, replaceNode: false, isInsideCref: isInsideCref, omitLeftHandSide: omitLeftSideOfExpression); } else { if (!IsPropertyNameOfObjectInitializer(originalSimpleName)) { ExpressionSyntax left; // Assumption here is, if the enclosing and containing types are different then there is inheritance relationship if (_semanticModel.GetEnclosingNamedType(originalSimpleName.SpanStart, _cancellationToken) != symbol.ContainingType) { left = SyntaxFactory.BaseExpression(); } else { left = SyntaxFactory.ThisExpression(); } var identifiersLeadingTrivia = newNode.GetLeadingTrivia(); newNode = TryAddTypeArgumentToIdentifierName(newNode, symbol); newNode = newNode.CopyAnnotationsTo( SyntaxFactory.MemberAccessExpression( SyntaxKind.SimpleMemberAccessExpression, left, (SimpleNameSyntax)newNode.WithLeadingTrivia(null)) .WithLeadingTrivia(identifiersLeadingTrivia)); } } } var result = newNode.WithAdditionalAnnotations(Simplifier.Annotation); result = AppendElasticTriviaIfNecessary(result, originalSimpleName); return result; } private ExpressionSyntax TryReplaceAngleBracesWithCurlyBraces(ExpressionSyntax expression, bool isInsideCref) { if (isInsideCref) { var leftTokens = expression.DescendantTokens(); List<SyntaxToken> candidateTokens = new List<SyntaxToken>(); foreach (var candidateToken in leftTokens) { if (candidateToken.Kind() == SyntaxKind.LessThanToken || candidateToken.Kind() == SyntaxKind.GreaterThanToken) { candidateTokens.Add(candidateToken); continue; } } expression = expression.ReplaceTokens(candidateTokens, computeReplacementToken: ReplaceTokenForCref); } return expression; } private ExpressionSyntax TryAddTypeArgumentToIdentifierName(ExpressionSyntax newNode, ISymbol symbol) { if (newNode.Kind() == SyntaxKind.IdentifierName && symbol.Kind == SymbolKind.Method) { if (((IMethodSymbol)symbol).TypeArguments.Length != 0) { var typeArguments = ((IMethodSymbol)symbol).TypeArguments; if (!typeArguments.Any(t => t.ContainsAnonymousType())) { var genericName = SyntaxFactory.GenericName( ((IdentifierNameSyntax)newNode).Identifier, SyntaxFactory.TypeArgumentList( SyntaxFactory.SeparatedList( typeArguments.Select(p => SyntaxFactory.ParseTypeName(p.ToDisplayParts(s_typeNameFormatWithGenerics).ToDisplayString()))))) .WithLeadingTrivia(newNode.GetLeadingTrivia()) .WithTrailingTrivia(newNode.GetTrailingTrivia()) .WithAdditionalAnnotations(Simplifier.Annotation); genericName = newNode.CopyAnnotationsTo(genericName); return genericName; } } } return newNode; } private IList<ISymbol> TypeArgumentSymbolsPresentInName(SimpleNameSyntax simpleName) { List<ISymbol> typeArgumentSymbols = new List<ISymbol>(); var typeArgumentListSyntax = simpleName.DescendantNodesAndSelf().Where(n => n is TypeArgumentListSyntax); foreach (var typeArgumentList in typeArgumentListSyntax) { var castedTypeArgument = (TypeArgumentListSyntax)typeArgumentList; foreach (var typeArgument in castedTypeArgument.Arguments) { var symbol = _semanticModel.GetSymbolInfo(typeArgument).Symbol; if (symbol != null && !typeArgumentSymbols.Contains(symbol)) { typeArgumentSymbols.Add(symbol); } } } return typeArgumentSymbols; } private bool IsInvocationWithDynamicArguments(SimpleNameSyntax originalSimpleName, SemanticModel semanticModel) { var invocationExpression = originalSimpleName.Ancestors().OfType<InvocationExpressionSyntax>().FirstOrDefault(); // Check to see if this is the invocation Expression we wanted to work with if (invocationExpression != null && invocationExpression.Expression.GetLastToken() == originalSimpleName.GetLastToken()) { if (invocationExpression.ArgumentList != null) { foreach (var argument in invocationExpression.ArgumentList.Arguments) { if (argument != null && argument.Expression != null) { var typeinfo = semanticModel.GetTypeInfo(argument.Expression); if (typeinfo.Type != null && typeinfo.Type.TypeKind == TypeKind.Dynamic) { return true; } } } } } return false; } private bool IsTypeArgumentDefinedRecursive(ISymbol symbol, IList<ISymbol> typeArgumentSymbols, bool enterContainingSymbol) { if (symbol == symbol.OriginalDefinition) { return false; } var typeArgumentsInSymbol = new List<ISymbol>(); TypeArgumentsInAllContainingSymbol(symbol, typeArgumentsInSymbol, enterContainingSymbol, isRecursive: true); var typeArgumentsInOriginalDefinition = new List<ISymbol>(); TypeArgumentsInAllContainingSymbol(symbol.OriginalDefinition, typeArgumentsInOriginalDefinition, enterContainingSymbol, isRecursive: false); if (typeArgumentsInSymbol.Intersect(typeArgumentsInOriginalDefinition).Any(n => !typeArgumentSymbols.Contains(n))) { return true; } return false; } private void TypeArgumentsInAllContainingSymbol(ISymbol symbol, IList<ISymbol> typeArgumentSymbols, bool enterContainingSymbol, bool isRecursive) { if (symbol == null || symbol.IsNamespace()) { // This is the terminating condition return; } if (symbol is INamedTypeSymbol) { var namedTypedSymbol = (INamedTypeSymbol)symbol; if (namedTypedSymbol.TypeArguments.Length != 0) { foreach (var typeArgument in namedTypedSymbol.TypeArguments) { if (!typeArgumentSymbols.Contains(typeArgument)) { typeArgumentSymbols.Add(typeArgument); if (isRecursive) { TypeArgumentsInAllContainingSymbol(typeArgument, typeArgumentSymbols, enterContainingSymbol, isRecursive); } } } } } if (enterContainingSymbol) { TypeArgumentsInAllContainingSymbol(symbol.ContainingSymbol, typeArgumentSymbols, enterContainingSymbol, isRecursive); } } private bool IsPropertyNameOfObjectInitializer(SimpleNameSyntax identifierName) { SyntaxNode currentNode = identifierName; SyntaxNode parent = identifierName; while (parent != null) { if (parent.Kind() == SyntaxKind.ObjectInitializerExpression) { return currentNode.Kind() == SyntaxKind.SimpleAssignmentExpression && object.Equals(((AssignmentExpressionSyntax)currentNode).Left, identifierName); } else if (parent is ExpressionSyntax) { currentNode = parent; parent = parent.Parent; continue; } else { return false; } } return false; } private ExpressionSyntax FullyQualifyIdentifierName( ISymbol symbol, ExpressionSyntax rewrittenNode, ExpressionSyntax originalNode, bool replaceNode, bool isInsideCref, bool omitLeftHandSide) { Debug.Assert(!replaceNode || rewrittenNode.Kind() == SyntaxKind.IdentifierName); //// TODO: use and expand Generate*Syntax(isymbol) to not depend on symbol display any more. //// See GenerateExpressionSyntax(); var result = rewrittenNode; // only if this symbol has a containing type or namespace there is work for us to do. if (replaceNode || symbol.ContainingType != null || symbol.ContainingNamespace != null) { ImmutableArray<SymbolDisplayPart> displayParts; ExpressionSyntax left = null; // we either need to create an AliasQualifiedName if the symbol is directly contained in the global namespace, // otherwise it a QualifiedName. if (!replaceNode && symbol.ContainingType == null && symbol.ContainingNamespace.IsGlobalNamespace) { return rewrittenNode.CopyAnnotationsTo( SyntaxFactory.AliasQualifiedName( SyntaxFactory.IdentifierName(SyntaxFactory.Token(SyntaxKind.GlobalKeyword)), (SimpleNameSyntax)rewrittenNode.WithLeadingTrivia(null)) .WithLeadingTrivia(rewrittenNode.GetLeadingTrivia())); } displayParts = replaceNode ? symbol.ToDisplayParts(s_typeNameFormatWithGenerics) : (symbol.ContainingType ?? (ISymbol)symbol.ContainingNamespace).ToDisplayParts(s_typeNameFormatWithGenerics); rewrittenNode = TryAddTypeArgumentToIdentifierName(rewrittenNode, symbol); // Replaces the '<' token with the '{' token since we are inside crefs rewrittenNode = TryReplaceAngleBracesWithCurlyBraces(rewrittenNode, isInsideCref); result = rewrittenNode; if (!omitLeftHandSide) { left = SyntaxFactory.ParseTypeName(displayParts.ToDisplayString()); // Replaces the '<' token with the '{' token since we are inside crefs left = TryReplaceAngleBracesWithCurlyBraces(left, isInsideCref); if (replaceNode) { return left .WithLeadingTrivia(rewrittenNode.GetLeadingTrivia()) .WithTrailingTrivia(rewrittenNode.GetTrailingTrivia()); } // now create syntax for the combination of left and right syntax, or a simple replacement in case of an identifier var parent = originalNode.Parent; var leadingTrivia = rewrittenNode.GetLeadingTrivia(); rewrittenNode = rewrittenNode.WithLeadingTrivia(null); switch (parent.Kind()) { case SyntaxKind.QualifiedName: var qualifiedParent = (QualifiedNameSyntax)parent; result = rewrittenNode.CopyAnnotationsTo( SyntaxFactory.QualifiedName( (NameSyntax)left, (SimpleNameSyntax)rewrittenNode)); break; case SyntaxKind.SimpleMemberAccessExpression: var memberAccessParent = (MemberAccessExpressionSyntax)parent; result = rewrittenNode.CopyAnnotationsTo( SyntaxFactory.MemberAccessExpression( SyntaxKind.SimpleMemberAccessExpression, left, (SimpleNameSyntax)rewrittenNode)); break; default: Debug.Assert(rewrittenNode is SimpleNameSyntax); if (SyntaxFacts.IsInNamespaceOrTypeContext(originalNode)) { var right = (SimpleNameSyntax)rewrittenNode; result = rewrittenNode.CopyAnnotationsTo(SyntaxFactory.QualifiedName((NameSyntax)left, right.WithAdditionalAnnotations(Simplifier.SpecialTypeAnnotation))); } else if (originalNode.Parent is CrefSyntax) { var right = (SimpleNameSyntax)rewrittenNode; result = rewrittenNode.CopyAnnotationsTo(SyntaxFactory.QualifiedName((NameSyntax)left, right)); } else { result = rewrittenNode.CopyAnnotationsTo( SyntaxFactory.MemberAccessExpression( SyntaxKind.SimpleMemberAccessExpression, left, (SimpleNameSyntax)rewrittenNode)); } break; } result = result.WithLeadingTrivia(leadingTrivia); } } return result; } private SyntaxToken ReplaceTokenForCref(SyntaxToken oldToken, SyntaxToken dummySameToken) { if (oldToken.Kind() == SyntaxKind.LessThanToken) { return SyntaxFactory.Token(oldToken.LeadingTrivia, SyntaxKind.LessThanToken, "{", "{", oldToken.TrailingTrivia); } if (oldToken.Kind() == SyntaxKind.GreaterThanToken) { return SyntaxFactory.Token(oldToken.LeadingTrivia, SyntaxKind.GreaterThanToken, "}", "}", oldToken.TrailingTrivia); } Debug.Assert(false, "This method is used only replacing the '<' and '>' to '{' and '}' respectively"); return default(SyntaxToken); } private bool IsTypeOfUnboundGenericType(SemanticModel semanticModel, TypeOfExpressionSyntax typeOfExpression) { if (typeOfExpression != null) { var type = semanticModel.GetTypeInfo(typeOfExpression.Type, _cancellationToken).Type as INamedTypeSymbol; // It's possible the immediate type might not be an unbound type, such as typeof(A<>.B). So walk through // parent types too while (type != null) { if (type.IsUnboundGenericType) { return true; } type = type.ContainingType; } } return false; } public override SyntaxNode VisitInvocationExpression(InvocationExpressionSyntax originalNode) { var rewrittenNode = (InvocationExpressionSyntax)base.VisitInvocationExpression(originalNode); if (originalNode.Expression.IsKind(SyntaxKind.SimpleMemberAccessExpression)) { var memberAccess = (MemberAccessExpressionSyntax)originalNode.Expression; var targetSymbol = SimplificationHelpers.GetOriginalSymbolInfo(_semanticModel, memberAccess.Name); if (targetSymbol != null && targetSymbol.IsReducedExtension() && memberAccess.Expression != null) { rewrittenNode = RewriteExtensionMethodInvocation(originalNode, rewrittenNode, ((MemberAccessExpressionSyntax)rewrittenNode.Expression).Expression, (IMethodSymbol)targetSymbol); } } return rewrittenNode; } private InvocationExpressionSyntax RewriteExtensionMethodInvocation( InvocationExpressionSyntax originalNode, InvocationExpressionSyntax rewrittenNode, ExpressionSyntax thisExpression, IMethodSymbol reducedExtensionMethod) { var originalMemberAccess = (MemberAccessExpressionSyntax)originalNode.Expression; if (originalMemberAccess.GetParentConditionalAccessExpression() != null) { // Bail out on extension method invocations in conditional access expression. // Note that this is a temporary workaround for https://github.com/dotnet/roslyn/issues/2593. // Issue https://github.com/dotnet/roslyn/issues/3260 tracks fixing this workaround. return rewrittenNode; } var expression = RewriteExtensionMethodInvocation(rewrittenNode, thisExpression, reducedExtensionMethod, s_typeNameFormatWithoutGenerics); // Let's rebind this and verify the original method is being called properly var binding = _semanticModel.GetSpeculativeSymbolInfo(originalNode.SpanStart, expression, SpeculativeBindingOption.BindAsExpression); if (binding.Symbol != null) { return expression; } // We'll probably need generic type arguments as well return RewriteExtensionMethodInvocation(rewrittenNode, thisExpression, reducedExtensionMethod, s_typeNameFormatWithGenerics); } private InvocationExpressionSyntax RewriteExtensionMethodInvocation( InvocationExpressionSyntax originalNode, ExpressionSyntax thisExpression, IMethodSymbol reducedExtensionMethod, SymbolDisplayFormat symbolDisplayFormat) { var containingType = reducedExtensionMethod.ContainingType.ToDisplayString(symbolDisplayFormat); var newMemberAccess = SyntaxFactory.MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression, SyntaxFactory.ParseExpression(containingType), ((MemberAccessExpressionSyntax)originalNode.Expression).OperatorToken, ((MemberAccessExpressionSyntax)originalNode.Expression).Name) .WithLeadingTrivia(thisExpression.GetFirstToken().LeadingTrivia); // Copies the annotation for the member access expression newMemberAccess = originalNode.Expression.CopyAnnotationsTo(newMemberAccess).WithAdditionalAnnotations(Simplifier.Annotation); var thisArgument = SyntaxFactory.Argument(thisExpression).WithLeadingTrivia(SyntaxTriviaList.Empty); // Copies the annotation for the left hand side of the member access expression to the first argument in the complexified form thisArgument = ((MemberAccessExpressionSyntax)originalNode.Expression).Expression.CopyAnnotationsTo(thisArgument); var arguments = originalNode.ArgumentList.Arguments.Insert(0, thisArgument); var replacementNode = SyntaxFactory.InvocationExpression( newMemberAccess, originalNode.ArgumentList.WithArguments(arguments)); // This Annotation copy is for the InvocationExpression return originalNode.CopyAnnotationsTo(replacementNode).WithAdditionalAnnotations(Simplifier.Annotation, Formatter.Annotation); } } } }
49.415905
295
0.544884
[ "Apache-2.0" ]
sharadagrawal/NameDidntPrePopulate
src/Workspaces/CSharp/Portable/Simplification/CSharpSimplificationService.Expander.cs
54,063
C#
// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information. // Ported from um/mfidl.h in the Windows SDK for Windows 10.0.20348.0 // Original source is Copyright © Microsoft. All rights reserved. using NUnit.Framework; using System; using System.Runtime.InteropServices; using static TerraFX.Interop.Windows; namespace TerraFX.Interop.UnitTests { /// <summary>Provides validation of the <see cref="IMFClockStateSink" /> struct.</summary> public static unsafe class IMFClockStateSinkTests { /// <summary>Validates that the <see cref="Guid" /> of the <see cref="IMFClockStateSink" /> struct is correct.</summary> [Test] public static void GuidOfTest() { Assert.That(typeof(IMFClockStateSink).GUID, Is.EqualTo(IID_IMFClockStateSink)); } /// <summary>Validates that the <see cref="IMFClockStateSink" /> struct is blittable.</summary> [Test] public static void IsBlittableTest() { Assert.That(Marshal.SizeOf<IMFClockStateSink>(), Is.EqualTo(sizeof(IMFClockStateSink))); } /// <summary>Validates that the <see cref="IMFClockStateSink" /> struct has the right <see cref="LayoutKind" />.</summary> [Test] public static void IsLayoutSequentialTest() { Assert.That(typeof(IMFClockStateSink).IsLayoutSequential, Is.True); } /// <summary>Validates that the <see cref="IMFClockStateSink" /> struct has the correct size.</summary> [Test] public static void SizeOfTest() { if (Environment.Is64BitProcess) { Assert.That(sizeof(IMFClockStateSink), Is.EqualTo(8)); } else { Assert.That(sizeof(IMFClockStateSink), Is.EqualTo(4)); } } } }
37.057692
145
0.63726
[ "MIT" ]
phizch/terrafx.interop.windows
tests/Interop/Windows/um/mfidl/IMFClockStateSinkTests.cs
1,929
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Choosability.Utility { public static class LinqExtensions { public static IEnumerable<Tuple<T, T>> CartesianProduct<T>(this IEnumerable<T> a, IEnumerable<T> b) { return CartesianProduct(new[] { a, b }).Select(s => new Tuple<T, T>(s.ElementAt(0), s.ElementAt(1))); } public static IEnumerable<IEnumerable<T>> CartesianProduct<T>(this IEnumerable<IEnumerable<T>> sequences) { IEnumerable<IEnumerable<T>> emptyProduct = new[] { Enumerable.Empty<T>() }; return sequences.Aggregate( emptyProduct, (accumulator, sequence) => from accseq in accumulator from item in sequence select accseq.Concat(new[] { item })); } public static IEnumerable<IEnumerable<T>> CartesianProduct<T>(this IEnumerable<List<T>> sequences) { IEnumerable<IEnumerable<T>> emptyProduct = new[] { Enumerable.Empty<T>() }; return sequences.Aggregate( emptyProduct, (accumulator, sequence) => from accseq in accumulator from item in sequence select accseq.Concat(new[] { item })); } public static IEnumerable<T> Concat<T>(this IEnumerable<T> e, T value) { foreach (var v in e) yield return v; yield return value; } public static IEnumerable<T> Distinct<T>(this IEnumerable<T> source, Func<T, T, bool> areEqual) { var yielded = new List<T>(); foreach (var t in source) { if (yielded.All(x => !areEqual(x, t))) { yielded.Add(t); yield return t; } } } } }
32.316667
113
0.537906
[ "MIT" ]
landon/WebGraphs
Choosability/Utility/LinqExtensions.cs
1,941
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class UiInGameMenu : MonoBehaviour { public Button saveBtn, exitBtn; public GameObject gameMenuPanel, loadingPanel; public bool MenuVisible { get => gameMenuPanel.activeSelf; } private void Start() { GameManager manager = FindObjectOfType<GameManager>(); saveBtn.onClick.AddListener(manager.SaveGame); exitBtn.onClick.AddListener(manager.ExitToMainMenu); gameMenuPanel.SetActive(false); } public void ToggleMenu() { gameMenuPanel.SetActive(!gameMenuPanel.activeSelf); } public void ToggleLoadingPanel() { loadingPanel.SetActive(!loadingPanel.activeSelf); } }
24.806452
64
0.708713
[ "MIT" ]
SunnyValleyStudio/SGC
UiInGameMenu.cs
771
C#
using System.Collections.Generic; using System.Linq; using CallMeMaybe; using ComponentBasedTestTool.Domain; using ComponentBasedTestTool.Domain.OperationStates; using ComponentBasedTestTool.ViewModels.Ports; using ExtensionPoints; using ExtensionPoints.ImplementedByComponents; using ExtensionPoints.ImplementedByContext; using ExtensionPoints.ImplementedByContext.StateMachine; using ViewModels.Composition; namespace ViewModels.ViewModels { public class OperationEntries { private readonly BackgroundTasks _backgroundTasks; private readonly List<OperationEntry> _operations; public OperationEntries(BackgroundTasks backgroundTasks) { _backgroundTasks = backgroundTasks; _operations = new List<OperationEntry>(); } public void Add(string componentInstanceName, string name, OperationStateMachine operation, Maybe<string> dependencyName) { _operations.Add(OperationEntry.With(componentInstanceName, name, operation, dependencyName, operation)); } public OperationViewModelsSource ConvertUsing(OperationViewModelFactory operationViewModelFactory) { var operationViewModels = OperationViewModelsSource .CreateOperationViewModels(operationViewModelFactory, _operations); return operationViewModels; } } }
33.205128
125
0.80695
[ "MIT" ]
grzesiek-galezowski/component-based-test-tool
ComponentBasedTestTool/ViewModels/ViewModels/OperationEntries.cs
1,295
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class CameraController : MonoBehaviour { Camera playerCam; public float dampTime = 0.15f; private Vector3 velocity = Vector3.zero; public Transform player; public float shakeDuration = 0f; public float shakeMagnitude = 0.2f; public float dampingSpeed = 1.0f; Vector3 initialPosition; private bool canShake = false; public float defaultCamSize = 10f; // Camera Size bool resetting; bool changing; float newSize; float sizeTime; float curVel = 0f; private Transform playerTarget; public float bossDeathDelay = 2f; private float bossTimer; private bool bossDeath = false; void OnEnable () { playerCam = this.GetComponent<Camera> (); playerTarget = player; bossTimer = bossDeathDelay; // Sets the position of the camera Vector3 point = playerCam.WorldToViewportPoint (player.position); Vector3 delta = player.position - playerCam.ViewportToWorldPoint (new Vector3 (0.5f, 0.5f, point.z)); Vector3 destination = transform.position + delta; transform.position = destination; } void Update () { if (canShake) { if (shakeDuration > 0) { transform.localPosition = initialPosition + Random.insideUnitSphere * shakeMagnitude; shakeDuration -= Time.deltaTime * dampingSpeed; } else { shakeDuration = 0f; transform.localPosition = initialPosition; canShake = false; } } if (resetting) { playerCam.orthographicSize = Mathf.SmoothDamp (playerCam.orthographicSize, defaultCamSize, ref curVel, 0.2f); } if (changing) { playerCam.orthographicSize = Mathf.SmoothDamp (playerCam.orthographicSize, newSize, ref curVel, sizeTime); } if (bossDeath) { if (bossTimer <= 0) { player = playerTarget; defaultCamSize = 18f; ResetSize (); bossTimer = bossDeathDelay; bossDeath = false; } else { bossTimer -= Time.deltaTime; } } } void FixedUpdate() { Follow (); } public void Follow() { if (player) { Vector3 point = playerCam.WorldToViewportPoint (player.position); Vector3 delta = player.position - playerCam.ViewportToWorldPoint (new Vector3 (0.5f, 0.5f, point.z)); Vector3 destination = transform.position + delta; transform.position = Vector3.SmoothDamp (transform.position, destination, ref velocity, dampTime); } } public void TriggerShake(float shakeMag, float dampSpeed, float shakeDur) { shakeMagnitude = shakeMag; dampingSpeed = dampSpeed; shakeDuration = shakeDur; initialPosition = transform.localPosition; canShake = true; } public void ChangeSize(float size, float time) { resetting = false; newSize = size; sizeTime = time; changing = true; } public void ResetSize() { changing = false; resetting = true; } public void BossRoom(Transform boss, float size) { player = boss; defaultCamSize = size; ChangeSize (size, 0.5f); } public void BossDead() { bossDeath = true; } public float GetSize() { return defaultCamSize; } }
21.609929
112
0.703315
[ "MIT" ]
msummersBU/Cursed-Plains
Assets/Scripts/Entities/Player/CameraController.cs
3,049
C#
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT license. See License.txt in the project root for license information. #nullable disable using System.Threading; using System.Threading.Tasks; using OmniSharp.Extensions.JsonRpc; using OmniSharp.Extensions.LanguageServer.Protocol.Models; using OmniSharp.Extensions.LanguageServer.Protocol.Server; namespace Microsoft.AspNetCore.Razor.LanguageServer { // The VSCode OmniSharp client starts the RazorServer before all of its handlers are registered // because of this we need to wait until everthing is initialized to make some client requests like // razor\serverReady. This class takes a TCS which will complete when everything is initialized // ensuring that no requests are sent before the client is ready. internal abstract class ClientNotifierServiceBase: IOnLanguageServerStarted { public abstract Task<IResponseRouterReturns> SendRequestAsync(string method); public abstract Task<IResponseRouterReturns> SendRequestAsync<T>(string method, T @params); public abstract Task OnStarted(ILanguageServer server, CancellationToken cancellationToken); public abstract InitializeParams ClientSettings { get; } } }
43.37931
103
0.786169
[ "MIT" ]
50Wliu/razor-tooling
src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/ClientNotifierServiceBase.cs
1,260
C#
using OrderCloud.SDK; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ordercloud.integrations.avalara { public static class ShipEstimateMapper { public static ShipMethod GetSelectedShippingMethod(this ShipEstimate estimates) { return estimates.ShipMethods.First(method => method.ID == estimates.SelectedShipMethodID); } public static (Address, Address) GetAddresses(this ShipEstimate estimates, IList<LineItem> allLines) { var firstItemInShipmentID = estimates.ShipEstimateItems.FirstOrDefault().LineItemID; var lineItem = allLines.First(item => item.ID == firstItemInShipmentID); return (lineItem.ShipFromAddress, lineItem.ShippingAddress); } } }
30.25
102
0.787879
[ "MIT" ]
Labedlam/headstart
src/Middleware/integrations/ordercloud.integrations.avalara/Mappers/ShipEstimateMapper.cs
728
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System.Threading; using Microsoft.Bot.Builder.Dialogs; namespace Microsoft.Bot.Builder.TestBot.Json { public class TestBotAccessors { public IStatePropertyAccessor<DialogState> ConversationDialogState { get; set; } public ConversationState ConversationState { get; set; } public UserState UserState { get; set; } public SemaphoreSlim SemaphoreSlim { get; } = new SemaphoreSlim(1, 1); } }
27
88
0.716667
[ "MIT" ]
Acidburn0zzz/botbuilder-dotnet
tests/Microsoft.Bot.Builder.TestBot.Json/TestBotAccessors.cs
542
C#
using DestinyMod.Common.Items.ItemTypes; using Microsoft.Xna.Framework; using Terraria; using Terraria.DataStructures; using Terraria.ID; using Terraria.Audio; using Terraria.ModLoader; namespace DestinyMod.Content.Items.Weapons.Ranged { public class DeadMansTale : Gun { public override void SetStaticDefaults() { DisplayName.SetDefault("Dead Man's Tale"); Tooltip.SetDefault("'Long, short, they all end the same way. -Katabasis'"); } public override void DestinySetDefaults() { Item.damage = 35; Item.useTime = 20; Item.useAnimation = 20; Item.knockBack = 4; Item.crit = 2; Item.value = Item.buyPrice(gold: 1); Item.rare = ItemRarityID.Yellow; Item.UseSound = new SoundStyle("DestinyMod/Assets/Sounds/Item/Weapons/Ranged/MidaMultiTool"); Item.shootSpeed = 30f; } public override bool Shoot(Player player, EntitySource_ItemUse_WithAmmo source, Vector2 position, Vector2 velocity, int type, int damage, float knockback) { Projectile projectile = Projectile.NewProjectileDirect(source, new Vector2(position.X, position.Y - 7), velocity, type, damage, knockback, player.whoAmI); if (projectile.extraUpdates < 3) { projectile.extraUpdates = 3; } return false; } public override Vector2? HoldoutOffset() => new Vector2(-12, 0); } }
29.704545
157
0.731446
[ "MIT" ]
MikhailMCraft/DestinyMod
Content/Items/Weapons/Ranged/DeadMansTale.cs
1,309
C#
using AL.Core.Interfaces; using Newtonsoft.Json; namespace AL.APIClient.Model { /// <summary> /// Represents a character this user owns. /// </summary> /// <seealso cref="IInstancedLocation" /> public record CharacterInfo : IInstancedLocation { /// <summary> /// The id of the character. (this is not the name) /// </summary> public string Id { get; init; } = null!; public string In { get; init; } = null!; /// <summary> /// The level of the character. /// </summary> public int Level { get; init; } public string Map { get; init; } = null!; /// <summary> /// The name of the character. /// </summary> public string Name { get; init; } = null!; /// <summary> /// Whether or not the character is already logged in. /// </summary> public bool Online { get; init; } /// <summary> /// TODO: unknown /// </summary> public string? Secret { get; init; } /// <summary> /// If the character is <see cref="Online" />, this is the <see cref="AL.APIClient.Definitions.ServerRegion" /> and /// <see cref="AL.APIClient.Definitions.ServerId" /> /// </summary> [JsonProperty("server")] public string? ServerKey { get; init; } public float X { get; init; } public float Y { get; init; } public virtual bool Equals(IPoint? other) => IPoint.Comparer.Equals(this, other); public virtual bool Equals(ILocation? other) => ILocation.Comparer.Equals(this, other); public override string ToString() => IInstancedLocation.ToString(this); } }
32.407407
127
0.549714
[ "MIT" ]
Sichii/ALClientCS
AL.APIClient/Model/CharacterInfo.cs
1,752
C#
using Adventures; using Classes; using Companions; using Equipment; using GroupFinder; using LobotJR.Command; using LobotJR.Data; using LobotJR.Data.Import; using LobotJR.Data.Migration; using LobotJR.Data.User; using LobotJR.Modules; using LobotJR.Modules.Fishing; using LobotJR.Shared.Authentication; using LobotJR.Shared.Utility; using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Runtime.InteropServices; using System.Text; using System.Threading; using Wolfcoins; namespace TwitchBot { public class Better { public int betAmount; public int vote; public Better() { betAmount = -1; vote = -1; } } class Program { static void Whisper(string user, string message, IrcClient whisperClient) { string toSend = ".w " + user + " " + message; whisperClient.sendChatMessage(toSend); } static void Whisper(Party party, string message, IrcClient whisperClient) { for (int i = 0; i < party.NumMembers(); i++) { string toSend = ".w " + party.members.ElementAt(i).name + " " + message; whisperClient.sendChatMessage(toSend); } } static void HandleCommandResult(string whisperSender, string whisperMessage, CommandResult result, IrcClient irc, IrcClient group) { if (result.Responses?.Count > 0) { foreach (var response in result.Responses) { Whisper(whisperSender, response, group); } } if (result.Messages?.Count > 0) { foreach (var broadcastMessage in result.Messages) { irc.sendChatMessage(broadcastMessage); } } if (result.Errors?.Count > 0) { Console.WriteLine($"Errors encountered while processing command \"{whisperMessage}\" from user {whisperSender}"); foreach (var error in result.Errors) { Console.WriteLine(error); } } if (result.Debug?.Count > 0) { Console.WriteLine($"Debug output generated by command \"{whisperMessage}\" from user {whisperSender}"); foreach (var error in result.Debug) { Console.WriteLine(error); } } } static void UpdateDungeons(string dungeonListPath, ref Dictionary<int, string> dungeonList) { IEnumerable<string> fileText; if (File.Exists(dungeonListPath)) { fileText = File.ReadLines(dungeonListPath, UTF8Encoding.Default); } else { fileText = new List<string>(); Console.WriteLine($"Failed to load dungeon list file, {dungeonListPath} not found."); } dungeonList = new Dictionary<int, string>(); int dungeonIter = 1; foreach (var line in fileText) { string[] temp = line.Split(','); int id = -1; int.TryParse(temp[0], out id); if (id != -1) dungeonList.Add(id, temp[1]); else Console.WriteLine("Invalid dungeon read on line " + dungeonIter); dungeonIter++; } } static void UpdateItems(string itemListPath, ref Dictionary<int, string> itemList, ref Dictionary<int, Item> itemDatabase) { IEnumerable<string> fileText; if (File.Exists(itemListPath)) { fileText = File.ReadLines(itemListPath, UTF8Encoding.Default); } else { fileText = new List<string>(); Console.WriteLine($"Failed to load item list file, {itemListPath} not found."); } itemDatabase = new Dictionary<int, Item>(); itemList = new Dictionary<int, string>(); int itemIter = 1; // ALERT: Was there a reason you were loading this from the file twice? // fileText = System.IO.File.ReadLines(itemListPath, UTF8Encoding.Default); foreach (var line in fileText) { string[] temp = line.Split(','); int id = -1; int.TryParse(temp[0], out id); if (id != -1) itemList.Add(id, "content/items/" + temp[1]); else Console.WriteLine("Invalid item read on line " + itemIter); itemIter++; } itemIter = 0; foreach (var item in itemList) { Item myItem = new Item(); int parsedInt = -1; int line = 0; string[] temp = { "" }; fileText = System.IO.File.ReadLines(itemList.ElementAt(itemIter).Value, UTF8Encoding.Default); // item ID myItem.itemID = itemList.ElementAt(itemIter).Key; // item name temp = fileText.ElementAt(line).Split('='); myItem.itemName = temp[1]; line++; // item type (1=weapon, 2=armor, 3=other) temp = fileText.ElementAt(line).Split('='); int.TryParse(temp[1], out parsedInt); myItem.itemType = parsedInt; line++; // Class designation (1=Warrior,2=Mage,3=Rogue,4=Ranger,5=Cleric) temp = fileText.ElementAt(line).Split('='); int.TryParse(temp[1], out parsedInt); myItem.forClass = parsedInt; line++; // Item rarity (1=Uncommon,2=Rare,3=Epic,4=Artifact) temp = fileText.ElementAt(line).Split('='); int.TryParse(temp[1], out parsedInt); myItem.itemRarity = parsedInt; line++; // success boost (%) temp = fileText.ElementAt(line).Split('='); int.TryParse(temp[1], out parsedInt); myItem.successChance = parsedInt; line++; // item find (%) temp = fileText.ElementAt(line).Split('='); int.TryParse(temp[1], out parsedInt); myItem.itemFind = parsedInt; line++; // coin boost (%) temp = fileText.ElementAt(line).Split('='); int.TryParse(temp[1], out parsedInt); myItem.coinBonus = parsedInt; line++; // xp boost (%) temp = fileText.ElementAt(line).Split('='); int.TryParse(temp[1], out parsedInt); myItem.xpBonus = parsedInt; line++; // prevent death boost (%) temp = fileText.ElementAt(line).Split('='); int.TryParse(temp[1], out parsedInt); myItem.preventDeathBonus = parsedInt; line++; // item description temp = fileText.ElementAt(line).Split('='); myItem.description = temp[1]; itemDatabase.Add(itemIter, myItem); itemIter++; } } static void UpdatePets(string petListPath, ref Dictionary<int, string> petList, ref Dictionary<int, Pet> petDatabase) { IEnumerable<string> fileText; if (File.Exists(petListPath)) { fileText = File.ReadLines(petListPath, UTF8Encoding.Default); } else { fileText = new List<string>(); Console.WriteLine($"Failed to load item list file, {petListPath} not found."); } petDatabase = new Dictionary<int, Pet>(); petList = new Dictionary<int, string>(); int petIter = 1; foreach (var line in fileText) { string[] temp = line.Split(','); int id = -1; int.TryParse(temp[0], out id); if (id != -1) petList.Add(id, "content/pets/" + temp[1]); else Console.WriteLine("Invalid pet read on line " + petIter); petIter++; } petIter = 0; foreach (var pet in petList) { Pet mypet = new Pet(); int parsedInt = -1; int line = 0; string[] temp = { "" }; fileText = System.IO.File.ReadLines(petList.ElementAt(petIter).Value, UTF8Encoding.Default); // pet ID mypet.ID = petList.ElementAt(petIter).Key; // pet name temp = fileText.ElementAt(line).Split('='); mypet.name = temp[1]; line++; // pet type (string ex: Fox, Cat, Dog) temp = fileText.ElementAt(line).Split('='); mypet.type = temp[1]; line++; // pet size (string ex: tiny, small, large) temp = fileText.ElementAt(line).Split('='); mypet.size = temp[1]; line++; // pet rarity (1=Common,2=Uncommon,3=Rare,4=Epic,5=Artifact) temp = fileText.ElementAt(line).Split('='); int.TryParse(temp[1], out parsedInt); mypet.petRarity = parsedInt; line++; // pet description temp = fileText.ElementAt(line).Split('='); mypet.description = temp[1]; line++; // pet emote temp = fileText.ElementAt(line).Split('='); mypet.emote = temp[1]; line++; int numLines = fileText.Count(); if (numLines <= line) { petDatabase.Add(petIter, mypet); petIter++; continue; } // success boost (%) temp = fileText.ElementAt(line).Split('='); int.TryParse(temp[1], out parsedInt); mypet.successChance = parsedInt; line++; // item find (%) temp = fileText.ElementAt(line).Split('='); int.TryParse(temp[1], out parsedInt); mypet.itemFind = parsedInt; line++; // coin boost (%) temp = fileText.ElementAt(line).Split('='); int.TryParse(temp[1], out parsedInt); mypet.coinBonus = parsedInt; line++; // xp boost (%) temp = fileText.ElementAt(line).Split('='); int.TryParse(temp[1], out parsedInt); mypet.xpBonus = parsedInt; line++; // prevent death boost (%) temp = fileText.ElementAt(line).Split('='); int.TryParse(temp[1], out parsedInt); mypet.preventDeathBonus = parsedInt; line++; petDatabase.Add(petIter, mypet); petIter++; } } #region TwitchPlaysData const int INPUT_MOUSE = 0; const int INPUT_KEYBOARD = 1; const int INPUT_HARDWARE = 2; const int KEYEVENTF_EXTENDEDKEY = 0x0001; const int KEYEVENTF_KEYUP = 0x0002; const ushort KEYEVENTF_KEYDOWN = 0x0000; const ushort KEYEVENTF_SCANCODE = 0x0008; const ushort KEYEVENTF_UNICODE = 0x0004; [DllImport("User32.dll")] static extern int SetForegroundWindow(IntPtr point); [DllImport("user32.dll")] public static extern int SendMessage(IntPtr hWnd, uint wMsg, IntPtr wParam, IntPtr lParam); [DllImport("user32.dll")] static extern IntPtr GetMessageExtraInfo(); [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)] static extern uint SendInput(uint nInputs, INPUT[] pInputs, int cbSize); [DllImport("user32.dll")] static extern byte VkKeyScan(char ch); [DllImport("user32.dll")] static extern uint MapVirtualKey(uint uCode, uint uMapType); [StructLayout(LayoutKind.Explicit)] struct INPUT { [FieldOffset(0)] public int type; [FieldOffset(4)] public MOUSEINPUT mi; [FieldOffset(4)] public KEYBDINPUT ki; [FieldOffset(4)] public HARDWAREINPUT hi; } [StructLayout(LayoutKind.Sequential)] struct HARDWAREINPUT { public int uMsg; public short wParamL; public short wParamH; } [StructLayout(LayoutKind.Sequential)] struct KEYBDINPUT { public short wVk; public short wScan; public int dwFlags; public int time; public IntPtr dwExtraInfo; } [StructLayout(LayoutKind.Sequential)] struct MOUSEINPUT { public int dx; public int dy; public int mouseData; public int dwFlags; public int time; public IntPtr dwExtraInfo; } #endregion [STAThread] static void Main(string[] args) { bool twitchPlays = false; bool connected = true; bool broadcasting = false; // How often to award Wolfcoins in minutes const int DUNGEON_MAX = 3; const int PARTY_FORMING = 1; const int PARTY_FULL = 2; const int PARTY_STARTED = 3; const int PARTY_COMPLETE = 4; const int PARTY_READY = 2; const int SUCCEED = 0; const int FAIL = 1; const int LOW_DETAIL = 0; const int HIGH_DETAIL = 1; int subCounter = 0; int awardMultiplier = 1; int awardInterval = 30; int awardAmount = 1; int awardTotal = 0; int gloatCost = 25; int pryCost = 1; Dictionary<int, Item> itemDatabase = new Dictionary<int, Item>(); Dictionary<int, Pet> petDatabase = new Dictionary<int, Pet>(); var subathonPath = "C:/Users/Lobos/Dropbox/Stream/subathon.txt"; IEnumerable<string> subathonFile; if (File.Exists(subathonPath)) { subathonFile = File.ReadLines(subathonPath, UTF8Encoding.Default); } else { subathonFile = new List<string>(); Console.WriteLine($"Failed to load subathon file, {subathonPath} not found."); } Dictionary<int, string> dungeonList = new Dictionary<int, string>(); string dungeonListPath = "content/dungeonlist.ini"; Dictionary<int, string> itemList = new Dictionary<int, string>(); string itemListPath = "content/itemlist.ini"; Dictionary<int, string> petList = new Dictionary<int, string>(); string petListPath = "content/petlist.ini"; Dictionary<int, Party> parties = new Dictionary<int, Party>(); int maxPartyID = 0; GroupFinderQueue groupFinder; const int baseDungeonCost = 25; //const int baseRaidCost = 150; const int baseRespecCost = 250; Dictionary<string, Better> betters = new Dictionary<string, Better>(); //string betStatement = ""; bool betActive = false; bool betsAllowed = false; var clientData = FileUtils.ReadClientData(); var tokenData = FileUtils.ReadTokenData(); IrcClient irc = new IrcClient("irc.chat.twitch.tv", 80, tokenData.ChatUser, tokenData.ChatToken.AccessToken); IrcClient group = new IrcClient("irc.chat.twitch.tv", 80, tokenData.ChatUser, tokenData.ChatToken.AccessToken); // 199.9.253.119 connected = irc.connected; #region Sql Data Setup var context = new SqliteContext(); context.Database.Initialize(false); var repoManager = new SqliteRepositoryManager(context); var userLookup = new UserLookup(repoManager.Users, new AppSettings()); var updater = new SqliteDatabaseUpdater(repoManager, context, userLookup, tokenData.BroadcastToken.AccessToken, clientData.ClientId); if (updater.GetDatabaseVersion(repoManager) < SqliteDatabaseUpdater.LatestVersion) { Console.WriteLine($"Database is out of date, updating to {SqliteDatabaseUpdater.LatestVersion}. This could take a few minutes."); var updateResult = updater.UpdateDatabase(); if (!updateResult.Success) { throw new Exception($"Error occurred updating database from {updateResult.PreviousVersion} to {updateResult.NewVersion}. {updateResult.DebugOutput}"); } Console.WriteLine("Update complete!"); } var appSettings = repoManager.AppSettings.Read().FirstOrDefault(); if (appSettings == null) { appSettings = new AppSettings(); repoManager.AppSettings.Create(appSettings); repoManager.AppSettings.Commit(); } userLookup = new UserLookup(repoManager.Users, appSettings); #endregion #region System Setup var systemManager = new SystemManager(repoManager, repoManager); systemManager.LoadAllSystems(); #endregion if (connected) { UpdateTokens(tokenData, clientData); Console.WriteLine($"Logged in as {tokenData.ChatUser}"); irc.sendIrcMessage("twitch.tv/membership"); } if (group.connected) { group.sendIrcMessage("CAP REQ :twitch.tv/tags twitch.tv/commands twitch.tv/membership"); } if (!twitchPlays) { #region NormalBot string channel = tokenData.BroadcastUser; irc.joinRoom(channel); group.joinRoom("jtv"); DateTime awardLast = DateTime.Now; Currency wolfcoins = new Currency(clientData); wolfcoins.UpdateViewers(channel); wolfcoins.UpdateSubs(tokenData.BroadcastToken.AccessToken, clientData.ClientId); #region Command Manager Setup var commandManager = new CommandManager(repoManager, userLookup); commandManager.LoadAllModules(systemManager, wolfcoins); commandManager.PushNotifications += (string userId, CommandResult commandResult) => { string username = userId == null ? null : userLookup.GetUsername(userId); string message = "Push Notification"; HandleCommandResult(username, message, commandResult, irc, group); }; #endregion #region Import Legacy Data Into Sql if (File.Exists(FishDataImport.FishDataPath)) { Console.WriteLine("Detected legacy fish data file, migrating to SQLite."); FishDataImport.ImportFishDataIntoSql(FishDataImport.FishDataPath, repoManager.FishData); File.Move(FishDataImport.FishDataPath, $"{FishDataImport.FishDataPath}.{DateTime.Now.ToFileTimeUtc()}.backup"); Console.WriteLine("Fish data migration complete!"); } var hasFisherData = File.Exists(FisherDataImport.FisherDataPath); var hasLeaderboardData = File.Exists(FisherDataImport.FishingLeaderboardPath); if (hasFisherData || hasLeaderboardData) { Console.WriteLine("Detected legacy fisher data file, migrating to SQLite. This could take a few minutes."); IEnumerable<string> users = new List<string>(); Dictionary<string, LegacyFisher> legacyFisherData = FisherDataImport.LoadLegacyFisherData(FisherDataImport.FisherDataPath); List<LegacyCatch> legacyLeaderboardData = FisherDataImport.LoadLegacyFishingLeaderboardData(FisherDataImport.FishingLeaderboardPath); Console.WriteLine("Converting usernames to user ids..."); FisherDataImport.FetchUserIds(legacyFisherData.Keys.Union(legacyLeaderboardData.Select(x => x.caughtBy)), userLookup, tokenData.BroadcastToken.AccessToken, clientData.ClientId); if (hasFisherData) { Console.WriteLine("Importing user records..."); FisherDataImport.ImportFisherDataIntoSql(legacyFisherData, repoManager.Fishers, repoManager.FishData, userLookup); File.Move(FisherDataImport.FisherDataPath, $"{FisherDataImport.FisherDataPath}.{DateTime.Now.ToFileTimeUtc()}.backup"); } if (hasLeaderboardData) { Console.WriteLine("Importing leaderboard..."); FisherDataImport.ImportLeaderboardDataIntoSql(legacyLeaderboardData, repoManager.FishingLeaderboard, repoManager.FishData, userLookup); File.Move(FisherDataImport.FishingLeaderboardPath, $"{FisherDataImport.FishingLeaderboardPath}.{DateTime.Now.ToFileTimeUtc()}.backup"); } Console.WriteLine("Fisher data migration complete!"); } #endregion UpdateDungeons(dungeonListPath, ref dungeonList); UpdateItems(itemListPath, ref itemList, ref itemDatabase); UpdatePets(petListPath, ref petList, ref petDatabase); groupFinder = new GroupFinderQueue(dungeonList); foreach (var member in wolfcoins.classList) { member.Value.ClearQueue(); } wolfcoins.SaveClassData(); DateTime lastConnectAttempt = DateTime.Now; while (true) { if (!irc.connected) { UpdateTokens(tokenData, clientData); if ((DateTime.Now - lastConnectAttempt).TotalSeconds > 5) { irc = new IrcClient("irc.chat.twitch.tv", 80, tokenData.ChatUser, tokenData.ChatToken.AccessToken); group = new IrcClient("irc.chat.twitch.tv", 80, tokenData.ChatUser, tokenData.ChatToken.AccessToken); lastConnectAttempt = DateTime.Now; if (!connected) { Console.WriteLine("Disconnected from server. Attempting to reconnect in 30 seconds..."); } else { Console.WriteLine("Reconnected to server."); } } continue; } #region System Processing if (userLookup.IsUpdateTime(DateTime.Now)) { userLookup.UpdateCache(tokenData.BroadcastToken.AccessToken, clientData.ClientId); } systemManager.Process(broadcasting); #endregion // message[0] has username, message[1] has message string[] message = irc.readMessage(wolfcoins, channel); string[] whispers = group.readMessage(wolfcoins, channel); string whisperSender; string whisperMessage; if (irc.messageQueue.Count > 0) { irc.processQueue(); } if (group.messageQueue.Count > 0) { group.processQueue(); } List<int> partiesToRemove = new List<int>(); foreach (var party in parties) { if (party.Value.status == PARTY_STARTED && party.Value.myDungeon.messenger.messageQueue.Count() > 0) { if (party.Value.myDungeon.messenger.processQueue() == 1) { // grant rewards here foreach (var member in party.Value.members) { // if player had an active pet, lower its hunger and affection if (member.myPets.Count > 0) { bool petUpdated = false; foreach (var pet in wolfcoins.classList[member.name].myPets) { // if we updated the active pet already (should only be one), we're done if (petUpdated) break; // check for active pet if (pet.isActive) { Random RNG = new Random(); int hungerToLose = RNG.Next(Pet.DUNGEON_HUNGER, Pet.DUNGEON_HUNGER + 6); pet.affection -= Pet.DUNGEON_AFFECTION; if (pet.hunger <= 0) { // PET DIES HERE Whisper(member.name, pet.name + " starved to death.", group); wolfcoins.classList[member.name].releasePet(pet.stableID); wolfcoins.SaveClassData(); break; } else if (pet.hunger <= 10) { Whisper(member.name, pet.name + " is very hungry and will die if you don't feed it soon!", group); } else if (pet.hunger <= 25) { Whisper(member.name, pet.name + " is hungry! Be sure to !feed them!", group); } if (pet.affection < 0) pet.affection = 0; petUpdated = true; } } } if (member.xpEarned == 0 || member.coinsEarned == 0) continue; if ((member.xpEarned + member.coinsEarned) > 0 && member.usedGroupFinder && (DateTime.Now - member.lastDailyGroupFinder).TotalDays >= 1) { member.lastDailyGroupFinder = DateTime.Now; member.xpEarned *= 2; member.coinsEarned *= 2; Whisper(member.name, "You earned double rewards for completing a daily Group Finder dungeon! Queue up again in 24 hours to receive the 2x bonus again! (You can whisper me '!daily' for a status.)", group); } wolfcoins.AwardXP(member.xpEarned, member.name, group); wolfcoins.AwardCoins(member.coinsEarned, member.name); if (member.xpEarned > 0 && member.coinsEarned > 0) Whisper(member.name, member.name + ", you've earned " + member.xpEarned + " XP and " + member.coinsEarned + " Wolfcoins for completing the dungeon!", group); if (wolfcoins.classList[member.name].itemEarned != -1) { int itemID = GrantItem(wolfcoins.classList[member.name].itemEarned, wolfcoins, member.name, itemDatabase); Whisper(member.name, "You looted " + itemDatabase[(itemID - 1)].itemName + "!", group); } // if a pet is waiting to be awarded if (wolfcoins.classList[member.name].petEarned != -1) { Dictionary<int, Pet> allPets = new Dictionary<int, Pet>(petDatabase); Pet newPet = GrantPet(member.name, wolfcoins, allPets, irc, group); if (newPet.stableID != -1) { string logPath = "petlog.txt"; string timestamp = DateTime.Now.ToString(); if (newPet.isSparkly) { System.IO.File.AppendAllText(logPath, timestamp + ": " + member.name + " found a SPARKLY pet " + newPet.name + "." + Environment.NewLine); } else { System.IO.File.AppendAllText(logPath, timestamp + ": " + member.name + " found a pet " + newPet.name + "." + Environment.NewLine); } } //if (wolfcoins.classList[member.name].petEarned != -1) //{ // List<Pet> toAward = new List<Pet>(); // bool hasActivePet = false; // // figure out the rarity of pet to give and build a list of non-duplicate pets to award // int rarity = wolfcoins.classList[member.name].petEarned; // foreach (var basePet in petDatabase) // { // if (basePet.Value.petRarity != rarity) // continue; // bool alreadyOwned = false; // foreach(var pet in wolfcoins.classList[member.name].myPets) // { // if (pet.isActive) // hasActivePet = true; // if (pet.ID == basePet.Value.ID) // alreadyOwned = true; // } // if(!alreadyOwned) // { // toAward.Add(basePet.Value); // } // } // // now that we have a list of eligible pets, randomly choose one from the list to award // Pet newPet = new Pet(); // if(toAward.Count > 0) // { // string toSend = ""; // Random RNG = new Random(); // int petToAward = RNG.Next(1, toAward.Count); // newPet = toAward[petToAward - 1]; // int sparklyCheck = RNG.Next(1, 100); // if (sparklyCheck == 1) // newPet.isSparkly = true; // newPet.stableID = wolfcoins.classList[member.name].myPets.Count; // wolfcoins.classList[member.name].myPets.Count = wolfcoins.classList[member.name].myPets.Count; // if (!hasActivePet) // { // newPet.isActive = true; // toSend = "You found your first pet! You now have a pet " + newPet.name + ". Whisper me !pethelp for more info."; // } // else // { // toSend = "You found a new pet buddy! You earned a " + newPet.name + " pet!"; // } // if(newPet.isSparkly) // { // toSend += " WOW! And it's a sparkly version! Luck you!"; // } // wolfcoins.classList[member.name].myPets.Add(newPet); // wolfcoins.classList[member.name].petEarned = -1; // Whisper(member.name, toSend, group); // if (newPet.isSparkly) // { // Console.WriteLine(DateTime.Now.ToString() + "WOW! " + ": " + member.name + " just found a SPARKLY pet " + newPet.name + "!"); // irc.sendChatMessage("WOW! " + member.name + " just found a SPARKLY pet " + newPet.name + "! What luck!"); // } // else // { // Console.WriteLine(DateTime.Now.ToString() + ": " + member.name + " just found a pet " + newPet.name + "!"); // irc.sendChatMessage(member.name + " just found a pet " + newPet.name + "!"); // } // } //} } if (wolfcoins.classList[member.name].queueDungeons.Count > 0) wolfcoins.classList[member.name].ClearQueue(); } party.Value.PostDungeon(wolfcoins); wolfcoins.SaveClassData(); wolfcoins.SaveXP(); wolfcoins.SaveCoins(); party.Value.status = PARTY_READY; if (party.Value.usedDungeonFinder) { partiesToRemove.Add(party.Key); } } } } for (int i = 0; i < partiesToRemove.Count; i++) { int Key = partiesToRemove[i]; foreach (var member in parties[Key].members) { Whisper(member.name, "You completed a group finder dungeon. Type !queue to join another group!", group); wolfcoins.classList[member.name].groupID = -1; wolfcoins.classList[member.name].numInvitesSent = 0; wolfcoins.classList[member.name].isPartyLeader = false; wolfcoins.classList[member.name].ClearQueue(); } parties.Remove(Key); } if (((DateTime.Now - awardLast).TotalMinutes > awardInterval)) { if (broadcasting) { awardTotal = awardAmount * awardMultiplier; wolfcoins.UpdateViewers(channel); // Halloween Treats //Random rnd = new Random(); //int numViewers = wolfcoins.viewers.chatters.viewers.Count; //int winner = rnd.Next(0, (numViewers - 1)); //string winnerName = wolfcoins.viewers.chatters.viewers.ElementAt(winner); //int coinsToAward = (rnd.Next(5, 10)) * 50; //wolfcoins.AddCoins(winnerName, coinsToAward.ToString()); wolfcoins.AwardCoins(awardTotal * 3); // Give 3x as many coins as XP wolfcoins.AwardXP(awardTotal, group); //string path2 = "C:/Users/Lobos/AppData/Roaming/DarkSoulsII/01100001004801af/`s" + DateTime.Now.Ticks + ".sl2"; //File.Copy(@"C:\Users\Lobos\AppData\Roaming\DarkSoulsII\01100001004801af\DS2SOFS0000.sl2", @path2); //string path = "C:/Users/Lobos/AppData/Roaming/DarkSoulsIII/01100001004801af/Backups/DS30000_" + DateTime.Now.Ticks + ".sl2"; //File.Copy(@"C:/Users/Lobos/AppData/Roaming/DarkSoulsIII/01100001004801af/DS30000.sl2", @path); irc.sendChatMessage("Thanks for watching! Viewers awarded " + awardTotal + " XP & " + (awardTotal * 3) + " Wolfcoins. Subscribers earn double that amount!"); //irc.sendChatMessage("Happy Halloween! Viewer " + winnerName + " just won a treat of " + coinsToAward + " wolfcoins!"); } wolfcoins.SaveCoins(); wolfcoins.SaveXP(); wolfcoins.SaveClassData(); awardLast = DateTime.Now; } #region whisperRegion if (whispers.Length > 1) { if (whispers[0] != null && whispers[1] != null) { whisperSender = whispers[0]; whisperMessage = whispers[1]; if (wolfcoins.Exists(wolfcoins.classList, whisperSender)) { if (wolfcoins.determineLevel(whisperSender) >= 3 && wolfcoins.determineClass(whisperSender) == "INVALID CLASS" && !whisperMessage.StartsWith("c") && !whisperMessage.StartsWith("C")) { Whisper(whisperSender, "ATTENTION! You are high enough level to pick a class, but have not picked one yet! Whisper me one of the following to choose your class: ", group); Whisper(whisperSender, "'C1' (Warrior), 'C2' (Mage), 'C3' (Rogue), 'C4' (Ranger), or 'C5' (Cleric)", group); } } #region Command Module Processing if (whisperMessage.StartsWith("!")) { var result = commandManager.ProcessMessage(whisperMessage.Substring(1), whisperSender); if (result != null && result.Processed) { HandleCommandResult(whisperSender, whisperMessage, result, irc, group); continue; } } #endregion if (whisperMessage == "?" || whisperMessage == "help" || whisperMessage == "!help" || whisperMessage == "faq" || whisperMessage == "!faq") { //Whisper(whisperSender, "Help command coming soon. For now, know that only viewers Level 2 & higher can post hyperlinks. This helps keep chat free of bots!"); Whisper(whisperSender, "Hi I'm LobotJR! I'm a chat bot written by LobosJR to help out with things. To ask me about a certain topic, whisper me the number next to what you want to know about! (Ex: Whisper me 1 for information on Wolfcoins)", group); Whisper(whisperSender, "Here's a list of things you can ask me about: Wolfcoins (1) - Leveling System (2)", group); } else if (whisperMessage == "!cleartesters" && (whisperSender == tokenData.BroadcastUser || whisperSender == tokenData.ChatUser)) { //string[] users = { "lobosjr", "spectrumknight", "floogoss", "shoumpaloumpa", "nemesis_of_green", "donotgogently", "twitchmage", "kidgreen4", "cuddling", "androsv", "jaranous94", "lambchop2559", "hockeyboy1257", "dumj00", "stennisberetheon", "bionicmeech", "blargh201", "arampizzatime"}; //for(int i = 0; i < users.Length; i++) //{ // if (wolfcoins.Exists(wolfcoins.classList, users[i])) // { // wolfcoins.classList.Remove(users[i]); // wolfcoins.SetXP(1, users[i], group); // wolfcoins.SetXP(600, users[i], group); // } // else // { // wolfcoins.SetXP(1, users[i], group); // wolfcoins.SetXP(600, users[i], group); // } //} } else if (whisperMessage.StartsWith("!dungeon")) { if (wolfcoins.Exists(wolfcoins.classList, whisperSender)) { string[] msgData = whispers[1].Split(' '); int dungeonID = -1; if (msgData.Count() > 1) { int.TryParse(msgData[1], out dungeonID); if (dungeonID != -1 && dungeonList.ContainsKey(dungeonID)) { string dungeonPath = "content/dungeons/" + dungeonList[dungeonID]; Dungeon tempDungeon = new Dungeon(dungeonPath); Whisper(whisperSender, tempDungeon.dungeonName + " (Levels " + tempDungeon.minLevel + " - " + tempDungeon.maxLevel + ") -- " + tempDungeon.description, group); } else { Whisper(whisperSender, "Invalid Dungeon ID provided.", group); } } } } else if (whisperMessage.StartsWith("!bug")) { if (wolfcoins.Exists(wolfcoins.classList, whisperSender)) { string[] msgData = whispers[1].Split(' '); if (msgData.Count() > 1) { string bugMessage = ""; for (int i = 1; i < msgData.Count(); i++) { bugMessage += msgData[i] + " "; } string logPath = "bugreports.log"; System.IO.File.AppendAllText(logPath, whisperSender + ": " + bugMessage + Environment.NewLine); System.IO.File.AppendAllText(logPath, "------------------------------------------" + Environment.NewLine); Whisper(whisperSender, "Bug report submitted.", group); Whisper(tokenData.BroadcastUser, DateTime.Now + ": " + whisperSender + " submitted a bug report.", group); Console.WriteLine(DateTime.Now + ": " + whisperSender + " submitted a bug report."); } } } else if (whisperMessage.StartsWith("!item")) { if (wolfcoins.Exists(wolfcoins.classList, whisperSender)) { if (wolfcoins.classList[whisperSender].myItems.Count == 0) { Whisper(whisperSender, "You have no items.", group); continue; } string[] msgData = whispers[1].Split(' '); int invID = -1; if (msgData.Count() > 1) { int.TryParse(msgData[1], out invID); if (invID != -1) { bool itemFound = false; foreach (var item in wolfcoins.classList[whisperSender].myItems) { if (item.inventoryID == invID) { string desc = itemDatabase[item.itemID - 1].description; string name = itemDatabase[item.itemID - 1].itemName; Whisper(whisperSender, name + " -- " + desc, group); itemFound = true; break; } } if (!itemFound) { Whisper(whisperSender, "Invalid Inventory ID provided.", group); } } else { Whisper(whisperSender, "Invalid Inventory ID provided.", group); } } } } else if (whisperMessage == "!updateviewers") { if (whisperSender != tokenData.BroadcastUser && whisperSender != tokenData.ChatUser) { continue; } wolfcoins.UpdateViewers(channel); } else if (whisperMessage == "!updateitems") { if (whisperSender != tokenData.BroadcastUser && whisperSender != tokenData.ChatUser) continue; UpdateItems(itemListPath, ref itemList, ref itemDatabase); foreach (var player in wolfcoins.classList) { if (player.Value.myItems.Count == 0) continue; foreach (var item in player.Value.myItems) { Item newItem = itemDatabase[item.itemID - 1]; item.itemName = newItem.itemName; item.itemRarity = newItem.itemRarity; item.itemFind = newItem.itemFind; item.successChance = newItem.successChance; item.coinBonus = newItem.coinBonus; item.preventDeathBonus = newItem.preventDeathBonus; item.xpBonus = newItem.xpBonus; } } } else if (whisperMessage == "!godmode") { if (whisperSender != tokenData.BroadcastUser && whisperSender != tokenData.ChatUser) continue; wolfcoins.classList[whisperSender].successChance = 1000; } else if (whisperMessage.StartsWith("!addplayer")) { if (whisperSender != tokenData.BroadcastUser && whisperSender != tokenData.ChatUser) continue; string[] msgData = whispers[1].Split(' '); if (msgData.Count() == 2) { string name = msgData[1]; string toSend = ""; if (!wolfcoins.classList.ContainsKey(name)) { wolfcoins.classList.Add(name.ToLower(), new CharClass()); toSend += "class, "; } if (!wolfcoins.coinList.ContainsKey(name)) { wolfcoins.coinList.Add(name, 0); toSend += "coin, "; } if (!wolfcoins.xpList.ContainsKey(name)) { wolfcoins.xpList.Add(name, 0); toSend += "xp"; } Whisper(tokenData.BroadcastUser, name + " added to the following lists: " + toSend, group); } } else if (whisperMessage.StartsWith("!transfer")) { if (whisperSender != tokenData.BroadcastUser && whisperSender != tokenData.ChatUser) continue; string[] msgData = whispers[1].Split(' '); if (msgData.Count() > 2 && msgData.Count() < 4) { string prevName = msgData[1]; string newName = msgData[2]; if (!wolfcoins.coinList.ContainsKey(prevName) || !wolfcoins.xpList.ContainsKey(prevName)) { Whisper(whisperSender, prevName + " has no stats to transfer.", group); continue; } if (!wolfcoins.coinList.ContainsKey(newName)) { wolfcoins.coinList.Add(newName, 0); } if (!wolfcoins.xpList.ContainsKey(newName)) { wolfcoins.xpList.Add(newName, 0); } int prevCoins = wolfcoins.coinList[prevName]; int prevXP = wolfcoins.xpList[prevName]; wolfcoins.coinList[newName] += prevCoins; wolfcoins.xpList[newName] += prevXP; if (!wolfcoins.classList.ContainsKey(newName)) { CharClass playerClass = new CharClass(); wolfcoins.classList.Add(newName.ToLower(), new CharClass()); } Whisper(whisperSender, "Transferred " + prevName + "'s xp/coins to " + newName + ".", group); Whisper(newName, "Your xp/coin total has been updated by Lobos! Thanks for playing the RPG lobosHi", group); wolfcoins.SaveCoins(); wolfcoins.SaveXP(); } } else if (whisperMessage.StartsWith("!checkpets")) { if (whisperSender != tokenData.BroadcastUser && whisperSender != tokenData.ChatUser) continue; string[] msgData = whispers[1].Split(' '); if (msgData.Count() > 1) { string toCheck = msgData[1]; foreach (var pet in wolfcoins.classList[toCheck].myPets) { WhisperPet(whisperSender, pet, group, LOW_DETAIL); } } else { Whisper(whisperSender, "!checkpets <username>", group); } } else if (whisperMessage.StartsWith("!grantpet")) { if (whisperSender != tokenData.BroadcastUser && whisperSender != tokenData.ChatUser) continue; string[] msgData = whispers[1].Split(' '); if (msgData.Count() > 1) { int rarity = -1; if (int.TryParse(msgData[1], out rarity)) { wolfcoins.classList[whisperSender].petEarned = rarity; } } else { Random rng = new Random(); wolfcoins.classList[whisperSender].petEarned = rng.Next(1, 6); } Dictionary<int, Pet> allPets = petDatabase; GrantPet(whisperSender, wolfcoins, allPets, irc, group); //Random RNG = new Random(); //Pet newPet = new Pet(); //int petToAward = RNG.Next(1, petDatabase.Count); //newPet = petDatabase[petToAward]; //int sparklyCheck = RNG.Next(1, 100); //if (sparklyCheck == 1) // newPet.isSparkly = true; //wolfcoins.classList[whisperSender].myPets.Count++; //newPet.stableID = wolfcoins.classList[whisperSender].myPets.Count; //wolfcoins.classList[whisperSender].myPets.Add(newPet); //Whisper(whisperSender, "Added a random pet.", group); } else if (whisperMessage == "!clearpets") { if (whisperSender != tokenData.BroadcastUser && whisperSender != tokenData.ChatUser) continue; wolfcoins.classList[whisperSender].myPets = new List<Pet>(); wolfcoins.classList[whisperSender].toRelease = new Pet(); wolfcoins.classList[whisperSender].pendingPetRelease = false; Whisper(whisperSender, "Pets cleared.", group); } else if (whisperMessage == "!updatedungeons") { if (whisperSender != tokenData.BroadcastUser && whisperSender != tokenData.ChatUser) continue; UpdateDungeons(dungeonListPath, ref dungeonList); } else if (whisperMessage.StartsWith("/p") || whisperMessage.StartsWith("/party")) { if (wolfcoins.Exists(wolfcoins.classList, whisperSender)) { if (wolfcoins.classList[whisperSender].groupID != -1) { string[] msgData = whispers[1].Split(' '); if (msgData.Count() > 1) { string partyMessage = ""; for (int i = 1; i < msgData.Count(); i++) { partyMessage += msgData[i] + " "; } int partyID = wolfcoins.classList[whisperSender].groupID; foreach (var member in parties[partyID].members) { if (member.name == whisperSender) { Whisper(member.name, "You whisper: \" " + partyMessage + "\" ", group); continue; } Whisper(member.name, whisperSender + " says: \" " + partyMessage + "\" ", group); } } } } } else if (whisperMessage == "!respec") { if (wolfcoins.classList != null) { if (wolfcoins.classList.Keys.Contains(whisperSender.ToLower()) && wolfcoins.determineClass(whisperSender) != "INVALID_CLASS") { if (wolfcoins.classList[whisperSender].groupID == -1) { if (wolfcoins.Exists(wolfcoins.coinList, whisperSender)) { int respecCost = (baseRespecCost * (wolfcoins.classList[whisperSender].level - 4)); if (respecCost < baseRespecCost) respecCost = baseRespecCost; if (wolfcoins.coinList[whisperSender] <= respecCost) { Whisper(whisperSender, "It costs " + respecCost + " Wolfcoins to respec at your level. You have " + wolfcoins.coinList[whisperSender] + " coins.", group); } int classNumber = wolfcoins.classList[whisperSender].classType * 10; wolfcoins.classList[whisperSender].classType = classNumber; Whisper(whisperSender, "You've chosen to respec your class! It will cost you " + respecCost + " coins to respec and you will lose all your items. Reply 'Nevermind' to cancel or one of the following codes to select your new class: ", group); Whisper(whisperSender, "'C1' (Warrior), 'C2' (Mage), 'C3' (Rogue), 'C4' (Ranger), or 'C5' (Cleric)", group); } else { Whisper(whisperSender, "You have no coins to respec with.", group); } } else { Whisper(whisperSender, "You can't respec while in a party!", group); } } } } else if (whisperMessage == "!inventory" || whisperMessage == "!inv" || whisperMessage == "inv" || whisperMessage == "inventory") { if (wolfcoins.Exists(wolfcoins.classList, whisperSender)) { if (wolfcoins.classList[whisperSender].myItems.Count > 0) { Whisper(whisperSender, "You have " + wolfcoins.classList[whisperSender].myItems.Count + " items: ", group); foreach (var item in wolfcoins.classList[whisperSender].myItems) { WhisperItem(whisperSender, item, group, itemDatabase); } } else { Whisper(whisperSender, "You have no items.", group); } } } else if (whisperMessage == "!pets" || whisperMessage == "!stable" || whisperMessage == "pets" || whisperMessage == "stable") { if (wolfcoins.Exists(wolfcoins.classList, whisperSender)) { if (wolfcoins.classList[whisperSender].myPets.Count > 0) { Whisper(whisperSender, "You have " + wolfcoins.classList[whisperSender].myPets.Count + " pets: ", group); foreach (var pet in wolfcoins.classList[whisperSender].myPets) { WhisperPet(whisperSender, pet, group, LOW_DETAIL); } } else { Whisper(whisperSender, "You have no pets.", group); } } } else if (whisperMessage == "!pethelp") { Whisper(whisperSender, "View all your pets by whispering me '!pets'. View individual pet stats using '!pet <stable id>' where the id is the number next to your pet's name in brackets [].", group); Whisper(whisperSender, "A summoned/active pet will join you on dungeon runs and possibly even bring benefits! But this will drain its energy, which you can restore by feeding it.", group); Whisper(whisperSender, "You can !dismiss, !summon, !release, !feed, and !hug* your pets using their stable id (ex: !summon 2)", group); Whisper(whisperSender, "*: In development, available soon!", group); } else if (whisperMessage.StartsWith("!fixpets")) { if (whisperSender != tokenData.BroadcastUser && whisperSender != tokenData.ChatUser) continue; //string[] msgData = whispers[1].Split(' '); //if (msgData.Count() != 2) //{ // Whisper(whisperSender, "Invalid number of parameters. Syntax: !feed <stable ID>", group); // continue; //} //string playerToFix = msgData[1]; foreach (var player in wolfcoins.classList) { if (player.Value.myPets.Count == 0) { continue; } int stableIDFix = 1; foreach (var pet in player.Value.myPets) { pet.stableID = stableIDFix; stableIDFix++; } Whisper(whisperSender, "Fixed " + player.Value.name + "'s pet IDs.", group); } } else if (whisperMessage.StartsWith("!feed")) { if (wolfcoins.Exists(wolfcoins.classList, whisperSender) && wolfcoins.Exists(wolfcoins.coinList, whisperSender)) { if (wolfcoins.classList[whisperSender].myPets.Count > 0) { string[] msgData = whispers[1].Split(' '); if (msgData.Count() != 2) { Whisper(whisperSender, "Invalid number of parameters. Syntax: !feed <stable ID>", group); continue; } int petToFeed = -1; if (int.TryParse(msgData[1], out petToFeed)) { if (petToFeed > wolfcoins.classList[whisperSender].myPets.Count || petToFeed < 1) { Whisper(whisperSender, "Invalid Stable ID given. Check !pets for each pet's stable ID!", group); continue; } if (wolfcoins.coinList[whisperSender] < 5) { Whisper(whisperSender, "You lack the 5 wolfcoins to feed your pet! Hop in a Lobos stream soon!", group); continue; } // build a dummy pet to do calculations Pet tempPet = wolfcoins.classList[whisperSender].myPets.ElementAt(petToFeed - 1); if (tempPet.hunger >= Pet.HUNGER_MAX) { Whisper(whisperSender, tempPet.name + " is full and doesn't need to eat!", group); continue; } int currentHunger = tempPet.hunger; int currentXP = tempPet.xp; int currentLevel = tempPet.level; int currentAffection = tempPet.affection + Pet.FEEDING_AFFECTION; // Charge the player for pet food wolfcoins.coinList[whisperSender] = wolfcoins.coinList[whisperSender] - Pet.FEEDING_COST; Whisper(whisperSender, "You were charged " + Pet.FEEDING_COST + " wolfcoins to feed " + tempPet.name + ". They feel refreshed!", group); // earn xp equal to amount of hunger 'fed' currentXP += (Pet.HUNGER_MAX - currentHunger); // check if pet leveled if (currentXP >= Pet.XP_TO_LEVEL && currentLevel < Pet.LEVEL_MAX) { currentLevel++; currentXP = currentXP - Pet.XP_TO_LEVEL; Whisper(whisperSender, tempPet.name + " leveled up! They are now level " + currentLevel + ".", group); } // refill hunger value currentHunger = Pet.HUNGER_MAX; // update temp pet w/ new data tempPet.affection = currentAffection; tempPet.hunger = currentHunger; tempPet.xp = currentXP; tempPet.level = currentLevel; // update actual pet data wolfcoins.classList[whisperSender].myPets.ElementAt(petToFeed - 1).affection = currentAffection; wolfcoins.classList[whisperSender].myPets.ElementAt(petToFeed - 1).hunger = currentHunger; wolfcoins.classList[whisperSender].myPets.ElementAt(petToFeed - 1).xp = currentXP; wolfcoins.classList[whisperSender].myPets.ElementAt(petToFeed - 1).level = currentLevel; wolfcoins.SaveClassData(); wolfcoins.SaveCoins(); } } } } else if (whisperMessage.StartsWith("!sethunger")) { if (whisperSender != tokenData.BroadcastUser && whisperSender != tokenData.ChatUser) continue; string[] msgData = whispers[1].Split(' '); if (msgData.Count() > 3) { Whisper(whisperSender, "Too many parameters. Syntax: !sethunger <stable ID>", group); continue; } int petToSet = -1; int amount = -1; if (int.TryParse(msgData[1], out petToSet) && int.TryParse(msgData[2], out amount)) { wolfcoins.classList[whisperSender].myPets.ElementAt(petToSet - 1).hunger = amount; Whisper(whisperSender, wolfcoins.classList[whisperSender].myPets.ElementAt(petToSet - 1).name + "'s energy set to " + amount + ".", group); } else { Whisper(whisperSender, "Ya dun fucked somethin' up.", group); } } else if (whisperMessage.StartsWith("!release")) { if (wolfcoins.Exists(wolfcoins.classList, whisperSender)) { if (wolfcoins.classList[whisperSender].myPets.Count > 0) { string[] msgData = whispers[1].Split(' '); if (msgData.Count() != 2) { Whisper(whisperSender, "Invalid number of parameters. Syntax: !release <stable ID>", group); continue; } int petToRelease = -1; if (int.TryParse(msgData[1], out petToRelease)) { if (petToRelease > wolfcoins.classList[whisperSender].myPets.Count || petToRelease < 1) { Whisper(whisperSender, "Invalid Stable ID given. Check !pets for each pet's stable ID!", group); continue; } string petName = wolfcoins.classList[whisperSender].myPets.ElementAt(petToRelease - 1).name; //wolfcoins.classList[whisperSender].toRelease = petToRelease; wolfcoins.classList[whisperSender].pendingPetRelease = true; wolfcoins.classList[whisperSender].toRelease = new Pet(); wolfcoins.classList[whisperSender].toRelease.stableID = wolfcoins.classList[whisperSender].myPets.ElementAt(petToRelease - 1).stableID; Whisper(whisperSender, "If you release " + petName + ", they will be gone forever. Are you sure you want to release them? (y/n)", group); } } else { Whisper(whisperSender, "You don't have a pet.", group); } } } else if (whisperMessage.StartsWith("!dismiss")) { if (wolfcoins.Exists(wolfcoins.classList, whisperSender)) { if (wolfcoins.classList[whisperSender].myPets.Count > 0) { string[] msgData = whispers[1].Split(' '); if (msgData.Count() != 2) { Whisper(whisperSender, "Invalid number of parameters. Syntax: !dismiss <stable ID>", group); continue; } int petToDismiss = -1; if (int.TryParse(msgData[1], out petToDismiss)) { if (petToDismiss > wolfcoins.classList[whisperSender].myPets.Count || petToDismiss < 1) { Whisper(whisperSender, "Invalid Stable ID given. Check !pets for each pet's stable ID!", group); continue; } if (wolfcoins.classList[whisperSender].myPets.ElementAt(petToDismiss - 1).isActive) { wolfcoins.classList[whisperSender].myPets.ElementAt(petToDismiss - 1).isActive = false; Whisper(whisperSender, "You dismissed " + wolfcoins.classList[whisperSender].myPets.ElementAt(petToDismiss - 1).name + ".", group); wolfcoins.SaveClassData(); } else { Whisper(whisperSender, "That pet is not currently summoned.", group); continue; } } } else { Whisper(whisperSender, "You don't have a pet.", group); } } } else if (whisperMessage.StartsWith("!summon")) { if (wolfcoins.Exists(wolfcoins.classList, whisperSender)) { if (wolfcoins.classList[whisperSender].myPets.Count > 0) { string[] msgData = whispers[1].Split(' '); if (msgData.Count() != 2) { Whisper(whisperSender, "Invalid number of parameters. Syntax: !summon <stable ID>", group); continue; } int petToSummon = -1; int currentlyActivePet = -1; if (int.TryParse(msgData[1], out petToSummon)) { if (petToSummon > wolfcoins.classList[whisperSender].myPets.Count || petToSummon < 1) { Whisper(whisperSender, "Invalid Stable ID given. Check !pets for each pet's stable ID!", group); continue; } foreach (var pet in wolfcoins.classList[whisperSender].myPets) { if (pet.isActive) { currentlyActivePet = pet.stableID; } } if (currentlyActivePet > wolfcoins.classList[whisperSender].myPets.Count) { Whisper(whisperSender, "Sorry, your stableID is corrupt. Lobos is working on this issue :(", group); continue; } if (!wolfcoins.classList[whisperSender].myPets.ElementAt(petToSummon - 1).isActive) { wolfcoins.classList[whisperSender].myPets.ElementAt(petToSummon - 1).isActive = true; Whisper(whisperSender, "You summoned " + wolfcoins.classList[whisperSender].myPets.ElementAt(petToSummon - 1).name + ".", group); if (currentlyActivePet != -1) { wolfcoins.classList[whisperSender].myPets.ElementAt(currentlyActivePet - 1).isActive = false; Whisper(whisperSender, wolfcoins.classList[whisperSender].myPets.ElementAt(currentlyActivePet - 1).name + " was dismissed.", group); } } else { Whisper(whisperSender, wolfcoins.classList[whisperSender].myPets.ElementAt(petToSummon - 1).name + " is already summoned!", group); } } } else { Whisper(whisperSender, "You don't have a pet.", group); } } } else if (whisperMessage.StartsWith("!pet")) { if (wolfcoins.Exists(wolfcoins.classList, whisperSender)) { if (wolfcoins.classList[whisperSender].myPets.Count > 0) { string[] msgData = whispers[1].Split(' '); if (msgData.Count() != 2) { Whisper(whisperSender, "Invalid number of parameters. Syntax: !pet <stable ID>", group); continue; } int petToSend = -1; if (int.TryParse(msgData[1], out petToSend)) { if (petToSend > wolfcoins.classList[whisperSender].myPets.Count || petToSend < 1) { Whisper(whisperSender, "Invalid Stable ID given. Check !pets for each pet's stable ID!", group); continue; } WhisperPet(whisperSender, wolfcoins.classList[whisperSender].myPets.ElementAt(petToSend - 1), group, HIGH_DETAIL); } } else { Whisper(whisperSender, "You don't have any pets.", group); } } } else if (whisperMessage.StartsWith("!rename")) { if (wolfcoins.Exists(wolfcoins.classList, whisperSender)) { if (wolfcoins.classList[whisperSender].myPets.Count > 0) { string[] msgData = whispers[1].Split(' '); if (msgData.Count() != 3) { Whisper(whisperSender, "Invalid number of parameters. Note: names cannot contain spaces.", group); continue; } else if (msgData.Count() == 3) { int petToRename = -1; if (int.TryParse(msgData[1], out petToRename)) { if (petToRename > (wolfcoins.classList[whisperSender].myPets.Count) || petToRename < 1) { Whisper(whisperSender, "Sorry, the Stable ID given was invalid. Please try again.", group); continue; } string newName = msgData[2]; if (newName.Length > 16) { Whisper(whisperSender, "Name can only be 16 characters max.", group); continue; } string prevName = wolfcoins.classList[whisperSender].myPets.ElementAt(petToRename - 1).name; wolfcoins.classList[whisperSender].myPets.ElementAt(petToRename - 1).name = newName; Whisper(whisperSender, prevName + " was renamed to " + newName + "!", group); } } else { Whisper(whisperSender, "Sorry, the data you provided didn't work. Syntax: !rename <stable id> <new name>", group); } } else { Whisper(whisperSender, "You don't have any pets to rename. :(", group); } } } else if (whisperMessage.StartsWith("!start")) { if (wolfcoins.Exists(wolfcoins.classList, whisperSender)) { int partyID = wolfcoins.classList[whisperSender].groupID; if (parties.Count() > 0 && partyID != -1 && parties.ContainsKey(partyID)) { if (parties[partyID].status == PARTY_READY) { if (!(parties[partyID].partyLeader == whisperSender)) { Whisper(whisperSender, "You are not the party leader!", group); continue; } string[] msgData = whispers[1].Split(' '); int dungeonID = -1; if (msgData.Count() > 1) { int.TryParse(msgData[1], out dungeonID); } else if (wolfcoins.classList[whisperSender].groupFinderDungeon != -1) { dungeonID = wolfcoins.classList[whisperSender].groupFinderDungeon; wolfcoins.classList[whisperSender].groupFinderDungeon = -1; } //else if (wolfcoins.classList[whisperSender].queueDungeons.Count > 0) //{ // dungeonID = wolfcoins.classList[whisperSender].queueDungeons.ElementAt(0); //} else { Whisper(whisperSender, "Invalid Dungeon ID provided.", group); continue; } if (dungeonList.Count() >= dungeonID && dungeonID > 0) { string dungeonPath = "content/dungeons/" + dungeonList[dungeonID]; IEnumerable<string> fileText = System.IO.File.ReadLines(dungeonPath, UTF8Encoding.Default); string[] type = fileText.ElementAt(0).Split('='); if (type[1] == "Dungeon" && parties[partyID].NumMembers() > 3) { Whisper(whisperSender, "You can't have more than 3 party members for a Dungeon.", group); continue; } if (wolfcoins.classList[whisperSender].queueDungeons.Count > 0) { foreach (var member in parties[partyID].members) { wolfcoins.classList[member.name].queueDungeons = new List<int>(); } } Dungeon newDungeon = new Dungeon(dungeonPath, channel, itemDatabase); bool outOfLevelRange = false; foreach (var member in parties[partyID].members) { member.level = wolfcoins.determineLevel(member.name); //if (member.level < newDungeon.minLevel) //{ // Whisper(parties[partyID], member.name + " is not high enough level for the requested dungeon. (Min Level: " + newDungeon.minLevel + ")", group); // outOfLevelRange = true; //} } int minLevel = 3; List<string> brokeBitches = new List<string>(); bool enoughMoney = true; foreach (var member in parties[partyID].members) { if (wolfcoins.Exists(wolfcoins.coinList, member.name)) { if (wolfcoins.coinList[member.name] < (baseDungeonCost + ((member.level - minLevel) * 10))) { brokeBitches.Add(member.name); enoughMoney = false; } } } if (!enoughMoney) { string names = ""; foreach (var bitch in brokeBitches) { names += bitch + " "; } Whisper(parties[partyID], "The following party members do not have enough money to run " + newDungeon.dungeonName + ": " + names, group); } if (!outOfLevelRange && enoughMoney) { foreach (var member in parties[partyID].members) { wolfcoins.coinList[member.name] -= (baseDungeonCost + ((member.level - minLevel) * 10)); } Whisper(parties[partyID], "Successfully initiated " + newDungeon.dungeonName + "! Wolfcoins deducted.", group); string memberInfo = ""; foreach (var member in parties[partyID].members) { memberInfo += member.name + " (Level " + member.level + " " + member.className + ") "; } Whisper(parties[partyID], "Your party consists of: " + memberInfo, group); parties[partyID].status = PARTY_STARTED; parties[partyID].myDungeon = newDungeon; parties[partyID] = parties[partyID].myDungeon.RunDungeon(parties[partyID], ref group); } } } } } } else if (whisperMessage == "y") { if (wolfcoins.Exists(wolfcoins.classList, whisperSender)) { if (wolfcoins.classList[whisperSender].pendingPetRelease) { int toRelease = wolfcoins.classList[whisperSender].toRelease.stableID; if (toRelease > wolfcoins.classList[whisperSender].myPets.Count) { Whisper(whisperSender, "Stable ID mismatch. Try !release again.", group); continue; } string petName = wolfcoins.classList[whisperSender].myPets.ElementAt(toRelease - 1).name; if (wolfcoins.classList[whisperSender].releasePet(toRelease)) { Whisper(whisperSender, "You released " + petName + ". Goodbye, " + petName + "!", group); wolfcoins.SaveClassData(); } else { Whisper(whisperSender, "Something went wrong. " + petName + " is still with you!", group); } wolfcoins.classList[whisperSender].pendingPetRelease = false; wolfcoins.classList[whisperSender].toRelease = new Pet(); } if (wolfcoins.classList[whisperSender].pendingInvite) { int partyID = wolfcoins.classList[whisperSender].groupID; wolfcoins.classList[whisperSender].pendingInvite = false; string partyLeader = parties[partyID].partyLeader; int partySize = parties[partyID].NumMembers(); string myClass = wolfcoins.classList[whisperSender].className; int myLevel = wolfcoins.determineLevel(wolfcoins.xpList[whisperSender]); string myMembers = ""; foreach (var member in parties[partyID].members) { myMembers += member.name + " "; } Whisper(whisperSender, "You successfully joined a party with the following members: " + myMembers, group); foreach (var member in parties[partyID].members) { if (member.name == whisperSender) continue; if (member.pendingInvite) continue; Whisper(member.name, whisperSender + ", Level " + myLevel + " " + myClass + " has joined your party! (" + partySize + "/" + DUNGEON_MAX + ")", group); } if (partySize == DUNGEON_MAX) { Whisper(partyLeader, "Your party is now full.", group); parties[partyID].status = PARTY_FULL; } if (partySize == 3) { Whisper(partyLeader, "You've reached 3 party members! You're ready to dungeon!", group); parties[partyID].status = PARTY_READY; } Console.WriteLine(DateTime.Now.ToString() + ": " + whisperSender + " added to Group " + partyID); string temp = "Updated Member List: "; foreach (var member in parties[partyID].members) { temp += member.name + " "; } Console.WriteLine(DateTime.Now.ToString() + ": " + temp); } } } else if (whisperMessage == "!unready") { if (wolfcoins.Exists(wolfcoins.classList, whisperSender)) { CharClass myClass = wolfcoins.classList[whisperSender]; if (myClass.isPartyLeader) { if (parties[myClass.groupID].status == PARTY_READY && parties[myClass.groupID].members.Count <= DUNGEON_MAX) { parties[myClass.groupID].status = PARTY_FORMING; Whisper(parties[myClass.groupID], "Party 'Ready' status has been revoked.", group); } } } } else if (whisperMessage == "!ready") { if (wolfcoins.Exists(wolfcoins.classList, whisperSender)) { CharClass myClass = wolfcoins.classList[whisperSender]; if (myClass.isPartyLeader) { if (parties.ContainsKey(myClass.groupID) && parties[myClass.groupID].status == PARTY_FORMING) { parties[myClass.groupID].status = PARTY_READY; Whisper(parties[myClass.groupID], "Party set to 'Ready'. Be careful adventuring without a full party!", group); } } } } else if (whisperMessage == "n") { if (wolfcoins.Exists(wolfcoins.classList, whisperSender)) { if (wolfcoins.classList[whisperSender].pendingPetRelease) { string petName = wolfcoins.classList[whisperSender].toRelease.name; wolfcoins.classList[whisperSender].pendingPetRelease = false; wolfcoins.classList[whisperSender].toRelease = new Pet(); Whisper(whisperSender, "You decided to keep " + petName + ".", group); } if (wolfcoins.classList[whisperSender].pendingInvite) { wolfcoins.classList[whisperSender].pendingInvite = false; string partyLeader = parties[wolfcoins.classList[whisperSender].groupID].partyLeader; parties[wolfcoins.classList[whisperSender].groupID].RemoveMember(whisperSender); wolfcoins.classList[whisperSender].groupID = -1; Whisper(whisperSender, "You declined " + partyLeader + "'s invite.", group); Whisper(partyLeader, whisperSender + " has declined your party invite.", group); wolfcoins.classList[partyLeader].numInvitesSent--; } } } else if (whisperMessage.StartsWith("!kick")) { if (wolfcoins.Exists(wolfcoins.classList, whisperSender) && wolfcoins.classList[whisperSender].isPartyLeader) { if (wolfcoins.classList[whisperSender].groupID != -1) { if (parties[wolfcoins.classList[whisperSender].groupID].status == PARTY_STARTED) { Whisper(whisperSender, "You can't kick a party member in the middle of a dungoen!", group); continue; } if (whispers[1] != null) { string[] msgData = whispers[1].Split(' '); if (msgData.Count() > 1) { string toKick = msgData[1]; if (whisperSender == toKick) { Whisper(whisperSender, "You can't kick yourself from a group! Do !leaveparty instead.", group); continue; } toKick = toKick.ToLower(); if (wolfcoins.classList.Keys.Contains(toKick.ToLower())) { if (wolfcoins.classList[whisperSender].isPartyLeader) { int myID = wolfcoins.classList[whisperSender].groupID; for (int i = 0; i < parties[myID].members.Count(); i++) { if (parties[myID].members.ElementAt(i).name == toKick) { parties[myID].RemoveMember(toKick); wolfcoins.classList[toKick].groupID = -1; wolfcoins.classList[toKick].pendingInvite = false; wolfcoins.classList[toKick].numInvitesSent = 0; wolfcoins.classList[whisperSender].numInvitesSent--; Whisper(toKick, "You were removed from " + whisperSender + "'s party.", group); Whisper(parties[myID], toKick + " was removed from the party.", group); } } } else { Whisper(whisperSender, "You are not the party leader.", group); } } else { Whisper(whisperSender, "Couldn't find that party member to remove.", group); } } } } } } else if (whisperMessage.StartsWith("!add")) { if (wolfcoins.Exists(wolfcoins.classList, whisperSender) && wolfcoins.classList[whisperSender].isPartyLeader) { if (wolfcoins.classList[whisperSender].groupID != -1) { if (parties[wolfcoins.classList[whisperSender].groupID].status == PARTY_STARTED) continue; if (wolfcoins.classList[whisperSender].usedGroupFinder && parties[wolfcoins.classList[whisperSender].groupID].NumMembers() == 3) { Whisper(whisperSender, "You can't have more than 3 party members for a Group Finder dungeon.", group); continue; } if (whispers[1] != null) { string[] msgData = whispers[1].Split(' '); if (msgData.Count() > 1) { string invitee = msgData[1]; if (whisperSender == invitee) { Whisper(whisperSender, "You can't invite yourself to a group!", group); continue; } if (wolfcoins.Exists(wolfcoins.classList, invitee) && wolfcoins.classList[invitee].queueDungeons.Count > 0) { Whisper(whisperSender, invitee + " is currently queued for Group Finder and cannot be added to the group.", group); Whisper(invitee, whisperSender + " tried to invite you to a group, but you are queued in the Group Finder. Type '!leavequeue' to leave the queue.", group); continue; } invitee = invitee.ToLower(); if (wolfcoins.classList.Keys.Contains(invitee.ToLower())) { int myID = wolfcoins.classList[whisperSender].groupID; if (wolfcoins.classList[invitee].classType != -1 && wolfcoins.classList[invitee].groupID == -1 && !wolfcoins.classList[invitee].pendingInvite && wolfcoins.classList[whisperSender].numInvitesSent < DUNGEON_MAX && parties.ContainsKey(myID)) { if (parties[myID].status != PARTY_FORMING && parties[myID].status != PARTY_READY) { continue; } wolfcoins.classList[whisperSender].numInvitesSent++; wolfcoins.classList[invitee].pendingInvite = true; wolfcoins.classList[invitee].groupID = myID; wolfcoins.classList[invitee].ClearQueue(); string myClass = wolfcoins.classList[whisperSender].className; int myLevel = wolfcoins.classList[whisperSender].level; parties[myID].AddMember(wolfcoins.classList[invitee]); string msg = whisperSender + ", Level " + myLevel + " " + myClass + ", has invited you to join a party. Accept? (y/n)"; Whisper(whisperSender, "You invited " + invitee + " to a group.", group); Whisper(invitee, msg, group); } else if (wolfcoins.classList[whisperSender].numInvitesSent >= DUNGEON_MAX) { Whisper(whisperSender, "You have the max number of invites already pending.", group); } else if (wolfcoins.classList[invitee].groupID != -1) { Whisper(whisperSender, invitee + " is already in a group.", group); Whisper(invitee, whisperSender + " tried to invite you to a group, but you are already in one! Type '!leaveparty' to abandon your current group.", group); } } else { if (wolfcoins.Exists(wolfcoins.xpList, invitee)) { int level = wolfcoins.determineLevel(invitee); if (level < 3) { //Whisper(whisperSender, invitee + " is not high enough level. (" + level + ")", group); } else { Whisper(whisperSender, invitee + " is high enough level, but has not picked a class!", group); } } } } } } } } else if (whisperMessage.StartsWith("!promote")) { if (wolfcoins.Exists(wolfcoins.classList, whisperSender)) { int partyID = wolfcoins.classList[whisperSender].groupID; if (partyID == -1) { continue; } if (!wolfcoins.classList[whisperSender].isPartyLeader) { Whisper(whisperSender, "You must be the party leader to promote.", group); continue; } if (whispers[1] != null) { string[] msgData = whispers[1].Split(' '); if (msgData.Count() > 1 && msgData.Count() <= 3) { string newLeader = msgData[1].ToLower(); bool newLeaderCreated = false; foreach (var member in parties[partyID].members) { if (newLeaderCreated) continue; if (member.name == whisperSender) member.isPartyLeader = false; if (member.name == newLeader) { wolfcoins.classList[whisperSender].isPartyLeader = false; parties[partyID].partyLeader = newLeader; wolfcoins.classList[newLeader].isPartyLeader = true; member.isPartyLeader = true; newLeaderCreated = true; } } if (newLeaderCreated) { foreach (var member in parties[partyID].members) { if (member.name != newLeader && member.name != whisperSender) { Whisper(member.name, whisperSender + " has promoted " + newLeader + " to Party Leader.", group); } } Whisper(newLeader, whisperSender + " has promoted you to Party Leader.", group); Whisper(whisperSender, "You have promoted " + newLeader + " to Party Leader.", group); } else { Whisper(whisperSender, "Party member '" + newLeader + "' not found. You are still party leader.", group); } } } } } else if (whisperMessage == "!leaveparty") { if (parties.Count() > 0 && wolfcoins.Exists(wolfcoins.classList, whisperSender)) { int myID = wolfcoins.classList[whisperSender].groupID; if (myID != -1 && parties[myID].status == PARTY_STARTED) { Whisper(whisperSender, "You can't leave your party while a dungeon is in progress!", group); continue; } if (myID != -1 && !wolfcoins.classList[whisperSender].pendingInvite) { if (parties.Count() > 0 && parties.ContainsKey(myID)) { if (wolfcoins.classList[whisperSender].isPartyLeader) { wolfcoins.classList[whisperSender].groupID = -1; wolfcoins.classList[whisperSender].numInvitesSent = 0; wolfcoins.classList[whisperSender].isPartyLeader = false; wolfcoins.classList[whisperSender].ClearQueue(); parties[myID].RemoveMember(whisperSender); Console.WriteLine("Party Leader " + whisperSender + " left group #" + myID); string myMembers = ""; foreach (var member in parties[myID].members) { myMembers += member.name + " "; } Console.WriteLine(DateTime.Now.ToString() + ": Remaining members: " + myMembers); Whisper(parties[myID], "The party leader (" + whisperSender + ") has left. Your party has been disbanded.", group); for (int i = 0; i < parties[myID].members.Count(); i++) { string dude = parties[myID].members.ElementAt(i).name; wolfcoins.classList[dude].groupID = -1; wolfcoins.classList[dude].pendingInvite = false; wolfcoins.classList[dude].numInvitesSent = 0; wolfcoins.classList[dude].ClearQueue(); } parties.Remove(myID); Whisper(whisperSender, "Your party has been disbanded.", group); } else if (parties.ContainsKey(myID) && (parties[myID].RemoveMember(whisperSender))) { if (parties[myID].status == PARTY_FORMING) { string partyleader = parties[myID].partyLeader; wolfcoins.classList[partyleader].numInvitesSent--; } else if (parties[myID].status == PARTY_FULL) { string partyleader = parties[myID].partyLeader; parties[myID].status = PARTY_FORMING; wolfcoins.classList[partyleader].numInvitesSent--; } Whisper(parties[myID], whisperSender + " has left the party.", group); Whisper(whisperSender, "You left the party.", group); wolfcoins.classList[whisperSender].groupID = -1; wolfcoins.classList[whisperSender].ClearQueue(); Console.WriteLine(DateTime.Now.ToString() + ": " + whisperSender + " left group with ID " + myID); string myMembers = ""; foreach (var member in parties[myID].members) { myMembers += member.name + " "; } Console.WriteLine(DateTime.Now.ToString() + ": Remaining Members: " + myMembers); } } } } } else if (whisperMessage == "!daily") { if (wolfcoins.Exists(wolfcoins.classList, whisperSender)) { double minutes = (DateTime.Now - wolfcoins.classList[whisperSender].lastDailyGroupFinder).TotalMinutes; double totalHours = (DateTime.Now - wolfcoins.classList[whisperSender].lastDailyGroupFinder).TotalHours; double totalDays = (DateTime.Now - wolfcoins.classList[whisperSender].lastDailyGroupFinder).TotalDays; if (totalDays >= 1) { Whisper(whisperSender, "You are eligible for daily Group Finder rewards! Go queue up!", group); continue; } else { double minutesLeft = Math.Truncate(60 - (minutes % 60)); double hoursLeft = Math.Truncate(24 - (totalHours)); Whisper(whisperSender, "Your daily Group Finder reward resets in " + hoursLeft + " hours and " + minutesLeft + " minutes.", group); } } } else if (whisperMessage.StartsWith("!queue")) { if (wolfcoins.Exists(wolfcoins.classList, whisperSender) && wolfcoins.classList[whisperSender].name != "NAMELESS ONE") { if (whisperMessage == "!queuetime") { if (wolfcoins.classList[whisperSender].queueDungeons.Count == 0) continue; string myQueuedDungeons = "You are queued for the following dungeons: "; bool firstAdded = false; foreach (var dung in wolfcoins.classList[whisperSender].queueDungeons) { if (!firstAdded) { firstAdded = true; } else { myQueuedDungeons += ","; } myQueuedDungeons += dung; } double timeSpan = ((DateTime.Now - wolfcoins.classList[whisperSender].queueTime)).TotalSeconds; double seconds = timeSpan % 60; seconds = Math.Truncate(seconds); double minutes = ((DateTime.Now - wolfcoins.classList[whisperSender].queueTime)).TotalMinutes % 60; minutes = Math.Truncate(minutes); if (minutes >= 60) minutes = minutes % 60; double hours = ((DateTime.Now - wolfcoins.classList[whisperSender].queueTime)).TotalHours; string timeMessage = "You've been waiting in the Group Finder queue for "; string lastFormed = "The last group was formed "; hours = Math.Truncate(hours); if (hours > 0) timeMessage += hours + " hours, "; if (minutes > 0) timeMessage += minutes + " minutes, and "; timeMessage += seconds + " seconds."; timeSpan = ((DateTime.Now - groupFinder.lastFormed).TotalSeconds); seconds = timeSpan % 60; seconds = Math.Truncate(seconds); minutes = timeSpan / 60; minutes = Math.Truncate(minutes); hours = minutes / 60; hours = Math.Truncate(hours); if (minutes >= 60) minutes = minutes % 60; if (hours > 0) lastFormed += hours + " hours, "; if (minutes > 0) lastFormed += minutes + " minutes, and "; lastFormed += seconds + " seconds ago."; Whisper(whisperSender, myQueuedDungeons, group); Whisper(whisperSender, timeMessage, group); Whisper(whisperSender, lastFormed, group); continue; } if (whisperMessage == "!queuestatus" && (whisperSender == tokenData.BroadcastUser || whisperSender == tokenData.ChatUser)) { if (groupFinder.queue.Count == 0) { Whisper(whisperSender, "No players in queue.", group); } Whisper(whisperSender, groupFinder.queue.Count + " players in queue.", group); Dictionary<int, int> queueData = new Dictionary<int, int>(); foreach (var player in groupFinder.queue) { foreach (var dungeonID in player.queueDungeons) { if (!queueData.ContainsKey(dungeonID)) { queueData.Add(dungeonID, 1); } else { queueData[dungeonID]++; } } } foreach (var dataPoint in queueData) { Whisper(whisperSender, "Dungeon ID <" + dataPoint.Key + ">: " + dataPoint.Value + " players", group); } continue; } if (wolfcoins.classList[whisperSender].queueDungeons.Count > 0) { Whisper(whisperSender, "You are already queued in the Group Finder! Type !queuetime for more information.", group); continue; } if (!wolfcoins.classList[whisperSender].pendingInvite && wolfcoins.classList[whisperSender].groupID == -1) { string[] msgData = whispers[1].Split(' '); string[] tempDungeonData; bool didRequest = false; if (msgData.Count() > 1) { tempDungeonData = msgData[1].Split(','); didRequest = true; } else { tempDungeonData = GetEligibleDungeons(whisperSender, wolfcoins, dungeonList).Split(','); } List<int> requestedDungeons = new List<int>(); //string[] tempDungeonData = msgData[1].Split(','); string errorMessage = "Unable to join queue. Reason(s): "; bool eligible = true; for (int i = 0; i < tempDungeonData.Count(); i++) { int tempInt = -1; int.TryParse(tempDungeonData[i], out tempInt); int eligibility = DetermineEligibility(whisperSender, tempInt, dungeonList, baseDungeonCost, wolfcoins); switch (eligibility) { case 0: // player not high enough level { eligible = false; errorMessage += "Not appropriate level. (ID: " + tempInt + ") "; } break; case -1: // invalid dungeon id { eligible = false; errorMessage += "Invalid Dungeon ID provided. (ID: " + tempInt + ") "; } break; case -2: // not enough money { eligible = false; errorMessage += "You don't have enough money!"; } break; case 1: { requestedDungeons.Add(tempInt); } break; default: break; } if (eligibility == -2) break; //if (tempInt != -1) // requestedDungeons.Add(tempInt); } if (!eligible) { Whisper(whisperSender, errorMessage, group); continue; } wolfcoins.classList[whisperSender].queuePriority = groupFinder.priority; groupFinder.priority++; wolfcoins.classList[whisperSender].usedGroupFinder = true; wolfcoins.classList[whisperSender].queueDungeons = requestedDungeons; Party myParty = groupFinder.Add(wolfcoins.classList[whisperSender]); if (myParty.members.Count != 3) { wolfcoins.classList[whisperSender].queueTime = DateTime.Now; Whisper(whisperSender, "You have been placed in the Group Finder queue.", group); continue; } myParty.members.ElementAt(0).isPartyLeader = true; myParty.partyLeader = myParty.members.ElementAt(0).name; myParty.status = PARTY_FULL; myParty.members.ElementAt(0).numInvitesSent = 3; myParty.myID = maxPartyID; myParty.usedDungeonFinder = true; int lowestNumOfDungeons = myParty.members.ElementAt(0).queueDungeons.Count; int pickiestMember = 0; int count = 0; // Pick the party member with the least available dungeons (to narrow down options) foreach (var member in myParty.members) { if (member.name == myParty.partyLeader) continue; count++; if (member.queueDungeons.Count < lowestNumOfDungeons) { pickiestMember = count; lowestNumOfDungeons = member.queueDungeons.Count; } } Random RNG = new Random(); int numAvailableDungeons = myParty.members.ElementAt(pickiestMember).queueDungeons.Count(); //choose a random dungeon out of the available options int randDungeon = RNG.Next(0, (numAvailableDungeons - 1)); // set the id based on that random dungeon int dungeonID = (myParty.members.ElementAt(pickiestMember).queueDungeons.ElementAt(randDungeon)) - 1; dungeonID++; myParty.members.ElementAt(0).groupFinderDungeon = dungeonID; string dungeonName = GetDungeonName(dungeonID, dungeonList); string members = "Group Finder group created for " + dungeonName + ": "; foreach (var member in myParty.members) { member.groupID = maxPartyID; member.usedGroupFinder = true; members += member.name + ", " + member.className + "; "; string otherMembers = ""; foreach (var player in myParty.members) { if (player.name == member.name) continue; otherMembers += player.name + " (" + player.className + ") "; } Whisper(member.name, "You've been matched for " + dungeonName + " with: " + otherMembers + ".", group); if (member.isPartyLeader) Whisper(member.name, "You are the party leader. Whisper me '!start' to begin!", group); } parties.Add(maxPartyID, myParty); Console.WriteLine(DateTime.Now.ToString() + ": " + members); maxPartyID++; } else if (wolfcoins.classList[whisperSender].isPartyLeader) { string reason = ""; if (parties.ContainsKey(wolfcoins.classList[whisperSender].groupID)) { switch (parties[wolfcoins.classList[whisperSender].groupID].status) { case PARTY_FORMING: { reason = "Party is currently forming. Add members with '!add <username>'"; } break; case PARTY_READY: { reason = "Party is filled and ready to adventure! Type '!start' to begin!"; } break; case PARTY_STARTED: { reason = "Your party is currently on an adventure!"; } break; case PARTY_COMPLETE: { reason = "Your party just finished an adventure!"; } break; default: { reason = "I have no idea the status of your party."; } break; } } Whisper(whisperSender, "You already have a party created! " + reason, group); } else { Whisper(whisperSender, "You currently have an outstanding invite to another party. Couldn't create new party!", group); } } } else if (whisperMessage == "!classes") { if (wolfcoins.classList != null) { double numClasses = 0; double numWarriors = 0; double numMages = 0; double numRogues = 0; double numRangers = 0; double numClerics = 0; foreach (var member in wolfcoins.classList) { numClasses++; switch (member.Value.classType) { case CharClass.WARRIOR: { numWarriors++; } break; case CharClass.MAGE: { numMages++; } break; case CharClass.ROGUE: { numRogues++; } break; case CharClass.RANGER: { numRangers++; } break; case CharClass.CLERIC: { numClerics++; } break; default: break; } } double percentWarriors = (numWarriors / numClasses) * 100; percentWarriors = Math.Round(percentWarriors, 1); double percentMages = (numMages / numClasses) * 100; percentMages = Math.Round(percentMages, 1); double percentRogues = (numRogues / numClasses) * 100; percentRogues = Math.Round(percentRogues, 1); double percentRangers = (numRangers / numClasses) * 100; percentRangers = Math.Round(percentRangers, 1); double percentClerics = (numClerics / numClasses) * 100; percentClerics = Math.Round(percentClerics, 1); Whisper(whisperSender, "Class distribution for the Wolfpack RPG: ", group); Whisper(whisperSender, "Warriors: " + percentWarriors + "%", group); Whisper(whisperSender, "Mages: " + percentMages + "%", group); Whisper(whisperSender, "Rogues: " + percentRogues + "%", group); Whisper(whisperSender, "Rangers: " + percentRangers + "%", group); Whisper(whisperSender, "Clerics " + percentClerics + "%", group); } } else if (whisperMessage == "!leavequeue") { if (wolfcoins.Exists(wolfcoins.classList, whisperSender)) { if (wolfcoins.classList[whisperSender].queueDungeons.Count > 0) { groupFinder.RemoveMember(whisperSender); wolfcoins.classList[whisperSender].ClearQueue(); Whisper(whisperSender, "You were removed from the Group Finder.", group); } } } else if (whisperMessage == "!createparty") { if (wolfcoins.Exists(wolfcoins.classList, whisperSender)) { if (!wolfcoins.classList[whisperSender].pendingInvite && wolfcoins.classList[whisperSender].groupID == -1) { if (wolfcoins.classList[whisperSender].queueDungeons.Count > 0) { Whisper(whisperSender, "Can't create a party while queued with the Group Finder. Message me '!leavequeue' to exit.", group); continue; } wolfcoins.classList[whisperSender].isPartyLeader = true; wolfcoins.classList[whisperSender].numInvitesSent = 1; Wolfcoins.Party myParty = new Wolfcoins.Party(); myParty.status = PARTY_FORMING; myParty.partyLeader = whisperSender; int myLevel = wolfcoins.determineLevel(whisperSender); wolfcoins.classList[whisperSender].groupID = maxPartyID; myParty.AddMember(wolfcoins.classList[whisperSender]); myParty.myID = maxPartyID; parties.Add(maxPartyID, myParty); Whisper(whisperSender, "Party created! Use '!add <username>' to invite party members.", group); Console.WriteLine(DateTime.Now.ToString() + ": Party created: "); Console.WriteLine(DateTime.Now.ToString() + ": ID: " + maxPartyID); Console.WriteLine(DateTime.Now.ToString() + ": Total number of parties: " + parties.Count()); maxPartyID++; } else if (wolfcoins.classList[whisperSender].isPartyLeader) { string reason = ""; if (parties.ContainsKey(wolfcoins.classList[whisperSender].groupID)) { switch (parties[wolfcoins.classList[whisperSender].groupID].status) { case PARTY_FORMING: { reason = "Party is currently forming. Add members with '!add <username>'"; } break; case PARTY_READY: { reason = "Party is filled and ready to adventure! Type '!start' to begin!"; } break; case PARTY_STARTED: { reason = "Your party is currently on an adventure!"; } break; case PARTY_COMPLETE: { reason = "Your party just finished an adventure!"; } break; default: { reason = "I have no idea the status of your party."; } break; } } Whisper(whisperSender, "You already have a party created! " + reason, group); } else { Whisper(whisperSender, "You currently have an outstanding invite to another party. Couldn't create new party!", group); } } } else if (whisperMessage.Equals("nevermind", StringComparison.InvariantCultureIgnoreCase)) { if (wolfcoins.Exists(wolfcoins.classList, whisperSender)) { if (wolfcoins.classList[whisperSender].classType >= 10) { int oldClass = wolfcoins.classList[whisperSender].classType / 10; wolfcoins.classList[whisperSender].classType = oldClass; Whisper(whisperSender, "Respec cancelled. No Wolfcoins deducted from your balance.", group); } } } else if (whisperMessage == "!partydata") { if (parties.Count() > 0) { if (wolfcoins.Exists(wolfcoins.classList, whisperSender)) { int myID = wolfcoins.classList[whisperSender].groupID; if (myID != -1) { string partyMembers = ""; if (parties.ContainsKey(myID)) { for (int i = 0; i < parties[myID].members.Count(); i++) { partyMembers += parties[myID].members.ElementAt(i).name + " "; } string status = ""; switch (parties[myID].status) { case PARTY_FORMING: { status = "PARTY_FORMING"; } break; case PARTY_READY: { status = "PARTY_READY"; } break; case PARTY_STARTED: { status = "PARTY_STARTED"; } break; case PARTY_COMPLETE: { status = "PARTY_COMPLETE"; } break; default: { status = "UNKNOWN_STATUS"; } break; } irc.sendChatMessage(whisperSender + " requested his Party Data. Group ID: " + wolfcoins.classList[whisperSender].groupID + "; Members: " + partyMembers + "; Status: " + status); } } } } } else if (whisperMessage.StartsWith("!clearitems")) { if (whisperSender != tokenData.BroadcastUser && whisperSender != tokenData.ChatUser) continue; string[] whisperMSG = whispers[1].Split(); if (whisperMSG.Length > 1) { string target = whisperMSG[1]; if (wolfcoins.Exists(wolfcoins.classList, target)) { wolfcoins.classList[target].totalItemCount = 0; wolfcoins.classList[target].myItems = new List<Item>(); wolfcoins.SaveClassData(); Whisper(whisperSender, "Cleared " + target + "'s item list.", group); } } } else if (whisperMessage == "!fixstats") { if (whisperSender != tokenData.BroadcastUser && whisperSender != tokenData.ChatUser) continue; if (wolfcoins.classList != null) { foreach (var user in wolfcoins.classList) { if (user.Value.name == "NAMELESS ONE") continue; int classType = wolfcoins.classList[user.Value.name].classType; CharClass defaultClass; switch (classType) { case CharClass.WARRIOR: { defaultClass = new Warrior(); } break; case CharClass.MAGE: { defaultClass = new Mage(); } break; case CharClass.ROGUE: { defaultClass = new Rogue(); } break; case CharClass.RANGER: { defaultClass = new Ranger(); } break; case CharClass.CLERIC: { defaultClass = new Cleric(); } break; default: { defaultClass = new CharClass(); } break; } wolfcoins.classList[user.Value.name].coinBonus = defaultClass.coinBonus; wolfcoins.classList[user.Value.name].xpBonus = defaultClass.xpBonus; wolfcoins.classList[user.Value.name].itemFind = defaultClass.itemFind; wolfcoins.classList[user.Value.name].successChance = defaultClass.successChance; wolfcoins.classList[user.Value.name].preventDeathBonus = defaultClass.preventDeathBonus; wolfcoins.classList[user.Value.name].itemEarned = -1; wolfcoins.classList[user.Value.name].ClearQueue(); } wolfcoins.SaveClassData(); Whisper(whisperSender, "Reset all user's stats to default.", group); } } else if (whisperMessage.StartsWith("!giveitem")) { if (whisperSender != tokenData.BroadcastUser && whisperSender != tokenData.ChatUser) continue; string[] whisperMSG = whispers[1].Split(); if (whisperMSG.Length > 2) { string temp = whisperMSG[2]; int id = -1; int.TryParse(temp, out id); if (id < 1 || id > itemDatabase.Count()) { Whisper(whisperSender, "Invalid ID was attempted to be given.", group); } string user = whisperMSG[1]; bool hasItem = false; if (wolfcoins.Exists(wolfcoins.classList, user)) { if (wolfcoins.classList[user].myItems.Count > 0) { foreach (var item in wolfcoins.classList[user].myItems) { if (item.itemID == id) { hasItem = true; Whisper(whisperSender, user + " already has " + itemDatabase[id - 1].itemName + ".", group); } } } if (!hasItem && itemDatabase.ContainsKey(id)) { GrantItem(id, wolfcoins, user, itemDatabase); wolfcoins.SaveClassData(); //if(wolfcoins.classList[user].totalItemCount != -1) //{ // wolfcoins.classList[user].totalItemCount++; //} //else //{ // wolfcoins.classList[user].totalItemCount = 1; //} //wolfcoins.classList[user].myItems.Add(itemDatabase[id]); Whisper(whisperSender, "Gave " + user + " a " + itemDatabase[id - 1].itemName + ".", group); } } } } // player requests to equip an item. make sure they actually *have* items // check if their item is equippable ('other' type items are not), and that it isn't already active // set it to true, then iterate through item list. if inventoryID does *not* match and it *IS* active, deactivate it else if (whisperMessage.StartsWith("!activate") || whisperMessage.StartsWith("activate") || whisperMessage.StartsWith("!equip") || whisperMessage.StartsWith("equip")) { string[] whisperMSG = whispers[1].Split(); if (whisperMSG.Length > 1) { string temp = whisperMSG[1]; int id = -1; int.TryParse(temp, out id); if (wolfcoins.Exists(wolfcoins.classList, whisperSender)) { if (wolfcoins.classList[whisperSender].myItems.Count > 0) { Item toActivate = wolfcoins.classList[whisperSender].GetItem(id); int itemPos = wolfcoins.classList[whisperSender].GetItemPos(id); if (toActivate.itemType == Item.TYPE_ARMOR || toActivate.itemType == Item.TYPE_WEAPON) { if (toActivate.isActive) { Whisper(whisperSender, toActivate.itemName + " is already equipped.", group); continue; } wolfcoins.classList[whisperSender].myItems.ElementAt(itemPos).isActive = true; foreach (var itm in wolfcoins.classList[whisperSender].myItems) { if (itm.inventoryID == id) continue; if (itm.itemType != toActivate.itemType) continue; if (itm.isActive) { itm.isActive = false; Whisper(whisperSender, "Unequipped " + itm.itemName + ".", group); } } Whisper(whisperSender, "Equipped " + toActivate.itemName + ".", group); } } else { Whisper(whisperSender, "You have no items.", group); } } } } // player requests to unequip an item. make sure they actually *have* items // check if their item is equippable ('other' type items are not), and that it isn't already inactive else if (whisperMessage.StartsWith("!deactivate") || whisperMessage.StartsWith("deactivate") || whisperMessage.StartsWith("!unequip") || whisperMessage.StartsWith("unequip")) { string[] whisperMSG = whispers[1].Split(); if (whisperMSG.Length > 1) { string temp = whisperMSG[1]; int id = -1; int.TryParse(temp, out id); if (wolfcoins.Exists(wolfcoins.classList, whisperSender) && id != -1) { if (wolfcoins.classList[whisperSender].myItems.Count > 0) { Item toDeactivate = wolfcoins.classList[whisperSender].GetItem(id); int itemPos = wolfcoins.classList[whisperSender].GetItemPos(id); if (toDeactivate.itemType == Item.TYPE_ARMOR || toDeactivate.itemType == Item.TYPE_WEAPON) { if (toDeactivate.isActive) { wolfcoins.classList[whisperSender].myItems.ElementAt(itemPos).isActive = false; Whisper(whisperSender, "Unequipped " + toDeactivate.itemName + ".", group); } } } else { Whisper(whisperSender, "You have no items.", group); } } } } else if (whisperMessage.StartsWith("!printinfo")) { if (whisperSender != tokenData.BroadcastUser && whisperSender != tokenData.ChatUser) break; // first[1] is the user to print info for if (whispers.Length >= 2 && whispers[1] != null) { string[] whisperMSG = whispers[1].Split(); string player = whisperMSG[1].ToString(); if (wolfcoins.Exists(wolfcoins.classList, player)) { // print out all the user's info int numItems = wolfcoins.classList[player].totalItemCount; Console.WriteLine("Name: " + player); Console.WriteLine("Level: " + wolfcoins.classList[player].level); Console.WriteLine("Prestige Level: " + wolfcoins.classList[player].prestige); Console.WriteLine("Class: " + wolfcoins.classList[player].className); Console.WriteLine("Dungeon success chance: " + wolfcoins.classList[player].GetTotalSuccessChance()); Console.WriteLine("Number of Items: " + numItems); Console.WriteLine(wolfcoins.classList[player].PrintItems()); } else { Console.WriteLine("Player name not found."); } } } else if (whisperMessage.StartsWith("!setxp")) { if (whisperSender != tokenData.BroadcastUser && whisperSender != tokenData.ChatUser) continue; string[] whisperMSG = whispers[1].Split(); if (whisperMSG.Length > 2) { if (int.TryParse(whisperMSG[2], out int value)) { int newXp = wolfcoins.SetXP(value, whisperMSG[1], group); if (newXp != -1) { Whisper(whisperSender, "Set " + whisperMSG[1] + "'s XP to " + newXp + ".", group); } else { Whisper(whisperSender, "Error updating XP amount.", group); } } else { Whisper(whisperSender, "Invalid data provided for !setxp command.", group); } } else { Whisper(whisperSender, "Not enough data provided for !setxp command.", group); } } else if (whisperMessage.StartsWith("!setprestige")) { if (whisperSender != tokenData.BroadcastUser && whisperSender != tokenData.ChatUser) continue; string[] whisperMSG = whispers[1].Split(); if (whisperMSG.Length > 2) { int value = -1; if (int.TryParse(whisperMSG[2], out value)) { if (value != -1 && wolfcoins.classList.ContainsKey(whisperMSG[1])) { wolfcoins.classList[whisperMSG[1].ToString()].prestige = value; Whisper(whisperSender, "Set " + whisperMSG[1] + "'s Prestige to " + value + ".", group); } else { Whisper(whisperSender, "Error updating Prestige Level.", group); } } else { Whisper(whisperSender, "Invalid data provided for !setprestige command.", group); } } else { Whisper(whisperSender, "Not enough data provided for !setprestige command.", group); } } else if (whisperMessage.StartsWith("C") || whisperMessage.StartsWith("c")) { if (wolfcoins.classList != null) { if (wolfcoins.classList.Keys.Contains(whisperSender.ToLower())) { if (wolfcoins.classList[whisperSender].classType == -1) { wolfcoins.SetClass(whisperSender, whisperMessage, group); } if (wolfcoins.classList[whisperSender].classType.ToString().EndsWith("0")) { char c = whisperMessage.Last(); int newClass = -1; int.TryParse(c.ToString(), out newClass); wolfcoins.ChangeClass(whisperSender, newClass, group); } } } } // // // COMMANDS TO FIX STUFF // // else if (whisperMessage == "!patch1") { if (whisperSender != tokenData.BroadcastUser && whisperSender != tokenData.ChatUser) continue; if (wolfcoins.xpList != null) { CharClass emptyClass = new CharClass(); emptyClass.classType = -1; emptyClass.totalItemCount = -1; foreach (var viewer in wolfcoins.xpList) { int myLevel = wolfcoins.determineLevel(viewer.Key); if (myLevel >= 3 && !wolfcoins.classList.ContainsKey(viewer.Key)) { emptyClass.name = viewer.Key; emptyClass.level = myLevel; wolfcoins.classList.Add(viewer.Key, emptyClass); Console.WriteLine("Added " + viewer.Key + " to the Class List."); } } wolfcoins.SaveClassData(); } } // command to fix multiple inventory ids and active states else if (whisperMessage == "!fixinventory") { if (whisperSender != tokenData.BroadcastUser && whisperSender != tokenData.ChatUser) continue; foreach (var player in wolfcoins.classList) { player.Value.FixItems(); } //Console.WriteLine(wolfcoins.classList["kraad_"].FixItems()); wolfcoins.SaveClassData(); } else if (whisperMessage == "1") { Whisper(whisperSender, "Wolfcoins are a currency you earn by watching the stream! You can check your coins by whispering me '!coins' or '!stats'. To find out what you can spend coins on, message me '!shop'.", group); } else if (whisperMessage == "2") { Whisper(whisperSender, "Did you know you gain experience by watching the stream? You can level up as you get more XP! Max level is 20. To check your level & xp, message me '!xp' '!level' or '!stats'. Only Level 2+ viewers can post links. This helps prevent bot spam!", group); } else if (whisperMessage == "!shop") { Whisper(whisperSender, "Whisper me '!stats <username>' to check another users stats! (Cost: 1 coin) Whisper me '!gloat' to spend 10 coins and show off your level! (Cost: 10 coins)", group); } else if (whisperMessage == "!dungeonlist") { Whisper(whisperSender, "List of Wolfpack RPG Adventures: http://tinyurl.com/WolfpackAdventureList", group); } else if (whisperMessage.StartsWith("!debuglevel5")) { if (whisperSender == tokenData.BroadcastUser || whisperSender == tokenData.ChatUser) { string[] whisperMSG = whispers[1].Split(); if (whisperMSG.Length > 1) { string user = whisperMSG[1]; if (wolfcoins.Exists(wolfcoins.classList, user)) { wolfcoins.classList.Remove(user); wolfcoins.SetXP(1, user, group); wolfcoins.SetXP(600, user, group); } else { wolfcoins.SetXP(1, user, group); wolfcoins.SetXP(600, user, group); } } } } else if (whisperMessage.StartsWith("!clearclass")) { if (whisperSender == tokenData.BroadcastUser || whisperSender == tokenData.ChatUser) { if (wolfcoins.classList != null) { string[] whisperMSG = whispers[1].Split(); if (whisperMSG.Length > 1) { string user = whisperMSG[1]; if (wolfcoins.classList.Keys.Contains(user.ToLower())) { wolfcoins.classList.Remove(user); wolfcoins.SaveClassData(); Whisper(whisperSender, "Cleared " + user + "'s class.", group); } else { Whisper(whisperSender, "Couldn't find you in the class table.", group); } } } } } else if (whisperMessage.StartsWith("!setcoins")) { if (whisperSender != tokenData.BroadcastUser && whisperSender != tokenData.ChatUser) break; string[] whisperMSG = whispers[1].Split(); if (whisperMSG.Length > 2) { if (int.TryParse(whisperMSG[2], out int value)) { if (!wolfcoins.Exists(wolfcoins.coinList, whisperMSG[1])) { wolfcoins.coinList.Add(whisperMSG[1], 0); } int newCoins = wolfcoins.SetCoins(value, whisperMSG[1]); if (newCoins != -1) { Whisper(whisperSender, "Set " + whisperMSG[1] + "'s coins to " + newCoins + ".", group); } else { Whisper(whisperSender, "Error updating Coin amount.", group); } } else { Whisper(whisperSender, "Invalid data provided for !setcoins command.", group); } } else { Whisper(whisperSender, "Not enough data provided for !setcoins command.", group); } } if (whisperMessage == "!coins" || whisperMessage == "coins") { if (wolfcoins.coinList != null) { if (wolfcoins.coinList.ContainsKey(whisperSender)) { Whisper(whisperSender, "You have: " + wolfcoins.coinList[whisperSender] + " coins.", group); } else { Whisper(whisperSender, "You don't have any coins yet! Stick around during the livestream to earn coins.", group); } } } else if (whisperMessage.StartsWith("!gloatpet") || whisperMessage.StartsWith("!petgloat")) { if (wolfcoins.classList.ContainsKey(whisperSender)) { if (wolfcoins.coinList[whisperSender] < gloatCost) { Whisper(whisperSender, "You don't have enough coins to gloat!", group); continue; } if (wolfcoins.classList[whisperSender].myPets.Count > 0) { bool hasActive = false; Pet toGloat = new Pet(); foreach (var pet in wolfcoins.classList[whisperSender].myPets) { if (pet.isActive) { hasActive = true; toGloat = pet; break; } } if (!hasActive) { Whisper(whisperSender, "You don't have an active pet to show off! Activate one with !summon <id>", group); continue; } string temp = gloatCost.ToString(); wolfcoins.RemoveCoins(whisperSender, temp); string petType = ""; if (toGloat.isSparkly) petType += "SPARKLY " + toGloat.type; else petType = toGloat.type; irc.sendChatMessage(whisperSender + " watches proudly as their level " + toGloat.level + " " + petType + " named " + toGloat.name + " struts around!"); Whisper(whisperSender, "You spent " + temp + " wolfcoins to brag about " + toGloat.name + ".", group); } } } else if (whisperMessage.StartsWith("!gloat") || whisperMessage.StartsWith("gloat")) { if (wolfcoins.coinList != null && wolfcoins.xpList != null) { if (wolfcoins.coinList.ContainsKey(whisperSender) && wolfcoins.xpList.ContainsKey(whisperSender)) { if (wolfcoins.coinList[whisperSender] >= gloatCost) { string temp = gloatCost.ToString(); string gloatMessage = ""; int level = wolfcoins.determineLevel(whisperSender); string levelWithPrestige = wolfcoins.gloatWithPrestige(whisperSender); wolfcoins.RemoveCoins(whisperSender, temp); #region gloatMessages switch (level) { case 1: { gloatMessage = "Just a baby! lobosMindBlank"; } break; case 2: { gloatMessage = "Scrubtastic!"; } break; case 3: { gloatMessage = "Pretty weak!"; } break; case 4: { gloatMessage = "Not too shabby."; } break; case 5: { gloatMessage = "They can hold their own!"; } break; case 6: { gloatMessage = "Getting pretty strong Kreygasm"; } break; case 7: { gloatMessage = "A formidable opponent!"; } break; case 8: { gloatMessage = "A worthy adversary!"; } break; case 9: { gloatMessage = "A most powerful combatant!"; } break; case 10: { gloatMessage = "A seasoned war veteran!"; } break; case 11: { gloatMessage = "A fearsome champion of the Wolfpack!"; } break; case 12: { gloatMessage = "A vicious pack leader!"; } break; case 13: { gloatMessage = "A famed Wolfpack Captain!"; } break; case 14: { gloatMessage = "A brutal commander of the Wolfpack!"; } break; case 15: { gloatMessage = "Decorated Chieftain of the Wolfpack!"; } break; case 16: { gloatMessage = "A War Chieftain of the Wolfpack!"; } break; case 17: { gloatMessage = "A sacred Wolfpack Justicar!"; } break; case 18: { gloatMessage = "Demigod of the Wolfpack!"; } break; case 19: { gloatMessage = "A legendary Wolfpack demigod veteran!"; } break; case 20: { gloatMessage = "The Ultimate Wolfpack God Rank. A truly dedicated individual."; } break; default: break; } #endregion irc.sendChatMessage(whisperSender + " has spent " + gloatCost + " Wolfcoins to show off that they are " + levelWithPrestige + "! " + gloatMessage); } else { Whisper(whisperSender, "You don't have enough coins to gloat (Cost: " + gloatCost + " Wolfcoins)", group); } } else { Whisper(whisperSender, "You don't have coins and/or xp yet!", group); } } } else if ((whisperMessage.StartsWith("!bet") || whisperMessage.StartsWith("bet")) && betsAllowed && betActive && wolfcoins.Exists(wolfcoins.coinList, whisperSender)) { string[] whisperMSG = whispers[1].Split(); if (whisperMSG.Length > 1) { Better betInfo = new Better(); string user = whispers[1]; string vote = whispers[2].ToLower(); int betAmount = -1; if (int.TryParse(whispers[3], out betAmount)) { if (!wolfcoins.CheckCoins(user, betAmount)) { Whisper(user, "There was an error placing your bet. (not enough coins?)", group); continue; } betInfo.betAmount = betAmount; if (!betters.ContainsKey(user)) { wolfcoins.RemoveCoins(user, betAmount.ToString()); if (vote == "succeed") { betInfo.vote = SUCCEED; betters.Add(user, betInfo); } else if (vote == "fail") { betInfo.vote = FAIL; betters.Add(user, betInfo); } } } } } else if (whisperMessage.StartsWith("!givexp")) { if (whisperSender != tokenData.BroadcastUser && whisperSender != tokenData.ChatUser) break; string[] whisperMSG = whispers[1].Split(); if (whisperMSG[0] != null && whisperMSG[1] != null && whisperMSG[2] != null) { if (!(int.TryParse(whisperMSG[2].ToString(), out int value))) { break; } string user = whisperMSG[1].ToString(); wolfcoins.AwardXP(value, user, group); wolfcoins.SaveClassData(); wolfcoins.SaveXP(); Whisper(whisperSender, "Gave " + user + " " + value + " XP.", group); } else { irc.sendChatMessage("Not enough data provided for !givexp command."); } } else if (whisperMessage.StartsWith("!xp") || whisperMessage.StartsWith("xp") || whisperMessage.StartsWith("level") || whisperMessage.StartsWith("!level") || whisperMessage.StartsWith("!lvl") || whisperMessage.StartsWith("lvl")) { if (wolfcoins.xpList != null) { if (wolfcoins.xpList.ContainsKey(whisperSender)) { int myLevel = wolfcoins.determineLevel(whisperSender); int xpToNextLevel = wolfcoins.XpToNextLevel(whisperSender); int myPrestige = -1; if (wolfcoins.classList.ContainsKey(whisperSender)) { myPrestige = wolfcoins.classList[whisperSender].prestige; } //if(!wolfcoins.Exists(wolfcoins.classList, whisperSender)) //{ // Whisper(whisperSender, "You are Level " + myLevel + " (Total XP: " + wolfcoins.xpList[whisperSender] + ")", group); //} //else //{ // string myClass = wolfcoins.determineClass(whisperSender); // Whisper(whisperSender, "You are a Level " + myLevel + " " + myClass + " (Total XP: " + wolfcoins.xpList[whisperSender] + ")", group); //} if (wolfcoins.classList.Keys.Contains(whisperSender.ToLower())) { string myClass = wolfcoins.determineClass(whisperSender); Whisper(whisperSender, "You are a Level " + myLevel + " " + myClass + ", and you are Prestige Level " + myPrestige + ". (Total XP: " + wolfcoins.xpList[whisperSender] + " | XP To Next Level: " + xpToNextLevel + ")", group); } else { Whisper(whisperSender, "You are Level " + myLevel + " (Total XP: " + wolfcoins.xpList[whisperSender] + " | XP To Next Level: " + xpToNextLevel + ")", group); } } else { Whisper(whisperSender, "You don't have any XP yet! Hang out in chat during the livestream to earn XP & coins.", group); } } } else if (whisperMessage.StartsWith("!shutdown")) { if (whisperSender != tokenData.BroadcastUser && whisperSender != tokenData.ChatUser) break; string[] temp = whispers[1].Split(' '); if (temp.Count() > 1) { int numMinutes = -1; if (int.TryParse(temp[1], out numMinutes)) { foreach (var player in groupFinder.queue) { Whisper(player.name, "Attention! Wolfpack RPG will be coming down for maintenance in about " + numMinutes + " minutes. If you are dungeoning while the bot shuts down, your progress may not be saved.", group); } } } } else if (whisperMessage.StartsWith("!stats") || whisperMessage.StartsWith("stats")) { if (wolfcoins.coinList != null && wolfcoins.xpList != null) { string[] temp = whispers[1].Split(' '); if (temp.Count() > 1) { string desiredUser = temp[1].ToLower(); if (wolfcoins.xpList.ContainsKey(desiredUser) && wolfcoins.coinList.ContainsKey(desiredUser)) { wolfcoins.RemoveCoins(whisperSender, pryCost.ToString()); if (wolfcoins.Exists(wolfcoins.classList, desiredUser)) { Whisper(whisperSender, "" + desiredUser + " is a Level " + wolfcoins.determineLevel(desiredUser) + " " + wolfcoins.determineClass(desiredUser) + " (" + wolfcoins.xpList[desiredUser] + " XP), Prestige Level " + wolfcoins.classList[desiredUser].prestige + ", and has " + wolfcoins.coinList[desiredUser] + " Wolfcoins.", group); } else { Whisper(whisperSender, "" + desiredUser + " is Level " + " " + wolfcoins.determineLevel(desiredUser) + " (" + wolfcoins.xpList[desiredUser] + " XP) and has " + wolfcoins.coinList[desiredUser] + " Wolfcoins.", group); } Whisper(whisperSender, "It cost you " + pryCost + " Wolfcoins to discover this information.", group); } else { Whisper(whisperSender, "User does not exist in database. You were charged no coins.", group); } } else if (wolfcoins.coinList.ContainsKey(whisperSender) && wolfcoins.xpList.ContainsKey(whisperSender)) { int myLevel = wolfcoins.determineLevel(whisperSender); int myPrestige = -1; if (wolfcoins.classList.ContainsKey(whisperSender)) { myPrestige = wolfcoins.classList[whisperSender].prestige; } int xpToNextLevel = wolfcoins.XpToNextLevel(whisperSender); Whisper(whisperSender, "You have: " + wolfcoins.coinList[whisperSender] + " coins.", group); if (wolfcoins.classList.Keys.Contains(whisperSender.ToLower())) { string myClass = wolfcoins.determineClass(whisperSender); Whisper(whisperSender, "You are a Level " + myLevel + " " + myClass + ", and you are Prestige Level " + myPrestige + ". (Total XP: " + wolfcoins.xpList[whisperSender] + " | XP To Next Level: " + xpToNextLevel + ")", group); } else { Whisper(whisperSender, "You are Level " + myLevel + " (Total XP: " + wolfcoins.xpList[whisperSender] + " | XP To Next Level: " + xpToNextLevel + ")", group); } } if (!(wolfcoins.coinList.ContainsKey(whisperSender)) || !(wolfcoins.xpList.ContainsKey(whisperSender))) { Whisper(whisperSender, "You either don't have coins or xp yet. Hang out in chat during the livestream to earn them!", group); } } } } } #endregion #region messageRegion if (message.Length > 1) { if (message[0] != null && message[1] != null) { string[] first = message[1].Split(' '); string sender = message[0]; if (sender == "twitchnotify" && first.Last() == "subscribed!") { // This code updates subcounter.txt for Subathon. Problem is having to recode the modifier update when the goal is met //var text = File.ReadAllText(@"C:\Users\Lobos\Dropbox\Stream\subcounter.txt"); //int count = int.Parse(text); //count--; //File.WriteAllText(@"C:\Users\Lobos\Dropbox\Stream\subcounter.txt", count.ToString()); string newSub = first[0].ToLower(); if (!wolfcoins.subSet.Contains(newSub)) { wolfcoins.subSet.Add(newSub); Console.WriteLine("Added " + first[0] + " to the subs list."); } } if (first[0] == "!stats" || first[0] == "!xp" || first[0] == "!lvl" || first[0] == "!level" || first[0] == "!exp") { irc.sendChatMessage("/timeout " + sender + " 1"); Whisper(sender, "I see you're trying to check your stats! You'll need to WHISPER to me to get any information. Type '/w lobotjr' and then stats, xp, coins, etc. for that information.", group); Whisper(sender, "Sorry for purging you. Just trying to do my job to keep chat clear! <3", group); } switch (first[0]) { case "!nextaward": { if (sender != tokenData.BroadcastUser && sender != tokenData.ChatUser) break; double totalSec = (DateTime.Now - awardLast).TotalSeconds; int timeRemaining = (awardInterval * 60) - (int)(DateTime.Now - awardLast).TotalSeconds; int secondsRemaining = timeRemaining % 60; int minutesRemaining = timeRemaining / 60; irc.sendChatMessage(minutesRemaining + " minutes and " + secondsRemaining + " seconds until next coins/xp are awarded."); } break; case "!setinterval": { if (sender != tokenData.BroadcastUser && sender != tokenData.ChatUser) break; int newAmount = 0; if (first.Count() > 1) { if (int.TryParse(first[1], out newAmount)) { awardInterval = newAmount; irc.sendChatMessage("XP & Coins will now be awarded every " + newAmount + " minutes."); } } } break; case "!setmultiplier": { if (sender != tokenData.BroadcastUser && sender != tokenData.ChatUser) break; int newAmount = 0; if (first.Count() > 1) { if (int.TryParse(first[1], out newAmount)) { awardMultiplier = newAmount; irc.sendChatMessage(newAmount + "x XP & Coins will now be awarded."); } } } break; //case "!endbet": // { // if (!betActive) // break; // if (wolfcoins.viewers.chatters.moderators.Contains(sender)) // { // if (first.Count() > 1 && !betActive) // { // string result = first[1].ToLower(); // if(result == "succeed") // { // foreach(var element in betters) // { // //wolfcoins.AddCoins() // } // } // else if(result == "fail") // { // } // } // } // } break; //case "!closebet": // { // if(!betActive || !betsAllowed) // break; // if (wolfcoins.viewers.chatters.moderators.Contains(sender)) // { // betsAllowed = false; // irc.sendChatMessage("Bets are now closed! Good luck FrankerZ"); // } // } break; //case "!startbet": // { // betStatement = ""; // if (wolfcoins.viewers.chatters.moderators.Contains(sender)) // { // if (first.Count() > 1 && !betActive) // { // betActive = true; // betsAllowed = true; // for (int i = 0; i < first.Count() - 1; i++) // { // betStatement += first[i + 1]; // } // irc.sendChatMessage("New bet started: " + betStatement + " Type '!bet succeed' or '!bet fail' to bet."); // } // } // } break; case "!xpon": { wolfcoins.UpdateViewers(channel); if ((wolfcoins.viewers.chatters.moderators.Contains(sender) || sender == tokenData.BroadcastUser || sender == tokenData.ChatUser || sender == "lan5432") && !broadcasting) { broadcasting = true; awardLast = DateTime.Now; var fishingSystem = systemManager.Get<FishingSystem>(); fishingSystem.Tournament.NextTournament = DateTime.Now.AddMinutes(15); irc.sendChatMessage("Wolfcoins & XP will be awarded."); } } break; case "!xpoff": { wolfcoins.UpdateViewers(channel); if ((wolfcoins.viewers.chatters.moderators.Contains(sender) || sender == tokenData.BroadcastUser || sender == tokenData.ChatUser || sender == "lan5432") && broadcasting) { broadcasting = false; irc.sendChatMessage("Wolfcoins & XP will no longer be awarded."); wolfcoins.BackupData(); } } break; case "!setxp": { if (sender != tokenData.BroadcastUser && sender != tokenData.ChatUser) break; if (first.Length >= 3 && first[1] != null && first[2] != null) { if (int.TryParse(first[2], out int value)) { int newXp = wolfcoins.SetXP(value, first[1], group); if (newXp != -1) { irc.sendChatMessage("Set " + first[1] + "'s XP to " + newXp + "."); } else { irc.sendChatMessage("Error updating XP amount."); } } else { irc.sendChatMessage("Invalid data provided for !setxp command."); } } else { irc.sendChatMessage("Not enough data provided for !setxp command."); } } break; case "!grantxp": { if (sender != tokenData.BroadcastUser && sender != tokenData.ChatUser) break; if (first[0] != null && first[1] != null) { if (int.TryParse(first[1], out int value)) { wolfcoins.AwardXP(value, group); } else { irc.sendChatMessage("Invalid data provided for !givexp command."); } } else { irc.sendChatMessage("Not enough data provided for !givexp command."); } } break; case "!setcoins": { } break; #region NormalBotStuff //case "!hug": // { // irc.sendChatMessage("/me gives " + sender + " a big hug!"); // } break; //case "!playlist": // { // irc.sendChatMessage("Lobos' Spotify Playlist: http://open.spotify.com/user/1251282601/playlist/2j1FVSjJ4zdJiqGQgXgW3t"); // } break; //case "!opinion": // { // irc.sendChatMessage("Opinions go here: http:////i.imgur.com/3jRQ2fa.jpg"); // } break; //case "!quote": // { // string path = @"C:\Users\Owner\Dropbox\Stream\quotes.txt"; // string myFile = ""; // if (File.Exists(path)) // { // myFile = File.ReadAllText(path); // string[] quotes = myFile.Split('\n'); // int numQuotes = quotes.Length; // Random random = new Random(); // int randomNumber = random.Next(0, numQuotes); // irc.sendChatMessage(quotes[randomNumber]); // } // else // { // irc.sendChatMessage("Quotes file does not exist."); // } // } break; //case "!pun": // { // string path = @"C:\Users\Owner\Dropbox\Stream\puns.txt"; // string myFile = ""; // if (File.Exists(path)) // { // myFile = File.ReadAllText(path); // string[] puns = myFile.Split('\n'); // int numPuns = puns.Length; // Random random = new Random(); // int randomNumber = random.Next(0, numPuns); // irc.sendChatMessage(puns[randomNumber]); // } // else // { // irc.sendChatMessage("Puns file does not exist."); // } // } break; //case "!whisper": // { // if (group.connected) // { // group.sendChatMessage(".w " + sender + " Psssssst!"); // } // } break; #endregion // remove coins from a target. Ex: !removecoins lobosjr 200 case "!removecoins": { if (first.Length < 3) { irc.sendChatMessage("Not enough information provided."); break; } string target = first[1]; string coins = first[2]; if (sender == tokenData.BroadcastUser || sender == tokenData.ChatUser) { if (wolfcoins.RemoveCoins(target, coins)) { Console.WriteLine(sender + " removed " + coins + " coins from " + target + "."); irc.sendChatMessage(sender + " removed " + coins + " coins from " + target + "."); } else { Console.WriteLine("Coin add operation failed with the following information: "); Console.WriteLine("Sender: " + sender); Console.WriteLine("Target: " + target); Console.WriteLine("Amount: " + coins + " coins."); } } else { Console.WriteLine("Non-Moderator attempted to add coins."); irc.sendChatMessage("Sorry, " + sender + ", AddCoins is a moderator-only command."); } } break; case "!addcoins": { if (first.Length < 3) { irc.sendChatMessage("Not enough information provided."); break; } string target = first[1]; string coins = first[2]; if (sender == tokenData.BroadcastUser || sender == tokenData.ChatUser) { if (wolfcoins.AddCoins(target, coins)) { Console.WriteLine(sender + " granted " + target + " " + coins + " coins."); irc.sendChatMessage(sender + " granted " + target + " " + coins + " coins."); } else { Console.WriteLine("Coin add operation failed with the following information: "); Console.WriteLine("Sender: " + sender); Console.WriteLine("Target: " + target); Console.WriteLine("Amount: " + coins + " coins."); } } else { Console.WriteLine("Non-Moderator attempted to add coins."); irc.sendChatMessage("Sorry, " + sender + ", AddCoins is a moderator-only command."); } } break; default: break; } } } #endregion } Console.WriteLine("Connection terminated."); UpdateTokens(tokenData, clientData, true); connected = false; #endregion } else { #region TwitchPlaysDS irc.joinRoom("lobosjr"); Process[] p = Process.GetProcessesByName("DARKSOULS"); IntPtr h = (IntPtr)0; if (p.Length > 0) { h = p[0].MainWindowHandle; SetForegroundWindow(h); } while (connected) { // message[0] has username, message[1] has message string[] message = irc.readMessage(); if (message.Length > 1) { if (message[0] != null && message[1] != null) { string[] first = message[1].Split(' '); string sender = message[0]; char[] keys = { }; const int MOVE_AMOUNT = 1000; switch (first[0].ToLower()) { // M preceds movement. MF = Move Forward, MB = Move Backwards, etc. case "mf": { sendFor('W', MOVE_AMOUNT); Console.WriteLine("MF - Move Forward"); } break; case "mb": { sendFor('S', MOVE_AMOUNT); Console.WriteLine("MB - Move Back"); } break; case "ml": { sendFor('A', MOVE_AMOUNT); Console.WriteLine("ML - Move Left"); } break; case "mr": { sendFor('D', MOVE_AMOUNT); Console.WriteLine("MR - Move Right"); } break; // Camera Up, Down, Left, Right case "cu": { sendFor('I', MOVE_AMOUNT); Console.WriteLine("CU - Camera Up"); } break; case "cd": { sendFor('K', MOVE_AMOUNT); Console.WriteLine("CD - Camera Down"); } break; case "cl": { sendFor('J', MOVE_AMOUNT); } break; case "cr": { sendFor('L', MOVE_AMOUNT); } break; // Lock on/off case "l": { sendFor('O', 100); } break; // Use item case "u": { sendFor('E', 100); } break; // 2h toggle case "y": { sendFor(56, 100); } break; // Attacks case "r1": { sendFor('H', 100); } break; case "r2": { sendFor('U', 100); } break; case "l1": { sendFor(42, 100); } break; case "l2": { sendFor(15, 100); } break; // Rolling directions case "rl": { keys = new char[] { 'A', ' ' }; sendFor(keys, 100); } break; case "rr": { keys = new char[] { 'D', ' ' }; sendFor(keys, 100); } break; case "rf": { keys = new char[] { 'W', ' ' }; sendFor(keys, 100); } break; case "rb": { keys = new char[] { 'S', ' ' }; sendFor(keys, 100); } break; case "x": { sendFor('Q', 100); sendFor(28, 100); } break; // switch LH weap case "dl": { sendFor('C', 100); } break; case "dr": { sendFor('V', 100); } break; case "du": { sendFor('R', 100); } break; case "dd": { sendFor('F', 100); } break; //case "just subscribed": // { // sendFor('G', 500); // sendFor(13, 100); // } break; default: break; } } } } Console.WriteLine("Connection terminated."); #endregion } } static Pet GrantPet(string playerName, Currency wolfcoins, Dictionary<int, Pet> petDatabase, IrcClient irc, IrcClient group) { List<Pet> toAward = new List<Pet>(); // figure out the rarity of pet to give and build a list of non-duplicate pets to award int rarity = wolfcoins.classList[playerName].petEarned; foreach (var basePet in petDatabase) { if (basePet.Value.petRarity != rarity) continue; bool alreadyOwned = false; foreach (var pet in wolfcoins.classList[playerName].myPets) { if (pet.ID == basePet.Value.ID) { alreadyOwned = true; break; } } if (!alreadyOwned) { toAward.Add(basePet.Value); } } // now that we have a list of eligible pets, randomly choose one from the list to award Pet newPet; if (toAward.Count > 0) { string toSend = ""; Random RNG = new Random(); int petToAward = RNG.Next(1, toAward.Count + 1); newPet = new Pet(toAward[petToAward - 1]); int sparklyCheck = RNG.Next(1, 101); bool firstPet = false; if (wolfcoins.classList[playerName].myPets.Count == 0) firstPet = true; if (sparklyCheck == 1) newPet.isSparkly = true; if (firstPet) { newPet.isActive = true; toSend = "You found your first pet! You now have a pet " + newPet.type + ". Whisper me !pethelp for more info."; } else { toSend = "You found a new pet buddy! You earned a " + newPet.type + " pet!"; } if (newPet.isSparkly) { toSend += " WOW! And it's a sparkly version! Luck you!"; } newPet.stableID = wolfcoins.classList[playerName].myPets.Count + 1; wolfcoins.classList[playerName].myPets.Add(newPet); Whisper(playerName, toSend, group); if (newPet.isSparkly) { Console.WriteLine(DateTime.Now.ToString() + "WOW! " + ": " + playerName + " just found a SPARKLY pet " + newPet.name + "!"); irc.sendChatMessage("WOW! " + playerName + " just found a SPARKLY pet " + newPet.name + "! What luck!"); } else { Console.WriteLine(DateTime.Now.ToString() + ": " + playerName + " just found a pet " + newPet.name + "!"); irc.sendChatMessage(playerName + " just found a pet " + newPet.name + "!"); } if (wolfcoins.classList[playerName].myPets.Count == petDatabase.Count) { Whisper(playerName, "You've collected all of the available pets! Congratulations!", group); } wolfcoins.classList[playerName].petEarned = -1; return newPet; } return new Pet(); } static void UpdateTokens(TokenData tokenData, LobotJR.Shared.Client.ClientData clientData, bool force = false) { bool tokenUpdated = false; if (force || DateTime.Now >= tokenData.ChatToken.ExpirationDate) { tokenUpdated = true; try { tokenData.ChatToken = AuthToken.Refresh(clientData.ClientId, clientData.ClientSecret, tokenData.ChatToken.RefreshToken); } catch (Exception e) { Console.WriteLine($"Exception occurred refreshing the chat token: {e.Message}\n{e.StackTrace}"); } } if (force || DateTime.Now >= tokenData.BroadcastToken.ExpirationDate) { tokenUpdated = true; try { tokenData.BroadcastToken = AuthToken.Refresh(clientData.ClientId, clientData.ClientSecret, tokenData.BroadcastToken.RefreshToken); } catch (Exception e) { Console.WriteLine($"Exception occurred refreshing the streamer token: {e.Message}\n{e.StackTrace}"); } } if (tokenUpdated) { try { FileUtils.WriteTokenData(tokenData); } catch (Exception e) { Console.WriteLine($"Exception occurred writing the updated token data: {e.Message}\n{e.StackTrace}"); } } } static string GetDungeonName(int dungeonID, Dictionary<int, string> dungeonList) { if (!dungeonList.ContainsKey(dungeonID)) return "Invalid DungeonID"; Dungeon tempDungeon = new Dungeon("content/dungeons/" + dungeonList[dungeonID]); return tempDungeon.dungeonName; } static string GetEligibleDungeons(string user, Currency wolfcoins, Dictionary<int, string> dungeonList) { string eligibleDungeons = ""; int playerLevel = wolfcoins.determineLevel(user); List<Dungeon> dungeons = new List<Dungeon>(); Dungeon tempDungeon; foreach (var id in dungeonList) { tempDungeon = new Dungeon("content/dungeons/" + dungeonList[id.Key]); tempDungeon.dungeonID = id.Key; dungeons.Add(tempDungeon); } if (dungeons.Count == 0) return eligibleDungeons; bool firstAdded = false; foreach (var dungeon in dungeons) { //if(dungeon.minLevel <= playerLevel) //{ if (!firstAdded) { firstAdded = true; } else { eligibleDungeons += ","; } eligibleDungeons += dungeon.dungeonID; //} } return eligibleDungeons; } static int DetermineEligibility(string user, int dungeonID, Dictionary<int, string> dungeonList, int baseDungeonCost, Currency wolfcoins) { if (!dungeonList.ContainsKey(dungeonID)) return -1; int playerLevel = wolfcoins.determineLevel(wolfcoins.xpList[user]); Dungeon tempDungeon = new Dungeon("content/dungeons/" + dungeonList[dungeonID]); if (wolfcoins.Exists(wolfcoins.coinList, user)) { if (wolfcoins.coinList[user] < (baseDungeonCost + ((playerLevel - 3) * 10))) { //not enough money return -2; } } // no longer gate dungeons by level //if (tempDungeon.minLevel <= playerLevel) // return 1; return 1; } static void WhisperPet(string user, Pet pet, IrcClient whisperClient, int detail) { const int LOW_DETAIL = 0; const int HIGH_DETAIL = 1; string name = pet.name; int stableID = pet.stableID; string rarity = ""; switch (pet.petRarity) { case (Pet.QUALITY_COMMON): { rarity = "Common"; } break; case (Pet.QUALITY_UNCOMMON): { rarity = "Uncommon"; } break; case (Pet.QUALITY_RARE): { rarity = "Rare"; } break; case (Pet.QUALITY_EPIC): { rarity = "Epic"; } break; case (Pet.QUALITY_ARTIFACT): { rarity = "Legendary"; } break; default: { rarity = "Error"; } break; } List<string> stats = new List<string>(); if (detail == HIGH_DETAIL) stats.Add("Level: " + pet.level + " | Affection: " + pet.affection + " | Energy: " + pet.hunger); bool active = pet.isActive; string status = ""; string myStableID = ""; if (active) { status = "Active"; myStableID = "<[" + pet.stableID + "]> "; } else { status = "In the Stable"; myStableID = "[" + pet.stableID + "] "; } Whisper(user, myStableID + name + " the " + pet.type + " (" + rarity + ") ", whisperClient); string sparkly = ""; if (pet.isSparkly) sparkly = "Yes!"; else sparkly = "No"; if (detail == HIGH_DETAIL) Whisper(user, "Status: " + status + " | Sparkly? " + sparkly, whisperClient); foreach (var stat in stats) { Whisper(user, stat, whisperClient); } } static void WhisperItem(string user, Item itm, IrcClient whisperClient, Dictionary<int, Item> itemDatabase) { string name = itm.itemName; string type = ""; int inventoryID = itm.inventoryID; switch (itm.itemType) { case (Item.TYPE_ARMOR): { type = "Armor"; } break; case (Item.TYPE_WEAPON): { type = "Weapon"; } break; case (Item.TYPE_OTHER): { type = "Misc. Item"; } break; default: { type = "Broken"; } break; } string rarity = ""; switch (itm.itemRarity) { case Item.QUALITY_UNCOMMON: { rarity = "Uncommon"; } break; case Item.QUALITY_RARE: { rarity = "Rare"; } break; case Item.QUALITY_EPIC: { rarity = "Epic"; } break; case Item.QUALITY_ARTIFACT: { rarity = "Artifact"; } break; default: { rarity = "Broken"; } break; } List<string> stats = new List<string>(); if (itm.successChance > 0) { stats.Add("+" + itm.successChance + "% Success Chance"); } if (itm.xpBonus > 0) { stats.Add("+" + itm.xpBonus + "% XP Bonus"); } if (itm.coinBonus > 0) { stats.Add("+" + itm.coinBonus + "% Wolfcoin Bonus"); } if (itm.itemFind > 0) { stats.Add("+" + itm.itemFind + "% Item Find"); } if (itm.preventDeathBonus > 0) { stats.Add("+" + itm.preventDeathBonus + "% to Prevent Death"); } bool active = itm.isActive; string status = ""; if (active) { status = "(Equipped)"; } else { status = "(Unequipped)"; } Whisper(user, name + " (" + rarity + " " + type + ") " + status, whisperClient); Whisper(user, "Inventory ID: " + inventoryID, whisperClient); foreach (var stat in stats) { Whisper(user, stat, whisperClient); } } static int GrantItem(int id, Currency wolfcoins, string user, Dictionary<int, Item> itemDatabase) { string logPath = "dungeonlog.txt"; if (id < 1) return -1; Item newItem = itemDatabase[id - 1]; bool hasActiveItem = false; foreach (var item in wolfcoins.classList[user].myItems) { if (item.itemType == newItem.itemType && item.isActive) hasActiveItem = true; } if (!hasActiveItem) newItem.isActive = true; wolfcoins.classList[user].totalItemCount++; newItem.inventoryID = wolfcoins.classList[user].totalItemCount; wolfcoins.classList[user].myItems.Add(newItem); wolfcoins.classList[user].itemEarned = -1; System.IO.File.AppendAllText(logPath, user + " looted a " + newItem.itemName + "!" + Environment.NewLine); Console.WriteLine(user + " just looted a " + newItem.itemName + "!"); return newItem.itemID; } static void sendFor(char key, int ms) { // Send a keydown, leaving the key down indefinitely. It seems you have to do this for even // single inputs with shorter times because putting the keyup right after the keydown in the // buffer is too fast for Dark Souls var inputData = new INPUT[1]; short scanCode = (short)MapVirtualKey(VkKeyScan(key), 0); inputData[0].type = INPUT_KEYBOARD; inputData[0].ki.wScan = scanCode; inputData[0].ki.dwFlags = KEYEVENTF_SCANCODE; SendInput((uint)inputData.Length, inputData, Marshal.SizeOf(typeof(INPUT))); // A timer is probably more suitable Thread.Sleep(ms); // After waiting, send the keyup inputData[0].ki.dwFlags = KEYEVENTF_KEYUP | KEYEVENTF_SCANCODE; inputData[0].ki.time = 0; inputData[0].ki.dwExtraInfo = IntPtr.Zero; SendInput((uint)inputData.Length, inputData, Marshal.SizeOf(typeof(INPUT))); } static void sendFor(short key, int ms) { // Send a keydown, leaving the key down indefinitely. It seems you have to do this for even // single inputs with shorter times because putting the keyup right after the keydown in the // buffer is too fast for Dark Souls var inputData = new INPUT[1]; short scanCode = key; inputData[0].type = INPUT_KEYBOARD; inputData[0].ki.wScan = scanCode; inputData[0].ki.dwFlags = KEYEVENTF_SCANCODE; SendInput((uint)inputData.Length, inputData, Marshal.SizeOf(typeof(INPUT))); // A timer is probably more suitable Thread.Sleep(ms); // After waiting, send the keyup inputData[0].ki.dwFlags = KEYEVENTF_KEYUP | KEYEVENTF_SCANCODE; inputData[0].ki.time = 0; inputData[0].ki.dwExtraInfo = IntPtr.Zero; SendInput((uint)inputData.Length, inputData, Marshal.SizeOf(typeof(INPUT))); } // overloaded to handle more than one character send at a time static void sendFor(char[] key, int ms) { // Send a keydown, leaving the key down indefinitely. It seems you have to do this for even // single inputs with shorter times because putting the keyup right after the keydown in the // buffer is too fast for Dark Souls var inputData = new INPUT[1]; short scanCode = (short)MapVirtualKey(VkKeyScan(key[0]), 0); inputData[0].type = INPUT_KEYBOARD; inputData[0].ki.wScan = scanCode; inputData[0].ki.dwFlags = KEYEVENTF_SCANCODE; SendInput((uint)inputData.Length, inputData, Marshal.SizeOf(typeof(INPUT))); if (key.Length > 1) { inputData[0].ki.wScan = (short)MapVirtualKey(VkKeyScan(key[1]), 0); SendInput((uint)inputData.Length, inputData, Marshal.SizeOf(typeof(INPUT))); } // A timer is probably more suitable Thread.Sleep(ms); // After waiting, send the keyup inputData[0].ki.dwFlags = KEYEVENTF_KEYUP | KEYEVENTF_SCANCODE; inputData[0].ki.time = 0; inputData[0].ki.dwExtraInfo = IntPtr.Zero; SendInput((uint)inputData.Length, inputData, Marshal.SizeOf(typeof(INPUT))); if (key.Length > 1) { inputData[0].ki.wScan = scanCode; SendInput((uint)inputData.Length, inputData, Marshal.SizeOf(typeof(INPUT))); } } } }
56.224068
320
0.335763
[ "MIT" ]
lobosjrgaming/lobotjr
LobotJR/Program.cs
263,974
C#
/* Yet Another Forum.NET * Copyright (C) 2003-2005 Bjørnar Henden * Copyright (C) 2006-2013 Jaben Cargman * Copyright (C) 2014-2022 Ingo Herbote * https://www.yetanotherforum.net/ * * 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 * https://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ namespace YAF.Modules { using System; using System.Web.UI.HtmlControls; using YAF.Configuration; using YAF.Core.Helpers; using YAF.Core.Utilities; using YAF.Types; using YAF.Types.Attributes; /// <summary> /// Generates the Favicon code inside the head section /// </summary> [Module("Favicon Module", "Ingo Herbote", 1)] public class FaviconModule : SimpleBaseForumModule { /// <summary> /// The initialization after page. /// </summary> public override void InitAfterPage() { this.CurrentForumPage.PreRender += this.CurrentForumPage_PreRender; } /// <summary> /// Handles the PreRender event of the ForumPage control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param> private void CurrentForumPage_PreRender([NotNull] object sender, [NotNull] EventArgs e) { var head = this.ForumControl.Page.Header ?? this.CurrentForumPage.FindControlRecursiveBothAs<HtmlHead>("YafHead"); if (head == null || Config.IsAnyPortal) { return; } // Link tags var appleTouchIcon = new HtmlLink { Href = BoardInfo.GetURLToContent("favicons/apple-touch-icon.png") }; appleTouchIcon.Attributes.Add("rel", "apple-touch-icon"); appleTouchIcon.Attributes.Add("sizes", "180x180"); head.Controls.Add(appleTouchIcon); var icon32 = new HtmlLink { Href = BoardInfo.GetURLToContent("favicons/favicon-32x32.png") }; icon32.Attributes.Add("rel", "icon"); icon32.Attributes.Add("sizes", "32x32"); head.Controls.Add(icon32); var icon16 = new HtmlLink { Href = BoardInfo.GetURLToContent("favicons/favicon-16x16.png") }; icon16.Attributes.Add("rel", "icon"); icon16.Attributes.Add("sizes", "16x16"); head.Controls.Add(icon16); var manifest = new HtmlLink { Href = BoardInfo.GetURLToContent("favicons/site.webmanifest") }; manifest.Attributes.Add("rel", "manifest"); head.Controls.Add(manifest); var maskIcon = new HtmlLink { Href = BoardInfo.GetURLToContent("favicons/safari-pinned-tab.svg") }; maskIcon.Attributes.Add("rel", "mask-icon"); maskIcon.Attributes.Add("color", "#5bbad5"); head.Controls.Add(maskIcon); var shortcutIcon = new HtmlLink { Href = BoardInfo.GetURLToContent("favicons/favicon.ico") }; shortcutIcon.Attributes.Add("rel", "shortcut icon"); head.Controls.Add(shortcutIcon); // Meta Tags head.Controls.Add(new HtmlMeta { Name = "msapplication-TileColor", Content = "#da532c" }); head.Controls.Add( new HtmlMeta { Name = "msapplication-config", Content = BoardInfo.GetURLToContent("favicons/browserconfig.xml") }); head.Controls.Add(new HtmlMeta { Name = "theme-color", Content = "#ffffff" }); } } }
41.780952
117
0.610212
[ "Apache-2.0" ]
correaAlex/YAFNET
yafsrc/YetAnotherForum.NET/Modules/FaviconModule.cs
4,286
C#
/* * Copyright (c) 2013 Calvin Rien * * Based on the JSON parser by Patrick van Bergen * http://techblog.procurios.nl/k/618/news/view/14605/14863/How-do-I-write-my-own-parser-for-JSON.html * * Simplified it so that it doesn't throw exceptions * and can be used in Unity iPhone with maximum code stripping. * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Text; namespace MiniJSON { // Example usage: // // using UnityEngine; // using System.Collections; // using System.Collections.Generic; // using MiniJSON; // // public class MiniJSONTest : MonoBehaviour { // void Start () { // var jsonString = "{ \"array\": [1.44,2,3], " + // "\"object\": {\"key1\":\"value1\", \"key2\":256}, " + // "\"string\": \"The quick brown fox \\\"jumps\\\" over the lazy dog \", " + // "\"unicode\": \"\\u3041 Men\u00fa sesi\u00f3n\", " + // "\"int\": 65536, " + // "\"float\": 3.1415926, " + // "\"bool\": true, " + // "\"null\": null }"; // // var dict = Json.Deserialize(jsonString) as Dictionary<string,object>; // // Debug.Log("deserialized: " + dict.GetType()); // Debug.Log("dict['array'][0]: " + ((List<object>) dict["array"])[0]); // Debug.Log("dict['string']: " + (string) dict["string"]); // Debug.Log("dict['float']: " + (double) dict["float"]); // floats come out as doubles // Debug.Log("dict['int']: " + (long) dict["int"]); // ints come out as longs // Debug.Log("dict['unicode']: " + (string) dict["unicode"]); // // var str = Json.Serialize(dict); // // Debug.Log("serialized: " + str); // } // } /// <summary> /// This class encodes and decodes JSON strings. /// Spec. details, see http://www.json.org/ /// /// JSON uses Arrays and Objects. These correspond here to the datatypes IList and IDictionary. /// All numbers are parsed to doubles. /// </summary> public static class Json { /// <summary> /// Parses the string json into a value /// </summary> /// <param name="json">A JSON string.</param> /// <returns>An List&lt;object&gt;, a Dictionary&lt;string, object&gt;, a double, an integer,a string, null, true, or false</returns> public static object Deserialize(string json) { // save the string for debug information if (json == null) { return null; } return Parser.Parse(json); } sealed class Parser : IDisposable { const string WORD_BREAK = "{}[],:\""; public static bool IsWordBreak(char c) { return Char.IsWhiteSpace(c) || WORD_BREAK.IndexOf(c) != -1; } const string HEX_DIGIT = "0123456789ABCDEFabcdef"; public static bool IsHexDigit(char c) { return HEX_DIGIT.IndexOf(c) != -1; } enum TOKEN { NONE, CURLY_OPEN, CURLY_CLOSE, SQUARED_OPEN, SQUARED_CLOSE, COLON, COMMA, STRING, NUMBER, TRUE, FALSE, NULL }; StringReader json; Parser(string jsonString) { json = new StringReader(jsonString); } public static object Parse(string jsonString) { using (var instance = new Parser(jsonString)) { return instance.ParseValue(); } } public void Dispose() { json.Dispose(); json = null; } Dictionary<string, object> ParseObject() { Dictionary<string, object> table = new Dictionary<string, object>(); // ditch opening brace json.Read(); // { while (true) { switch (NextToken) { case TOKEN.NONE: return null; case TOKEN.COMMA: continue; case TOKEN.CURLY_CLOSE: return table; case TOKEN.STRING: // name string name = ParseString(); if (name == null) { return null; } // : if (NextToken != TOKEN.COLON) { return null; } // ditch the colon json.Read(); // value TOKEN valueToken = NextToken; object value = ParseByToken(valueToken); if(value==null && valueToken!=TOKEN.NULL) return null; table[name] = value; break; default: return null; } } } List<object> ParseArray() { List<object> array = new List<object>(); // ditch opening bracket json.Read(); // [ var parsing = true; while (parsing) { TOKEN nextToken = NextToken; switch (nextToken) { case TOKEN.NONE: return null; case TOKEN.COMMA: continue; case TOKEN.SQUARED_CLOSE: parsing = false; break; default: object value = ParseByToken(nextToken); if(value==null && nextToken!=TOKEN.NULL) return null; array.Add(value); break; } } return array; } object ParseValue() { TOKEN nextToken = NextToken; return ParseByToken(nextToken); } object ParseByToken(TOKEN token) { switch (token) { case TOKEN.STRING: return ParseString(); case TOKEN.NUMBER: return ParseNumber(); case TOKEN.CURLY_OPEN: return ParseObject(); case TOKEN.SQUARED_OPEN: return ParseArray(); case TOKEN.TRUE: return true; case TOKEN.FALSE: return false; case TOKEN.NULL: return null; default: return null; } } string ParseString() { StringBuilder s = new StringBuilder(); char c; // ditch opening quote json.Read(); bool parsing = true; while (parsing) { if (json.Peek() == -1) { parsing = false; break; } c = NextChar; switch (c) { case '"': parsing = false; break; case '\\': if (json.Peek() == -1) { parsing = false; break; } c = NextChar; switch (c) { case '"': case '\\': case '/': s.Append(c); break; case 'b': s.Append('\b'); break; case 'f': s.Append('\f'); break; case 'n': s.Append('\n'); break; case 'r': s.Append('\r'); break; case 't': s.Append('\t'); break; case 'u': var hex = new char[4]; for (int i=0; i< 4; i++) { hex[i] = NextChar; if (!IsHexDigit(hex[i])) return null; } s.Append((char) Convert.ToInt32(new string(hex), 16)); break; } break; default: s.Append(c); break; } } return s.ToString(); } object ParseNumber() { string number = NextWord; if (number.IndexOf('.') == -1 && number.IndexOf('E') == -1 && number.IndexOf('e') == -1) { long parsedInt; Int64.TryParse(number, System.Globalization.NumberStyles.Any, System.Globalization.CultureInfo.InvariantCulture, out parsedInt); return parsedInt; } double parsedDouble; Double.TryParse(number, System.Globalization.NumberStyles.Any, System.Globalization.CultureInfo.InvariantCulture, out parsedDouble); return parsedDouble; } void EatWhitespace() { while (Char.IsWhiteSpace(PeekChar)) { json.Read(); if (json.Peek() == -1) { break; } } } char PeekChar { get { return Convert.ToChar(json.Peek()); } } char NextChar { get { return Convert.ToChar(json.Read()); } } string NextWord { get { StringBuilder word = new StringBuilder(); while (!IsWordBreak(PeekChar)) { word.Append(NextChar); if (json.Peek() == -1) { break; } } return word.ToString(); } } TOKEN NextToken { get { EatWhitespace(); if (json.Peek() == -1) { return TOKEN.NONE; } switch (PeekChar) { case '{': return TOKEN.CURLY_OPEN; case '}': json.Read(); return TOKEN.CURLY_CLOSE; case '[': return TOKEN.SQUARED_OPEN; case ']': json.Read(); return TOKEN.SQUARED_CLOSE; case ',': json.Read(); return TOKEN.COMMA; case '"': return TOKEN.STRING; case ':': return TOKEN.COLON; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case '-': return TOKEN.NUMBER; } switch (NextWord) { case "false": return TOKEN.FALSE; case "true": return TOKEN.TRUE; case "null": return TOKEN.NULL; } return TOKEN.NONE; } } } /// <summary> /// Converts a IDictionary / IList object or a simple type (string, int, etc.) into a JSON string /// </summary> /// <param name="json">A Dictionary&lt;string, object&gt; / List&lt;object&gt;</param> /// <returns>A JSON encoded string, or null if object 'json' is not serializable</returns> public static string Serialize(object obj) { return Serializer.Serialize(obj); } sealed class Serializer { StringBuilder builder; Serializer() { builder = new StringBuilder(); } public static string Serialize(object obj) { var instance = new Serializer(); instance.SerializeValue(obj); return instance.builder.ToString(); } void SerializeValue(object value) { IList asList; IDictionary asDict; string asStr; if (value == null) { builder.Append("null"); } else if ((asStr = value as string) != null) { SerializeString(asStr); } else if (value is bool) { builder.Append((bool) value ? "true" : "false"); } else if ((asList = value as IList) != null) { SerializeArray(asList); } else if ((asDict = value as IDictionary) != null) { SerializeObject(asDict); } else if (value is char) { SerializeString(new string((char) value, 1)); } else { SerializeOther(value); } } void SerializeObject(IDictionary obj) { bool first = true; builder.Append('{'); foreach (object e in obj.Keys) { if (!first) { builder.Append(','); } SerializeString(e.ToString()); builder.Append(':'); SerializeValue(obj[e]); first = false; } builder.Append('}'); } void SerializeArray(IList anArray) { builder.Append('['); bool first = true; for (int i=0; i<anArray.Count; i++) { object obj = anArray[i]; if (!first) { builder.Append(','); } SerializeValue(obj); first = false; } builder.Append(']'); } void SerializeString(string str) { builder.Append('\"'); char[] charArray = str.ToCharArray(); for (int i=0; i<charArray.Length; i++) { char c = charArray[i]; switch (c) { case '"': builder.Append("\\\""); break; case '\\': builder.Append("\\\\"); break; case '\b': builder.Append("\\b"); break; case '\f': builder.Append("\\f"); break; case '\n': builder.Append("\\n"); break; case '\r': builder.Append("\\r"); break; case '\t': builder.Append("\\t"); break; default: int codepoint = Convert.ToInt32(c); if ((codepoint >= 32) && (codepoint <= 126)) { builder.Append(c); } else { builder.Append("\\u"); builder.Append(codepoint.ToString("x4")); } break; } } builder.Append('\"'); } void SerializeOther(object value) { // NOTE: decimals lose precision during serialization. // They always have, I'm just letting you know. // Previously floats and doubles lost precision too. if (value is float) { builder.Append(((float) value).ToString("R", System.Globalization.CultureInfo.InvariantCulture)); } else if (value is int || value is uint || value is long || value is sbyte || value is byte || value is short || value is ushort || value is ulong) { builder.Append(value); } else if (value is double || value is decimal) { builder.Append(Convert.ToDouble(value).ToString("R", System.Globalization.CultureInfo.InvariantCulture)); } else { SerializeString(value.ToString()); } } } } }
34.202128
148
0.392691
[ "Apache-2.0" ]
RichLogan/CiscoSpark-UnityProject
SparkUnity/Assets/Plugins/MiniJSON.cs
19,290
C#
namespace CustomScriptableObjects.Core.Collections { using System; using UnityEngine; [CreateAssetMenu(menuName = MenuPath.COLLECTIONS + "SByte")] [Serializable] public class CollectionSByte : BaseCollection<sbyte> { } }
25.111111
61
0.787611
[ "MIT" ]
cordonez/CustomScriptableObjects
Core/Collections/CollectionSByte.cs
226
C#
using System.Diagnostics; using Sitecore.DataBlaster.Load.Sql; namespace Sitecore.DataBlaster.Load.Processors { public class SyncPublishQueue : ISyncInTransaction { public void Process(BulkLoadContext loadContext, BulkLoadSqlContext sqlContext) { if (!loadContext.UpdatePublishQueue.GetValueOrDefault()) return; if (loadContext.ItemChanges.Count == 0) return; var stopwatch = Stopwatch.StartNew(); var sql = sqlContext.GetEmbeddedSql(loadContext, "Sql.10.UpdatePublishQueue.sql"); sqlContext.ExecuteSql(sql, commandProcessor: cmd => cmd.Parameters.AddWithValue("@UserName", Sitecore.Context.User.Name)); loadContext.Log.Info($"Updated publish queue: {(int)stopwatch.Elapsed.TotalSeconds}s"); } } }
37.545455
111
0.682809
[ "MIT" ]
Elyseum/sitecore-data-blaster
src/Sitecore.DataBlaster/Load/Processors/SyncPublishQueue.cs
828
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Data.API.Interfaces.DO; namespace Data.DO { public class Translation : ITranslation { public long ID { get; set; } public String Source { get; set; } public Dictionary<String, String> Results { get; set;} public IEnumerable<String> Rejected { get; set;} public IEnumerable<String> Unknowns { get; set;} public DateTime Created { get; set;} } }
24.95
62
0.655311
[ "MIT" ]
SwiftAusterity/BuzzMyResume
Data/DO/Translation.cs
501
C#
namespace Schema.NET { using System; using System.Runtime.Serialization; using Newtonsoft.Json; /// <summary> /// This type covers computer programming languages such as Scheme and Lisp, as well as other language-like computer representations. Natural languages are best represented with the &lt;a class="localLink" href="http://schema.org/Language"&gt;Language&lt;/a&gt; type. /// </summary> public partial interface IComputerLanguage : IIntangible { } /// <summary> /// This type covers computer programming languages such as Scheme and Lisp, as well as other language-like computer representations. Natural languages are best represented with the &lt;a class="localLink" href="http://schema.org/Language"&gt;Language&lt;/a&gt; type. /// </summary> [DataContract] public partial class ComputerLanguage : Intangible, IComputerLanguage, IEquatable<ComputerLanguage> { /// <summary> /// Gets the name of the type as specified by schema.org. /// </summary> [DataMember(Name = "@type", Order = 1)] public override string Type => "ComputerLanguage"; /// <inheritdoc/> public bool Equals(ComputerLanguage other) { if (other is null) { return false; } if (ReferenceEquals(this, other)) { return true; } return this.Type == other.Type && base.Equals(other); } /// <inheritdoc/> public override bool Equals(object obj) => this.Equals(obj as ComputerLanguage); /// <inheritdoc/> public override int GetHashCode() => HashCode.Of(this.Type) .And(base.GetHashCode()); } }
35.882353
272
0.596175
[ "MIT" ]
csdecrypt/Schema.NET
Source/Schema.NET/core/ComputerLanguage.cs
1,832
C#
namespace Community.CsharpSqlite { using System.Diagnostics; using System.IO; using System.Text; using Bitmask = System.UInt64; using FILE = System.IO.TextWriter; using i16 = System.Int16; using i32 = System.Int32; using i64 = System.Int64; using u8 = System.Byte; using u16 = System.UInt16; using u32 = System.UInt32; using u64 = System.UInt64; using Pgno = System.UInt32; #if !SQLITE_MAX_VARIABLE_NUMBER using ynVar = System.Int16; #else using ynVar = System.Int32; #endif /* ** The yDbMask datatype for the bitmask of all attached databases. */ #if SQLITE_MAX_ATTACHED//>30 // typedef sqlite3_uint64 yDbMask; using yDbMask = System.Int64; #else // typedef unsigned int yDbMask; using yDbMask = System.Int32; #endif /* ** An instance of the following structure holds all information about a ** WHERE clause. Mostly this is a container for one or more WhereTerms. */ public class WhereClause { public Parse pParse; /* The parser context */ public WhereMaskSet pMaskSet; /* Mapping of table cursor numbers to bitmasks */ public Bitmask vmask; /* Bitmask identifying virtual table cursors */ public u8 op; /* Split operator. TK_AND or TK_OR */ public int nTerm; /* Number of terms */ public int nSlot; /* Number of entries in a[] */ public WhereTerm[] a; /* Each a[] describes a term of the WHERE cluase */ #if (SQLITE_SMALL_STACK) public WhereTerm[] aStatic = new WhereTerm[1]; /* Initial static space for a[] */ #else public WhereTerm[] aStatic = new WhereTerm[8]; /* Initial static space for a[] */ #endif public void CopyTo( WhereClause wc ) { wc.pParse = this.pParse; wc.pMaskSet = new WhereMaskSet(); this.pMaskSet.CopyTo( wc.pMaskSet ); wc.op = this.op; wc.nTerm = this.nTerm; wc.nSlot = this.nSlot; wc.a = (WhereTerm[])this.a.Clone(); wc.aStatic = (WhereTerm[])this.aStatic.Clone(); } }; }
35.449275
110
0.540474
[ "MIT" ]
ArsenShnurkov/csharp-sqlite
Community.CsharpSqlite/src/parsing/WhereClause.cs
2,448
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Native.Csharp.App.Gameplay.AbstractTool; using Native.Csharp.App.UserInteract; namespace Native.Csharp.App.Gameplay.CharacterUtil.Skills { public abstract class Skill : IElement { public Character Owner { get; internal set; } public int SkillLevel { get; protected internal set; } public bool IsClassSkill { get; protected internal set; } public string InternalName { get; set; } public LocaleKey DisplayName { get; set; } public LocaleKey Description { get; set; } /// <summary> /// 获取升级至下一等级的技能点需求 /// 如果无法再升级,返回-1 /// </summary> /// <returns>下一等级的技能点需求</returns> public int GetNextLevelCost() { int HD = Owner.Properties.HealthDices; int maxSkillLevel = IsClassSkill ? HD : HD + 3; if (SkillLevel < maxSkillLevel) return (IsClassSkill && (SkillLevel < 3)) ? 0 : 1; return -1; } public bool Check(int DC, bool is20AutoSuccess = false) { int result = Plugin.Values.GetDice("1d20").GetResult().IntResult; if (is20AutoSuccess && (result == 20)) return true; return (result + GetTotalModifier()) >= DC; } public bool Check10(int DC) { return (10 + GetTotalModifier()) >= DC; } public bool Check20(int DC) { return (20 + GetTotalModifier()) >= DC; } //先别着急 public abstract int GetTotalModifier(); } }
28.508475
77
0.577883
[ "MIT" ]
apflu/DungeonBot
Native.Csharp/App/Gameplay/CharacterUtil/Skills/Skill.cs
1,762
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. using Microsoft.Azure.Management.Compute.Fluent.Models; using Microsoft.Azure.Management.Graph.RBAC.Fluent; using Microsoft.Azure.Management.Msi.Fluent; using Microsoft.Azure.Management.Network.Fluent; using Microsoft.Azure.Management.ResourceManager.Fluent; using Microsoft.Azure.Management.ResourceManager.Fluent.Core; using Microsoft.Azure.Management.ResourceManager.Fluent.Core.ResourceActions; using Microsoft.Azure.Management.Storage.Fluent; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.Serialization.Json; using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using Newtonsoft.Json.Linq; using Extensions = Microsoft.Azure.Management.ResourceManager.Fluent.Core.Extensions; namespace Microsoft.Azure.Management.Compute.Fluent { /// <summary> /// The implementation for VirtualMachine and its create and update interfaces. /// </summary> ///GENTHASH:Y29tLm1pY3Jvc29mdC5henVyZS5tYW5hZ2VtZW50LmNvbXB1dGUuaW1wbGVtZW50YXRpb24uVmlydHVhbE1hY2hpbmVJbXBs internal partial class VirtualMachineImpl : GroupableResource<IVirtualMachine, VirtualMachineInner, VirtualMachineImpl, IComputeManager, VirtualMachine.Definition.IWithGroup, VirtualMachine.Definition.IWithNetwork, VirtualMachine.Definition.IWithCreate, VirtualMachine.Update.IUpdate>, IVirtualMachine, VirtualMachine.DefinitionManagedOrUnmanaged.IDefinitionManagedOrUnmanaged, VirtualMachine.DefinitionManaged.IDefinitionManaged, VirtualMachine.DefinitionUnmanaged.IDefinitionUnmanaged, VirtualMachine.Update.IUpdate, VirtualMachine.Definition.IWithSystemAssignedIdentityBasedAccessOrCreate, VirtualMachine.Update.IWithSystemAssignedIdentityBasedAccessOrUpdate { private readonly IStorageManager storageManager; private readonly INetworkManager networkManager; private readonly string vmName; // used to generate unique name for any dependency resources private readonly IResourceNamer namer; // unique key of a creatable storage account to be used for virtual machine child resources that // requires storage [OS disk, data disk etc..] requires storage [OS disk, data disk, boot diagnostics etc..] private string creatableStorageAccountKey; // unique key of a creatable availability set that this virtual machine to put private string creatableAvailabilitySetKey; // unique key of a creatable network interface that needs to be used as virtual machine's primary network interface private string creatablePrimaryNetworkInterfaceKey; // unique key of a creatable network interfaces that needs to be used as virtual machine's secondary network interface private IList<string> creatableSecondaryNetworkInterfaceKeys; // reference to an existing storage account to be used for virtual machine child resources that // requires storage [OS disk, data disk, boot diagnostics etc..] private IStorageAccount existingStorageAccountToAssociate; // reference to an existing availability set that this virtual machine to put private IAvailabilitySet existingAvailabilitySetToAssociate; // reference to an existing network interface that needs to be used as virtual machine's primary network interface private INetworkInterface existingPrimaryNetworkInterfaceToAssociate; // reference to a list of existing network interfaces that needs to be used as virtual machine's secondary network interface private IList<INetworkInterface> existingSecondaryNetworkInterfacesToAssociate; private VirtualMachineInstanceView virtualMachineInstanceView; private bool isMarketplaceLinuxImage; // Intermediate state of network interface definition to which private IP can be associated private Network.Fluent.NetworkInterface.Definition.IWithPrimaryPrivateIP nicDefinitionWithPrivateIP; // Intermediate state of network interface definition to which subnet can be associated private Network.Fluent.NetworkInterface.Definition.IWithPrimaryNetworkSubnet nicDefinitionWithSubnet; // Intermediate state of network interface definition to which public IP can be associated private Network.Fluent.NetworkInterface.Definition.IWithCreate nicDefinitionWithCreate; // The entry point to manage extensions associated with the virtual machine private VirtualMachineExtensionsImpl virtualMachineExtensions; // Flag indicates native disk is selected for OS and Data disks private bool isUnmanagedDiskSelected; // The native data disks associated with the virtual machine private IList<IVirtualMachineUnmanagedDataDisk> unmanagedDataDisks; // To track the managed data disks private ManagedDataDiskCollection managedDataDisks; // unique key of a creatable storage account to be used for boot diagnostics private string creatableDiagnosticsStorageAccountKey; // Utility to setup MSI for the virtual machine private VirtualMachineMsiHelper virtualMachineMsiHelper; // Reference to the PublicIp creatable that is implicitly created private Network.Fluent.PublicIPAddress.Definition.IWithCreate implicitPipCreatable; // Name of the new proximity placement group private String newProximityPlacementGroupName; // Type fo the new proximity placement group private ProximityPlacementGroupType newProximityPlacementGroupType; ///GENMHASH:0A331C2401291DF824493E64F2798884:D3B04C536032C2BDC056A8F85225875E internal VirtualMachineImpl( string name, VirtualMachineInner innerModel, IComputeManager computeManager, IStorageManager storageManager, INetworkManager networkManager, IGraphRbacManager rbacManager) : base(name, innerModel, computeManager) { this.storageManager = storageManager; this.networkManager = networkManager; this.vmName = name; this.isMarketplaceLinuxImage = false; this.namer = SdkContext.CreateResourceNamer(this.vmName); this.creatableSecondaryNetworkInterfaceKeys = new List<string>(); this.existingSecondaryNetworkInterfacesToAssociate = new List<INetworkInterface>(); InitializeExtensions(); this.managedDataDisks = new ManagedDataDiskCollection(this); InitializeDataDisks(); this.virtualMachineMsiHelper = new VirtualMachineMsiHelper(rbacManager, this); newProximityPlacementGroupName = null; newProximityPlacementGroupType = null; } public VirtualMachineImpl WithLicenseType(string licenseType) { this.Inner.LicenseType = licenseType; return this; } public VirtualMachineImpl WithoutSystemAssignedManagedServiceIdentity() { this.virtualMachineMsiHelper.WithoutLocalManagedServiceIdentity(); return this; } public RunCommandResultInner RunCommand(RunCommandInput inputCommand) { return Extensions.Synchronize(() => this.RunCommandAsync(inputCommand)); } public async Task<Models.RunCommandResultInner> RunCommandAsync(RunCommandInput inputCommand, CancellationToken cancellationToken = default(CancellationToken)) { return await this.Manager.VirtualMachines.RunCommandAsync(this.ResourceGroupName, this.Name, inputCommand, cancellationToken); } public RunCommandResultInner RunPowerShellScript(IList<string> scriptLines, IList<Models.RunCommandInputParameter> scriptParameters) { return Extensions.Synchronize(() => RunPowerShellScriptAsync(scriptLines, scriptParameters)); } public async Task<Models.RunCommandResultInner> RunPowerShellScriptAsync(IList<string> scriptLines, IList<Models.RunCommandInputParameter> scriptParameters, CancellationToken cancellationToken = default(CancellationToken)) { return await this.Manager.VirtualMachines.RunPowerShellScriptAsync(this.ResourceGroupName, this.Name, scriptLines, scriptParameters, cancellationToken); } public RunCommandResultInner RunShellScript(IList<string> scriptLines, IList<Models.RunCommandInputParameter> scriptParameters) { return Extensions.Synchronize(() => RunShellScriptAsync(scriptLines, scriptParameters)); } public async Task<Models.RunCommandResultInner> RunShellScriptAsync(IList<string> scriptLines, IList<Models.RunCommandInputParameter> scriptParameters, CancellationToken cancellationToken = default(CancellationToken)) { return await this.Manager.VirtualMachines.RunShellScriptAsync(this.ResourceGroupName, this.Name, scriptLines, scriptParameters, cancellationToken); } ///GENMHASH:BC4103A90A606609FAB346997701A4DE:F96317098E1E2EA0D5CD8D759145745A public ResourceIdentityType? ManagedServiceIdentityType() { return VirtualMachineMsiHelper.ManagedServiceIdentityType(this.Inner); } ///GENMHASH:4002186478A1CB0B59732EBFB18DEB3A:4C74CDEFBB89F8ADB720DB2B740C1AB3 public override async Task<IVirtualMachine> RefreshAsync(CancellationToken cancellationToken = default(CancellationToken)) { var response = await GetInnerAsync(cancellationToken); SetInner(response); ClearCachedRelatedResources(); InitializeDataDisks(); virtualMachineExtensions.Refresh(); return this; } protected override async Task<VirtualMachineInner> GetInnerAsync(CancellationToken cancellationToken) { return await Manager.Inner.VirtualMachines.GetAsync(ResourceGroupName, Name, cancellationToken: cancellationToken); } ///GENMHASH:667E734583F577A898C6389A3D9F4C09:B1A3725E3B60B26D7F37CA7ABFE371B0 public void Deallocate() { Extensions.Synchronize(() => Manager.Inner.VirtualMachines.DeallocateAsync(this.ResourceGroupName, this.Name)); } public async Task DeallocateAsync(CancellationToken cancellationToken = default(CancellationToken)) { await Manager.Inner.VirtualMachines.DeallocateAsync(this.ResourceGroupName, this.Name, cancellationToken); await RefreshAsync(cancellationToken); } ///GENMHASH:F5949CB4AFA8DD0B8DED0F369B12A8F6:6AC69BE8BE090CDE9822C84DD5F906F3 public VirtualMachineInstanceView RefreshInstanceView() { return Extensions.Synchronize(() => RefreshInstanceViewAsync()); } ///GENMHASH:D97B6272C7E7717C00D4F9B818A713C0:8DD09B90F0555BB3E1AEF7B9AF044379 public async Task<Models.VirtualMachineInstanceView> RefreshInstanceViewAsync(CancellationToken cancellationToken = default(CancellationToken)) { var virtualMachineInner = await this.Manager.Inner.VirtualMachines.GetAsync(this.ResourceGroupName, this.Name, InstanceViewTypes.InstanceView, cancellationToken); this.virtualMachineInstanceView = new VirtualMachineInstanceView( virtualMachineInner.InstanceView.PlatformFaultDomain, virtualMachineInner.InstanceView.PlatformUpdateDomain, virtualMachineInner.InstanceView.ComputerName, virtualMachineInner.InstanceView.OsName, virtualMachineInner.InstanceView.OsVersion, virtualMachineInner.InstanceView.HyperVGeneration, virtualMachineInner.InstanceView.RdpThumbPrint, virtualMachineInner.InstanceView.VmAgent, virtualMachineInner.InstanceView.MaintenanceRedeployStatus, virtualMachineInner.InstanceView.Disks, virtualMachineInner.InstanceView.Extensions, virtualMachineInner.InstanceView.VmHealth, virtualMachineInner.InstanceView.BootDiagnostics, virtualMachineInner.InstanceView.AssignedHost, virtualMachineInner.InstanceView.Statuses, virtualMachineInner.InstanceView.PatchStatus); return this.virtualMachineInstanceView; } ///GENMHASH:0745971EF3F2CE7276C7E535722C5E6C:F7A7B3A36B61441CF0850BDE432A2805 public void Generalize() { Extensions.Synchronize(() => Manager.Inner.VirtualMachines.GeneralizeAsync(this.ResourceGroupName, this.Name)); } public async Task GeneralizeAsync(CancellationToken cancellationToken = default(CancellationToken)) { await Manager.Inner.VirtualMachines.GeneralizeAsync(this.ResourceGroupName, this.Name, cancellationToken); } ///GENMHASH:8761D0D225B7C49A7A5025186E94B263:21AAF0008CE6CF3F9846F2DFE1CBEBCB public void PowerOff(bool skipShutdown) { Extensions.Synchronize(() => Manager.Inner.VirtualMachines.PowerOffAsync(this.ResourceGroupName, this.Name, skipShutdown)); } public async Task PowerOffAsync(bool skipShutdown, CancellationToken cancellationToken = default(CancellationToken)) { await Manager.Inner.VirtualMachines.PowerOffAsync(this.ResourceGroupName, this.Name, skipShutdown, cancellationToken); } ///GENMHASH:08CFC096AC6388D1C0E041ECDF099E3D:4479808A1E2B2A23538E662AD3F721EE public void Restart() { Extensions.Synchronize(() => Manager.Inner.VirtualMachines.RestartAsync(this.ResourceGroupName, this.Name)); } public async Task RestartAsync(CancellationToken cancellationToken = default(CancellationToken)) { await Manager.Inner.VirtualMachines.RestartAsync(this.ResourceGroupName, this.Name, cancellationToken); } ///GENMHASH:0F38250A3837DF9C2C345D4A038B654B:5723E041D4826DFBE50B8B49C31EAF08 public void Start() { Extensions.Synchronize(() => Manager.Inner.VirtualMachines.StartAsync(this.ResourceGroupName, this.Name)); } public async Task StartAsync(CancellationToken cancellationToken = default(CancellationToken)) { await Manager.Inner.VirtualMachines.StartAsync(this.ResourceGroupName, this.Name, cancellationToken); } public void Reimage(bool? tempDisk = default(bool?)) { Extensions.Synchronize(() => Manager.Inner.VirtualMachines.ReimageAsync(this.ResourceGroupName, this.Name, tempDisk)); } public async Task ReimageAsync(bool? tempDisk = default(bool?), CancellationToken cancellationToken = default(CancellationToken)) { await Manager.Inner.VirtualMachines.ReimageAsync(this.ResourceGroupName, this.Name, tempDisk, cancellationToken); } ///GENMHASH:D9EB75AF88B1A07EDC0965B26A7F7C04:E30F1E083D68AA7A68C7128405BA3741 public void Redeploy() { Extensions.Synchronize(() => Manager.Inner.VirtualMachines.RedeployAsync(this.ResourceGroupName, this.Name)); } public async Task RedeployAsync(CancellationToken cancellationToken = default(CancellationToken)) { await Manager.Inner.VirtualMachines.RedeployAsync(this.ResourceGroupName, this.Name, cancellationToken); } ///GENMHASH:BF8CE5C594210A476EF389DC52B15805:2795B67DFA718D9C0FFC69E152857591 public void ConvertToManaged() { Extensions.Synchronize(() => this.ConvertToManagedAsync()); } ///GENMHASH:BE99BB2DEA25942BB991922E902344B7:BB9B58DA6D2DB651B79BA46AE181759B public async Task ConvertToManagedAsync(CancellationToken cancellationToken = default(CancellationToken)) { await Manager.Inner.VirtualMachines.ConvertToManagedDisksAsync(this.ResourceGroupName, this.Name, cancellationToken); await this.RefreshAsync(cancellationToken); } ///GENMHASH:842FBE4DCB8BFE1B50632DBBE157AEA8:B5262187B60CE486998F800E9A96B659 public IEnumerable<Microsoft.Azure.Management.Compute.Fluent.IVirtualMachineSize> AvailableSizes() { return Extensions.Synchronize(() => Manager.Inner.VirtualMachines.ListAvailableSizesAsync(this.ResourceGroupName, this.Name)) .Select(inner => new VirtualMachineSizeImpl(inner)); } ///GENMHASH:1F383B6B989059B78D6ECB949E789CD4:D3D812C91301FB29508197FA8534CDDC public string Capture(string containerName, string vhdPrefix, bool overwriteVhd) { return Extensions.Synchronize(() => this.CaptureAsync(containerName, vhdPrefix, overwriteVhd)); } ///GENMHASH:C345130B595C0FF585A57651EFDC3A0F:E97CAC99D13041F7FEAACC7E4508DC7B public async Task<string> CaptureAsync(string containerName, string vhdPrefix, bool overwriteVhd, CancellationToken cancellationToken = default(CancellationToken)) { VirtualMachineCaptureParameters parameters = new VirtualMachineCaptureParameters(); parameters.DestinationContainerName = containerName; parameters.OverwriteVhds = overwriteVhd; parameters.VhdPrefix = vhdPrefix; using (var _result = await ((VirtualMachinesOperations)Manager.Inner.VirtualMachines).CaptureWithHttpMessagesAsync(ResourceGroupName, vmName, parameters, null, cancellationToken).ConfigureAwait(false)) { var content = await _result.Response.Content.ReadAsStringAsync().ConfigureAwait(false); return content; } } ///GENMHASH:3FAB18211D6DAAAEF5CA426426D16F0C:AD7170076BCB5437E69B77AC63B3373E public VirtualMachineImpl WithNewPrimaryNetwork(ICreatable<Microsoft.Azure.Management.Network.Fluent.INetwork> creatable) { this.nicDefinitionWithPrivateIP = this.PreparePrimaryNetworkInterface(this.namer.RandomName("nic", 20)) .WithNewPrimaryNetwork(creatable); return this; } ///GENMHASH:C8A4DDE66256242DF61087375BF710B0:BE10050EE1789706DD7774B3C47BE916 public VirtualMachineImpl WithNewPrimaryNetwork(string addressSpace) { this.nicDefinitionWithPrivateIP = this.PreparePrimaryNetworkInterface(this.namer.RandomName("nic", 20)) .WithNewPrimaryNetwork(addressSpace); return this; } ///GENMHASH:EE2847D8AC43E9B7C3BFB967F80560D4:A3EFBF1BD0F4CAB5595668104129F2F4 public VirtualMachineImpl WithExistingPrimaryNetwork(INetwork network) { this.nicDefinitionWithSubnet = this.PreparePrimaryNetworkInterface(this.namer.RandomName("nic", 20)) .WithExistingPrimaryNetwork(network); return this; } ///GENMHASH:0FBBECB150CBC82F165D8BA614AB135A:D0002A3AE79C25026E85606A72066F48 public VirtualMachineImpl WithSubnet(string name) { this.nicDefinitionWithPrivateIP = this.nicDefinitionWithSubnet .WithSubnet(name); return this; } ///GENMHASH:022FCEBED3C6606D834C45EAD65C0D6F:29E2281B1650F8D65A367942B42B75EF public VirtualMachineImpl WithPrimaryPrivateIPAddressDynamic() { this.nicDefinitionWithCreate = this.nicDefinitionWithPrivateIP .WithPrimaryPrivateIPAddressDynamic(); return this; } ///GENMHASH:655D6F837286729FEB47BD78B3EB9A08:D2502E1AE46296B5C8F75C71F9B84C27 public VirtualMachineImpl WithPrimaryPrivateIPAddressStatic(string staticPrivateIPAddress) { this.nicDefinitionWithCreate = this.nicDefinitionWithPrivateIP .WithPrimaryPrivateIPAddressStatic(staticPrivateIPAddress); return this; } ///GENMHASH:54B52B6B32A26AD456CFB5E00BE4A7E1:A19C73689F2772054260CA742BE6FC13 public async Task<IReadOnlyList<Microsoft.Azure.Management.Compute.Fluent.IVirtualMachineExtension>> ListExtensionsAsync(CancellationToken cancellationToken = default(CancellationToken)) { return await this.virtualMachineExtensions.ListAsync(cancellationToken); } ///GENMHASH:979FFAEA86882618784D4077FB80332F:B79EEB6C251B19AEB675FFF7A365C818 public IReadOnlyDictionary<string, Microsoft.Azure.Management.Compute.Fluent.IVirtualMachineExtension> ListExtensions() { return this.virtualMachineExtensions.AsMap(); } ///GENMHASH:12E96FEFBC60AB582A0B69EBEEFD1E59:C1EAF0B5EE0258D48F9956AEFBA1EA2D public VirtualMachineImpl WithNewPrimaryPublicIPAddress(ICreatable<Microsoft.Azure.Management.Network.Fluent.IPublicIPAddress> creatable) { var nicCreatable = this.nicDefinitionWithCreate .WithNewPrimaryPublicIPAddress(creatable); this.creatablePrimaryNetworkInterfaceKey = nicCreatable.Key; this.AddCreatableDependency(nicCreatable as IResourceCreator<IHasId>); return this; } ///GENMHASH:493C4B7BDF89C914E95EEE1D0DE7160E:822C2C149045D9889CBFE50421B57410 public VirtualMachineImpl WithNewPrimaryPublicIPAddress(string leafDnsLabel) { Network.Fluent.PublicIPAddress.Definition.IWithGroup definitionWithGroup = this.networkManager.PublicIPAddresses .Define(this.namer.RandomName("pip", 15)) .WithRegion(this.RegionName); Network.Fluent.PublicIPAddress.Definition.IWithCreate definitionAfterGroup; if (this.newGroup != null) { definitionAfterGroup = definitionWithGroup.WithNewResourceGroup(this.newGroup); } else { definitionAfterGroup = definitionWithGroup.WithExistingResourceGroup(this.ResourceGroupName); } this.implicitPipCreatable = definitionAfterGroup.WithLeafDomainLabel(leafDnsLabel); // Create NIC with creatable PIP // var nicCreatable = this.nicDefinitionWithCreate .WithNewPrimaryPublicIPAddress(this.implicitPipCreatable); this.creatablePrimaryNetworkInterfaceKey = nicCreatable.Key; this.AddCreatableDependency(nicCreatable as IResourceCreator<IHasId>); return this; } ///GENMHASH:2B7C2F1E86A359473717299AD4D4DCBA:2EE2D29B7C228132508D27F040A79175 public VirtualMachineImpl WithExistingPrimaryPublicIPAddress(IPublicIPAddress publicIPAddress) { var nicCreatable = this.nicDefinitionWithCreate .WithExistingPrimaryPublicIPAddress(publicIPAddress); this.creatablePrimaryNetworkInterfaceKey = nicCreatable.Key; this.AddCreatableDependency(nicCreatable as IResourceCreator<IHasId>); return this; } ///GENMHASH:D0AB91F51DBDFA04880ED371AD9E48EE:8727C9A4820EB72700E55883936D2638 public VirtualMachineImpl WithoutPrimaryPublicIPAddress() { var nicCreatable = this.nicDefinitionWithCreate; this.creatablePrimaryNetworkInterfaceKey = nicCreatable.Key; this.AddCreatableDependency(nicCreatable as IResourceCreator<IHasId>); return this; } ///GENMHASH:6C6E9480071A571B23369210C67E4329:BAD887D9D5A633B4D6DE3058819C017C public VirtualMachineImpl WithNewPrimaryNetworkInterface(ICreatable<Microsoft.Azure.Management.Network.Fluent.INetworkInterface> creatable) { this.creatablePrimaryNetworkInterfaceKey = creatable.Key; this.AddCreatableDependency(creatable as IResourceCreator<IHasId>); return this; } ///GENMHASH:ADDFF59E01604BE661F6CB8C83CD4B0F:2125FE20491BB581219A9D8E245DECB9 public VirtualMachineImpl WithNewPrimaryNetworkInterface(string name, string publicDnsNameLabel) { var definitionCreatable = PrepareNetworkInterface(name) .WithNewPrimaryPublicIPAddress(publicDnsNameLabel); return WithNewPrimaryNetworkInterface(definitionCreatable); } ///GENMHASH:CBAE11E07A4D8591E942E289CE471B4E:541A4F4628D59C210D53444D29D4557B public VirtualMachineImpl WithExistingPrimaryNetworkInterface(INetworkInterface networkInterface) { this.existingPrimaryNetworkInterfaceToAssociate = networkInterface; return this; } ///GENMHASH:0B0B068704882D0210B822A215F5536D:D1A7C8363353BBD6CD981B3F2D3565F3 public VirtualMachineImpl WithStoredWindowsImage(string imageUrl) { VirtualHardDisk userImageVhd = new VirtualHardDisk(); userImageVhd.Uri = imageUrl; Inner.StorageProfile.OsDisk.CreateOption = DiskCreateOptionTypes.FromImage; Inner.StorageProfile.OsDisk.Image = userImageVhd; // For platform image osType will be null, azure will pick it from the image metadata. Inner.StorageProfile.OsDisk.OsType = OperatingSystemTypes.Windows; Inner.OsProfile.WindowsConfiguration = new WindowsConfiguration(); // sets defaults for "Stored(User)Image" or "VM(Platform)Image" Inner.OsProfile.WindowsConfiguration.ProvisionVMAgent = true; Inner.OsProfile.WindowsConfiguration.EnableAutomaticUpdates = true; return this; } ///GENMHASH:976BC0FCB9812014FA27474FCF6A694F:8E0FB1EEED9F15976FCF3F34580897D3 public VirtualMachineImpl WithStoredLinuxImage(string imageUrl) { VirtualHardDisk userImageVhd = new VirtualHardDisk(); userImageVhd.Uri = imageUrl; Inner.StorageProfile.OsDisk.CreateOption = DiskCreateOptionTypes.FromImage; Inner.StorageProfile.OsDisk.Image = userImageVhd; // For platform | custom image osType will be null, azure will pick it from the image metadata. // But for stored image, osType needs to be specified explicitly // Inner.StorageProfile.OsDisk.OsType = OperatingSystemTypes.Linux; Inner.OsProfile.LinuxConfiguration = new LinuxConfiguration(); return this; } ///GENMHASH:8FDBCB5DF6AFD1594DF170521CE46D5F:4DF21C8BC272D1C368C4F1F79237B3D0 public VirtualMachineImpl WithPopularWindowsImage(KnownWindowsVirtualMachineImage knownImage) { return WithSpecificWindowsImageVersion(knownImage.ImageReference()); } ///GENMHASH:9177073080371FB82A479834DA14F493:CB0A5903865A994CFC26F01586B9FD22 public VirtualMachineImpl WithPopularLinuxImage(KnownLinuxVirtualMachineImage knownImage) { return WithSpecificLinuxImageVersion(knownImage.ImageReference()); } ///GENMHASH:4A7665D6C5D507E115A9A8E551801DB6:AD810F1DA749F7286A899D037376A9E3 public VirtualMachineImpl WithSpecificWindowsImageVersion(ImageReference imageReference) { Inner.StorageProfile.OsDisk.CreateOption = DiskCreateOptionTypes.FromImage; Inner.StorageProfile.ImageReference = imageReference.Inner; Inner.OsProfile.WindowsConfiguration = new WindowsConfiguration(); // sets defaults for "Stored(User)Image" or "VM(Platform)Image" Inner.OsProfile.WindowsConfiguration.ProvisionVMAgent = true; Inner.OsProfile.WindowsConfiguration.EnableAutomaticUpdates = true; return this; } ///GENMHASH:B2876749E60D892750D75C97943BBB13:23C60ED2B7F40C8320F1091338191A7F public VirtualMachineImpl WithSpecificLinuxImageVersion(ImageReference imageReference) { Inner.StorageProfile.OsDisk.CreateOption = DiskCreateOptionTypes.FromImage; Inner.StorageProfile.ImageReference = imageReference.Inner; Inner.OsProfile.LinuxConfiguration = new LinuxConfiguration(); this.isMarketplaceLinuxImage = true; return this; } ///GENMHASH:3874257232804C74BD7501DE2BE2F0E9:742DE46D93113DBA276B0A311D52D664 public VirtualMachineImpl WithLatestWindowsImage(string publisher, string offer, string sku) { ImageReference imageReference = new ImageReference(); imageReference.Publisher = publisher; imageReference.Offer = offer; imageReference.Sku = sku; imageReference.Version = "latest"; return WithSpecificWindowsImageVersion(imageReference); } ///GENMHASH:6D51A334B57DF882E890FEBA9887BE77:3A21A7EF50A9FC7A93D7C8AEFA8F3130 public VirtualMachineImpl WithLatestLinuxImage(string publisher, string offer, string sku) { ImageReference imageReference = new ImageReference(); imageReference.Publisher = publisher; imageReference.Offer = offer; imageReference.Sku = sku; imageReference.Version = "latest"; return WithSpecificLinuxImageVersion(imageReference); } ///GENMHASH:F24EFD30F0D04113B41EA2C36B55F059:944E1D0765AA783776E77434132D18AA public VirtualMachineImpl WithWindowsCustomImage(string customImageId) { ImageReferenceInner imageReferenceInner = new ImageReferenceInner(); imageReferenceInner.Id = customImageId; Inner.StorageProfile.OsDisk.CreateOption = DiskCreateOptionTypes.FromImage; Inner.StorageProfile.ImageReference = imageReferenceInner; Inner.OsProfile.WindowsConfiguration = new WindowsConfiguration(); // sets defaults for "Stored(User)Image", "VM(Platform | Custom)Image" Inner.OsProfile.WindowsConfiguration.ProvisionVMAgent = true; Inner.OsProfile.WindowsConfiguration.EnableAutomaticUpdates = true; return this; } ///GENMHASH:C1CAA1ACCAE5C80BBC73F38DBB8A24DB:A5BEB46443374AE5FC100EE84133951F public VirtualMachineImpl WithWindowsGalleryImageVersion(string galleryImageVersionId) { return this.WithWindowsCustomImage(galleryImageVersionId); } ///GENMHASH:CE03CDBD07CA3BD7500B36B206A91A4A:5BEEBF6F7B101075BFFD1089DC6B2D0F public VirtualMachineImpl WithLinuxCustomImage(string customImageId) { ImageReferenceInner imageReferenceInner = new ImageReferenceInner(); imageReferenceInner.Id = customImageId; Inner.StorageProfile.OsDisk.CreateOption = DiskCreateOptionTypes.FromImage; Inner.StorageProfile.ImageReference = imageReferenceInner; Inner.OsProfile.LinuxConfiguration = new LinuxConfiguration(); this.isMarketplaceLinuxImage = true; return this; } ///GENMHASH:2B8B909D235B7D7AC3C105F6B606E684:7BC43BF2B183D2EF2284A56184ECD541 public VirtualMachineImpl WithLinuxGalleryImageVersion(string galleryImageVersionId) { return this.WithLinuxCustomImage(galleryImageVersionId); } ///GENMHASH:57A0D9F7821CCF113A2473B139EA6535:A5202C2E2CECEF8345A7B13AA2F45579 public VirtualMachineImpl WithSpecializedOSUnmanagedDisk(string osDiskUrl, OperatingSystemTypes osType) { VirtualHardDisk osVhd = new VirtualHardDisk(); osVhd.Uri = osDiskUrl; Inner.StorageProfile.OsDisk.CreateOption = DiskCreateOptionTypes.Attach; Inner.StorageProfile.OsDisk.Vhd = osVhd; Inner.StorageProfile.OsDisk.OsType = osType; Inner.StorageProfile.OsDisk.ManagedDisk = null; return this; } ///GENMHASH:1F74902637AB57C68DF7BEB69565D69F:E405AA329DD9CF5E18080043D36F5E0A public VirtualMachineImpl WithSpecializedOSDisk(IDisk disk, OperatingSystemTypes osType) { ManagedDiskParametersInner diskParametersInner = new ManagedDiskParametersInner(); diskParametersInner.Id = disk.Id; Inner.StorageProfile.OsDisk.CreateOption = DiskCreateOptionTypes.Attach; Inner.StorageProfile.OsDisk.ManagedDisk = diskParametersInner; Inner.StorageProfile.OsDisk.OsType = osType; Inner.StorageProfile.OsDisk.Vhd = null; return this; } ///GENMHASH:D5F141800B409906045662B0DD536DE4:E70AA61215804A9BAB05750F6C16BA9D public VirtualMachineImpl WithRootUsername(string rootUsername) { Inner.OsProfile.AdminUsername = rootUsername; return this; } ///GENMHASH:0E3F9BC2C5C0DB936DBA634A972BC916:8D59AD6440CA44B929F3A1907924F5BC public VirtualMachineImpl WithAdminUsername(string adminUsername) { Inner.OsProfile.AdminUsername = adminUsername; return this; } ///GENMHASH:9BBA27913235B4504FD9F07549E645CC:7C9396228419D56BC31B8BC248BB451A public VirtualMachineImpl WithSsh(string publicKeyData) { OSProfile osProfile = Inner.OsProfile; if (osProfile.LinuxConfiguration.Ssh == null) { SshConfiguration sshConfiguration = new SshConfiguration() { PublicKeys = new List<SshPublicKeyInner>() }; osProfile.LinuxConfiguration.Ssh = sshConfiguration; } SshPublicKeyInner sshPublicKey = new SshPublicKeyInner(); sshPublicKey.KeyData = publicKeyData; sshPublicKey.Path = "/home/" + osProfile.AdminUsername + "/.ssh/authorized_keys"; osProfile.LinuxConfiguration.Ssh.PublicKeys.Add(sshPublicKey); return this; } ///GENMHASH:F16446581B25DFD00E74CB1193EBF605:7DBCBEBCFCFF036703E8C4680854445D public VirtualMachineImpl WithoutVMAgent() { Inner.OsProfile.WindowsConfiguration.ProvisionVMAgent = false; return this; } ///GENMHASH:98B10909018928720DBCCEBE53E08820:C53BBE49BDF4B37F836CAF494E3A07C9 public VirtualMachineImpl WithoutAutoUpdate() { Inner.OsProfile.WindowsConfiguration.EnableAutomaticUpdates = false; return this; } ///GENMHASH:1BBF95374A03EFFD0583730762AB8753:A0586AA1F362669D4458B9D2C4605A9F public VirtualMachineImpl WithTimeZone(string timeZone) { Inner.OsProfile.WindowsConfiguration.TimeZone = timeZone; return this; } ///GENMHASH:F7E8AD723108078BE0FE19CD860DD3D3:7AB774480B8E9543A8CAEE7340C4B7B8 public VirtualMachineImpl WithWinRM(WinRMListener listener) { if (Inner.OsProfile.WindowsConfiguration.WinRM == null) { Inner.OsProfile.WindowsConfiguration.WinRM = new WinRMConfiguration() { Listeners = new List<WinRMListener>() }; } Inner.OsProfile .WindowsConfiguration .WinRM .Listeners .Add(listener); return this; } public VirtualMachineImpl WithVaultSecret(string vaultId, string certificateUrl, string certificateStore) { if (Inner.OsProfile.Secrets == null) { Inner.OsProfile.Secrets = new List<VaultSecretGroup>(); } var secretGroup = Inner.OsProfile.Secrets.FirstOrDefault(secret => secret.SourceVault.Id.Equals(vaultId, StringComparison.OrdinalIgnoreCase)); if (secretGroup == null) { secretGroup = new VaultSecretGroup(new SubResource(vaultId)); Inner.OsProfile.Secrets.Add(secretGroup); } if(secretGroup.VaultCertificates == null) { secretGroup.VaultCertificates = new List<VaultCertificate>(); } secretGroup.VaultCertificates.Add(new VaultCertificate(certificateUrl,certificateStore)); return this; } ///GENMHASH:F2FFAF5448D7DFAFBE00130C62E87053:31B639B9D779BF92E26C4DAAF832C9E7 public VirtualMachineImpl WithRootPassword(string password) { Inner.OsProfile.AdminPassword = password; return this; } ///GENMHASH:5810786355B161A5CD254C9E3BE76524:31B639B9D779BF92E26C4DAAF832C9E7 public VirtualMachineImpl WithAdminPassword(string password) { Inner.OsProfile.AdminPassword = password; return this; } public VirtualMachineImpl WithPriority(VirtualMachinePriorityTypes priority) { Inner.Priority = priority; return this; } public VirtualMachineImpl WithLowPriority() { Inner.Priority = VirtualMachinePriorityTypes.Low; return this; } public VirtualMachineImpl WithLowPriority(VirtualMachineEvictionPolicyTypes policy) { this.WithLowPriority(); Inner.EvictionPolicy = policy; return this; } public VirtualMachineImpl WithMaxPrice(double? maxPrice) { Inner.BillingProfile = new BillingProfile(maxPrice); return this; } ///GENMHASH:5D8D71845C83EB59F52EB2C4B1C05618:DAD67F2444F1C28988F244EE4625A3F5 public VirtualMachineImpl WithAvailabilityZone(AvailabilityZoneId zoneId) { if (IsInCreateMode) { // Note: Zone is not updatable as of now, so this is available only during definition time. // Service return `ResourceAvailabilityZonesCannotBeModified` upon attempt to append a new // zone or remove one. Trying to remove the last one means attempt to change resource from // zonal to regional, which is not supported. // // though not updatable, still adding above 'isInCreateMode' check just as a reminder to // take special handling of 'implicitPipCreatable' when avail zone update is supported. // if (this.Inner.Zones == null) { this.Inner.Zones = new List<String>(); } this.Inner.Zones.Add(zoneId.ToString()); // zone aware VM can be attached to only zone aware public IP. // if (this.implicitPipCreatable != null) { this.implicitPipCreatable.WithAvailabilityZone(zoneId); } } return this; } ///GENMHASH:E8024524BA316DC9DEEB983B272ABF81:A4BB71EB8065E0206CCD541A9DCF4958 public VirtualMachineImpl WithCustomData(string base64EncodedCustomData) { Inner.OsProfile.CustomData = base64EncodedCustomData; return this; } ///GENMHASH:51EBA8D3FB4D3F3417FFB3844F1E5D31:D277FC6E9690E3315F7B673013620ECF public VirtualMachineImpl WithComputerName(string computerName) { Inner.OsProfile.ComputerName = computerName; return this; } ///GENMHASH:3EDA6D9B767CDD07D76DD15C0E0B7128:7E4761B66D0FB9A09715DA978222FC55 public VirtualMachineImpl WithSize(string sizeName) { Inner.HardwareProfile.VmSize = VirtualMachineSizeTypes.Parse(sizeName); return this; } ///GENMHASH:619ABAAD3F8A01F52AFF9E0735BDAE77:EC0CEDDCD615AA4EFB41DF60CEE2588B public VirtualMachineImpl WithSize(VirtualMachineSizeTypes size) { Inner.HardwareProfile.VmSize = size; return this; } ///GENMHASH:68806A9EFF9AE1233F4E313BFAB88A1E:89DEE527C9AED179FFFF9E5303751431 public VirtualMachineImpl WithOSDiskCaching(CachingTypes cachingType) { Inner.StorageProfile.OsDisk.Caching = cachingType; return this; } public VirtualMachineImpl WithEphemeralOSDisk(DiffDiskOptions diffDiskOptions) { Inner.StorageProfile.OsDisk.DiffDiskSettings = new DiffDiskSettings(diffDiskOptions); return this; } ///GENMHASH:6AD476CF269D3B37CBD6D308C3557D31:16840EEFCED2B5791EEB29EDAE4CB087 public VirtualMachineImpl WithOSDiskVhdLocation(string containerName, string vhdName) { // Sets the native (un-managed) disk backing virtual machine OS disk // if (IsManagedDiskEnabled()) { return this; } StorageProfile storageProfile = Inner.StorageProfile; OSDisk osDisk = storageProfile.OsDisk; // Setting native (un-managed) disk backing virtual machine OS disk is valid only when // the virtual machine is created from image. // if (!this.IsOSDiskFromImage(osDisk)) { return this; } // Exclude custom user image as they won't support using native (un-managed) disk to back // virtual machine OS disk. // if (this.IsOsDiskFromCustomImage(storageProfile)) { return this; } // OS Disk from 'Platform image' requires explicit storage account to be specified. // if (this.IsOSDiskFromPlatformImage(storageProfile)) { VirtualHardDisk osVhd = new VirtualHardDisk(); osVhd.Uri = TemporaryBlobUrl(containerName, vhdName); Inner.StorageProfile.OsDisk.Vhd = osVhd; return this; } // 'Stored image' and 'Bring your own feature image' has a restriction that the native // disk backing OS disk based on these images should reside in the same storage account // as the image. if (this.IsOSDiskFromStoredImage(storageProfile)) { VirtualHardDisk osVhd = new VirtualHardDisk(); Uri sourceCustomImageUrl = new Uri(osDisk.Image.Uri); Uri destinationVhdUrl = new Uri(new Uri($"{sourceCustomImageUrl.Scheme}://{sourceCustomImageUrl.Host}"), $"{containerName}/{vhdName}"); osVhd.Uri = destinationVhdUrl.ToString(); Inner.StorageProfile.OsDisk.Vhd = osVhd; } return this; } ///GENMHASH:90924DCFADE551C6E90B738982E6C2F7:279439FCFF8597A1B86C671E92AB9C4F public VirtualMachineImpl WithOSDiskStorageAccountType(StorageAccountTypes accountType) { if (Inner.StorageProfile.OsDisk.ManagedDisk == null) { Inner .StorageProfile .OsDisk .ManagedDisk = new ManagedDiskParametersInner(); } Inner .StorageProfile .OsDisk .ManagedDisk .StorageAccountType = accountType; return this; } ///GENMHASH:621A22301B3EB5233E9DB4ED5BEC5735:E8427EEC4ACC25554660EF889ECD07A2 public VirtualMachineImpl WithDataDiskDefaultCachingType(CachingTypes cachingType) { this.managedDataDisks.SetDefaultCachingType(cachingType); return this; } ///GENMHASH:B37B5DD609CF1DB836ABB9CBB32E93E3:EBFBB1CB0457C2978B29376127013BE6 public VirtualMachineImpl WithDataDiskDefaultStorageAccountType(StorageAccountTypes storageAccountType) { this.managedDataDisks.SetDefaultStorageAccountType(storageAccountType); return this; } ///GENMHASH:75485319699D66A3C75429B0EB7E0665:AE8D3788AAA49304D58C3DFB3E942C15 public VirtualMachineImpl WithOSDiskEncryptionSettings(DiskEncryptionSettings settings) { Inner.StorageProfile.OsDisk.EncryptionSettings = settings; return this; } ///GENMHASH:48CC3BB0EDCE9EE56CB8FEBA4DD9E903:4FFC5F3F684247159297E3463471B6EA public VirtualMachineImpl WithOSDiskSizeInGB(int size) { Inner.StorageProfile.OsDisk.DiskSizeGB = size; return this; } ///GENMHASH:C5EB453493B1100152604C49B4350246:28D2B19DAE6A4D168B24165D74135721 public VirtualMachineImpl WithOSDiskName(string name) { Inner.StorageProfile.OsDisk.Name = name; return this; } ///GENMHASH:821D92F0F65352C735EB6081A9BEA9DC:D57B8D7D879942E6738D5D4440AE7921 public UnmanagedDataDiskImpl DefineUnmanagedDataDisk(string name) { ThrowIfManagedDiskEnabled(ManagedUnmanagedDiskErrors.VM_Both_Managed_And_Uumanaged_Disk_Not_Allowed); return UnmanagedDataDiskImpl.PrepareDataDisk(name, this); } ///GENMHASH:D4AA1D687C6ADC8E82CF97490E7E2840:4AA0CB7C28989E00E5658781AA7B4944 public VirtualMachineImpl WithNewUnmanagedDataDisk(int sizeInGB) { ThrowIfManagedDiskEnabled(ManagedUnmanagedDiskErrors.VM_Both_Managed_And_Uumanaged_Disk_Not_Allowed); return DefineUnmanagedDataDisk(null) .WithNewVhd(sizeInGB) .Attach(); } ///GENMHASH:D5B97545D30FE11F617914568F503B7C:EF873831879537CFDC6AB3A92D1B32E1 public VirtualMachineImpl WithExistingUnmanagedDataDisk(string storageAccountName, string containerName, string vhdName) { //$ throwIfManagedDiskEnabled(ManagedUnmanagedDiskErrors.VM_BOTH_MANAGED_AND_UNMANAGED_DISK_NOT_ALLOWED); return DefineUnmanagedDataDisk(null) .WithExistingVhd(storageAccountName, containerName, vhdName) .Attach(); } ///GENMHASH:986009C9CE2533065F3AE9DC169521A5:FB9664669ECF7CF62DE326E69D76F5DE public VirtualMachineImpl WithoutUnmanagedDataDisk(string name) { // Its ok not to throw here, since in general 'withoutXX' can be NOP int idx = -1; foreach (var dataDisk in this.unmanagedDataDisks) { idx++; if (dataDisk.Name.Equals(name, System.StringComparison.OrdinalIgnoreCase)) { this.unmanagedDataDisks.RemoveAt(idx); Inner.StorageProfile.DataDisks.RemoveAt(idx); break; } } return this; } ///GENMHASH:54D3B4BD3F03BEE3E2ACA4B49D0F23C0:1476C04BA42BC075365EAA5629BAD60A public VirtualMachineImpl WithoutUnmanagedDataDisk(int lun) { // Its ok not to throw here, since in general 'withoutXX' can be NOP int idx = -1; foreach (var dataDisk in this.unmanagedDataDisks) { idx++; if (dataDisk.Lun == lun) { this.unmanagedDataDisks.RemoveAt(idx); Inner.StorageProfile.DataDisks.RemoveAt(idx); break; } } return this; } ///GENMHASH:429C59D407353456A6B5003023273BD7:15F5523485D6FBD0739BA14B1BBC4FAD public UnmanagedDataDiskImpl UpdateUnmanagedDataDisk(string name) { ThrowIfManagedDiskEnabled(ManagedUnmanagedDiskErrors.VM_No_Unmanaged_Disk_To_Update); foreach (var dataDisk in this.unmanagedDataDisks) { if (dataDisk.Name.Equals(name, System.StringComparison.OrdinalIgnoreCase)) { return (UnmanagedDataDiskImpl)dataDisk; } } throw new Exception("A data disk with name '" + name + "' not found"); } ///GENMHASH:ED389F29DE6EBB941FA1654A4421A870:EFA122C6179091039C9A2EC452DF4EBB public VirtualMachineImpl WithNewDataDisk(ICreatable<Microsoft.Azure.Management.Compute.Fluent.IDisk> creatable) { ThrowIfManagedDiskDisabled(ManagedUnmanagedDiskErrors.VM_Both_Unmanaged_And_Managed_Disk_Not_Allowed); this.AddCreatableDependency(creatable as IResourceCreator<IHasId>); this.managedDataDisks.NewDisksToAttach.Add(creatable.Key, new DataDisk() { Lun = -1 }); return this; } ///GENMHASH:AF80B886368560BF40BD597B1A4C0333:269383EDE2B9B5C9085729DEEBBDCCF9 public VirtualMachineImpl WithNewDataDisk(ICreatable<Microsoft.Azure.Management.Compute.Fluent.IDisk> creatable, int lun, CachingTypes cachingType) { ThrowIfManagedDiskDisabled(ManagedUnmanagedDiskErrors.VM_Both_Unmanaged_And_Managed_Disk_Not_Allowed); this.AddCreatableDependency(creatable as IResourceCreator<IHasId>); this.managedDataDisks.NewDisksToAttach.Add(creatable.Key, new DataDisk() { Lun = lun, Caching = cachingType }); return this; } ///GENMHASH:674F68CEE727AFB7E6F6D9C7FADE1175:DD2D09ACF9139B1967714865BD1D48FB public VirtualMachineImpl WithNewDataDisk(int sizeInGB) { ThrowIfManagedDiskDisabled(ManagedUnmanagedDiskErrors.VM_Both_Unmanaged_And_Managed_Disk_Not_Allowed); this.managedDataDisks.ImplicitDisksToAssociate.Add(new DataDisk() { Lun = -1, DiskSizeGB = sizeInGB }); return this; } ///GENMHASH:B213E98FA6979257F6E6F61C9B5E550B:17763285B1830F7E43D5411D6D535DE5 public VirtualMachineImpl WithNewDataDisk(int sizeInGB, int lun, CachingTypes cachingType) { ThrowIfManagedDiskDisabled(ManagedUnmanagedDiskErrors.VM_Both_Unmanaged_And_Managed_Disk_Not_Allowed); this.managedDataDisks.ImplicitDisksToAssociate.Add(new DataDisk() { Lun = lun, DiskSizeGB = sizeInGB, Caching = cachingType }); return this; } ///GENMHASH:1D3A0A89681FFD35007B24FCED6BF299:A69C7823EE7EC5B383A6E9CA6366F777 public VirtualMachineImpl WithNewDataDisk(int sizeInGB, int lun, CachingTypes cachingType, StorageAccountTypes storageAccountType) { ThrowIfManagedDiskDisabled(ManagedUnmanagedDiskErrors.VM_Both_Unmanaged_And_Managed_Disk_Not_Allowed); ManagedDiskParametersInner managedDiskParameters = new ManagedDiskParametersInner(); managedDiskParameters.StorageAccountType = storageAccountType; this.managedDataDisks.ImplicitDisksToAssociate.Add(new DataDisk() { Lun = lun, DiskSizeGB = sizeInGB, Caching = cachingType, ManagedDisk = managedDiskParameters }); return this; } ///GENMHASH:780DFAACAB0C49C5480A9653F0D1B16F:CD32B2E3A381F3A5162D15E662EAE22E public VirtualMachineImpl WithExistingDataDisk(IDisk disk) { ThrowIfManagedDiskDisabled(ManagedUnmanagedDiskErrors.VM_Both_Unmanaged_And_Managed_Disk_Not_Allowed); ManagedDiskParametersInner managedDiskParameters = new ManagedDiskParametersInner(); managedDiskParameters.Id = disk.Id; this.managedDataDisks.ExistingDisksToAttach.Add(new DataDisk() { Lun = -1, ManagedDisk = managedDiskParameters }); return this; } ///GENMHASH:C0B5162CF8CEAACE1539900D43997C4E:ABA2632CB438B4020F743732E9561257 public VirtualMachineImpl WithExistingDataDisk(IDisk disk, int lun, CachingTypes cachingType) { ThrowIfManagedDiskDisabled(ManagedUnmanagedDiskErrors.VM_Both_Unmanaged_And_Managed_Disk_Not_Allowed); ManagedDiskParametersInner managedDiskParameters = new ManagedDiskParametersInner(); managedDiskParameters.Id = disk.Id; this.managedDataDisks.ExistingDisksToAttach.Add(new DataDisk() { Lun = lun, ManagedDisk = managedDiskParameters, Caching = cachingType }); return this; } ///GENMHASH:EE587883AA52548AF30AC4624CC57C2A:7255A6270AEAD6441F6727139E21D862 public VirtualMachineImpl WithExistingDataDisk(IDisk disk, int newSizeInGB, int lun, CachingTypes cachingType) { ThrowIfManagedDiskDisabled(ManagedUnmanagedDiskErrors.VM_Both_Unmanaged_And_Managed_Disk_Not_Allowed); ManagedDiskParametersInner managedDiskParameters = new ManagedDiskParametersInner(); managedDiskParameters.Id = disk.Id; this.managedDataDisks.ExistingDisksToAttach.Add(new DataDisk() { Lun = lun, DiskSizeGB = newSizeInGB, ManagedDisk = managedDiskParameters, Caching = cachingType }); return this; } ///GENMHASH:89EFB8F9AFBDF98FFAD5606983F59A03:39E3B69A49E68069F2BF73DCEFF3A443 public VirtualMachineImpl WithNewDataDiskFromImage(int imageLun) { this.managedDataDisks.NewDisksFromImage.Add(new DataDisk { Lun = imageLun }); return this; } ///GENMHASH:92519C2F478984EF05C22A5573361AFE:0CF3D5F4C913309400D9221477B87E1F public VirtualMachineImpl WithNewDataDiskFromImage(int imageLun, int newSizeInGB, CachingTypes cachingType) { this.managedDataDisks.NewDisksFromImage.Add(new DataDisk { Lun = imageLun, DiskSizeGB = newSizeInGB, Caching = cachingType }); return this; } ///GENMHASH:BABD7F4E5FDF4ECA60DB2F163B33F4C7:17AC541DFB3C3AEDF45259848089B054 public VirtualMachineImpl WithNewDataDiskFromImage(int imageLun, int newSizeInGB, CachingTypes cachingType, StorageAccountTypes storageAccountType) { ManagedDiskParametersInner managedDiskParameters = new ManagedDiskParametersInner(); managedDiskParameters.StorageAccountType = storageAccountType; this.managedDataDisks.NewDisksFromImage.Add(new DataDisk() { Lun = imageLun, DiskSizeGB = newSizeInGB, ManagedDisk = managedDiskParameters, Caching = cachingType }); return this; } ///GENMHASH:9C4A541B9A2E22540116BFA125189F57:2F8856B5F0BA5E1B741D68C6CED48D9A public VirtualMachineImpl WithoutDataDisk(int lun) { if (!IsManagedDiskEnabled()) { return this; } this.managedDataDisks.DiskLunsToRemove.Add(lun); return this; } ///GENMHASH:2DC51FEC3C45675856B4AC1D97BECBFD:03CBC8ECAD4A07D8AE9ABC931CB422F4 public VirtualMachineImpl WithNewStorageAccount(ICreatable<Microsoft.Azure.Management.Storage.Fluent.IStorageAccount> creatable) { // This method's effect is NOT additive. if (this.creatableStorageAccountKey == null) { this.creatableStorageAccountKey = creatable.Key; this.AddCreatableDependency(creatable as IResourceCreator<IHasId>); } return this; } ///GENMHASH:5880487AA9218E8DF536932A49A0ACDD:35850B81E88D88D68766589B9671E590 public VirtualMachineImpl WithNewStorageAccount(string name) { Storage.Fluent.StorageAccount.Definition.IWithGroup definitionWithGroup = this.storageManager .StorageAccounts .Define(name) .WithRegion(this.RegionName); Storage.Fluent.StorageAccount.Definition.IWithCreate definitionAfterGroup; if (this.newGroup != null) { definitionAfterGroup = definitionWithGroup.WithNewResourceGroup(this.newGroup); } else { definitionAfterGroup = definitionWithGroup.WithExistingResourceGroup(this.ResourceGroupName); } return WithNewStorageAccount(definitionAfterGroup); } ///GENMHASH:8CB9B7EEE4A4226A6F5BBB2958CC5E81:371A29A476B6231AF7CE026E180DF69D public VirtualMachineImpl WithExistingStorageAccount(IStorageAccount storageAccount) { this.existingStorageAccountToAssociate = storageAccount; return this; } ///GENMHASH:B0D2BED63AF533A1F9AA9D14B66DDA1E:49A8C40E80E0F9117A98775EBC1A348C public VirtualMachineImpl WithNewAvailabilitySet(ICreatable<Microsoft.Azure.Management.Compute.Fluent.IAvailabilitySet> creatable) { if (this.creatableAvailabilitySetKey == null) { this.creatableAvailabilitySetKey = creatable.Key; this.AddCreatableDependency(creatable as IResourceCreator<IHasId>); } return this; } ///GENMHASH:0BFC73C37B3D941247E33A0B1AC6113E:391711091FE21C5DAD7F2EAE81567FB0 public VirtualMachineImpl WithNewAvailabilitySet(string name) { AvailabilitySet.Definition.IWithGroup definitionWithGroup = base.Manager .AvailabilitySets .Define(name) .WithRegion(this.RegionName); AvailabilitySet.Definition.IWithSku definitionWithSku; if (this.newGroup != null) { definitionWithSku = definitionWithGroup.WithNewResourceGroup(this.newGroup); } else { definitionWithSku = definitionWithGroup.WithExistingResourceGroup(this.ResourceGroupName); } ICreatable<IAvailabilitySet> creatable; if (IsManagedDiskEnabled()) { creatable = definitionWithSku.WithSku(AvailabilitySetSkuTypes.Aligned); } else { creatable = definitionWithSku.WithSku(AvailabilitySetSkuTypes.Classic); } return this.WithNewAvailabilitySet(creatable); } ///GENMHASH:F2733A66EF0AF45C62E9C44FD29CC576:FC9409B8E6841C279554A2938B4E9F12 public VirtualMachineImpl WithExistingAvailabilitySet(IAvailabilitySet availabilitySet) { this.existingAvailabilitySetToAssociate = availabilitySet; return this; } public VirtualMachineImpl WithProximityPlacementGroup(String proximityPlacementGroupId) { this.newProximityPlacementGroupType = null; this.newProximityPlacementGroupName = null; this.Inner.ProximityPlacementGroup = new SubResource() { Id = proximityPlacementGroupId }; return this; } public VirtualMachineImpl WithNewProximityPlacementGroup(String proximityPlacementGroupName, ProximityPlacementGroupType type) { this.newProximityPlacementGroupName = proximityPlacementGroupName; this.newProximityPlacementGroupType = type; this.Inner.ProximityPlacementGroup = null; return this; } public VirtualMachineImpl WithoutProximityPlacementGroup() { this.newProximityPlacementGroupName = null; this.newProximityPlacementGroupType = null; this.Inner.ProximityPlacementGroup = null; return this; } ///GENMHASH:720FC1AD6CE12835DF562FA21CBA22C1:8E210E27AC5BBEFD085A05D8458DC632 public VirtualMachineImpl WithNewSecondaryNetworkInterface(ICreatable<Microsoft.Azure.Management.Network.Fluent.INetworkInterface> creatable) { this.creatableSecondaryNetworkInterfaceKeys.Add(creatable.Key); this.AddCreatableDependency(creatable as IResourceCreator<IHasId>); return this; } ///GENMHASH:2F9CE7894E6D642D5ABF71D29F2F4B37:60F56E8691A7813CC9E596CB262E800E public VirtualMachineImpl WithExistingSecondaryNetworkInterface(INetworkInterface networkInterface) { this.existingSecondaryNetworkInterfacesToAssociate.Add(networkInterface); return this; } ///GENMHASH:D4842E34F33259DEFED4C90844786E59:39378392E4693029B7DDB841A336DF68 public IVirtualMachineEncryption DiskEncryption() { return new VirtualMachineEncryptionImpl(this); } ///GENMHASH:1B6EFD4FB09DB19A9365B92299382732:6E8FA7A8D0E6C28DD34AA5ED876E9C3F public VirtualMachineImpl WithoutSecondaryNetworkInterface(string name) { if (Inner.NetworkProfile != null && Inner.NetworkProfile.NetworkInterfaces != null) { int idx = -1; foreach (NetworkInterfaceReferenceInner nicReference in Inner.NetworkProfile.NetworkInterfaces) { idx++; if (nicReference.Primary.HasValue && nicReference.Primary == false && name.Equals(ResourceUtils.NameFromResourceId(nicReference.Id), StringComparison.OrdinalIgnoreCase)) { Inner.NetworkProfile.NetworkInterfaces.RemoveAt(idx); break; } } } return this; } public VirtualMachineImpl WithoutNetworkInterface(string nicId) { if (Inner.NetworkProfile != null && Inner.NetworkProfile.NetworkInterfaces != null) { int idx = -1; foreach (NetworkInterfaceReferenceInner nicReference in Inner.NetworkProfile.NetworkInterfaces) { idx++; if (nicId.Equals(nicReference.Id, StringComparison.OrdinalIgnoreCase)) { Inner.NetworkProfile.NetworkInterfaces.RemoveAt(idx); if (nicReference.Primary.HasValue && nicReference.Primary == true) { // If removed NIC was primary then use next NIC as primary. // It looks like the concept of primary nic is legacy (followup service team to get rid of // this flag if that is the case). if (Inner.NetworkProfile.NetworkInterfaces.Any()) { Inner.NetworkProfile.NetworkInterfaces.First().Primary = true; } } break; } } } return this; } ///GENMHASH:D7A14F2EFF1E4165DA55EF07B6C19534:85E4528E76EBEB2F2002B48ABD89A8E5 public VirtualMachineExtensionImpl DefineNewExtension(string name) { return this.virtualMachineExtensions.Define(name); } ///GENMHASH:E7610DABE1E75344D9E0DBC0332E7F96:A6222B1A3B3DAF08C7A0DB8408674E80 public VirtualMachineExtensionImpl UpdateExtension(string name) { return this.virtualMachineExtensions.Update(name); } ///GENMHASH:1E53238DF79E665335390B7452E9A04C:C28505CD9AD86AC2345C0714B80220AF public VirtualMachineImpl WithoutExtension(string name) { this.virtualMachineExtensions.Remove(name); return this; } ///GENMHASH:4154589CF64AC591DEDEA5AD2CE5AB3E:0D1CED8472F2D89553DFD9B987FDC9E4 public VirtualMachineImpl WithPlan(PurchasePlan plan) { Inner.Plan = new Plan() { Publisher = plan.Publisher, Product = plan.Product, Name = plan.Name }; return this; } ///GENMHASH:168EACA3A73F047931B326C48BD71C2D:25C0F05C248DCD851959044BB5CDA543 public VirtualMachineImpl WithPromotionalPlan(PurchasePlan plan, string promotionCode) { this.WithPlan(plan); Inner.Plan.PromotionCode = promotionCode; return this; } ///GENMHASH:ED2B5B9A3A19B5A8C2C3E6E1CDBF9402:6A6DEBF76624FF70612A6981A86CC468 public VirtualMachineImpl WithUnmanagedDisks() { this.isUnmanagedDiskSelected = true; return this; } ///GENMHASH:4C7CAAD83BFD2178732EBCF6E061B2FA:E84D8725C76163C38C60209300BBC171 public VirtualMachineImpl WithBootDiagnostics() { // Diagnostics storage uri will be set later by this.HandleBootDiagnosticsStorageSettings(..) // this.EnableDisableBootDiagnostics(true); return this; } ///GENMHASH:863CDD9F8489B70A038C82A8B4339C1E:9ABCD9EF7B6D335327D3363AC01E0FFF public VirtualMachineImpl WithBootDiagnostics(ICreatable<Microsoft.Azure.Management.Storage.Fluent.IStorageAccount> creatable) { // Diagnostics storage uri will be set later by this.HandleBootDiagnosticsStorageSettings(..) // EnableDisableBootDiagnostics(true); this.creatableDiagnosticsStorageAccountKey = creatable.Key; this.AddCreatableDependency(creatable as IResourceCreator<IHasId>); return this; } ///GENMHASH:5719F860C08C586F249065EB7A86DED3:D78B3EDD6BE5C30863D9F9E21A28EE11 public VirtualMachineImpl WithBootDiagnostics(string storageAccountBlobEndpointUri) { this.EnableDisableBootDiagnostics(true); this.Inner .DiagnosticsProfile .BootDiagnostics .StorageUri = storageAccountBlobEndpointUri; return this; } ///GENMHASH:F731B4942EC78BDFB7DA69F73C48F080:7E7787C820A03B7F2B97B51FDACA8053 public VirtualMachineImpl WithBootDiagnostics(IStorageAccount storageAccount) { return this.WithBootDiagnostics(storageAccount.EndPoints.Primary.Blob); } ///GENMHASH:5892700B93394BCA74ABA1B081C6F158:455622D3AC079705ADC12CAFAD0028C2 public VirtualMachineImpl WithoutBootDiagnostics() { this.EnableDisableBootDiagnostics(false); return this; } ///GENMHASH:C81171F34FA85CED80852E725FF8B7A4:56767F3A519F0DF8AB9F685ABA15F2E4 public bool IsManagedDiskEnabled() { if (IsOsDiskFromCustomImage(Inner.StorageProfile)) { return true; } if (IsOSDiskAttachedManaged(Inner.StorageProfile.OsDisk)) { return true; } if (IsOSDiskFromStoredImage(Inner.StorageProfile)) { return false; } if (IsOSDiskAttachedUnmanaged(Inner.StorageProfile.OsDisk)) { return false; } if (IsOSDiskFromPlatformImage(Inner.StorageProfile)) { if (this.isUnmanagedDiskSelected) { return false; } } if (IsInCreateMode) { return true; } else { return Inner.StorageProfile.OsDisk.Vhd == null; } } ///GENMHASH:3EFB25CB32AC4B416B8E0501FDE1DBE9:9063BC00A181FC49D367F4FD1F0EB371 public string ComputerName() { if (Inner.OsProfile == null) { // VM created by attaching a specialized OS Disk VHD will not have the osProfile. return null; } return Inner.OsProfile.ComputerName; } ///GENMHASH:C19382933BDE655D0F0F95CD9474DFE7:2F66035F0CB425AA1735B96753E25A51 public VirtualMachineSizeTypes Size() { return Inner.HardwareProfile.VmSize; } ///GENMHASH:1BAF4F1B601F89251ABCFE6CC4867026:AACA43FF0E9DA39D6993719C23FB0486 public OperatingSystemTypes OSType() { return Inner.StorageProfile.OsDisk.OsType.Value; } ///GENMHASH:E6371CFFB9CB09E08DD4757D639CBF27:976273E359EA5250C90646DEEB682652 public string OSUnmanagedDiskVhdUri() { if (IsManagedDiskEnabled()) { return null; } return Inner.StorageProfile.OsDisk.Vhd.Uri; } ///GENMHASH:123FF0223083F789E78E45771A759A9C:1604791894B0C3EF16EEDF56536B8B70 public CachingTypes OSDiskCachingType() { return Inner.StorageProfile.OsDisk.Caching.Value; } ///GENMHASH:034DA366E39060AAD75E1DA786657383:65EDBB2144C128EB0C43030D512C5EED public int OSDiskSize() { if (Inner.StorageProfile.OsDisk.DiskSizeGB == null) { // Server returns OS disk size as 0 for auto-created disks for which // size was not explicitly set by the user. return 0; } return Inner.StorageProfile.OsDisk.DiskSizeGB.Value; } ///GENMHASH:E5CADE85564466522E512C04EB3F57B6:086F150AD4D805B10FE2EDCCE4784829 public StorageAccountTypes OSDiskStorageAccountType() { if (!IsManagedDiskEnabled() || this.StorageProfile().OsDisk.ManagedDisk == null || this.StorageProfile().OsDisk.ManagedDisk.StorageAccountType == null) { return null; } return this.StorageProfile().OsDisk.ManagedDisk.StorageAccountType; } ///GENMHASH:C6D786A0345B2C4ADB349E573A0BF6C7:E98CE6464DD63DE655EAFA519D693285 public string OSDiskId() { if (!IsManagedDiskEnabled()) { return null; } return this.StorageProfile().OsDisk.ManagedDisk.Id; } ///GENMHASH:0F25C4AF79F7680F2CB3C57410B5BC20:FFF5003A8246F7DB1BDBE31636E6CE9C public IReadOnlyDictionary<int, Microsoft.Azure.Management.Compute.Fluent.IVirtualMachineUnmanagedDataDisk> UnmanagedDataDisks() { Dictionary<int, IVirtualMachineUnmanagedDataDisk> dataDisks = new Dictionary<int, IVirtualMachineUnmanagedDataDisk>(); if (!IsManagedDiskEnabled()) { foreach (var dataDisk in this.unmanagedDataDisks) { dataDisks.Add(dataDisk.Lun, dataDisk); } } return dataDisks; } ///GENMHASH:353C54F9ADAEAEDD54EE4F0AACF9DF9B:E5641D026D42E80470787BB2990E88CE public IReadOnlyDictionary<int, Microsoft.Azure.Management.Compute.Fluent.IVirtualMachineDataDisk> DataDisks() { Dictionary<int, IVirtualMachineDataDisk> dataDisks = new Dictionary<int, IVirtualMachineDataDisk>(); if (IsManagedDiskEnabled()) { var innerDataDisks = Inner.StorageProfile.DataDisks; if (innerDataDisks != null) { foreach (var innerDataDisk in innerDataDisks) { dataDisks.Add(innerDataDisk.Lun, new VirtualMachineDataDiskImpl(innerDataDisk)); } } } return dataDisks; } ///GENMHASH:2A7ACF9E7DA59ECB74A3F0607B98CEA8:46FD353C4642C823383ED54BCE79C710 public INetworkInterface GetPrimaryNetworkInterface() { return this.networkManager.NetworkInterfaces.GetById(this.PrimaryNetworkInterfaceId()); } ///GENMHASH:D3ADA5DC7B5CC9C5BD29AC1110C61014:EC93403D80CE55A8079C6FDA3D5DE566 public IPublicIPAddress GetPrimaryPublicIPAddress() { return this.GetPrimaryNetworkInterface().PrimaryIPConfiguration.GetPublicIPAddress(); } ///GENMHASH:5977CC2F7355BB73CD32528805FEDA4D:8A6DCD2F68FE8ED005BB9933A0E74217 public string GetPrimaryPublicIPAddressId() { return this.GetPrimaryNetworkInterface().PrimaryIPConfiguration.PublicIPAddressId; } ///GENMHASH:606A3D349546DF27E3A091C321476658:DC63C44DC2A2862C6AC14F711DCB1EFA public IReadOnlyList<string> NetworkInterfaceIds() { List<string> nicIds = new List<string>(); foreach (NetworkInterfaceReferenceInner nicRef in Inner.NetworkProfile.NetworkInterfaces) { nicIds.Add(nicRef.Id); } return nicIds; } ///GENMHASH:8149ED362968AEDB6044CB62BAB0373B:2296DA5603B8E3273CF41C4869FD4795 public string PrimaryNetworkInterfaceId() { IList<NetworkInterfaceReferenceInner> nicRefs = Inner.NetworkProfile.NetworkInterfaces; String primaryNicRefId = null; if (nicRefs.Count == 1) { // One NIC so assume it to be primary primaryNicRefId = nicRefs[0].Id; } else if (nicRefs.Count == 0) { // No NICs so null primaryNicRefId = null; } else { // Find primary interface as flagged by Azure foreach (NetworkInterfaceReferenceInner nicRef in Inner.NetworkProfile.NetworkInterfaces) { if (nicRef.Primary != null && nicRef.Primary.HasValue && nicRef.Primary == true) { primaryNicRefId = nicRef.Id; break; } } // If Azure didn't flag any NIC as primary then assume the first one if (primaryNicRefId == null) { primaryNicRefId = nicRefs[0].Id; } } return primaryNicRefId; } ///GENMHASH:AE4C4EDD69D8398105E588BB437DB52F:66995F8696299A549C7E506466483AED public string AvailabilitySetId() { if (Inner.AvailabilitySet != null) { return Inner.AvailabilitySet.Id; } return null; } ///GENMHASH:99D5BF64EA8AA0E287C9B6F77AAD6FC4:3DB04077E6BABC0FB5A5ACDA19D11309 public string ProvisioningState() { return Inner.ProvisioningState; } ///GENMHASH:069B0F660FC41DE3B93D2DC7C8D6822E:32B4F61D2B05A6879D35794E524767CB public string LicenseType() { return Inner.LicenseType; } public IProximityPlacementGroup ProximityPlacementGroup() { if (Inner.ProximityPlacementGroup == null) { return null; } ResourceId id = ResourceId.FromString(Inner.ProximityPlacementGroup.Id); ProximityPlacementGroupInner plgInner = Extensions.Synchronize(() => this.Manager.Inner.ProximityPlacementGroups.GetAsync(this.ResourceGroupName, id.Name)); if (plgInner == null) { return null; } else { return new ProximityPlacementGroupImpl(plgInner); } } ///GENMHASH:283A7CD491ABC476D6646B943D8641A8:BB7251641858D1CBEADD4ABE2AF921D3 public Plan Plan() { return Inner.Plan; } ///GENMHASH:7F0A9CB4CB6BBC98F72CF50A81EBFBF4:3689C1A52147BB53E4C284572C790C00 public StorageProfile StorageProfile() { return Inner.StorageProfile; } ///GENMHASH:5390AD803419DE6CEAFF825AD0A94458:7197E049071CE2157D45362744EAD102 public OSProfile OSProfile() { return Inner.OsProfile; } ///GENMHASH:6DC69B57C0EF18B742D6A9F6EF064DB6:918D5C0812D3C8CF539A3DD9FC338819 public DiagnosticsProfile DiagnosticsProfile() { return Inner.DiagnosticsProfile; } ///GENMHASH:F91DF44F14D53833479DE592AB2B2890:A44F980B37B6696BA13F0A8DB633DCCA public string VMId() { return Inner.VmId; } ///GENMHASH:E21E3E6E61153DDD23E28BC18B49F1AC:BAF1B6669763368768C132F520B23A67 public VirtualMachineInstanceView InstanceView() { if (this.virtualMachineInstanceView == null) { this.RefreshInstanceView(); } return this.virtualMachineInstanceView; } ///GENMHASH:74D6BC0CA5239D9979A6C4F61D973616:C90E0C1B7FFF1EE7A6D2A1D595F52BE7 public PowerState PowerState() { return Fluent.PowerState.FromInstanceView(this.InstanceView()); } ///GENMHASH:54F48C4A15522D8E87E76E69BFD089CA:67C5008B7D86A1EA0300776CDD220599 public ISet<string> UserAssignedManagedServiceIdentityIds() { if (this.Inner.Identity != null && this.Inner.Identity.UserAssignedIdentities != null) { return new HashSet<string>(this.Inner.Identity.UserAssignedIdentities.Keys); } return new HashSet<string>(); } ///GENMHASH:D8D324B42ED7B0976032110E0D5D3320:32345B0AB329E6E420804CD852C47627 public bool IsBootDiagnosticsEnabled() { if (this.Inner.DiagnosticsProfile != null && this.Inner.DiagnosticsProfile.BootDiagnostics != null && this.Inner.DiagnosticsProfile.BootDiagnostics.Enabled != null && this.Inner.DiagnosticsProfile.BootDiagnostics.Enabled.HasValue) { return this.Inner.DiagnosticsProfile.BootDiagnostics.Enabled.Value; } return false; } public VirtualMachinePriorityTypes Priority() { return this.Inner.Priority; } public VirtualMachineEvictionPolicyTypes EvictionPolicy() { return this.Inner.EvictionPolicy; } public BillingProfile BillingProfile() { return this.Inner.BillingProfile; } ///GENMHASH:F842C1987E811B219C87CFA14349A00B:556CABFA1947D39EDB3AAE3870809862 public string BootDiagnosticsStorageUri() { // Even though diagnostics can disabled azure still keep the storage uri if (this.Inner.DiagnosticsProfile != null && this.Inner.DiagnosticsProfile.BootDiagnostics != null) { return this.Inner.DiagnosticsProfile.BootDiagnostics.StorageUri; } return null; } ///GENMHASH:9019C44FB9C28F62603D9972D45A9522:04EA2CF2FF84B5C44179285E14BA0FF0 public string SystemAssignedManagedServiceIdentityPrincipalId() { if (this.Inner.Identity != null) { return this.Inner.Identity.PrincipalId; } return null; } ///GENMHASH:9019C44FB9C28F62603D9972D45A9522:04EA2CF2FF84B5C44179285E14BA0FF0 public bool IsManagedServiceIdentityEnabled() { ResourceIdentityType? type = this.ManagedServiceIdentityType(); if (type == null) { return false; } else { return !type.Value.Equals(ResourceIdentityType.None); } } ///GENMHASH:D19E7D61822C4048249EC4B57FA6F59B:E55E888BE3583ADCF1863F5A9DC47299 public string SystemAssignedManagedServiceIdentityTenantId() { if (this.Inner.Identity != null) { return this.Inner.Identity.TenantId; } return null; } ///GENMHASH:F856C02184EB290DC74E5823D4280D7C:C06C8F12A2F1E86C908BE0388D483D06 public ISet<Microsoft.Azure.Management.ResourceManager.Fluent.Core.AvailabilityZoneId> AvailabilityZones() { var zones = new HashSet<Microsoft.Azure.Management.ResourceManager.Fluent.Core.AvailabilityZoneId>(); if (this.Inner.Zones != null) { foreach (var zone in this.Inner.Zones) { zones.Add(AvailabilityZoneId.Parse(zone)); } } return zones; } ///GENMHASH:E059E91FE0CBE4B6875986D1B46994D2:AF3425B1B2ADC5865D8191FBE2FE4BBC public VirtualMachineImpl WithSystemAssignedManagedServiceIdentity() { this.virtualMachineMsiHelper.WithLocalManagedServiceIdentity(); return this; } ///GENMHASH:DEF511724D2CC8CA91F24E084BC9AA22:72F0234D4EBEB820BB2E8EB0ED1665A6 public VirtualMachineImpl WithSystemAssignedIdentityBasedAccessTo(string scope, string roleDefinitionId) { this.virtualMachineMsiHelper.WithAccessTo(scope, roleDefinitionId); return this; } ///GENMHASH:F6C5721A84FA825F62951BE51537DD36:8A9263C84F0D839E6FAFC22D8AA1C9C4 public VirtualMachineImpl WithSystemAssignedIdentityBasedAccessToCurrentResourceGroup(BuiltInRole role) { this.virtualMachineMsiHelper.WithAccessToCurrentResourceGroup(role); return this; } ///GENMHASH:5FD7E26022EAFDACD062A87DDA8FD39A:7E679ACDB7E20973F54635A194130E55 public VirtualMachineImpl WithSystemAssignedIdentityBasedAccessToCurrentResourceGroup(string roleDefinitionId) { this.virtualMachineMsiHelper.WithAccessToCurrentResourceGroup(roleDefinitionId); return this; } ///GENMHASH:EFFF7ECD982913DB369E1EF1644031CB:C9A5FE940311449954FA688A4B3D8333 public VirtualMachineImpl WithSystemAssignedIdentityBasedAccessTo(string scope, BuiltInRole role) { this.virtualMachineMsiHelper.WithAccessTo(scope, role); return this; } ///GENMHASH:8239AEDA70F925E7A1DCD8BDB2803956:6A2804975F58F97B4F610E2DE8E8AACA public VirtualMachineImpl WithNewUserAssignedManagedServiceIdentity(ICreatable<IIdentity> creatableIdentity) { this.virtualMachineMsiHelper.WithNewExternalManagedServiceIdentity(creatableIdentity); return this; } ///GENMHASH:77198B23BCB8BA2F0DDF3A8A0E85805C:F68FE87A8E9ADCA783F40FB45364544F public VirtualMachineImpl WithoutUserAssignedManagedServiceIdentity(string identityId) { this.virtualMachineMsiHelper.WithoutExternalManagedServiceIdentity(identityId); return this; } ///GENMHASH:6836D267A7B5AB07D80A2EFAF13B9F3E:8504B108F30E0AC9DC210A1D9CFA85F3 public VirtualMachineImpl WithExistingUserAssignedManagedServiceIdentity(IIdentity identity) { this.virtualMachineMsiHelper.WithExistingExternalManagedServiceIdentity(identity); return this; } ///GENMHASH:0202A00A1DCF248D2647DBDBEF2CA865:272F8DA403745EB8C8C6DCCD8A4778E2 public async override Task<Microsoft.Azure.Management.Compute.Fluent.IVirtualMachine> CreateResourceAsync(CancellationToken cancellationToken = default(CancellationToken)) { if (IsInCreateMode) { // // -- set creation-time only properties SetOSDiskDefaults(); SetOSProfileDefaults(); SetHardwareProfileDefaults(); if (IsManagedDiskEnabled()) { managedDataDisks.SetDataDisksDefaults(); } else { UnmanagedDataDiskImpl.SetDataDisksDefaults(this.unmanagedDataDisks, this.vmName); } var diskStorageAccount = await HandleStorageSettingsAsync(cancellationToken); await HandleBootDiagnosticsStorageSettingsAsync(diskStorageAccount, cancellationToken); CreateNewProximityPlacementGroup(); HandleNetworkSettings(); HandleAvailabilitySettings(); this.virtualMachineMsiHelper.ProcessCreatedExternalIdentities(); this.virtualMachineMsiHelper.HandleExternalIdentities(); var response = await Manager.Inner.VirtualMachines.CreateOrUpdateAsync(ResourceGroupName, vmName, Inner, cancellationToken); var extensionsCommited = await this.virtualMachineExtensions.CommitAndGetAllAsync(cancellationToken); if (extensionsCommited.Any()) { // Another get to fetch vm inner with extensions list reflecting the commited changes to extensions // response = await Manager.Inner.VirtualMachines.GetAsync(ResourceGroupName, vmName, null, cancellationToken); } this.Reset(response); await virtualMachineMsiHelper.CommitsRoleAssignmentsPendingActionAsync(cancellationToken); } else { if (IsManagedDiskEnabled()) { managedDataDisks.SetDataDisksDefaults(); } else { UnmanagedDataDiskImpl.SetDataDisksDefaults(this.unmanagedDataDisks, this.vmName); } var diskStorageAccount = await HandleStorageSettingsAsync(cancellationToken); await HandleBootDiagnosticsStorageSettingsAsync(diskStorageAccount, cancellationToken); HandleNetworkSettings(); HandleAvailabilitySettings(); this.virtualMachineMsiHelper.ProcessCreatedExternalIdentities(); // VirtualMachineUpdate updateParameter = new VirtualMachineUpdate { Plan = this.Inner.Plan, HardwareProfile = this.Inner.HardwareProfile, StorageProfile = this.Inner.StorageProfile, OsProfile = this.Inner.OsProfile, BillingProfile = this.Inner.BillingProfile, Priority = this.Inner.Priority, EvictionPolicy = this.Inner.EvictionPolicy, NetworkProfile = this.Inner.NetworkProfile, DiagnosticsProfile = this.Inner.DiagnosticsProfile, AvailabilitySet = this.Inner.AvailabilitySet, LicenseType = this.Inner.LicenseType, ProximityPlacementGroup = this.Inner.ProximityPlacementGroup, Zones = this.Inner.Zones, Tags = this.Inner.Tags }; // this.virtualMachineMsiHelper.HandleExternalIdentities(updateParameter); // var response = await Manager.Inner.VirtualMachines.UpdateAsync(ResourceGroupName, vmName, updateParameter, cancellationToken); var extensionsCommited = await this.virtualMachineExtensions.CommitAndGetAllAsync(cancellationToken); if (extensionsCommited.Any()) { // Another get to fetch vm inner with extensions list reflecting the commited changes to extensions // response = await Manager.Inner.VirtualMachines.GetAsync(ResourceGroupName, vmName, null, cancellationToken); } this.Reset(response); await virtualMachineMsiHelper.CommitsRoleAssignmentsPendingActionAsync(cancellationToken); } return this; } ///GENMHASH:C39D7E2559FD1B42A87D25FE5A1DF9FB:66952279088908D6E3122C9FE427DCE3 private void Reset(VirtualMachineInner inner) { this.SetInner(inner); ClearCachedRelatedResources(); InitializeDataDisks(); InitializeExtensions(); this.virtualMachineMsiHelper.Clear(); } ///GENMHASH:F0BA5F3F27F923CBF88531E8051E2766:3A9860E56B386DEBF12E9494C009C2A3 internal VirtualMachineImpl WithExtension(VirtualMachineExtensionImpl extension) { this.virtualMachineExtensions.AddExtension(extension); return this; } ///GENMHASH:935C3974286F7E329FEE80FBDDC054A4:A1DADF029D57D1765F6994801B1B1197 internal VirtualMachineImpl WithUnmanagedDataDisk(UnmanagedDataDiskImpl dataDisk) { Inner .StorageProfile .DataDisks .Add(dataDisk.Inner); this.unmanagedDataDisks .Add(dataDisk); return this; } ///GENMHASH:F8B60EFFDA7AE3E1DE1C427665105067:0C39F05B8A560CA80F8F94A7A6DC6D17 private void SetOSDiskDefaults() { if (IsInUpdateMode()) { return; } StorageProfile storageProfile = Inner.StorageProfile; OSDisk osDisk = storageProfile.OsDisk; if (IsOSDiskFromImage(osDisk)) { // ODDisk CreateOption: FROM_IMAGE // if (IsManagedDiskEnabled()) { // Note: // Managed disk // Supported: PlatformImage and CustomImage // UnSupported: StoredImage // if (osDisk.ManagedDisk == null) { osDisk.ManagedDisk = new ManagedDiskParametersInner(); } if (osDisk.ManagedDisk.StorageAccountType == null) { osDisk.ManagedDisk .StorageAccountType = StorageAccountTypes.StandardLRS; } osDisk.Vhd = null; // We won't set osDisk.Name() explicitly for managed disk, if it is null CRP generates unique // name for the disk resource within the resource group. } else { // Note: // Native (un-managed) disk // Supported: PlatformImage and StoredImage // UnSupported: CustomImage // if (IsOSDiskFromPlatformImage(storageProfile) || IsOSDiskFromStoredImage(storageProfile)) { if (osDisk.Vhd == null) { string osDiskVhdContainerName = "vhds"; string osDiskVhdName = this.vmName + "-os-disk-" + Guid.NewGuid().ToString() + ".Vhd"; WithOSDiskVhdLocation(osDiskVhdContainerName, osDiskVhdName); } osDisk.ManagedDisk = null; } if (osDisk.Name == null) { WithOSDiskName(this.vmName + "-os-disk"); } } } else { // ODDisk CreateOption: ATTACH // if (IsManagedDiskEnabled()) { // In case of attach, it is not allowed to change the storage account type of the // managed disk. // if (osDisk.ManagedDisk != null) { osDisk.ManagedDisk.StorageAccountType = null; } osDisk.Vhd = null; } else { osDisk.ManagedDisk = null; if (osDisk.Name == null) { WithOSDiskName(this.vmName + "-os-disk"); } } } if (osDisk.Caching == null) { WithOSDiskCaching(CachingTypes.ReadWrite); } } ///GENMHASH:67723971057BB45E3F0FFEB5B7B65F34:0E41FE124CF67BA67B6A50BC9B9B57B0 private void SetOSProfileDefaults() { if (IsInUpdateMode()) { return; } StorageProfile storageProfile = Inner.StorageProfile; OSDisk osDisk = storageProfile.OsDisk; if (IsOSDiskFromImage(osDisk)) { // ODDisk CreateOption: FROM_IMAGE // if (osDisk.OsType == OperatingSystemTypes.Linux || this.isMarketplaceLinuxImage) { // linux image: PlatformImage | CustomImage | StoredImage // OSProfile osProfile = Inner.OsProfile; if (osProfile.LinuxConfiguration == null) { osProfile.LinuxConfiguration = new LinuxConfiguration(); } Inner.OsProfile .LinuxConfiguration .DisablePasswordAuthentication = osProfile.AdminPassword == null; } if (Inner.OsProfile.ComputerName == null) { // VM name cannot contain only numeric values and cannot exceed 15 chars if ((new Regex(@"^\d+$")).IsMatch(vmName)) { Inner.OsProfile.ComputerName = SdkContext.RandomResourceName("vm", 15); } else if (vmName.Length <= 15) { Inner.OsProfile.ComputerName = vmName; } else { Inner.OsProfile.ComputerName = SdkContext.RandomResourceName("vm", 15); } } } else { // ODDisk CreateOption: ATTACH // // OS Profile must be set to null when an VM's OS disk is ATTACH-ed to a managed disk or // Specialized VHD // Inner.OsProfile = null; } } ///GENMHASH:BAA70B10A8929783F1FC5D60B4D80538:733856474CD1EBA8B9EB83FA7C73D293 private void SetHardwareProfileDefaults() { if (!IsInCreateMode) { return; } HardwareProfile hardwareProfile = Inner.HardwareProfile; if (hardwareProfile.VmSize == null) { hardwareProfile.VmSize = VirtualMachineSizeTypes.BasicA0; } } ///GENMHASH:E9830BD8841F5F66740928BA7AA21EB0:52457D4653AB87BFDAB452BDB2A8B34C private async Task<IStorageAccount> HandleStorageSettingsAsync(CancellationToken cancellationToken = default(CancellationToken)) { IStorageAccount storageAccount = null; if (this.creatableStorageAccountKey != null) { storageAccount = (IStorageAccount)this.CreatedResource(this.creatableStorageAccountKey); } else if (this.existingStorageAccountToAssociate != null) { storageAccount = this.existingStorageAccountToAssociate; } else if (this.OsDiskRequiresImplicitStorageAccountCreation() || this.DataDisksRequiresImplicitStorageAccountCreation()) { storageAccount = await this.storageManager.StorageAccounts .Define(this.namer.RandomName("stg", 24).Replace("-", "")) .WithRegion(this.RegionName) .WithExistingResourceGroup(this.ResourceGroupName) .CreateAsync(cancellationToken); } if (!IsManagedDiskEnabled()) { if (IsInCreateMode) { if (this.IsOSDiskFromPlatformImage(Inner.StorageProfile)) { string uri = Inner.StorageProfile.OsDisk.Vhd.Uri; if (uri.StartsWith("{storage-base-url}")) { uri = uri.Remove(0, "{storage-base-url}".Length).Insert(0, storageAccount.EndPoints.Primary.Blob); } Inner.StorageProfile.OsDisk.Vhd.Uri = uri; } UnmanagedDataDiskImpl.EnsureDisksVhdUri(this.unmanagedDataDisks, storageAccount, this.vmName); } else { if (storageAccount != null) { UnmanagedDataDiskImpl.EnsureDisksVhdUri(this.unmanagedDataDisks, storageAccount, this.vmName); } else { UnmanagedDataDiskImpl.EnsureDisksVhdUri(this.unmanagedDataDisks, this.vmName); } } } return storageAccount; } ///GENMHASH:679C8E77D63CDAC3C75B428C73FDBA6F:810F9B4884B03FC354476CC848056897 private async Task<Microsoft.Azure.Management.Storage.Fluent.IStorageAccount> HandleBootDiagnosticsStorageSettingsAsync(IStorageAccount diskStorageAccount, CancellationToken cancellationToken = default(CancellationToken)) { if (this.Inner.DiagnosticsProfile == null || this.Inner.DiagnosticsProfile.BootDiagnostics == null) { return diskStorageAccount; } else if (this.Inner.DiagnosticsProfile.BootDiagnostics.StorageUri != null) { return diskStorageAccount; } else if (this.Inner.DiagnosticsProfile.BootDiagnostics.Enabled.HasValue && this.Inner.DiagnosticsProfile.BootDiagnostics.Enabled == true) { if (this.creatableDiagnosticsStorageAccountKey != null) { var diagnosticsStgAccount = (IStorageAccount)this.CreatedResource(this.creatableDiagnosticsStorageAccountKey); this.Inner.DiagnosticsProfile.BootDiagnostics.StorageUri = diagnosticsStgAccount.EndPoints.Primary.Blob; return diskStorageAccount == null ? diagnosticsStgAccount : diskStorageAccount; } if (diskStorageAccount != null) { this.Inner.DiagnosticsProfile.BootDiagnostics.StorageUri = diskStorageAccount.EndPoints.Primary.Blob; return diskStorageAccount; } else { var diagnosticsStgAccount = await this.storageManager.StorageAccounts .Define(this.namer.RandomName("stg", 24).Replace("-", "")) .WithRegion(this.RegionName) .WithExistingResourceGroup(this.ResourceGroupName) .CreateAsync(cancellationToken); this.Inner .DiagnosticsProfile .BootDiagnostics .StorageUri = diagnosticsStgAccount.EndPoints.Primary.Blob; return diagnosticsStgAccount; } } return diskStorageAccount; } private void CreateNewProximityPlacementGroup() { if (IsInCreateMode) { if (!String.IsNullOrWhiteSpace(this.newProximityPlacementGroupName)) { ProximityPlacementGroupInner plgInner = new ProximityPlacementGroupInner() { ProximityPlacementGroupType = this.newProximityPlacementGroupType, Location = this.Inner.Location }; plgInner = Extensions.Synchronize(() => this.Manager.Inner.ProximityPlacementGroups.CreateOrUpdateAsync(this.ResourceGroupName, newProximityPlacementGroupName, plgInner)); this.Inner.ProximityPlacementGroup = new SubResource() { Id = plgInner.Id }; } } } ///GENMHASH:D07A07F736607425258AAE80368A516D:168FE2B09726F397B3F197216CE80D80 private void HandleNetworkSettings() { if (IsInCreateMode) { INetworkInterface primaryNetworkInterface = null; if (this.creatablePrimaryNetworkInterfaceKey != null) { primaryNetworkInterface = (INetworkInterface)this.CreatedResource(this.creatablePrimaryNetworkInterfaceKey); } else if (this.existingPrimaryNetworkInterfaceToAssociate != null) { primaryNetworkInterface = this.existingPrimaryNetworkInterfaceToAssociate; } if (primaryNetworkInterface != null) { NetworkInterfaceReferenceInner nicReference = new NetworkInterfaceReferenceInner(); nicReference.Primary = true; nicReference.Id = primaryNetworkInterface.Id; Inner.NetworkProfile.NetworkInterfaces.Add(nicReference); } } // sets the virtual machine secondary network interfaces // foreach (string creatableSecondaryNetworkInterfaceKey in this.creatableSecondaryNetworkInterfaceKeys) { INetworkInterface secondaryNetworkInterface = (INetworkInterface)this.CreatedResource(creatableSecondaryNetworkInterfaceKey); NetworkInterfaceReferenceInner nicReference = new NetworkInterfaceReferenceInner(); nicReference.Primary = false; nicReference.Id = secondaryNetworkInterface.Id; Inner.NetworkProfile.NetworkInterfaces.Add(nicReference); } this.creatableSecondaryNetworkInterfaceKeys.Clear(); foreach (INetworkInterface secondaryNetworkInterface in this.existingSecondaryNetworkInterfacesToAssociate) { NetworkInterfaceReferenceInner nicReference = new NetworkInterfaceReferenceInner(); nicReference.Primary = false; nicReference.Id = secondaryNetworkInterface.Id; Inner.NetworkProfile.NetworkInterfaces.Add(nicReference); } this.existingSecondaryNetworkInterfacesToAssociate.Clear(); } ///GENMHASH:C5029F7D6B24C60F12C8C8EE00CA338D:4025A91B58E8284506099B34457E6276 private void EnableDisableBootDiagnostics(bool enable) { if (this.Inner.DiagnosticsProfile == null) { this.Inner.DiagnosticsProfile = new DiagnosticsProfile(); } if (this.Inner.DiagnosticsProfile.BootDiagnostics == null) { this.Inner.DiagnosticsProfile.BootDiagnostics = new BootDiagnostics(); } if (enable) { this.Inner.DiagnosticsProfile.BootDiagnostics.Enabled = true; } else { this.Inner.DiagnosticsProfile.BootDiagnostics.Enabled = false; this.Inner.DiagnosticsProfile.BootDiagnostics.StorageUri = null; } } ///GENMHASH:53777A14878B3B30AC6877B2675500B6:1AB26718B32878FC0C06014D270C9E47 private void HandleAvailabilitySettings() { if (!IsInCreateMode) { return; } IAvailabilitySet availabilitySet = null; if (this.creatableAvailabilitySetKey != null) { availabilitySet = (IAvailabilitySet)this.CreatedResource(this.creatableAvailabilitySetKey); } else if (this.existingAvailabilitySetToAssociate != null) { availabilitySet = this.existingAvailabilitySetToAssociate; } if (availabilitySet != null) { if (Inner.AvailabilitySet == null) { Inner.AvailabilitySet = new SubResource(); } Inner.AvailabilitySet.Id = availabilitySet.Id; } } ///GENMHASH:0F7707B8B59F80529877E77CA52B31EB:6699FB156B9D992393D42B866A411897 private bool OsDiskRequiresImplicitStorageAccountCreation() { if (IsManagedDiskEnabled()) { return false; } if (this.creatableStorageAccountKey != null || this.existingStorageAccountToAssociate != null || !IsInCreateMode) { return false; } return IsOSDiskFromPlatformImage(Inner.StorageProfile); } ///GENMHASH:E54BC4A600C7D7F1F1FE5ECD633F9B03:25941EB989277B5A8346038827B5F346 private bool DataDisksRequiresImplicitStorageAccountCreation() { if (IsManagedDiskEnabled()) { return false; } if (this.creatableStorageAccountKey != null || this.existingStorageAccountToAssociate != null || this.unmanagedDataDisks.Count == 0) { return false; } bool hasEmptyVhd = false; foreach (var dataDisk in this.unmanagedDataDisks) { if (dataDisk.CreationMethod == DiskCreateOptionTypes.Empty || dataDisk.CreationMethod == DiskCreateOptionTypes.FromImage) { if (dataDisk.Inner.Vhd == null) { hasEmptyVhd = true; break; } } } if (IsInCreateMode) { return hasEmptyVhd; } if (hasEmptyVhd) { // In update mode, if any of the data disk has vhd uri set then use same container // to store this disk, no need to create a storage account implicitly. foreach (var dataDisk in this.unmanagedDataDisks) { if (dataDisk.CreationMethod == DiskCreateOptionTypes.Attach && dataDisk.Inner.Vhd != null) { return false; } } return true; } return false; } /// <summary> /// Checks whether the OS disk is directly attached to a unmanaged VHD. /// </summary> /// <param name="osDisk">The osDisk value in the storage profile.</param> /// <return>True if the OS disk is attached to a unmanaged VHD, false otherwise.</return> ///GENMHASH:6CAC7BFC25EF528C827BF922106219DC:721D04FDAA4169ED19C4CC3CCA1A2EDC private bool IsOSDiskAttachedUnmanaged(OSDisk osDisk) { return osDisk.CreateOption == DiskCreateOptionTypes.Attach && osDisk.Vhd != null && osDisk.Vhd.Uri != null; } /// <summary> /// Checks whether the OS disk is directly attached to a managed disk. /// </summary> /// <param name="osDisk">The osDisk value in the storage profile.</param> /// <return>True if the OS disk is attached to a managed disk, false otherwise.</return> ///GENMHASH:854EABA33961F7FA017100E1888B2F8F:4738C912BD9ED6489A96318D934E8BC9 private bool IsOSDiskAttachedManaged(OSDisk osDisk) { return osDisk.CreateOption == DiskCreateOptionTypes.Attach && osDisk.ManagedDisk != null && osDisk.ManagedDisk.Id != null; } /// <summary> /// Checks whether the OS disk is based on an image (image from PIR or custom image [captured, bringYourOwnFeature]). /// </summary> /// <param name="osDisk">The osDisk value in the storage profile.</param> /// <return>True if the OS disk is configured to use image from PIR or custom image.</return> ///GENMHASH:2BC5DC58EDF7989592189AD8B4E29C17:4CD85EE98AD4F7CBC33994D722986AE5 private bool IsOSDiskFromImage(OSDisk osDisk) { return osDisk.CreateOption == DiskCreateOptionTypes.FromImage; } /// <summary> /// Checks whether the OS disk is based on an platform image (image in PIR). /// </summary> /// <param name="storageProfile">The storage profile.</param> /// <return>True if the OS disk is configured to be based on platform image.</return> ///GENMHASH:78EB0F392606FADDDAFE3E594B6F4E7F:8A0B58C5E0133CF29412CD658BAF8289 private bool IsOSDiskFromPlatformImage(StorageProfile storageProfile) { ImageReferenceInner imageReference = storageProfile.ImageReference; return IsOSDiskFromImage(storageProfile.OsDisk) && imageReference != null && imageReference.Publisher != null && imageReference.Offer != null && imageReference.Sku != null && imageReference.Version != null; } /// <summary> /// Checks whether the OS disk is based on a CustomImage. /// A custom image is represented by com.microsoft.azure.management.compute.VirtualMachineCustomImage. /// </summary> /// <param name="storageProfile">The storage profile.</param> /// <return>True if the OS disk is configured to be based on custom image.</return> ///GENMHASH:441A8F22C03964CEECA8AFEBA8740C9C:F979E27E10A5C3D262E33101E3EF232A private bool IsOsDiskFromCustomImage(StorageProfile storageProfile) { ImageReferenceInner imageReference = storageProfile.ImageReference; return IsOSDiskFromImage(storageProfile.OsDisk) && imageReference != null && imageReference.Id != null; } /// <summary> /// Checks whether the OS disk is based on a stored image ('captured' or 'bring your own feature'). /// A stored image is created by calling VirtualMachine.capture(String, String, boolean). /// </summary> /// <param name="storageProfile">The storage profile.</param> /// <return>True if the OS disk is configured to use custom image ('captured' or 'bring your own feature').</return> ///GENMHASH:195FC3E4B41990335C260656FB0A8071:F51CCA18341E6B7F7C44FBF50F4BFC68 private bool IsOSDiskFromStoredImage(StorageProfile storageProfile) { OSDisk osDisk = storageProfile.OsDisk; return IsOSDiskFromImage(osDisk) && osDisk.Image != null && osDisk.Image.Uri != null; } ///GENMHASH:8143A53E487619B77CA38F74DEA81560:B603F79C83B2E3EB33CD223B542FC5BB private string TemporaryBlobUrl(string containerName, string blobName) { return "{storage-base-url}" + containerName + "/" + blobName; } ///GENMHASH:E972A9EA7BC4745B11D042E506C9EC88:67C9F7C47AB1078BBDB948EE068D0EDC private Network.Fluent.NetworkInterface.Definition.IWithPrimaryPublicIPAddress PrepareNetworkInterface(string name) { Network.Fluent.NetworkInterface.Definition.IWithGroup definitionWithGroup = this.networkManager.NetworkInterfaces .Define(name) .WithRegion(this.RegionName); Network.Fluent.NetworkInterface.Definition.IWithPrimaryNetwork definitionWithNetwork; if (this.newGroup != null) { definitionWithNetwork = definitionWithGroup.WithNewResourceGroup(this.newGroup); } else { definitionWithNetwork = definitionWithGroup.WithExistingResourceGroup(this.ResourceGroupName); } return definitionWithNetwork .WithNewPrimaryNetwork("vnet" + name) .WithPrimaryPrivateIPAddressDynamic(); } ///GENMHASH:528DB7AD001AA15B5C463269BA0A948C:86593E909D0CD3E320C19512D2A5F96A private Network.Fluent.NetworkInterface.Definition.IWithPrimaryNetwork PreparePrimaryNetworkInterface(string name) { Network.Fluent.NetworkInterface.Definition.IWithGroup definitionWithGroup = this.networkManager.NetworkInterfaces .Define(name) .WithRegion(this.RegionName); Network.Fluent.NetworkInterface.Definition.IWithPrimaryNetwork definitionAfterGroup; if (this.newGroup != null) { definitionAfterGroup = definitionWithGroup.WithNewResourceGroup(this.newGroup); } else { definitionAfterGroup = definitionWithGroup.WithExistingResourceGroup(this.ResourceGroupName); } return definitionAfterGroup; } ///GENMHASH:5D074C2BCA5877F1D6C918952020AA65:1F2CEECDB6231FC6883D5B321DFBE9BF private void InitializeDataDisks() { if (Inner.StorageProfile.DataDisks == null) { Inner .StorageProfile .DataDisks = new List<DataDisk>(); } this.isUnmanagedDiskSelected = false; this.managedDataDisks.Clear(); this.unmanagedDataDisks = new List<IVirtualMachineUnmanagedDataDisk>(); if (!IsManagedDiskEnabled()) { foreach (var dataDiskInner in this.StorageProfile().DataDisks) { this.unmanagedDataDisks.Add(new UnmanagedDataDiskImpl(dataDiskInner, this)); } } } private void InitializeExtensions() { this.virtualMachineExtensions = new VirtualMachineExtensionsImpl(this); } ///GENMHASH:7F6A7E961EA5A11F2B8013E54123A7D0:C1CDD6BC19A1D800E2865E3DC44941E1 private void ClearCachedRelatedResources() { this.virtualMachineInstanceView = null; } ///GENMHASH:15C87FF18F2D92A7CA828FB69E15D8F4:FAB35812CDE5256B5EEDB90655E51B75 private void ThrowIfManagedDiskEnabled(string message) { if (this.IsManagedDiskEnabled()) { throw new NotSupportedException(message); } } ///GENMHASH:CD7DD8B4BD138F5F21FC2A082781B05E:DF7F973BA6DA44DB874A039E8656D907 private void ThrowIfManagedDiskDisabled(string message) { if (!this.IsManagedDiskEnabled()) { throw new NotSupportedException(message); } } ///GENMHASH:B521ECE36A8645ACCD4603A46DF73D20:6C43F204834714CB74740068BED95D98 private bool IsInUpdateMode() { return !this.IsInCreateMode; } ///GENMHASH:31F1AF1FE9C5F41A363BCD2478A5DEE0:7DFBFA37EDE490851B9F2FD6F2A6E971 internal AzureEnvironment Environment() { return this.Manager.RestClient.Environment; } ///GENTHASH:Y29tLm1pY3Jvc29mdC5henVyZS5tYW5hZ2VtZW50LmNvbXB1dGUuaW1wbGVtZW50YXRpb24uVmlydHVhbE1hY2hpbmVJbXBsLk1hbmFnZWREYXRhRGlza0NvbGxlY3Rpb24= partial class ManagedDataDiskCollection { public IDictionary<string, Models.DataDisk> NewDisksToAttach; public IList<Models.DataDisk> ExistingDisksToAttach; public IList<Models.DataDisk> ImplicitDisksToAssociate; public IList<int> DiskLunsToRemove; public IList<Models.DataDisk> NewDisksFromImage; private VirtualMachineImpl vm; private CachingTypes? defaultCachingType; private StorageAccountTypes defaultStorageAccountType; ///GENMHASH:CA7F491172B86E1C8B0D8508E4161245:D1D4C18FF276F4E074EBD85D149B5349 internal void SetDataDisksDefaults() { VirtualMachineInner vmInner = this.vm.Inner; if (IsPending()) { if (vmInner.StorageProfile.DataDisks == null) { vmInner.StorageProfile.DataDisks = new List<DataDisk>(); } var dataDisks = vmInner.StorageProfile.DataDisks; var usedLuns = new HashSet<int>(); // Get all used luns // foreach (var dataDisk in dataDisks) { if (dataDisk.Lun != -1) { usedLuns.Add(dataDisk.Lun); } } foreach (var dataDisk in this.NewDisksToAttach.Values) { if (dataDisk.Lun != -1) { usedLuns.Add(dataDisk.Lun); } } foreach (var dataDisk in this.ExistingDisksToAttach) { if (dataDisk.Lun != -1) { usedLuns.Add(dataDisk.Lun); } } foreach (var dataDisk in this.ImplicitDisksToAssociate) { if (dataDisk.Lun != -1) { usedLuns.Add(dataDisk.Lun); } } foreach (var dataDisk in this.NewDisksFromImage) { if (dataDisk.Lun != -1) { usedLuns.Add(dataDisk.Lun); } } // Func to get the next available lun // Func<int> nextLun = () => { int l = 0; while (usedLuns.Contains(l)) { l++; } usedLuns.Add(l); return l; }; SetAttachableNewDataDisks(nextLun); SetAttachableExistingDataDisks(nextLun); SetImplicitDataDisks(nextLun); SetImageBasedDataDisks(); RemoveDataDisks(); } if (vmInner.StorageProfile.DataDisks != null && vmInner.StorageProfile.DataDisks.Count == 0) { if (vm.IsInCreateMode) { // If there is no data disks at all, then setting it to null rather than [] is necessary. // This is for take advantage of CRP's implicit creation of the data disks if the image has // more than one data disk image(s). // vmInner.StorageProfile.DataDisks = null; } } this.Clear(); } ///GENMHASH:0829442EB7C4FFD252C60EC2CCEF6312:62D273A513407F6CCA06E06DD3D01589 internal void SetAttachableNewDataDisks(Func<int> nextLun) { var dataDisks = vm.Inner.StorageProfile.DataDisks; foreach (var entry in this.NewDisksToAttach) { var managedDisk = (IDisk)vm.CreatedResource(entry.Key); DataDisk dataDisk = entry.Value; dataDisk.CreateOption = DiskCreateOptionTypes.Attach; if (dataDisk.Lun == -1) { dataDisk.Lun = nextLun(); } dataDisk.ManagedDisk = new ManagedDiskParametersInner(); dataDisk.ManagedDisk.Id = managedDisk.Id; if (dataDisk.Caching == null) { dataDisk.Caching = GetDefaultCachingType(); } // Don't set default storage account type for the attachable managed disks, it is already // defined in the managed disk and not allowed to change. dataDisk.Name = null; dataDisks.Add(dataDisk); } } ///GENMHASH:BDEEEC08EF65465346251F0F99D16258:03DF97ED7F5E19A604383CDB6F977583 internal void Clear() { NewDisksToAttach.Clear(); ExistingDisksToAttach.Clear(); ImplicitDisksToAssociate.Clear(); DiskLunsToRemove.Clear(); } ///GENMHASH:0E80C978BE389A20F8B9BDDCBC308EBF:F8C8996370B742865324C10D4FF7ACF4 internal void SetImplicitDataDisks(Func<int> nextLun) { var dataDisks = vm.Inner.StorageProfile.DataDisks; foreach (var dataDisk in this.ImplicitDisksToAssociate) { dataDisk.CreateOption = DiskCreateOptionTypes.Empty; if (dataDisk.Lun == -1) { dataDisk.Lun = nextLun(); } if (dataDisk.Caching == null) { dataDisk.Caching = GetDefaultCachingType(); } if (dataDisk.ManagedDisk == null) { dataDisk.ManagedDisk = new ManagedDiskParametersInner(); } if (dataDisk.ManagedDisk.StorageAccountType == null) { dataDisk.ManagedDisk.StorageAccountType = GetDefaultStorageAccountType(); } dataDisk.Name = null; dataDisks.Add(dataDisk); } } ///GENMHASH:EC209EBA0DF87A8C3CEA3D68742EA90D:5A0A84D8C0755F9E394C7D219CCD1CA5 internal bool IsPending() { return NewDisksToAttach.Count > 0 || ExistingDisksToAttach.Count > 0 || ImplicitDisksToAssociate.Count > 0 || DiskLunsToRemove.Count > 0; } ///GENMHASH:1B972065A6AA6248776B41DE6F26CB8F:E48C33EDF09F7C0FF8274C18F487CABF internal void SetAttachableExistingDataDisks(Func<int> nextLun) { var dataDisks = vm.Inner.StorageProfile.DataDisks; foreach (var dataDisk in this.ExistingDisksToAttach) { dataDisk.CreateOption = DiskCreateOptionTypes.Attach; if (dataDisk.Lun == -1) { dataDisk.Lun = nextLun(); } if (dataDisk.Caching == null) { dataDisk.Caching = GetDefaultCachingType(); } // Don't set default storage account type for the attachable managed disks, it is already // defined in the managed disk and not allowed to change. dataDisk.Name = null; dataDisks.Add(dataDisk); } } ///GENMHASH:E896A9714FD3ED579D3A806B2D670211:9EC21D752F2334263B0BF51F5BEF2FE2 internal void SetDefaultStorageAccountType(StorageAccountTypes defaultStorageAccountType) { this.defaultStorageAccountType = defaultStorageAccountType; } ///GENMHASH:77E6B131587760C1313B68052BA1F959:3583CA6C895B07FD3877A9CFC685B07B internal CachingTypes GetDefaultCachingType() { if (defaultCachingType == null) { return CachingTypes.ReadWrite; } return defaultCachingType.Value; } ///GENMHASH:B33308470B073DF5A31970C4C53291A4:4521033F354DF5B57E3BD39652BD8FF9 internal void SetImageBasedDataDisks() { var dataDisks = vm.Inner.StorageProfile.DataDisks; foreach (var dataDisk in this.NewDisksFromImage) { dataDisk.CreateOption = DiskCreateOptionTypes.FromImage; // Don't set default caching type for the disk, either user has to specify it explicitly or let CRP pick // it from the image // Don't set default storage account type for the disk, either user has to specify it explicitly or let // CRP pick it from the image dataDisk.Name = null; dataDisks.Add(dataDisk); } } ///GENMHASH:C474BAF5F2762CA941D8C01DC8F0A2CB:123893CCEC4625CDE4B7BCBFC68DCF5B internal void SetDefaultCachingType(CachingTypes cachingType) { this.defaultCachingType = cachingType; } ///GENMHASH:8F31500456F297BA5B51A162318FE60B:D8B2ED5EFB9DF0321EAAF10ACCE8A1C3 internal void RemoveDataDisks() { var dataDisks = vm.Inner.StorageProfile.DataDisks; foreach (var lun in this.DiskLunsToRemove) { int indexToRemove = 0; foreach (var dataDisk in dataDisks) { if (dataDisk.Lun == lun) { dataDisks.RemoveAt(indexToRemove); break; } indexToRemove++; } } } ///GENMHASH:647794DB64052F8555CB8ABDABF9F24D:419FDCEEC4AAB55470C80A42C1D69868 internal StorageAccountTypes GetDefaultStorageAccountType() { if (defaultStorageAccountType == null) { return StorageAccountTypes.StandardLRS; } return defaultStorageAccountType; } ///GENMHASH:F6F68BF2F3D740A8BBA2AA1A30D0B189:428C729973EF037C0B0B7EF8BA639DD8 internal ManagedDataDiskCollection(VirtualMachineImpl vm) { this.vm = vm; this.NewDisksToAttach = new Dictionary<string, DataDisk>(); this.ExistingDisksToAttach = new List<DataDisk>(); this.ImplicitDisksToAssociate = new List<DataDisk>(); this.NewDisksFromImage = new List<DataDisk>(); this.DiskLunsToRemove = new List<int>(); } } } }
44.015193
230
0.622478
[ "MIT" ]
HarveyLink/azure-libraries-for-net
src/ResourceManagement/Compute/VirtualMachineImpl.cs
127,468
C#
using System.Collections.Generic; using Oakton; namespace NSwagen.Cli.Inputs { public class ConfigInput : BaseInput { public CommandAction Action { get; set; } = CommandAction.init; [FlagAlias('d')] [Description("Generates configurations with default values.")] public bool DefaultFlag { get; set; } [FlagAlias("output", 'o')] [Description("Directory to create the config file. If not specified, current directory is used.")] public string? OutputFlag { get; set; } [FlagAlias("client-output", 'c')] [Description("File path to create the client proxy.")] public string? ClientOutputFlag { get; set; } [FlagAlias("swagger", true)] [Description("The swagger document file or url path used to generate client.")] public string SwaggerFlag { get; set; } = null!; [FlagAlias("prop")] [Description("The property required for client generation.")] #pragma warning disable CA1051 // Do not declare visible instance fields #pragma warning disable S1104 // Fields should not have public accessibility #pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. #pragma warning disable SA1401 // Fields should be private public Dictionary<string, string> PropFlag = new Dictionary<string, string>(); #pragma warning restore SA1401 // Fields should be private #pragma warning restore CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. #pragma warning restore S1104 // Fields should not have public accessibility #pragma warning restore CA1051 // Do not declare visible instance fields public enum CommandAction { #pragma warning disable SA1300 // Element should begin with upper-case letter init, add, } #pragma warning restore SA1300 // Element should begin with upper-case letter } }
42.041667
140
0.699703
[ "MIT" ]
prathimanm/NSwagen
src/NSwagen/Inputs/ConfigInput.cs
2,020
C#
using Portal.CMS.Entities; using Portal.CMS.Entities.Entities; using System; using System.Collections.Generic; using System.Linq; namespace Portal.CMS.Services.PageBuilder { public interface IPageAssociationService { List<PagePartial> Get(); PageAssociation Get(int pageAssociationId); void Delete(int pageAssociationId); void EditRoles(int pageAssociationId, List<string> roleList); void EditOrder(int pageId, string associationList); void Clone(int pageAssociationId, int pageId); } public class PageAssociationService : IPageAssociationService { #region Dependencies private readonly PortalEntityModel _context; public PageAssociationService(PortalEntityModel context) { _context = context; } #endregion Dependencies public List<PagePartial> Get() { var existingPartialList = _context.PagePartials.ToList(); var distinctPartialList = new List<PagePartial>(); foreach (var partial in existingPartialList) if (!distinctPartialList.Any(x => x.RouteArea == partial.RouteArea && x.RouteController == partial.RouteController && x.RouteAction == partial.RouteAction)) distinctPartialList.Add(partial); return distinctPartialList; } public PageAssociation Get(int pageAssociationId) { var pageAssociation = _context.PageAssociations.SingleOrDefault(pa => pa.PageAssociationId == pageAssociationId); return pageAssociation; } public void Delete(int pageAssociationId) { var pageAssociation = _context.PageAssociations.SingleOrDefault(x => x.PageAssociationId == pageAssociationId); if (pageAssociation == null) return; if (pageAssociation.PageSection != null) { if (!_context.PageAssociations.Any(x => x.PageSectionId == pageAssociation.PageSectionId)) { var pageSection = _context.PageSections.SingleOrDefault(x => x.PageSectionId == pageAssociation.PageSectionId); _context.PageSections.Remove(pageSection); } } else if (pageAssociation.PagePartial != null) { if (!_context.PageAssociations.Any(x => x.PagePartialId == pageAssociation.PagePartialId)) { var pagePartial = _context.PagePartials.SingleOrDefault(x => x.PagePartialId == pageAssociation.PagePartialId); _context.PagePartials.Remove(pagePartial); } } _context.PageAssociations.Remove(pageAssociation); _context.SaveChanges(); } public void EditRoles(int pageAssociationId, List<string> roleList) { var pageAssociation = _context.PageAssociations.SingleOrDefault(pa => pa.PageAssociationId == pageAssociationId); if (pageAssociation == null) return; var roles = _context.Roles.ToList(); foreach (var role in pageAssociation.PageAssociationRoles.ToList()) _context.PageAssociationRoles.Remove(role); foreach (var roleName in roleList) { var currentRole = roles.FirstOrDefault(x => x.RoleName == roleName); if (currentRole == null) continue; _context.PageAssociationRoles.Add(new PageAssociationRole { PageAssociationId = pageAssociationId, RoleId = currentRole.RoleId }); } _context.SaveChanges(); } public void EditOrder(int pageId, string associationList) { var page = _context.Pages.SingleOrDefault(x => x.PageId == pageId); if (page == null) return; var associations = associationList.Split(','); foreach (var associationProperties in associations) { var properties = associationProperties.Split('-'); var orderId = properties[0]; var associationId = properties[1]; var pageAssociation = page.PageAssociations.SingleOrDefault(x => x.PageAssociationId.ToString() == associationId.ToString()); if (pageAssociation == null) continue; pageAssociation.PageAssociationOrder = Convert.ToInt32(orderId); } _context.SaveChanges(); } public void Clone(int pageAssociationId, int pageId) { var pageAssociation = _context.PageAssociations.FirstOrDefault(pa => pa.PageAssociationId == pageAssociationId); if (pageAssociation == null) return; var page = _context.Pages.FirstOrDefault(p => p.PageId == pageId); if (page == null) return; if (pageAssociation.PageSection != null) { var clonePageAssociation = new PageAssociation { PageSectionId = pageAssociation.PageSectionId, PageId = page.PageId, PageAssociationRoles = pageAssociation.PageAssociationRoles, }; if (page.PageAssociations.Any()) clonePageAssociation.PageAssociationOrder = page.PageAssociations.Max(pa => pa.PageAssociationOrder + 1); else clonePageAssociation.PageAssociationOrder = 1; _context.PageAssociations.Add(clonePageAssociation); _context.SaveChanges(); } } } }
35.375
172
0.606537
[ "MIT" ]
garora/PortalCMS
Portal.CMS.Services/PageBuilder/PageAssociationService.cs
5,662
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.ComponentModel; namespace System.Diagnostics { [Flags] public enum SourceLevels { Off = 0, Critical = 0x01, Error = 0x03, Warning = 0x07, Information = 0x0F, Verbose = 0x1F, All = unchecked((int)0xFFFFFFFF), } }
21.583333
71
0.640927
[ "MIT" ]
OceanYan/corefx
src/System.Diagnostics.TraceSource/src/System/Diagnostics/SourceLevels.cs
518
C#
// --------------------------------------------------------------------------------------- // <copyright file="KeypadStaticTests.cs" company="Corale"> // Copyright © 2015-2021 by Adam Hellberg and Brandon Scott. // // 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. // // "Razer" is a trademark of Razer USA Ltd. // </copyright> // --------------------------------------------------------------------------------------- namespace Colore.Tests.Effects.Keypad.Effects { using Colore.Data; using Colore.Effects.Keypad; using NUnit.Framework; [TestFixture] public class KeypadStaticTests { [Test] public void ShouldConstructWithCorrectColor() { Assert.AreEqual(Color.Red, new StaticKeypadEffect(Color.Red).Color); } [Test] public void ShouldEqualEffectWithSameColor() { var a = new StaticKeypadEffect(Color.Red); var b = new StaticKeypadEffect(Color.Red); Assert.AreEqual(a, b); } [Test] public void ShouldNotEqualEffectWithDifferentColor() { var a = new StaticKeypadEffect(Color.Red); var b = new StaticKeypadEffect(Color.Blue); Assert.AreNotEqual(a, b); } [Test] public void ShouldEqualEffectWithSameColorUsingEqualOp() { var a = new StaticKeypadEffect(Color.Red); var b = new StaticKeypadEffect(Color.Red); Assert.True(a == b); } [Test] public void ShouldNotEqualEffectWithDifferentColorUsingEqualOp() { var a = new StaticKeypadEffect(Color.Red); var b = new StaticKeypadEffect(Color.Blue); Assert.False(a == b); } [Test] public void ShouldEqualEffectWithSameColorUsingNotEqualOp() { var a = new StaticKeypadEffect(Color.Red); var b = new StaticKeypadEffect(Color.Red); Assert.False(a != b); } [Test] public void ShouldNotEqualEffectWithDifferentColorUsingNotEqualOp() { var a = new StaticKeypadEffect(Color.Red); var b = new StaticKeypadEffect(Color.Blue); Assert.True(a != b); } [Test] public void ShouldNotEqualNull() { var effect = new StaticKeypadEffect(Color.Red); Assert.AreNotEqual(effect, null); Assert.False(effect.Equals(null)); } [Test] public void ShouldHaveSameHashcodeAsColor() { var color = Color.Red; var hashcode = color.GetHashCode(); var effect = new StaticKeypadEffect(color); Assert.AreEqual(hashcode, effect.GetHashCode()); } [Test] public void ShouldNotEqualArbitraryObject() { var effect = new StaticKeypadEffect(Color.Red); var obj = new object(); Assert.False(effect.Equals(obj)); } [Test] public void ShouldEqualEffectWithSameColorCastAsObject() { var effect = new StaticKeypadEffect(Color.Red); var obj = new StaticKeypadEffect(Color.Red) as object; Assert.True(effect.Equals(obj)); } [Test] public void ShouldNotEqualEffectWithDifferentColorCastAsObject() { var effect = new StaticKeypadEffect(Color.Red); var obj = new StaticKeypadEffect(Color.Blue) as object; Assert.False(effect.Equals(obj)); } } }
35.295455
90
0.592402
[ "MIT" ]
CoraleStudios/Colore
tests/Colore.Tests/Effects/Keypad/Effects/KeypadStaticTests.cs
4,660
C#
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.Services; using System.Web.Script.Services; using System.Data.SqlClient; using System.Configuration; using System.IO; using System.Data; using System.Text; using System.Net.Mail; using System.Text.RegularExpressions; public partial class news_items : System.Web.UI.Page { public int currRegion = 1; protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { if (Session["currLang"] != null) { TableContent.SelectParameters["region"].DefaultValue = Session["currLang"].ToString(); currRegion = Convert.ToInt32(Session["currLang"]); } } string uniqStr = Guid.NewGuid().ToString(); string thumbnail = "-thumbnail"; foreach (string s in Request.Files) { HttpPostedFile file = Request.Files[s]; int fileSizeInBytes = file.ContentLength; string fileName = file.FileName; string fileExtension = ""; if (!string.IsNullOrEmpty(fileName)) { fileExtension = Path.GetExtension(fileName); } // IMPORTANT! Make sure to validate uploaded file contents, size, etc. to prevent scripts being uploaded into your web app directory string savedFileName = Path.Combine(Server.MapPath("~/images/product_images/"), uniqStr + thumbnail + fileExtension); file.SaveAs(savedFileName); //Response.Write("<script>alert('Filename: " + fileName + "|| Extention: " + fileExtension + "||" + savedFileName + " || Query: " + Request.QueryString + "');</script>"); if (thumbnail == "") { using (SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["SPEXCertiprep"].ConnectionString)) { string SQL = "INSERT INTO certiProdImages_List (img, title, dateupload) VALUES (@img, @title, @dateupload)"; using (SqlCommand cmd = new SqlCommand(SQL, cn)) { cmd.CommandType = CommandType.Text; cmd.Parameters.Add("@img", SqlDbType.NVarChar, 255).Value = uniqStr + fileExtension; cmd.Parameters.Add("@title", SqlDbType.NVarChar, 100).Value = fileName.Replace(fileExtension, ""); cmd.Parameters.Add("@dateupload", SqlDbType.DateTime).Value = DateTime.Now; cmd.Connection.Open(); cmd.ExecuteNonQuery(); cmd.Connection.Close(); } } } thumbnail = ""; } lvNewsTable.DataSource = TableContent; lvNewsTable.DataBind(); } protected void ddlDisplay_SelectedIndexChanged(object sender, EventArgs e) { DataPager1.PageSize = Convert.ToInt32(ddlDisplay.SelectedValue); lvNewsTable.DataSource = TableContent; lvNewsTable.DataBind(); } protected void ddlLang_SelectedIndexChanged(object sender, EventArgs e) { currRegion = Convert.ToInt32(ddlLang.SelectedValue); Session["currLang"] = currRegion; } [WebMethod()] public static string saveImgDetails(int id, string title, string caption, string alttext, string description) { string SQL = ""; using (SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["SPEXCertiprep"].ConnectionString)) { SQL = "UPDATE certiProdImages_List SET [title] = @title, [caption] = @caption, [altText] = @altText, [description] = @desc WHERE id = @ID"; using (SqlCommand cmd = new SqlCommand(SQL, cn)) { cmd.CommandType = CommandType.Text; cmd.Connection.Open(); cmd.Parameters.Add("ID", SqlDbType.Int).Value = id; cmd.Parameters.Add("title", SqlDbType.NVarChar, 256).Value = title; cmd.Parameters.Add("caption", SqlDbType.NVarChar, 256).Value = caption; cmd.Parameters.Add("altText", SqlDbType.NVarChar, 256).Value = alttext; cmd.Parameters.Add("desc", SqlDbType.Text).Value = description; cmd.ExecuteNonQuery(); cmd.Connection.Close(); } } return "<div class='alert alert-success alert-dismissable bg-success'><button type='button' class='close' data-dismiss='alert' aria-hidden='true'>×</button>Image details has been updated!</div>"; } [WebMethod()] public static string saveImgProduct(int id, string partnum) { string SQL = ""; string output = ""; bool exist = false; using (SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["SPEXCertiprep"].ConnectionString)) { SQL = "SELECT cpPart FROM cp_roi_Prods WHERE cpPart = @part"; using (SqlCommand cmd = new SqlCommand(SQL, cn)) { cmd.CommandType = CommandType.Text; cmd.Parameters.Add("part", SqlDbType.NVarChar, 50).Value = partnum; cmd.Connection.Open(); SqlDataReader dr = cmd.ExecuteReader(); if (dr.HasRows) { exist = true; }else { output = "<div class='alert alert-danger alert-dismissable bg-danger'><button type='button' class='close' data-dismiss='alert' aria-hidden='true'>×</button>Product does not exist! Please check your Part Number.</div>"; } cmd.Connection.Close(); } if (exist == true) { SQL = "INSERT INTO certiProdImages (PartNumber, img_id) VALUES (@part, @ID)"; using (SqlCommand cmd = new SqlCommand(SQL, cn)) { cmd.CommandType = CommandType.Text; cmd.Connection.Open(); cmd.Parameters.Add("ID", SqlDbType.Int).Value = id; cmd.Parameters.Add("part", SqlDbType.NVarChar, 50).Value = partnum; cmd.ExecuteNonQuery(); cmd.Connection.Close(); } output = "<div class='alert alert-success alert-dismissable bg-success'><button type='button' class='close' data-dismiss='alert' aria-hidden='true'>×</button>Product has been added.</div>"; } } return output; } [WebMethod()] public static string deleteItem(int newsid) { string SQL = ""; using (SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["SPEXCertiprep"].ConnectionString)) { using (SqlCommand cmd = new SqlCommand("SELECT thumb FROM sp_News WHERE id = @ID", cn)) { cmd.CommandType = CommandType.Text; cmd.Parameters.Add("ID", SqlDbType.Int).Value = newsid; cmd.Connection.Open(); SqlDataReader dr = cmd.ExecuteReader(CommandBehavior.SingleRow); if (dr.HasRows) { dr.Read(); if(File.Exists(mapMethod("~/news-and-events/images/" + dr["thumb"].ToString()))) { File.Delete(mapMethod("~/news-and-events/images/" + dr["thumb"].ToString())); } cmd.Connection.Close(); } } SQL = "DELETE FROM [sp_News] WHERE id = " + newsid; using (SqlCommand cmd = new SqlCommand(SQL, cn)) { cmd.CommandType = CommandType.Text; cmd.Connection.Open(); cmd.ExecuteNonQuery(); cmd.Connection.Close(); } SQL = "DELETE FROM [sp_News_Locale] WHERE newsID = " + newsid; using (SqlCommand cmd = new SqlCommand(SQL, cn)) { cmd.CommandType = CommandType.Text; cmd.Connection.Open(); cmd.ExecuteNonQuery(); cmd.Connection.Close(); } } return "<div class='alert alert-success alert-dismissable bg-success'><button type='button' class='close' data-dismiss='alert' aria-hidden='true'>×</button>News Item has been Deleted</div>"; } [WebMethod()] public static string removePart(int itemid) { string SQL = ""; using (SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["SPEXCertiprep"].ConnectionString)) { SQL = "DELETE FROM [certiProdImages] WHERE id = " + itemid; using (SqlCommand cmd = new SqlCommand(SQL, cn)) { cmd.CommandType = CommandType.Text; cmd.Connection.Open(); cmd.ExecuteNonQuery(); cmd.Connection.Close(); } } return ""; } [WebMethod()] public static string uploadImage() { string SQL = ""; /*using (SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["SPEXCertiprep"].ConnectionString)) { SQL = "DELETE FROM [certiProdImages] WHERE id = " + itemid; using (SqlCommand cmd = new SqlCommand(SQL, cn)) { cmd.CommandType = CommandType.Text; cmd.Connection.Open(); cmd.ExecuteNonQuery(); cmd.Connection.Close(); } }*/ return "<script>alert('Upload return')</script>"; } public string getThumbnail(string img) { string imgURL = img; //imgURL = img.Replace(".png", "-thumbnail.png"); //imgURL = img.Replace(".jpg", "-thumbnail.png"); if(File.Exists(mapMethod("~/images/product_images/" + imgURL))) { imgURL = "/images/product_images/" + imgURL; }else { imgURL = "https://placehold.it/145x145"; } return imgURL; } public static string mapMethod(string path) { var mappedPath = HttpContext.Current.Server.MapPath(path); return mappedPath; } public string getProducts(string id) { string output = ""; using (SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["SPEXCertiprep"].ConnectionString)) { using (SqlCommand cmd = new SqlCommand("SELECT * FROM certiProdImages WHERE img_id = @ID", cn)) { cmd.CommandType = CommandType.Text; cmd.Parameters.Add("ID", SqlDbType.Int).Value = id; cmd.Connection.Open(); SqlDataReader dr = cmd.ExecuteReader(); while(dr.Read()) { output += "<div id='close-" + dr["id"].ToString().Trim() + "' class='products'>" + dr["PartNumber"].ToString().Trim() + "<a class='close' data-id='" + dr["id"].ToString().Trim() + "'>x</a></div>"; } } } return output; } }
40.232932
224
0.62767
[ "MIT" ]
spexcertigit/spexcertiprep
admin/product-images/default.aspx.cs
10,024
C#
using Foundation; using UIKit; using System.IO; using Styles.Color; using Styles.Text; namespace ColorStyleDemo.iOS { // 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 TextStyle.Main.SetCSS (File.ReadAllText ("Style.css")); 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. } } }
34.830769
122
0.760159
[ "MIT" ]
ClintFrancis/Styles.Color
samples/ColorStyleDemo.iOS/AppDelegate.cs
2,266
C#
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AzureNextGen.Compute.V20180601.Outputs { [OutputType] public sealed class VaultCertificateResponse { /// <summary> /// For Windows VMs, specifies the certificate store on the Virtual Machine to which the certificate should be added. The specified certificate store is implicitly in the LocalMachine account. &lt;br&gt;&lt;br&gt;For Linux VMs, the certificate file is placed under the /var/lib/waagent directory, with the file name &amp;lt;UppercaseThumbprint&amp;gt;.crt for the X509 certificate file and &amp;lt;UppercaseThumbprint&amp;gt;.prv for private key. Both of these files are .pem formatted. /// </summary> public readonly string? CertificateStore; /// <summary> /// This is the URL of a certificate that has been uploaded to Key Vault as a secret. For adding a secret to the Key Vault, see [Add a key or secret to the key vault](https://docs.microsoft.com/azure/key-vault/key-vault-get-started/#add). In this case, your certificate needs to be It is the Base64 encoding of the following JSON Object which is encoded in UTF-8: &lt;br&gt;&lt;br&gt; {&lt;br&gt; "data":"&lt;Base64-encoded-certificate&gt;",&lt;br&gt; "dataType":"pfx",&lt;br&gt; "password":"&lt;pfx-file-password&gt;"&lt;br&gt;} /// </summary> public readonly string? CertificateUrl; [OutputConstructor] private VaultCertificateResponse( string? certificateStore, string? certificateUrl) { CertificateStore = certificateStore; CertificateUrl = certificateUrl; } } }
53.388889
540
0.700312
[ "Apache-2.0" ]
pulumi/pulumi-azure-nextgen
sdk/dotnet/Compute/V20180601/Outputs/VaultCertificateResponse.cs
1,922
C#
using System; using System.Collections; namespace UniRx { public sealed class MultipleAssignmentDisposable : IDisposable, ICancelable { static readonly BooleanDisposable True = new BooleanDisposable(true); object gate = new object(); IDisposable current; public bool IsDisposed { get { lock (gate) { return current == True; } } } public IDisposable Disposable { get { lock (gate) { return (current == True) ? UniRx.Disposable.Empty : current; } } set { var shouldDispose = false; lock (gate) { shouldDispose = (current == True); if (!shouldDispose) { current = value; } } if (shouldDispose && value != null) { value.Dispose(); } } } public void Dispose() { IDisposable old = null; lock (gate) { if (current != True) { old = current; current = True; } } if (old != null) old.Dispose(); } } }
22.927536
79
0.350822
[ "MIT" ]
142333lzg/jynew
jyx2/Assets/Plugins/UniRx/Scripts/Disposables/MultipleAssignmentDisposable.cs
1,584
C#
// Copyright (c) 2015-present, Parse, LLC. All rights reserved. This source code is licensed under the BSD-style license found in the LICENSE file in the root directory of this source tree. An additional grant of patent rights can be found in the PATENTS file in the same directory. using System; using System.Collections.Generic; using System.Linq; using System.Text; using Parse.Common.Internal; using Parse.Core.Internal; #if DEBUG [assembly: System.Runtime.CompilerServices.InternalsVisibleTo("Parse.Test")] #endif namespace Parse.Core.Internal { public class ParseCorePlugins : IParseCorePlugins { private static readonly object instanceMutex = new object(); private static IParseCorePlugins instance; public static IParseCorePlugins Instance { get { lock (instanceMutex) { return instance = instance ?? new ParseCorePlugins(); } } set { lock (instanceMutex) { instance = value; } } } private readonly object mutex = new object(); #region Server Controllers private IHttpClient httpClient; private IParseCommandRunner commandRunner; private IStorageController storageController; private IParseCloudCodeController cloudCodeController; private IParseConfigController configController; private IParseFileController fileController; private IParseObjectController objectController; private IParseQueryController queryController; private IParseSessionController sessionController; private IParseUserController userController; private IObjectSubclassingController subclassingController; #endregion #region Current Instance Controller private IParseCurrentUserController currentUserController; private IInstallationIdController installationIdController; #endregion public void Reset() { lock (mutex) { HttpClient = null; CommandRunner = null; StorageController = null; CloudCodeController = null; FileController = null; ObjectController = null; SessionController = null; UserController = null; SubclassingController = null; CurrentUserController = null; InstallationIdController = null; } } public IHttpClient HttpClient { get { lock (mutex) { return httpClient = httpClient ?? new HttpClient(); } } set { lock (mutex) { httpClient = value; } } } public IParseCommandRunner CommandRunner { get { lock (mutex) { return commandRunner = commandRunner ?? new ParseCommandRunner(HttpClient, InstallationIdController); } } set { lock (mutex) { commandRunner = value; } } } public IStorageController StorageController { get { lock (mutex) { return storageController = storageController ?? new StorageController(); } } set { lock (mutex) { storageController = value; } } } public IParseCloudCodeController CloudCodeController { get { lock (mutex) { return cloudCodeController = cloudCodeController ?? new ParseCloudCodeController(CommandRunner); } } set { lock (mutex) { cloudCodeController = value; } } } public IParseFileController FileController { get { lock (mutex) { return fileController = fileController ?? new ParseFileController(CommandRunner); } } set { lock (mutex) { fileController = value; } } } public IParseConfigController ConfigController { get { lock (mutex) { return configController ?? (configController = new ParseConfigController(CommandRunner, StorageController)); } } set { lock (mutex) { configController = value; } } } public IParseObjectController ObjectController { get { lock (mutex) { return objectController = objectController ?? new ParseObjectController(CommandRunner); } } set { lock (mutex) { objectController = value; } } } public IParseQueryController QueryController { get { lock (mutex) { return queryController ?? (queryController = new ParseQueryController(CommandRunner)); } } set { lock (mutex) { queryController = value; } } } public IParseSessionController SessionController { get { lock (mutex) { return sessionController = sessionController ?? new ParseSessionController(CommandRunner); } } set { lock (mutex) { sessionController = value; } } } public IParseUserController UserController { get { lock (mutex) { return (userController = userController ?? new ParseUserController(CommandRunner)); } } set { lock (mutex) { userController = value; } } } public IParseCurrentUserController CurrentUserController { get { lock (mutex) { return currentUserController = currentUserController ?? new ParseCurrentUserController(StorageController); } } set { lock (mutex) { currentUserController = value; } } } public IObjectSubclassingController SubclassingController { get { lock (mutex) { if (subclassingController == null) { subclassingController = new ObjectSubclassingController(); subclassingController.AddRegisterHook(typeof(ParseUser), () => CurrentUserController.ClearFromMemory()); } return subclassingController; } } set { lock (mutex) { subclassingController = value; } } } public IInstallationIdController InstallationIdController { get { lock (mutex) { return installationIdController = installationIdController ?? new InstallationIdController(StorageController); } } set { lock (mutex) { installationIdController = value; } } } } }
27.055556
285
0.448551
[ "BSD-3-Clause" ]
RxParse/Parse-SDK-dotNET
Parse/Internal/ParseCorePlugins.cs
8,766
C#
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Collections.Generic; using System.Runtime.Serialization; using Microsoft.AspNetCore.Mvc.ModelBinding; using Microsoft.AspNetCore.Mvc.ModelBinding.Metadata; using Xunit; namespace Microsoft.AspNetCore.Mvc.DataAnnotations.Internal { public class DataMemberRequiredBindingMetadataProviderTest { [Fact] public void IsBindingRequired_SetToTrue_WithDataMemberIsRequiredTrue() { // Arrange var provider = new DataMemberRequiredBindingMetadataProvider(); var attributes = new object[] { new DataMemberAttribute() { IsRequired = true, } }; var key = ModelMetadataIdentity.ForProperty( typeof(string), nameof(ClassWithDataMemberIsRequiredTrue.StringProperty), typeof(ClassWithDataMemberIsRequiredTrue)); var context = new BindingMetadataProviderContext(key, GetModelAttributes(new object[0], attributes)); // Act provider.CreateBindingMetadata(context); // Assert Assert.True(context.BindingMetadata.IsBindingRequired); } [Theory] [InlineData(true)] [InlineData(false)] public void IsBindingRequired_LeftAlone_DataMemberIsRequiredFalse(bool initialValue) { // Arrange var provider = new DataMemberRequiredBindingMetadataProvider(); var attributes = new object[] { new DataMemberAttribute() { IsRequired = false, } }; var key = ModelMetadataIdentity.ForProperty( typeof(string), nameof(ClassWithDataMemberIsRequiredFalse.StringProperty), typeof(ClassWithDataMemberIsRequiredFalse)); var context = new BindingMetadataProviderContext(key, GetModelAttributes(new object[0], attributes)); context.BindingMetadata.IsBindingRequired = initialValue; // Act provider.CreateBindingMetadata(context); // Assert Assert.Equal(initialValue, context.BindingMetadata.IsBindingRequired); } [Theory] [InlineData(true)] [InlineData(false)] public void IsBindingRequired_LeftAlone_ForNonPropertyMetadata(bool initialValue) { // Arrange var provider = new DataMemberRequiredBindingMetadataProvider(); var attributes = new object[] { new DataMemberAttribute() { IsRequired = true, } }; var key = ModelMetadataIdentity.ForType(typeof(ClassWithDataMemberIsRequiredTrue)); var context = new BindingMetadataProviderContext(key, GetModelAttributes(new object[0], attributes)); context.BindingMetadata.IsBindingRequired = initialValue; // Act provider.CreateBindingMetadata(context); // Assert Assert.Equal(initialValue, context.BindingMetadata.IsBindingRequired); } [Theory] [InlineData(true)] [InlineData(false)] public void IsBindingRequired_LeftAlone_WithoutDataMemberAttribute(bool initialValue) { // Arrange var provider = new DataMemberRequiredBindingMetadataProvider(); var key = ModelMetadataIdentity.ForProperty( typeof(string), nameof(ClassWithoutAttributes.StringProperty), typeof(ClassWithoutAttributes)); var context = new BindingMetadataProviderContext(key, GetModelAttributes(new object[0], new object[0])); context.BindingMetadata.IsBindingRequired = initialValue; // Act provider.CreateBindingMetadata(context); // Assert Assert.Equal(initialValue, context.BindingMetadata.IsBindingRequired); } [Theory] [InlineData(true)] [InlineData(false)] public void IsBindingRequired_LeftAlone_WithoutDataContractAttribute(bool initialValue) { // Arrange var provider = new DataMemberRequiredBindingMetadataProvider(); var attributes = new object[] { new DataMemberAttribute() { IsRequired = true, } }; var key = ModelMetadataIdentity.ForProperty( typeof(string), nameof(ClassWithDataMemberIsRequiredTrueWithoutDataContract.StringProperty), typeof(ClassWithDataMemberIsRequiredTrueWithoutDataContract)); var context = new BindingMetadataProviderContext(key, GetModelAttributes(new object[0], attributes)); context.BindingMetadata.IsBindingRequired = initialValue; // Act provider.CreateBindingMetadata(context); // Assert Assert.Equal(initialValue, context.BindingMetadata.IsBindingRequired); } private ModelAttributes GetModelAttributes( IEnumerable<object> typeAttributes, IEnumerable<object> propertyAttributes) { #pragma warning disable CS0618 // Type or member is obsolete var modelAttributes = new ModelAttributes(propertyAttributes, typeAttributes); #pragma warning restore CS0618 // Type or member is obsolete return modelAttributes; } [DataContract] private class ClassWithDataMemberIsRequiredTrue { [DataMember(IsRequired = true)] public string StringProperty { get; set; } } [DataContract] private class ClassWithDataMemberIsRequiredFalse { [DataMember(IsRequired = false)] public string StringProperty { get; set; } } private class ClassWithDataMemberIsRequiredTrueWithoutDataContract { [DataMember(IsRequired = true)] public string StringProperty { get; set; } } private class ClassWithoutAttributes { public string StringProperty { get; set; } } } }
35.083799
116
0.632803
[ "Apache-2.0" ]
Kartikexp/MvcDotnet
test/Microsoft.AspNetCore.Mvc.DataAnnotations.Test/Internal/DataMemberRequiredBindingMetadataProviderTest.cs
6,280
C#
namespace Oasis.EntityFramework.Mapper.Exceptions; public sealed class TypeConfiguratedException : EfCoreMapperException { public TypeConfiguratedException(Type type) : base($"Type {type} has been configurated already.") { } }
24.9
69
0.742972
[ "MIT" ]
keeper013/Oasis
EntityFramework/Oasis.EntityFramework.Mapper/Exceptions/TypeConfiguratedException.cs
251
C#
// This file is part of Hangfire. // Copyright © 2013-2014 Sergey Odinokov. // // Hangfire 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 any later version. // // Hangfire 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 Hangfire. If not, see <http://www.gnu.org/licenses/>. using Hangfire.Storage; namespace Hangfire.States { public interface IStateMachineFactory { IStateMachine Create(IStorageConnection connection); } }
35.72
75
0.742441
[ "MIT" ]
777Eternal777/Storm
Storm/Storm.Core/States/IStateMachineFactory.cs
896
C#
// Copyright (c) Josef Pihrt and Contributors. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; namespace Roslynator.CSharp.Refactorings { internal static class ExtractGenericTypeRefactoring { public static bool CanRefactor(RefactoringContext context, GenericNameSyntax name) { TypeSyntax typeArgument = name.TypeArgumentList?.Arguments.SingleOrDefault(shouldThrow: false); return typeArgument != null && context.Span.IsBetweenSpans(typeArgument) && !typeArgument.IsKind(SyntaxKind.TupleType) && IsTypeOrReturnType(name); } private static bool IsTypeOrReturnType(GenericNameSyntax name) { SyntaxNode parent = name.Parent; switch (parent.Kind()) { case SyntaxKind.TupleElement: return ((TupleElementSyntax)parent).Type == name; case SyntaxKind.RefType: return ((RefTypeSyntax)parent).Type == name; case SyntaxKind.RefValueExpression: return ((RefValueExpressionSyntax)parent).Type == name; case SyntaxKind.DefaultExpression: return ((DefaultExpressionSyntax)parent).Type == name; case SyntaxKind.TypeOfExpression: return ((TypeOfExpressionSyntax)parent).Type == name; case SyntaxKind.SizeOfExpression: return ((SizeOfExpressionSyntax)parent).Type == name; case SyntaxKind.DeclarationExpression: return ((DeclarationExpressionSyntax)parent).Type == name; case SyntaxKind.CastExpression: return ((CastExpressionSyntax)parent).Type == name; case SyntaxKind.ObjectCreationExpression: return ((ObjectCreationExpressionSyntax)parent).Type == name; case SyntaxKind.StackAllocArrayCreationExpression: return ((StackAllocArrayCreationExpressionSyntax)parent).Type == name; case SyntaxKind.FromClause: return ((FromClauseSyntax)parent).Type == name; case SyntaxKind.JoinClause: return ((JoinClauseSyntax)parent).Type == name; case SyntaxKind.DeclarationPattern: return ((DeclarationPatternSyntax)parent).Type == name; case SyntaxKind.VariableDeclaration: return ((VariableDeclarationSyntax)parent).Type == name; case SyntaxKind.ForEachStatement: return ((ForEachStatementSyntax)parent).Type == name; case SyntaxKind.CatchDeclaration: return ((CatchDeclarationSyntax)parent).Type == name; case SyntaxKind.SimpleBaseType: return ((SimpleBaseTypeSyntax)parent).Type == name; case SyntaxKind.TypeConstraint: return ((TypeConstraintSyntax)parent).Type == name; case SyntaxKind.ConversionOperatorDeclaration: return ((ConversionOperatorDeclarationSyntax)parent).Type == name; case SyntaxKind.PropertyDeclaration: return ((PropertyDeclarationSyntax)parent).Type == name; case SyntaxKind.EventDeclaration: return ((EventDeclarationSyntax)parent).Type == name; case SyntaxKind.IndexerDeclaration: return ((IndexerDeclarationSyntax)parent).Type == name; case SyntaxKind.Parameter: return ((ParameterSyntax)parent).Type == name; case SyntaxKind.TypeCref: return ((TypeCrefSyntax)parent).Type == name; case SyntaxKind.ConversionOperatorMemberCref: return ((ConversionOperatorMemberCrefSyntax)parent).Type == name; case SyntaxKind.CrefParameter: return ((CrefParameterSyntax)parent).Type == name; case SyntaxKind.LocalFunctionStatement: return ((LocalFunctionStatementSyntax)parent).ReturnType == name; case SyntaxKind.DelegateDeclaration: return ((DelegateDeclarationSyntax)parent).ReturnType == name; case SyntaxKind.MethodDeclaration: return ((MethodDeclarationSyntax)parent).ReturnType == name; case SyntaxKind.OperatorDeclaration: return ((OperatorDeclarationSyntax)parent).ReturnType == name; } return false; } public static Task<Document> RefactorAsync( Document document, GenericNameSyntax genericName, CancellationToken cancellationToken = default) { TypeSyntax typeSyntax = genericName .TypeArgumentList .Arguments[0] .WithTriviaFrom(genericName); return document.ReplaceNodeAsync(genericName, typeSyntax, cancellationToken); } } }
49.592593
156
0.606983
[ "Apache-2.0" ]
onexey/Roslynator
src/Refactorings/CSharp/Refactorings/ExtractGenericTypeRefactoring.cs
5,358
C#
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using System.Text; using System.Threading.Tasks; namespace timw255.Sitefinity.RestClient.Model { public class CurrentPageState { public ItemState ItemState { get; set; } public string Message { get; set; } public CurrentPageState() { } } }
21.222222
48
0.709424
[ "MIT" ]
timw255/timw255.Sitefinity.RestClient
timw255.Sitefinity.RestClient/Model/CurrentPageState.cs
384
C#
using System.Threading.Tasks; namespace Hestia.Model.Wrappers { public interface ICommandLineExecutor { string[] Execute(string commandToExecute, string args, string workingDirectory); string ExecuteNoSplit(string commandToExecute, string args, string workingDirectory); Task<string[]> ExecuteAsync(string commandToExecute, string args, string workingDirectory); Task<string> ExecuteAsyncNoSplit(string commandToExecute, string args, string workingDirectory); } }
32.0625
104
0.756335
[ "MIT" ]
marczinusd/hestia
src/Hestia.Model/Wrappers/ICommandLineExecutor.cs
515
C#
namespace CaptchaSharp.Enums { /// <summary></summary> public enum CaptchaLanguage { /// <summary></summary> NotSpecified, /// <summary></summary> English, /// <summary></summary> Russian, /// <summary></summary> Spanish, /// <summary></summary> Portuguese, /// <summary></summary> Ukrainian, /// <summary></summary> Vietnamese, /// <summary></summary> French, /// <summary></summary> Indonesian, /// <summary></summary> Arab, /// <summary></summary> Japanese, /// <summary></summary> Turkish, /// <summary></summary> German, /// <summary></summary> Chinese, /// <summary></summary> Philippine, /// <summary></summary> Polish, /// <summary></summary> Thai, /// <summary></summary> Italian, /// <summary></summary> Dutch, /// <summary></summary> Slovak, /// <summary></summary> Bulgarian, /// <summary></summary> Romanian, /// <summary></summary> Hungarian, /// <summary></summary> Korean, /// <summary></summary> Czech, /// <summary></summary> Azerbaijani, /// <summary></summary> Persian, /// <summary></summary> Bengali, /// <summary></summary> Greek, /// <summary></summary> Lithuanian, /// <summary></summary> Latvian, /// <summary></summary> Swedish, /// <summary></summary> Serbian, /// <summary></summary> Croatian, /// <summary></summary> Hebrew, /// <summary></summary> Hindi, /// <summary></summary> Norwegian, /// <summary></summary> Slovenian, /// <summary></summary> Danish, /// <summary></summary> Uzbek, /// <summary></summary> Finnish, /// <summary></summary> Catalan, /// <summary></summary> Georgian, /// <summary></summary> Malay, /// <summary></summary> Telugu, /// <summary></summary> Estonian, /// <summary></summary> Malayalam, /// <summary></summary> Belorussian, /// <summary></summary> Kazakh, /// <summary></summary> Marathi, /// <summary></summary> Nepali, /// <summary></summary> Burmese, /// <summary></summary> Bosnian, /// <summary></summary> Armenian, /// <summary></summary> Macedonian, /// <summary></summary> Punjabi } }
16.714286
31
0.431453
[ "MIT" ]
542980940984363224858439616269115634540/CaptchaSharp
CaptchaSharp/Enums/CaptchaLanguage.cs
2,927
C#
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using Microsoft.AspNetCore.Routing.Template; namespace Microsoft.AspNetCore.Routing.Tree { /// <summary> /// A candidate match for link generation in a <see cref="TreeRouter"/>. /// </summary> public class OutboundMatch { /// <summary> /// Gets or sets the <see cref="OutboundRouteEntry"/>. /// </summary> public OutboundRouteEntry Entry { get; set; } /// <summary> /// Gets or sets the <see cref="TemplateBinder"/>. /// </summary> public TemplateBinder TemplateBinder { get; set; } } }
31.083333
111
0.631367
[ "Apache-2.0" ]
06b/AspNetCore
src/Http/Routing/src/Tree/OutboundMatch.cs
748
C#
using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Threading.Tasks; namespace Filmary.Common.Interfaces { /// <summary> /// Generic repository provide all base needed methods (CRUD) /// </summary> /// <typeparam name="T"></typeparam> public interface IRepository<T> where T : class { /// <summary> /// Get all queries. /// </summary> /// <returns>IQueryable queries.</returns> IQueryable<T> GetAll(); /// <summary> /// Get entity async by predicate. /// </summary> /// <param name="predicate">LINQ predicate.</param> /// <returns>T entity.</returns> Task<T> GetEntityAsync(Expression<Func<T, bool>> predicate); /// <summary> /// Get entity async by predicate (without tracking). /// </summary> /// <param name="predicate">LINQ predicate.</param> /// <returns>T entity.</returns> Task<T> GetEntityWithoutTrackingAsync(Expression<Func<T, bool>> predicate); /// <summary> /// Add new entity async. /// </summary> /// <param name="entity">Entity object</param> Task AddAsync(T entity); /// <summary> /// Add new entities async. /// </summary> /// <param name="entities">Entity collection.</param> Task AddRangeAsync(IEnumerable<T> entities); /// <summary> /// Update entity /// </summary> /// <param name="entity">Entity object</param> void Update(T entity); /// <summary> /// Remove entity from database. /// </summary> /// <param name="entity">Entity object.</param> void Delete(T entity); /// <summary> /// Remove entities from database /// </summary> /// <param name="entity">Entity object</param> void DeleteRange(IEnumerable<T> entity); /// <summary> /// Persists all updates to the data source async. /// </summary> Task SaveChangesAsync(); } }
30.185714
83
0.558921
[ "MIT" ]
teachmeskills-dotnet/TMS-DotNet03-Bandarenka
src/Filmary.Common/Interfaces/IRepository.cs
2,115
C#
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AzureNextGen.Devices.V20190701Preview.Outputs { [OutputType] public sealed class StorageEndpointPropertiesResponse { /// <summary> /// The connection string for the Azure Storage account to which files are uploaded. /// </summary> public readonly string ConnectionString; /// <summary> /// The name of the root container where you upload files. The container need not exist but should be creatable using the connectionString specified. /// </summary> public readonly string ContainerName; /// <summary> /// The period of time for which the SAS URI generated by IoT Hub for file upload is valid. See: https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-file-upload#file-upload-notification-configuration-options. /// </summary> public readonly string? SasTtlAsIso8601; [OutputConstructor] private StorageEndpointPropertiesResponse( string connectionString, string containerName, string? sasTtlAsIso8601) { ConnectionString = connectionString; ContainerName = containerName; SasTtlAsIso8601 = sasTtlAsIso8601; } } }
36.186047
222
0.676735
[ "Apache-2.0" ]
pulumi/pulumi-azure-nextgen
sdk/dotnet/Devices/V20190701Preview/Outputs/StorageEndpointPropertiesResponse.cs
1,556
C#
// MonoGame - Copyright (C) The MonoGame Team // This file is subject to the terms and conditions defined in // file 'LICENSE.txt', which is part of this source code package. using System; namespace Microsoft.Xna.Framework.Graphics.PackedVector { /// <summary> /// Packed vector type containing four 8-bit unsigned integer values, ranging from 0 to 255. /// </summary> public struct Byte4 : IPackedVector<uint>, IEquatable<Byte4>, IPackedVector { uint packedValue; /// <summary> /// Initializes a new instance of the Byte4 class. /// </summary> /// <param name="vector">A vector containing the initial values for the components of the Byte4 structure.</param> public Byte4(Vector4 vector) { packedValue = Pack(ref vector); } /// <summary> /// Initializes a new instance of the Byte4 class. /// </summary> /// <param name="x">Initial value for the x component.</param> /// <param name="y">Initial value for the y component.</param> /// <param name="z">Initial value for the z component.</param> /// <param name="w">Initial value for the w component.</param> public Byte4(float x, float y, float z, float w) { var vector = new Vector4(x, y, z, w); packedValue = Pack(ref vector); } /// <summary> /// Compares the current instance of a class to another instance to determine whether they are different. /// </summary> /// <param name="a">The object to the left of the equality operator.</param> /// <param name="b">The object to the right of the equality operator.</param> /// <returns>true if the objects are different; false otherwise.</returns> public static bool operator !=(Byte4 a, Byte4 b) { return a.PackedValue != b.PackedValue; } /// <summary> /// Compares the current instance of a class to another instance to determine whether they are the same. /// </summary> /// <param name="a">The object to the left of the equality operator.</param> /// <param name="b">The object to the right of the equality operator.</param> /// <returns>true if the objects are the same; false otherwise.</returns> public static bool operator ==(Byte4 a, Byte4 b) { return a.PackedValue == b.PackedValue; } /// <summary> /// Directly gets or sets the packed representation of the value. /// </summary> /// <value>The packed representation of the value.</value> public uint PackedValue { get { return packedValue; } set { packedValue = value; } } /// <summary> /// Returns a value that indicates whether the current instance is equal to a specified object. /// </summary> /// <param name="obj">The object with which to make the comparison.</param> /// <returns>true if the current instance is equal to the specified object; false otherwise.</returns> public override bool Equals(object obj) { if (obj is Byte4) return this == (Byte4)obj; return false; } /// <summary> /// Returns a value that indicates whether the current instance is equal to a specified object. /// </summary> /// <param name="other">The object with which to make the comparison.</param> /// <returns>true if the current instance is equal to the specified object; false otherwise.</returns> public bool Equals(Byte4 other) { return this == other; } /// <summary> /// Gets the hash code for the current instance. /// </summary> /// <returns>Hash code for the instance.</returns> public override int GetHashCode() { return packedValue.GetHashCode(); } /// <summary> /// Returns a string representation of the current instance. /// </summary> /// <returns>String that represents the object.</returns> public override string ToString() { return packedValue.ToString("x8"); } /// <summary> /// Packs a vector into a uint. /// </summary> /// <param name="vector">The vector containing the values to pack.</param> /// <returns>The ulong containing the packed values.</returns> static uint Pack(ref Vector4 vector) { const float max = 255.0f; const float min = 0.0f; // clamp the value between min and max values var byte4 = (uint) Math.Round(MathHelper.Clamp(vector.X, min, max)) & 0xFF; var byte3 = ((uint) Math.Round(MathHelper.Clamp(vector.Y, min, max)) & 0xFF) << 0x8; var byte2 = ((uint) Math.Round(MathHelper.Clamp(vector.Z, min, max)) & 0xFF) << 0x10; var byte1 = ((uint) Math.Round(MathHelper.Clamp(vector.W, min, max)) & 0xFF) << 0x18; return byte4 | byte3 | byte2 | byte1; } /// <summary> /// Sets the packed representation from a Vector4. /// </summary> /// <param name="vector">The vector to create the packed representation from.</param> void IPackedVector.PackFromVector4(Vector4 vector) { packedValue = Pack(ref vector); } /// <summary> /// Expands the packed representation into a Vector4. /// </summary> /// <returns>The expanded vector.</returns> public Vector4 ToVector4() { return new Vector4( (float)(packedValue & 0xFF), (float)((packedValue >> 0x8) & 0xFF), (float)((packedValue >> 0x10) & 0xFF), (float)((packedValue >> 0x18) & 0xFF)); } } }
37.974843
122
0.56691
[ "MIT" ]
jocamar/Caravel
Libs/MonoGame.Framework/Graphics/PackedVector/Byte4.cs
6,040
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; #nullable disable namespace Microsoft.VisualStudio.TestPlatform.ObjectModel.DataCollection; /// <summary> /// Interface for data collectors add-ins that choose to handle attachment(s) generated /// </summary> [Obsolete("Interface is deprecated. Please use IDataCollectorAttachmentProcessor instead")] public interface IDataCollectorAttachments { /// <summary> /// Gets the attachment set after Test Run Session /// </summary> /// <returns>Gets the attachment set after Test Run Session</returns> ICollection<AttachmentSet> HandleDataCollectionAttachmentSets(ICollection<AttachmentSet> dataCollectionAttachments); /// <summary> /// Gets the attachment Uri, which is handled by current Collector /// </summary> Uri GetExtensionUri(); }
35.25
120
0.758865
[ "MIT" ]
Evangelink/vstest
src/Microsoft.TestPlatform.ObjectModel/DataCollector/IDataCollectorAttachments.cs
989
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.Media.Outputs { [OutputType] public sealed class MediaGraphTlsEndpointResponse { /// <summary> /// Polymorphic credentials to present to the endpoint. /// </summary> public readonly Outputs.MediaGraphUsernamePasswordCredentialsResponse? Credentials; /// <summary> /// The discriminator for derived types. /// Expected value is '#Microsoft.Media.MediaGraphTlsEndpoint'. /// </summary> public readonly string OdataType; /// <summary> /// What certificates should be trusted when authenticating a TLS connection. Null designates that Azure Media's source of trust should be used. /// </summary> public readonly Outputs.MediaGraphPemCertificateListResponse? TrustedCertificates; /// <summary> /// Url for the endpoint. /// </summary> public readonly string Url; /// <summary> /// Validation options to use when authenticating a TLS connection. By default, strict validation is used. /// </summary> public readonly Outputs.MediaGraphTlsValidationOptionsResponse? ValidationOptions; [OutputConstructor] private MediaGraphTlsEndpointResponse( Outputs.MediaGraphUsernamePasswordCredentialsResponse? credentials, string odataType, Outputs.MediaGraphPemCertificateListResponse? trustedCertificates, string url, Outputs.MediaGraphTlsValidationOptionsResponse? validationOptions) { Credentials = credentials; OdataType = odataType; TrustedCertificates = trustedCertificates; Url = url; ValidationOptions = validationOptions; } } }
36.017241
152
0.668262
[ "Apache-2.0" ]
pulumi-bot/pulumi-azure-native
sdk/dotnet/Media/Outputs/MediaGraphTlsEndpointResponse.cs
2,089
C#
using CharacterGen.CharacterClasses; using CharacterGen.Domain.Tables; using NUnit.Framework; using System.Linq; namespace CharacterGen.Tests.Integration.Tables.Magics.Spells.Known.Adepts { [TestFixture] public class Level18AdeptKnownSpellsTests : AdjustmentsTests { protected override string tableName { get { return string.Format(TableNameConstants.Formattable.Adjustments.LevelXCLASSKnownSpells, 18, CharacterClassConstants.Adept); } } [Test] public override void CollectionNames() { var names = Enumerable.Range(0, 6).Select(i => i.ToString()); AssertCollectionNames(names); } [TestCase(0, 3)] [TestCase(1, 3)] [TestCase(2, 3)] [TestCase(3, 3)] [TestCase(4, 2)] [TestCase(5, 1)] public void Adjustment(int spellLevel, int quantity) { base.Adjustment(spellLevel.ToString(), quantity); } } }
27.105263
139
0.602913
[ "MIT" ]
DnDGen/CharacterGen
CharacterGen.Tests.Integration.Tables/Magics/Spells/Known/Adepts/Level18AdeptKnownSpellsTests.cs
1,032
C#
using System; using OperationMicrosoft.DataStructures.Objects.Nodes; namespace OperationMicrosoft.DataStructures.Makers { public class LinkedList<TValue> { public ListNode<TValue> Head { get; private set; } public ListNode<TValue> Tail { get; private set; } public int ListSize { get; set; } private void IterateAllNodes(Action<ListNode<TValue>, ListNode<TValue>> work) { var currentNode = Head; ListNode<TValue> previousNode = null; while (currentNode != null) { work(currentNode, previousNode); previousNode = currentNode; currentNode = currentNode.Next; } } public void Add(ListNode<TValue> newNode) { if (Head == null) { Head = newNode; Tail = Head; } else { Tail.Next = newNode; Tail = newNode; } ListSize++; } public void AddAfter(TValue value, ListNode<TValue> itemToAdd) { var currentNode = Head; while (currentNode != null) { if (currentNode.Value.Equals(value)) { ListSize++; var nextNode = currentNode.Next; currentNode.Next = itemToAdd; itemToAdd.Next = nextNode; if (currentNode.Equals(Tail)) { Tail = itemToAdd; } } currentNode = currentNode.Next; } } public void Remove(TValue itemToRemove) { if (Head.Value.Equals(itemToRemove)) { ListSize--; Head = Head.Next; } else { IterateAllNodes((current, previous) => { if (current.Value.Equals(itemToRemove)) { ListSize--; previous.Next = current.Next; } }); } } public bool Contains(TValue o) { var found = false; IterateAllNodes((current, previous) => { if (current.Value.Equals(o)) { found = true; } }); return found; } public void Reverse() { Console.WriteLine("Reversing"); var currentNode = Head; ListNode<TValue> previousNode = null; while (currentNode != null) { var nextNode = currentNode.Next; currentNode.Next = previousNode; previousNode = currentNode; currentNode = nextNode; } Head = previousNode; } public void Traverse() { Console.WriteLine("Traversing"); IterateAllNodes((current, previous) => Console.WriteLine(current.Value)); } } }
27.833333
86
0.422754
[ "MIT" ]
Foxpips/Algorithms
OperationMicrosoft/DataStructures/Makers/LinkedList.cs
3,342
C#
using UnityEditor; using UnityEngine; namespace DELTation.DIFramework.Editor { [InitializeOnLoad] public static class HierarchyIcons { static HierarchyIcons() => EditorApplication.hierarchyWindowItemOnGUI += UpdateIcons; private static void UpdateIcons(int instanceId, Rect selectionRect) { if (!DiSettings.TryGetInstance(out var settings) || !settings.ShowIconsInHierarchy) return; if (!(EditorUtility.InstanceIDToObject(instanceId) is GameObject gameObject)) return; if (!gameObject.TryGetComponent(out IShowIconInHierarchy showIconInHierarchy)) return; if (!(showIconInHierarchy is Object @object)) return; DrawIcon(@object, selectionRect); } private static void DrawIcon(Object @object, Rect selectionRect) { const float iconSize = 16f; var rect = new Rect(selectionRect.x + selectionRect.width - iconSize, selectionRect.y, iconSize, iconSize); GUI.DrawTexture(rect, GetObjectIcon(@object)); } private static Texture GetObjectIcon(Object @object) => EditorGUIUtility.ObjectContent(@object, @object.GetType()).image; } }
38.0625
119
0.678161
[ "MIT" ]
Delt06/di-framework
Packages/com.deltation.di-framework/Assets/DELTation/DIFramework/Editor/HierarchyIcons.cs
1,220
C#
using System.Reflection; using JetBrains.Annotations; using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Metadata.Builders; using Microsoft.EntityFrameworkCore.Metadata.Conventions; using Microsoft.EntityFrameworkCore.Metadata.Conventions.Infrastructure; using Sprite.Data.Entities.Auditing; namespace Sprite.Data.EntityFrameworkCore.Conventions { public class CreateByAttributeConvention : PropertyAttributeConventionBase<CreateByAttribute> { public CreateByAttributeConvention([NotNull] ProviderConventionSetBuilderDependencies dependencies) : base(dependencies) { } protected override void ProcessPropertyAdded(IConventionPropertyBuilder propertyBuilder, CreateByAttribute attribute, MemberInfo clrMember, IConventionContext context) { propertyBuilder.ValueGenerated(ValueGenerated.OnAdd, fromDataAnnotation: true); } } }
42.272727
175
0.806452
[ "Apache-2.0" ]
beango-project/beango-framework
framework/src/Sprite.Data.EntityFrameworkCore/Metadata/Conventions/Auditing/CreateByAttributeConvention.cs
932
C#
using System; using System.Collections.Generic; using System.IO; using System.Reflection; using System.Runtime; using System.Windows; using Microsoft.Shell; using ReactiveUI; using SimpleMusicPlayer.Core; using SimpleMusicPlayer.Core.Player; using SimpleMusicPlayer.ViewModels; using SimpleMusicPlayer.Views; using TinyIoC; namespace SimpleMusicPlayer { /// <summary> /// Interaction logic for App.xaml /// </summary> public partial class App : Application, ISingleInstanceApp { public App() { TinyIoCContainer.Current.Register<AppHelper>().AsSingleton(); TinyIoCContainer.Current.Register<CoverManager>().AsSingleton(); TinyIoCContainer.Current.Register<PlayerSettings>().AsSingleton(); TinyIoCContainer.Current.Register<PlayerEngine>().AsSingleton(); TinyIoCContainer.Current.Register<IReactiveObject, MedialibViewModel>(); TinyIoCContainer.Current.Register<IReactiveObject, MainViewModel>(); var appHelper = TinyIoCContainer.Current.Resolve<AppHelper>(); appHelper.ConfigureApp(this, Assembly.GetExecutingAssembly().GetName().Name); // Enable Multi-JIT startup var profileRoot = Path.Combine(appHelper.ApplicationPath, "ProfileOptimization"); Directory.CreateDirectory(profileRoot); // Define the folder where to save the profile files ProfileOptimization.SetProfileRoot(profileRoot); // Start profiling and save it in Startup.profile ProfileOptimization.StartProfile("Startup.profile"); } protected override void OnStartup(StartupEventArgs e) { base.OnStartup(e); MainWindow = TinyIoCContainer.Current.Resolve<MainWindow>(); MainWindow.Show(); } protected override void OnExit(ExitEventArgs e) { base.OnExit(e); TinyIoCContainer.Current.Resolve<AppHelper>().OnExitApp(this); } public bool SignalExternalCommandLineArgs(IList<string> args) { if (this.MainWindow.WindowState == WindowState.Minimized) { WindowExtensions.Unminimize(this.MainWindow); } else { WindowExtensions.ShowAndActivate(this.MainWindow); } return this.ProcessCommandLineArgs(this.MainWindow as SimpleMusicPlayer.Views.MainWindow, args); } private bool ProcessCommandLineArgs(SimpleMusicPlayer.Views.MainWindow window, IEnumerable<string> args) { if (window != null) { var vm = window.DataContext as SimpleMusicPlayer.ViewModels.MainViewModel; if (vm != null) { vm.PlayListsViewModel.CommandLineArgs = new ReactiveList<string>(args); } } return true; } } }
35.357143
112
0.637037
[ "Apache-2.0", "MIT" ]
qwe7922142/simple-music-player
src/SimpleMusicPlayer/App.xaml.cs
2,972
C#
using System; using NUnit.Framework; using Plethora.Finance.Bond; using Plethora.Test.Finance.UtilityClasses; namespace Plethora.Test.Finance.Bond { [TestFixture] public class BondInterestCalculator30E_360_Test { [Test] public void Error_EndBeforeStart() { //Setup var bondInterestCalculator = this.CreateBondInterestCalculator(); try { //Exec Rational dayCountFraction = bondInterestCalculator.CalculateDayCountFraction(Dates.Jan10, Dates.Jan01); Assert.Fail(); } catch (ArgumentException) { } } [Test] public void Error_EndEqualsStart() { //Setup var bondInterestCalculator = this.CreateBondInterestCalculator(); try { //Exec Rational dayCountFraction = bondInterestCalculator.CalculateDayCountFraction(Dates.Jan01, Dates.Jan01); Assert.Fail(); } catch (ArgumentException) { } } [Test] public void Jan01_Jan02() { //Setup var bondInterestCalculator = this.CreateBondInterestCalculator(); //Exec Rational dayCountFraction = bondInterestCalculator.CalculateDayCountFraction(Dates.Jan01, Dates.Jan02); //Test Assert.AreEqual(new Rational(1, 360), dayCountFraction); } [Test] public void Jan01_Jan29() { //Setup var bondInterestCalculator = this.CreateBondInterestCalculator(); //Exec Rational dayCountFraction = bondInterestCalculator.CalculateDayCountFraction(Dates.Jan01, Dates.Jan29); //Test Assert.AreEqual(new Rational(28, 360), dayCountFraction); } [Test] public void Jan01_Jan30() { //Setup var bondInterestCalculator = this.CreateBondInterestCalculator(); //Exec Rational dayCountFraction = bondInterestCalculator.CalculateDayCountFraction(Dates.Jan01, Dates.Jan30); //Test Assert.AreEqual(new Rational(29, 360), dayCountFraction); } [Test] public void Jan01_Jan31() { //Setup var bondInterestCalculator = this.CreateBondInterestCalculator(); //Exec Rational dayCountFraction = bondInterestCalculator.CalculateDayCountFraction(Dates.Jan01, Dates.Jan31); //Test Assert.AreEqual(new Rational(29, 360), dayCountFraction); } [Test] public void Jan01_Feb01() { //Setup var bondInterestCalculator = this.CreateBondInterestCalculator(); //Exec Rational dayCountFraction = bondInterestCalculator.CalculateDayCountFraction(Dates.Jan01, Dates.Feb01); //Test Assert.AreEqual(new Rational(30, 360), dayCountFraction); } [Test] public void Feb01_Feb02_LeapYear() { //Setup var bondInterestCalculator = this.CreateBondInterestCalculator(); //Exec Rational dayCountFraction = bondInterestCalculator.CalculateDayCountFraction(Dates.Feb01, Dates.Feb02); //Test Assert.AreEqual(new Rational(1, 360), dayCountFraction); } [Test] public void Feb01_Feb28_LeapYear() { //Setup var bondInterestCalculator = this.CreateBondInterestCalculator(); //Exec Rational dayCountFraction = bondInterestCalculator.CalculateDayCountFraction(Dates.Feb01, Dates.Feb28); //Test Assert.AreEqual(new Rational(27, 360), dayCountFraction); } [Test] public void Feb01_Feb29_LeapYear() { //Setup var bondInterestCalculator = this.CreateBondInterestCalculator(); //Exec Rational dayCountFraction = bondInterestCalculator.CalculateDayCountFraction(Dates.Feb01, Dates.Feb29); //Test Assert.AreEqual(new Rational(28, 360), dayCountFraction); } [Test] public void Feb01_Mar01_LeapYear() { //Setup var bondInterestCalculator = this.CreateBondInterestCalculator(); //Exec Rational dayCountFraction = bondInterestCalculator.CalculateDayCountFraction(Dates.Feb01, Dates.Mar01); //Test Assert.AreEqual(new Rational(30, 360), dayCountFraction); } [Test] public void Feb01_Feb02_NotLeapYear() { //Setup var bondInterestCalculator = this.CreateBondInterestCalculator(); //Exec Rational dayCountFraction = bondInterestCalculator.CalculateDayCountFraction(new DateTime(2001, 02, 01), new DateTime(2001, 02, 02)); //Test Assert.AreEqual(new Rational(1, 360), dayCountFraction); } [Test] public void Feb01_Feb28_NotLeapYear() { //Setup var bondInterestCalculator = this.CreateBondInterestCalculator(); //Exec Rational dayCountFraction = bondInterestCalculator.CalculateDayCountFraction(new DateTime(2001, 02, 01), new DateTime(2001, 02, 28)); //Test Assert.AreEqual(new Rational(27, 360), dayCountFraction); } [Test] public void Feb01_Mar01_NotLeapYear() { //Setup var bondInterestCalculator = this.CreateBondInterestCalculator(); //Exec Rational dayCountFraction = bondInterestCalculator.CalculateDayCountFraction(new DateTime(2001, 02, 01), new DateTime(2001, 03, 01)); //Test Assert.AreEqual(new Rational(30, 360), dayCountFraction); } [Test] public void Apr01_Apr02() { //Setup var bondInterestCalculator = this.CreateBondInterestCalculator(); //Exec Rational dayCountFraction = bondInterestCalculator.CalculateDayCountFraction(Dates.Apr01, Dates.Apr02); //Test Assert.AreEqual(new Rational(1, 360), dayCountFraction); } [Test] public void Apr01_Apr29() { //Setup var bondInterestCalculator = this.CreateBondInterestCalculator(); //Exec Rational dayCountFraction = bondInterestCalculator.CalculateDayCountFraction(Dates.Apr01, Dates.Apr29); //Test Assert.AreEqual(new Rational(28, 360), dayCountFraction); } [Test] public void Apr01_Apr30() { //Setup var bondInterestCalculator = this.CreateBondInterestCalculator(); //Exec Rational dayCountFraction = bondInterestCalculator.CalculateDayCountFraction(Dates.Apr01, Dates.Apr30); //Test Assert.AreEqual(new Rational(29, 360), dayCountFraction); } [Test] public void Apr01_May01() { //Setup var bondInterestCalculator = this.CreateBondInterestCalculator(); //Exec Rational dayCountFraction = bondInterestCalculator.CalculateDayCountFraction(Dates.Apr01, Dates.May01); //Test Assert.AreEqual(new Rational(30, 360), dayCountFraction); } [Test] public void Jul31_Aug29() { //Setup var bondInterestCalculator = this.CreateBondInterestCalculator(); //Exec Rational dayCountFraction = bondInterestCalculator.CalculateDayCountFraction(Dates.Jul31, Dates.Aug29); //Test Assert.AreEqual(new Rational(29, 360), dayCountFraction); } [Test] public void Jul31_Aug30() { //Setup var bondInterestCalculator = this.CreateBondInterestCalculator(); //Exec Rational dayCountFraction = bondInterestCalculator.CalculateDayCountFraction(Dates.Jul31, Dates.Aug30); //Test Assert.AreEqual(new Rational(30, 360), dayCountFraction); } [Test] public void Jul31_Aug31() { //Setup var bondInterestCalculator = this.CreateBondInterestCalculator(); //Exec Rational dayCountFraction = bondInterestCalculator.CalculateDayCountFraction(Dates.Jul31, Dates.Aug31); //Test Assert.AreEqual(new Rational(30, 360), dayCountFraction); } [Test] public void Jul31_Sep01() { //Setup var bondInterestCalculator = this.CreateBondInterestCalculator(); //Exec Rational dayCountFraction = bondInterestCalculator.CalculateDayCountFraction(Dates.Jul31, Dates.Sep01); //Test Assert.AreEqual(new Rational(31, 360), dayCountFraction); } private BondInterestCalculator30E_360 CreateBondInterestCalculator() { return new BondInterestCalculator30E_360(); } } }
29.335423
145
0.587305
[ "MIT", "BSD-3-Clause" ]
mikebarker/Plethora.NET
src/Test/Plethora.Test.Finance/Bond/BondInterestCalculator30E_360_Test.cs
9,360
C#
using System.Collections.Generic; using System; namespace Leetspeak.Models { public class LeetspeakTranslator { private string _inputWord; private static List<string> _letters = new List<string> {}; private static List<string> _converted = new List<string> {}; public LeetspeakTranslator(string inputWord) { _inputWord = inputWord; _letters.Add(_inputWord); } public string GetInputWord() { return _inputWord; } public List<string> ChangeLetter() { char[] leetArray = _letters[0].ToCharArray(); for(int i = 0; i < leetArray.Length; i++) { if (leetArray[i] == 'e' || leetArray[i] == 'E') { leetArray[i] = '3'; } else if (leetArray[i] == 'o' || leetArray[i] == 'O') { leetArray[i] = '0'; } else if (leetArray[i] == 'I') { leetArray[i] = '1'; } else if (leetArray[i] == 't' || leetArray[i] == 'T') { leetArray[i] = '7'; } else if (leetArray[i] == 'S' || leetArray[i] == 's') { leetArray[i] = 'z'; } } string result = string.Join("", leetArray); _converted.Add(result); return _converted; } public static void ClearAll() { _letters.Clear(); _converted.Clear(); } } }
23.189655
65
0.528625
[ "Unlicense", "MIT" ]
kailinishihira/Leetspeak-MSTest
Leetspeak/Models/LeetspeakTranslator.cs
1,345
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CovApp3DimScore { class AnswerOption { public string Id { get; set; } public string Text { get; set; } } }
17.533333
40
0.676806
[ "MIT" ]
Brar/CovApp3DimScore
AnswerOption.cs
265
C#
/* * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the cognito-idp-2016-04-18.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using System.Net; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.CognitoIdentityProvider.Model { /// <summary> /// This is the response object from the AdminForgetDevice operation. /// </summary> public partial class AdminForgetDeviceResponse : AmazonWebServiceResponse { } }
30.184211
109
0.738448
[ "Apache-2.0" ]
DetlefGolze/aws-sdk-net
sdk/src/Services/CognitoIdentityProvider/Generated/Model/AdminForgetDeviceResponse.cs
1,147
C#
using System; using System.Collections.Generic; using Microsoft.Recognizers.Text.Choice; using Microsoft.Recognizers.Text.DateTime; using Microsoft.Recognizers.Text.DateTime.Dutch; using Microsoft.Recognizers.Text.DateTime.English; using Microsoft.Recognizers.Text.DateTime.French; using Microsoft.Recognizers.Text.DateTime.German; using Microsoft.Recognizers.Text.DateTime.Italian; using Microsoft.Recognizers.Text.DateTime.Portuguese; using Microsoft.Recognizers.Text.DateTime.Spanish; using Microsoft.Recognizers.Text.Number; using Microsoft.Recognizers.Text.NumberWithUnit; using Microsoft.Recognizers.Text.Sequence; using Microsoft.VisualStudio.TestTools.UnitTesting; using DateObject = System.DateTime; namespace Microsoft.Recognizers.Text.DataDrivenTests { public static class TestContextExtensions { private static IDictionary<Models, Func<TestModel, string, IList<ModelResult>>> modelFunctions = new Dictionary<Models, Func<TestModel, string, IList<ModelResult>>>() { { Models.Number, (test, culture) => NumberRecognizer.RecognizeNumber(test.Input, culture, fallbackToDefaultCulture: false) }, { Models.NumberPercentMode, (test, culture) => NumberRecognizer.RecognizeNumber(test.Input, culture, NumberOptions.PercentageMode, fallbackToDefaultCulture: false) }, { Models.NumberExperimentalMode, (test, culture) => NumberRecognizer.RecognizeNumber(test.Input, culture, NumberOptions.ExperimentalMode, fallbackToDefaultCulture: false) }, { Models.Ordinal, (test, culture) => NumberRecognizer.RecognizeOrdinal(test.Input, culture, fallbackToDefaultCulture: false) }, { Models.OrdinalEnablePreview, (test, culture) => NumberRecognizer.RecognizeOrdinal(test.Input, culture, NumberOptions.EnablePreview, fallbackToDefaultCulture: false) }, { Models.Percent, (test, culture) => NumberRecognizer.RecognizePercentage(test.Input, culture, fallbackToDefaultCulture: false) }, { Models.PercentPercentMode, (test, culture) => NumberRecognizer.RecognizePercentage(test.Input, culture, NumberOptions.PercentageMode, fallbackToDefaultCulture: false) }, { Models.NumberRange, (test, culture) => NumberRecognizer.RecognizeNumberRange(test.Input, culture, fallbackToDefaultCulture: false) }, { Models.NumberRangeExperimentalMode, (test, culture) => NumberRecognizer.RecognizeNumberRange(test.Input, culture, NumberOptions.ExperimentalMode, fallbackToDefaultCulture: false) }, { Models.Age, (test, culture) => NumberWithUnitRecognizer.RecognizeAge(test.Input, culture, fallbackToDefaultCulture: false) }, { Models.Currency, (test, culture) => NumberWithUnitRecognizer.RecognizeCurrency(test.Input, culture, fallbackToDefaultCulture: false) }, { Models.Dimension, (test, culture) => NumberWithUnitRecognizer.RecognizeDimension(test.Input, culture, fallbackToDefaultCulture: false) }, { Models.Temperature, (test, culture) => NumberWithUnitRecognizer.RecognizeTemperature(test.Input, culture, fallbackToDefaultCulture: false) }, { Models.DateTime, (test, culture) => DateTimeRecognizer.RecognizeDateTime(test.Input, culture, refTime: test.GetReferenceDateTime(), fallbackToDefaultCulture: false) }, { Models.DateTimeSplitDateAndTime, (test, culture) => DateTimeRecognizer.RecognizeDateTime(test.Input, culture, DateTimeOptions.SplitDateAndTime, refTime: test.GetReferenceDateTime(), fallbackToDefaultCulture: false) }, { Models.DateTimeCalendarMode, (test, culture) => DateTimeRecognizer.RecognizeDateTime(test.Input, culture, DateTimeOptions.CalendarMode, refTime: test.GetReferenceDateTime(), fallbackToDefaultCulture: false) }, { Models.DateTimeExtendedTypes, (test, culture) => DateTimeRecognizer.RecognizeDateTime(test.Input, culture, DateTimeOptions.ExtendedTypes, refTime: test.GetReferenceDateTime(), fallbackToDefaultCulture: false) }, { Models.DateTimeComplexCalendar, (test, culture) => DateTimeRecognizer.RecognizeDateTime(test.Input, culture, DateTimeOptions.ExtendedTypes | DateTimeOptions.CalendarMode | DateTimeOptions.EnablePreview, refTime: test.GetReferenceDateTime(), fallbackToDefaultCulture: false) }, { Models.DateTimeExperimentalMode, (test, culture) => DateTimeRecognizer.RecognizeDateTime(test.Input, culture, DateTimeOptions.ExperimentalMode, refTime: test.GetReferenceDateTime(), fallbackToDefaultCulture: false) }, { Models.PhoneNumber, (test, culture) => SequenceRecognizer.RecognizePhoneNumber(test.Input, culture, fallbackToDefaultCulture: false) }, { Models.IpAddress, (test, culture) => SequenceRecognizer.RecognizeIpAddress(test.Input, culture, fallbackToDefaultCulture: false) }, { Models.Mention, (test, culture) => SequenceRecognizer.RecognizeMention(test.Input, culture, fallbackToDefaultCulture: false) }, { Models.Hashtag, (test, culture) => SequenceRecognizer.RecognizeHashtag(test.Input, culture, fallbackToDefaultCulture: false) }, { Models.Email, (test, culture) => SequenceRecognizer.RecognizeEmail(test.Input, culture, fallbackToDefaultCulture: false) }, { Models.URL, (test, culture) => SequenceRecognizer.RecognizeURL(test.Input, culture, fallbackToDefaultCulture: false) }, { Models.GUID, (test, culture) => SequenceRecognizer.RecognizeGUID(test.Input, culture, fallbackToDefaultCulture: false) }, { Models.Boolean, (test, culture) => ChoiceRecognizer.RecognizeBoolean(test.Input, culture, fallbackToDefaultCulture: false) }, }; public static IList<ModelResult> GetModelParseResults(this TestContext context, TestModel test) { var culture = TestUtils.GetCulture(context.FullyQualifiedTestClassName); var modelName = TestUtils.GetModel(context.TestName); var modelFunction = modelFunctions[modelName]; return modelFunction(test, culture); } public static IDateTimeExtractor GetExtractor(this TestContext context) { var culture = TestUtils.GetCulture(context.FullyQualifiedTestClassName); var extractorName = TestUtils.GetExtractor(context.TestName); switch (culture) { case Culture.English: return GetEnglishExtractor(extractorName); case Culture.EnglishOthers: return GetEnglishOthersExtractor(extractorName); case Culture.Spanish: return GetSpanishExtractor(extractorName); case Culture.Portuguese: return GetPortugueseExtractor(extractorName); case Culture.Chinese: return GetChineseExtractor(extractorName); case Culture.French: return GetFrenchExtractor(extractorName); case Culture.German: return GetGermanExtractor(extractorName); case Culture.Italian: return GetItalianExtractor(extractorName); case Culture.Dutch: return GetDutchExtractor(extractorName); case Culture.Japanese: return GetJapaneseExtractor(extractorName); } throw new Exception($"Extractor '{extractorName}' for '{culture}' not supported"); } public static IDateTimeParser GetDateTimeParser(this TestContext context) { var culture = TestUtils.GetCulture(context.FullyQualifiedTestClassName); var parserName = TestUtils.GetParser(context.TestName); switch (culture) { case Culture.English: return GetEnglishParser(parserName); case Culture.EnglishOthers: return GetEnglishOthersParser(parserName); case Culture.Spanish: return GetSpanishParser(parserName); case Culture.Portuguese: return GetPortugueseParser(parserName); case Culture.Chinese: return GetChineseParser(parserName); case Culture.French: return GetFrenchParser(parserName); case Culture.German: return GetGermanParser(parserName); case Culture.Italian: return GetItalianParser(parserName); case Culture.Japanese: return GetJapaneseParser(parserName); case Culture.Dutch: return GetDutchParser(parserName); } throw new Exception($"Parser '{parserName}' for '{culture}' not supported"); } public static IDateTimeExtractor GetEnglishExtractor(DateTimeExtractors extractorName) { var config = new BaseOptionsConfiguration(); var previewConfig = new BaseOptionsConfiguration(DateTimeOptions.EnablePreview); switch (extractorName) { case DateTimeExtractors.Date: return new BaseDateExtractor(new EnglishDateExtractorConfiguration(config)); case DateTimeExtractors.Time: return new BaseTimeExtractor(new EnglishTimeExtractorConfiguration(config)); case DateTimeExtractors.DatePeriod: return new BaseDatePeriodExtractor(new EnglishDatePeriodExtractorConfiguration(config)); case DateTimeExtractors.TimePeriod: return new BaseTimePeriodExtractor(new EnglishTimePeriodExtractorConfiguration(config)); case DateTimeExtractors.DateTime: return new BaseDateTimeExtractor(new EnglishDateTimeExtractorConfiguration(config)); case DateTimeExtractors.DateTimePeriod: return new BaseDateTimePeriodExtractor(new EnglishDateTimePeriodExtractorConfiguration(config)); case DateTimeExtractors.Duration: return new BaseDurationExtractor(new EnglishDurationExtractorConfiguration(config)); case DateTimeExtractors.Holiday: return new BaseHolidayExtractor(new EnglishHolidayExtractorConfiguration(config)); case DateTimeExtractors.TimeZone: return new BaseTimeZoneExtractor(new EnglishTimeZoneExtractorConfiguration(previewConfig)); case DateTimeExtractors.Set: return new BaseSetExtractor(new EnglishSetExtractorConfiguration(config)); case DateTimeExtractors.Merged: return new BaseMergedDateTimeExtractor(new EnglishMergedExtractorConfiguration(config)); case DateTimeExtractors.MergedSkipFromTo: return new BaseMergedDateTimeExtractor(new EnglishMergedExtractorConfiguration(new BaseOptionsConfiguration(DateTimeOptions.SkipFromToMerge))); } throw new Exception($"Extractor '{extractorName}' for English not supported"); } public static IDateTimeParser GetEnglishParser(DateTimeParsers parserName) { var commonConfiguration = new EnglishCommonDateTimeParserConfiguration(new BaseOptionsConfiguration()); switch (parserName) { case DateTimeParsers.Date: return new BaseDateParser(new EnglishDateParserConfiguration(commonConfiguration)); case DateTimeParsers.Time: return new DateTime.English.TimeParser(new EnglishTimeParserConfiguration(commonConfiguration)); case DateTimeParsers.DatePeriod: return new BaseDatePeriodParser(new EnglishDatePeriodParserConfiguration(commonConfiguration)); case DateTimeParsers.TimePeriod: return new BaseTimePeriodParser(new EnglishTimePeriodParserConfiguration(commonConfiguration)); case DateTimeParsers.DateTime: return new BaseDateTimeParser(new EnglishDateTimeParserConfiguration(commonConfiguration)); case DateTimeParsers.DateTimePeriod: return new BaseDateTimePeriodParser(new EnglishDateTimePeriodParserConfiguration(commonConfiguration)); case DateTimeParsers.Duration: return new BaseDurationParser(new EnglishDurationParserConfiguration(commonConfiguration)); case DateTimeParsers.Holiday: return new BaseHolidayParser(new EnglishHolidayParserConfiguration(commonConfiguration)); case DateTimeParsers.TimeZone: return new BaseTimeZoneParser(); case DateTimeParsers.Set: return new BaseSetParser(new EnglishSetParserConfiguration(commonConfiguration)); case DateTimeParsers.Merged: return new BaseMergedDateTimeParser(new EnglishMergedParserConfiguration(new BaseOptionsConfiguration())); } throw new Exception($"Parser '{parserName}' for English not supported"); } public static IDateTimeExtractor GetEnglishOthersExtractor(DateTimeExtractors extractorName) { var enableDmyConfig = new BaseOptionsConfiguration(DateTimeOptions.None, true); var enableDmyPreviewConfig = new BaseOptionsConfiguration(DateTimeOptions.EnablePreview, true); switch (extractorName) { case DateTimeExtractors.Date: return new BaseDateExtractor(new EnglishDateExtractorConfiguration(enableDmyConfig)); case DateTimeExtractors.Time: return new BaseTimeExtractor(new EnglishTimeExtractorConfiguration(enableDmyConfig)); case DateTimeExtractors.DatePeriod: return new BaseDatePeriodExtractor(new EnglishDatePeriodExtractorConfiguration(enableDmyConfig)); case DateTimeExtractors.TimePeriod: return new BaseTimePeriodExtractor(new EnglishTimePeriodExtractorConfiguration(enableDmyConfig)); case DateTimeExtractors.DateTime: return new BaseDateTimeExtractor(new EnglishDateTimeExtractorConfiguration(enableDmyConfig)); case DateTimeExtractors.DateTimePeriod: return new BaseDateTimePeriodExtractor(new EnglishDateTimePeriodExtractorConfiguration(enableDmyConfig)); case DateTimeExtractors.Duration: return new BaseDurationExtractor(new EnglishDurationExtractorConfiguration(enableDmyConfig)); case DateTimeExtractors.Holiday: return new BaseHolidayExtractor(new EnglishHolidayExtractorConfiguration(enableDmyConfig)); case DateTimeExtractors.TimeZone: return new BaseTimeZoneExtractor(new EnglishTimeZoneExtractorConfiguration(enableDmyPreviewConfig)); case DateTimeExtractors.Set: return new BaseSetExtractor(new EnglishSetExtractorConfiguration(enableDmyConfig)); case DateTimeExtractors.Merged: return new BaseMergedDateTimeExtractor(new EnglishMergedExtractorConfiguration(enableDmyConfig)); case DateTimeExtractors.MergedSkipFromTo: return new BaseMergedDateTimeExtractor(new EnglishMergedExtractorConfiguration(new BaseOptionsConfiguration(DateTimeOptions.SkipFromToMerge, true))); } throw new Exception($"Extractor '{extractorName}' for English-Others not supported"); } public static IDateTimeParser GetEnglishOthersParser(DateTimeParsers parserName) { var commonConfiguration = new EnglishCommonDateTimeParserConfiguration(new BaseOptionsConfiguration(DateTimeOptions.None, true)); switch (parserName) { case DateTimeParsers.Date: return new BaseDateParser(new EnglishDateParserConfiguration(commonConfiguration)); case DateTimeParsers.Time: return new DateTime.English.TimeParser(new EnglishTimeParserConfiguration(commonConfiguration)); case DateTimeParsers.DatePeriod: return new BaseDatePeriodParser(new EnglishDatePeriodParserConfiguration(commonConfiguration)); case DateTimeParsers.TimePeriod: return new BaseTimePeriodParser(new EnglishTimePeriodParserConfiguration(commonConfiguration)); case DateTimeParsers.DateTime: return new BaseDateTimeParser(new EnglishDateTimeParserConfiguration(commonConfiguration)); case DateTimeParsers.DateTimePeriod: return new BaseDateTimePeriodParser(new EnglishDateTimePeriodParserConfiguration(commonConfiguration)); case DateTimeParsers.Duration: return new BaseDurationParser(new EnglishDurationParserConfiguration(commonConfiguration)); case DateTimeParsers.Holiday: return new BaseHolidayParser(new EnglishHolidayParserConfiguration(commonConfiguration)); case DateTimeParsers.TimeZone: return new BaseTimeZoneParser(); case DateTimeParsers.Set: return new BaseSetParser(new EnglishSetParserConfiguration(commonConfiguration)); case DateTimeParsers.Merged: return new BaseMergedDateTimeParser(new EnglishMergedParserConfiguration(new BaseOptionsConfiguration())); } throw new Exception($"Parser '{parserName}' for English-Others not supported"); } public static IDateTimeExtractor GetChineseExtractor(DateTimeExtractors extractorName) { switch (extractorName) { case DateTimeExtractors.Date: return new DateTime.Chinese.ChineseDateExtractorConfiguration(); case DateTimeExtractors.Time: return new DateTime.Chinese.ChineseTimeExtractorConfiguration(); case DateTimeExtractors.DatePeriod: return new DateTime.Chinese.ChineseDatePeriodExtractorConfiguration(); case DateTimeExtractors.TimePeriod: return new DateTime.Chinese.ChineseTimePeriodExtractorChsConfiguration(); case DateTimeExtractors.DateTime: return new DateTime.Chinese.ChineseDateTimeExtractorConfiguration(); case DateTimeExtractors.DateTimePeriod: return new DateTime.Chinese.ChineseDateTimePeriodExtractorConfiguration(); case DateTimeExtractors.Duration: return new DateTime.Chinese.ChineseDurationExtractorConfiguration(); case DateTimeExtractors.Holiday: return new BaseHolidayExtractor(new DateTime.Chinese.ChineseHolidayExtractorConfiguration()); case DateTimeExtractors.Set: return new DateTime.Chinese.ChineseSetExtractorConfiguration(); case DateTimeExtractors.Merged: return new DateTime.Chinese.ChineseMergedExtractorConfiguration(DateTimeOptions.None); case DateTimeExtractors.MergedSkipFromTo: return new DateTime.Chinese.ChineseMergedExtractorConfiguration(DateTimeOptions.SkipFromToMerge); } throw new Exception($"Extractor '{extractorName}' for English not supported"); } public static IDateTimeParser GetChineseParser(DateTimeParsers parserName) { // var commonConfiguration = new EnglishCommonDateTimeParserConfiguration(); switch (parserName) { case DateTimeParsers.Date: return new DateTime.Chinese.ChineseDateParserConfiguration(new DateTime.Chinese.ChineseDateTimeParserConfiguration()); case DateTimeParsers.Time: return new DateTime.Chinese.ChineseTimeParserConfiguration(new DateTime.Chinese.ChineseDateTimeParserConfiguration()); case DateTimeParsers.DatePeriod: return new DateTime.Chinese.ChineseDatePeriodParserConfiguration(new DateTime.Chinese.ChineseDateTimeParserConfiguration()); case DateTimeParsers.TimePeriod: return new DateTime.Chinese.ChineseTimePeriodParserConfiguration(new DateTime.Chinese.ChineseDateTimeParserConfiguration()); case DateTimeParsers.DateTime: return new DateTime.Chinese.ChineseDateTimeParser(new DateTime.Chinese.ChineseDateTimeParserConfiguration()); case DateTimeParsers.DateTimePeriod: return new DateTime.Chinese.ChineseDateTimePeriodParserConfiguration(new DateTime.Chinese.ChineseDateTimeParserConfiguration()); case DateTimeParsers.Duration: return new DateTime.Chinese.ChineseDurationParserConfiguration(new DateTime.Chinese.ChineseDateTimeParserConfiguration()); case DateTimeParsers.Holiday: return new DateTime.Chinese.ChineseHolidayParserConfiguration(new DateTime.Chinese.ChineseDateTimeParserConfiguration()); case DateTimeParsers.Set: return new DateTime.Chinese.ChineseSetParserConfiguration(new DateTime.Chinese.ChineseDateTimeParserConfiguration()); case DateTimeParsers.Merged: return new FullDateTimeParser(new DateTime.Chinese.ChineseDateTimeParserConfiguration()); } throw new Exception($"Parser '{parserName}' for English not supported"); } public static IDateTimeExtractor GetDutchExtractor(DateTimeExtractors extractorName) { var enableDmyConfig = new BaseOptionsConfiguration(DateTimeOptions.None, dmyDateFormat: true); switch (extractorName) { case DateTimeExtractors.Date: return new BaseDateExtractor(new DutchDateExtractorConfiguration(enableDmyConfig)); case DateTimeExtractors.Time: return new BaseTimeExtractor(new DutchTimeExtractorConfiguration(enableDmyConfig)); case DateTimeExtractors.DatePeriod: return new BaseDatePeriodExtractor(new DutchDatePeriodExtractorConfiguration(enableDmyConfig)); case DateTimeExtractors.TimePeriod: return new BaseTimePeriodExtractor(new DutchTimePeriodExtractorConfiguration(enableDmyConfig)); case DateTimeExtractors.DateTime: return new BaseDateTimeExtractor(new DutchDateTimeExtractorConfiguration(enableDmyConfig)); case DateTimeExtractors.DateTimePeriod: return new BaseDateTimePeriodExtractor(new DutchDateTimePeriodExtractorConfiguration(enableDmyConfig)); case DateTimeExtractors.Duration: return new BaseDurationExtractor(new DutchDurationExtractorConfiguration(enableDmyConfig)); case DateTimeExtractors.Holiday: return new BaseHolidayExtractor(new DutchHolidayExtractorConfiguration(enableDmyConfig)); case DateTimeExtractors.TimeZone: return new BaseTimeZoneExtractor(new DutchTimeZoneExtractorConfiguration(enableDmyConfig)); case DateTimeExtractors.Set: return new BaseSetExtractor(new DutchSetExtractorConfiguration(enableDmyConfig)); case DateTimeExtractors.Merged: return new BaseMergedDateTimeExtractor(new DutchMergedExtractorConfiguration(enableDmyConfig)); case DateTimeExtractors.MergedSkipFromTo: return new BaseMergedDateTimeExtractor(new DutchMergedExtractorConfiguration(new BaseOptionsConfiguration(DateTimeOptions.SkipFromToMerge))); } throw new Exception($"Extractor '{extractorName}' for Dutch not supported"); } public static IDateTimeParser GetDutchParser(DateTimeParsers parserName) { var commonConfiguration = new DutchCommonDateTimeParserConfiguration(new BaseOptionsConfiguration(DateTimeOptions.None, dmyDateFormat: true)); switch (parserName) { case DateTimeParsers.Date: return new BaseDateParser(new DutchDateParserConfiguration(commonConfiguration)); case DateTimeParsers.Time: return new DateTime.Dutch.TimeParser(new DutchTimeParserConfiguration(commonConfiguration)); case DateTimeParsers.DatePeriod: return new BaseDatePeriodParser(new DutchDatePeriodParserConfiguration(commonConfiguration)); case DateTimeParsers.TimePeriod: return new BaseTimePeriodParser(new DutchTimePeriodParserConfiguration(commonConfiguration)); case DateTimeParsers.DateTime: return new BaseDateTimeParser(new DutchDateTimeParserConfiguration(commonConfiguration)); case DateTimeParsers.DateTimePeriod: return new BaseDateTimePeriodParser(new DutchDateTimePeriodParserConfiguration(commonConfiguration)); case DateTimeParsers.Duration: return new BaseDurationParser(new DutchDurationParserConfiguration(commonConfiguration)); case DateTimeParsers.Holiday: return new BaseHolidayParser(new DutchHolidayParserConfiguration(commonConfiguration)); case DateTimeParsers.TimeZone: return new BaseTimeZoneParser(); case DateTimeParsers.Set: return new BaseSetParser(new DutchSetParserConfiguration(commonConfiguration)); case DateTimeParsers.Merged: return new BaseMergedDateTimeParser(new DutchMergedParserConfiguration(new BaseOptionsConfiguration(DateTimeOptions.None, dmyDateFormat: true))); } throw new Exception($"Parser '{parserName}' for Dutch not supported"); } public static IDateTimeExtractor GetJapaneseExtractor(DateTimeExtractors extractorName) { switch (extractorName) { case DateTimeExtractors.Date: return new DateTime.Japanese.JapaneseDateExtractorConfiguration(); case DateTimeExtractors.Time: return new DateTime.Japanese.JapaneseTimeExtractorConfiguration(); case DateTimeExtractors.DatePeriod: return new DateTime.Japanese.JapaneseDatePeriodExtractorConfiguration(); case DateTimeExtractors.TimePeriod: return new DateTime.Japanese.JapaneseTimePeriodExtractorConfiguration(); case DateTimeExtractors.DateTime: return new DateTime.Japanese.JapaneseDateTimeExtractorConfiguration(); case DateTimeExtractors.DateTimePeriod: return new DateTime.Japanese.JapaneseDateTimePeriodExtractorConfiguration(); case DateTimeExtractors.Duration: return new DateTime.Japanese.JapaneseDurationExtractorConfiguration(); case DateTimeExtractors.Holiday: return new BaseHolidayExtractor(new DateTime.Japanese.JapaneseHolidayExtractorConfiguration()); case DateTimeExtractors.Set: return new DateTime.Japanese.JapaneseSetExtractorConfiguration(); case DateTimeExtractors.Merged: return new DateTime.Japanese.JapaneseMergedExtractorConfiguration(DateTimeOptions.None); case DateTimeExtractors.MergedSkipFromTo: return new DateTime.Japanese.JapaneseMergedExtractorConfiguration(DateTimeOptions.SkipFromToMerge); } throw new Exception($"Extractor '{extractorName}' for Japanese not supported"); } public static IDateTimeParser GetJapaneseParser(DateTimeParsers parserName) { switch (parserName) { case DateTimeParsers.Date: return new DateTime.Japanese.JapaneseDateParserConfiguration(new DateTime.Japanese.JapaneseDateTimeParserConfiguration()); case DateTimeParsers.Time: return new DateTime.Japanese.JapaneseTimeParserConfiguration(new DateTime.Japanese.JapaneseDateTimeParserConfiguration()); case DateTimeParsers.DatePeriod: return new DateTime.Japanese.JapaneseDatePeriodParserConfiguration(new DateTime.Japanese.JapaneseDateTimeParserConfiguration()); case DateTimeParsers.TimePeriod: return new DateTime.Japanese.JapaneseTimePeriodParserConfiguration(new DateTime.Japanese.JapaneseDateTimeParserConfiguration()); case DateTimeParsers.DateTime: return new DateTime.Japanese.JapaneseDateTimeParser(new DateTime.Japanese.JapaneseDateTimeParserConfiguration()); case DateTimeParsers.DateTimePeriod: return new DateTime.Japanese.JapaneseDateTimePeriodParserConfiguration(new DateTime.Japanese.JapaneseDateTimeParserConfiguration()); case DateTimeParsers.Duration: return new DateTime.Japanese.JapaneseDurationParserConfiguration(new DateTime.Japanese.JapaneseDateTimeParserConfiguration()); case DateTimeParsers.Holiday: return new DateTime.Japanese.JapaneseHolidayParserConfiguration(new DateTime.Japanese.JapaneseDateTimeParserConfiguration()); case DateTimeParsers.Set: return new DateTime.Japanese.JapaneseSetParserConfiguration(new DateTime.Japanese.JapaneseDateTimeParserConfiguration()); case DateTimeParsers.Merged: return new FullDateTimeParser(new DateTime.Japanese.JapaneseDateTimeParserConfiguration()); } throw new Exception($"Parser '{parserName}' for Japanese not supported"); } public static IDateTimeExtractor GetSpanishExtractor(DateTimeExtractors extractorName) { var config = new BaseOptionsConfiguration(DateTimeOptions.None); switch (extractorName) { case DateTimeExtractors.Date: return new BaseDateExtractor(new SpanishDateExtractorConfiguration(config)); case DateTimeExtractors.Time: return new BaseTimeExtractor(new SpanishTimeExtractorConfiguration(config)); case DateTimeExtractors.DatePeriod: return new BaseDatePeriodExtractor(new SpanishDatePeriodExtractorConfiguration(config)); case DateTimeExtractors.TimePeriod: return new BaseTimePeriodExtractor(new SpanishTimePeriodExtractorConfiguration(config)); case DateTimeExtractors.DateTime: return new BaseDateTimeExtractor(new SpanishDateTimeExtractorConfiguration(config)); case DateTimeExtractors.DateTimePeriod: return new BaseDateTimePeriodExtractor(new SpanishDateTimePeriodExtractorConfiguration(config)); case DateTimeExtractors.Duration: return new BaseDurationExtractor(new SpanishDurationExtractorConfiguration(config)); case DateTimeExtractors.Holiday: return new BaseHolidayExtractor(new SpanishHolidayExtractorConfiguration(config)); case DateTimeExtractors.Set: return new BaseSetExtractor(new SpanishSetExtractorConfiguration(config)); case DateTimeExtractors.Merged: return new BaseMergedDateTimeExtractor(new SpanishMergedExtractorConfiguration(DateTimeOptions.None)); } throw new Exception($"Extractor '{extractorName}' for Spanish not supported"); } public static IDateTimeParser GetSpanishParser(DateTimeParsers parserName) { var commonConfiguration = new SpanishCommonDateTimeParserConfiguration(new BaseOptionsConfiguration()); switch (parserName) { case DateTimeParsers.Date: return new BaseDateParser(new SpanishDateParserConfiguration(commonConfiguration)); case DateTimeParsers.Time: return new BaseTimeParser(new SpanishTimeParserConfiguration(commonConfiguration)); case DateTimeParsers.DatePeriod: return new BaseDatePeriodParser(new SpanishDatePeriodParserConfiguration(commonConfiguration)); case DateTimeParsers.TimePeriod: return new BaseTimePeriodParser(new SpanishTimePeriodParserConfiguration(commonConfiguration)); case DateTimeParsers.DateTime: return new BaseDateTimeParser(new SpanishDateTimeParserConfiguration(commonConfiguration)); case DateTimeParsers.DateTimePeriod: return new DateTime.Spanish.DateTimePeriodParser(new SpanishDateTimePeriodParserConfiguration(commonConfiguration)); case DateTimeParsers.Duration: return new BaseDurationParser(new SpanishDurationParserConfiguration(commonConfiguration)); case DateTimeParsers.Holiday: return new BaseHolidayParser(new SpanishHolidayParserConfiguration(commonConfiguration)); case DateTimeParsers.Set: return new BaseSetParser(new SpanishSetParserConfiguration(commonConfiguration)); case DateTimeParsers.Merged: return new BaseMergedDateTimeParser(new SpanishMergedParserConfiguration(commonConfiguration)); } throw new Exception($"Parser '{parserName}' for Spanish not supported"); } public static IDateTimeExtractor GetPortugueseExtractor(DateTimeExtractors extractorName) { var config = new BaseOptionsConfiguration(); switch (extractorName) { case DateTimeExtractors.Date: return new BaseDateExtractor(new PortugueseDateExtractorConfiguration(config)); case DateTimeExtractors.Time: return new BaseTimeExtractor(new PortugueseTimeExtractorConfiguration(config)); case DateTimeExtractors.DatePeriod: return new BaseDatePeriodExtractor(new PortugueseDatePeriodExtractorConfiguration(config)); case DateTimeExtractors.TimePeriod: return new BaseTimePeriodExtractor(new PortugueseTimePeriodExtractorConfiguration(config)); case DateTimeExtractors.DateTime: return new BaseDateTimeExtractor(new PortugueseDateTimeExtractorConfiguration(config)); case DateTimeExtractors.DateTimePeriod: return new BaseDateTimePeriodExtractor(new PortugueseDateTimePeriodExtractorConfiguration(config)); case DateTimeExtractors.Duration: return new BaseDurationExtractor(new PortugueseDurationExtractorConfiguration(config)); case DateTimeExtractors.Holiday: return new BaseHolidayExtractor(new PortugueseHolidayExtractorConfiguration(config)); case DateTimeExtractors.Set: return new BaseSetExtractor(new PortugueseSetExtractorConfiguration(config)); case DateTimeExtractors.Merged: return new BaseMergedDateTimeExtractor(new PortugueseMergedExtractorConfiguration(DateTimeOptions.None)); } throw new Exception($"Extractor '{extractorName}' for Portuguese not supported"); } public static IDateTimeParser GetPortugueseParser(DateTimeParsers parserName) { var commonConfiguration = new PortugueseCommonDateTimeParserConfiguration(new BaseOptionsConfiguration()); switch (parserName) { case DateTimeParsers.Date: return new BaseDateParser(new PortugueseDateParserConfiguration(commonConfiguration)); case DateTimeParsers.Time: return new BaseTimeParser(new PortugueseTimeParserConfiguration(commonConfiguration)); case DateTimeParsers.DatePeriod: return new BaseDatePeriodParser(new PortugueseDatePeriodParserConfiguration(commonConfiguration)); case DateTimeParsers.TimePeriod: return new BaseTimePeriodParser(new PortugueseTimePeriodParserConfiguration(commonConfiguration)); case DateTimeParsers.DateTime: return new BaseDateTimeParser(new PortugueseDateTimeParserConfiguration(commonConfiguration)); case DateTimeParsers.DateTimePeriod: return new DateTime.Portuguese.DateTimePeriodParser(new PortugueseDateTimePeriodParserConfiguration(commonConfiguration)); case DateTimeParsers.Duration: return new BaseDurationParser(new PortugueseDurationParserConfiguration(commonConfiguration)); case DateTimeParsers.Holiday: return new BaseHolidayParser(new PortugueseHolidayParserConfiguration(commonConfiguration)); case DateTimeParsers.Set: return new BaseSetParser(new PortugueseSetParserConfiguration(commonConfiguration)); case DateTimeParsers.Merged: return new BaseMergedDateTimeParser(new PortugueseMergedParserConfiguration(commonConfiguration)); } throw new Exception($"Parser '{parserName}' for Portuguese not supported"); } public static IDateTimeExtractor GetFrenchExtractor(DateTimeExtractors extractorName) { var config = new BaseOptionsConfiguration(); switch (extractorName) { case DateTimeExtractors.Date: return new BaseDateExtractor(new FrenchDateExtractorConfiguration(config)); case DateTimeExtractors.Time: return new BaseTimeExtractor(new FrenchTimeExtractorConfiguration(config)); case DateTimeExtractors.DatePeriod: return new BaseDatePeriodExtractor(new FrenchDatePeriodExtractorConfiguration(config)); case DateTimeExtractors.TimePeriod: return new BaseTimePeriodExtractor(new FrenchTimePeriodExtractorConfiguration(config)); case DateTimeExtractors.DateTime: return new BaseDateTimeExtractor(new FrenchDateTimeExtractorConfiguration(config)); case DateTimeExtractors.DateTimePeriod: return new BaseDateTimePeriodExtractor(new FrenchDateTimePeriodExtractorConfiguration(config)); case DateTimeExtractors.Duration: return new BaseDurationExtractor(new FrenchDurationExtractorConfiguration(config)); case DateTimeExtractors.Holiday: return new BaseHolidayExtractor(new FrenchHolidayExtractorConfiguration(config)); case DateTimeExtractors.Set: return new BaseSetExtractor(new FrenchSetExtractorConfiguration(config)); case DateTimeExtractors.Merged: return new BaseMergedDateTimeExtractor(new FrenchMergedExtractorConfiguration(DateTimeOptions.None)); case DateTimeExtractors.MergedSkipFromTo: return new BaseMergedDateTimeExtractor(new FrenchMergedExtractorConfiguration(DateTimeOptions.SkipFromToMerge)); } throw new Exception($"Extractor '{extractorName}' for French not supported"); } public static IDateTimeParser GetFrenchParser(DateTimeParsers parserName) { var commonConfiguration = new FrenchCommonDateTimeParserConfiguration(new BaseOptionsConfiguration()); switch (parserName) { case DateTimeParsers.Date: return new BaseDateParser(new FrenchDateParserConfiguration(commonConfiguration)); case DateTimeParsers.Time: return new DateTime.French.TimeParser(new FrenchTimeParserConfiguration(commonConfiguration)); case DateTimeParsers.DatePeriod: return new BaseDatePeriodParser(new FrenchDatePeriodParserConfiguration(commonConfiguration)); case DateTimeParsers.TimePeriod: return new BaseTimePeriodParser(new FrenchTimePeriodParserConfiguration(commonConfiguration)); case DateTimeParsers.DateTime: return new BaseDateTimeParser(new FrenchDateTimeParserConfiguration(commonConfiguration)); case DateTimeParsers.DateTimePeriod: return new BaseDateTimePeriodParser(new FrenchDateTimePeriodParserConfiguration(commonConfiguration)); case DateTimeParsers.Duration: return new BaseDurationParser(new FrenchDurationParserConfiguration(commonConfiguration)); case DateTimeParsers.Holiday: return new BaseHolidayParser(new FrenchHolidayParserConfiguration(commonConfiguration)); case DateTimeParsers.Set: return new BaseSetParser(new FrenchSetParserConfiguration(commonConfiguration)); case DateTimeParsers.Merged: return new BaseMergedDateTimeParser(new FrenchMergedParserConfiguration(commonConfiguration)); } throw new Exception($"Parser '{parserName}' for French not supported"); } public static IDateTimeExtractor GetGermanExtractor(DateTimeExtractors extractorName) { var config = new BaseOptionsConfiguration(); switch (extractorName) { case DateTimeExtractors.Date: return new BaseDateExtractor(new GermanDateExtractorConfiguration(config)); case DateTimeExtractors.Time: return new BaseTimeExtractor(new GermanTimeExtractorConfiguration(config)); case DateTimeExtractors.DatePeriod: return new BaseDatePeriodExtractor(new GermanDatePeriodExtractorConfiguration(config)); case DateTimeExtractors.TimePeriod: return new BaseTimePeriodExtractor(new GermanTimePeriodExtractorConfiguration(config)); case DateTimeExtractors.DateTime: return new BaseDateTimeExtractor(new GermanDateTimeExtractorConfiguration(config)); case DateTimeExtractors.DateTimePeriod: return new BaseDateTimePeriodExtractor(new GermanDateTimePeriodExtractorConfiguration(config)); case DateTimeExtractors.Duration: return new BaseDurationExtractor(new GermanDurationExtractorConfiguration(config)); case DateTimeExtractors.Holiday: return new BaseHolidayExtractor(new GermanHolidayExtractorConfiguration(config)); case DateTimeExtractors.Set: return new BaseSetExtractor(new GermanSetExtractorConfiguration(config)); case DateTimeExtractors.Merged: return new BaseMergedDateTimeExtractor(new GermanMergedExtractorConfiguration(DateTimeOptions.None)); case DateTimeExtractors.MergedSkipFromTo: return new BaseMergedDateTimeExtractor(new GermanMergedExtractorConfiguration(DateTimeOptions.SkipFromToMerge)); } throw new Exception($"Extractor '{extractorName}' for German not supported"); } public static IDateTimeParser GetGermanParser(DateTimeParsers parserName) { var commonConfiguration = new GermanCommonDateTimeParserConfiguration(new BaseOptionsConfiguration()); switch (parserName) { case DateTimeParsers.Date: return new BaseDateParser(new GermanDateParserConfiguration(commonConfiguration)); case DateTimeParsers.Time: return new DateTime.German.TimeParser(new GermanTimeParserConfiguration(commonConfiguration)); case DateTimeParsers.DatePeriod: return new BaseDatePeriodParser(new GermanDatePeriodParserConfiguration(commonConfiguration)); case DateTimeParsers.TimePeriod: return new BaseTimePeriodParser(new GermanTimePeriodParserConfiguration(commonConfiguration)); case DateTimeParsers.DateTime: return new BaseDateTimeParser(new GermanDateTimeParserConfiguration(commonConfiguration)); case DateTimeParsers.DateTimePeriod: return new BaseDateTimePeriodParser(new GermanDateTimePeriodParserConfiguration(commonConfiguration)); case DateTimeParsers.Duration: return new BaseDurationParser(new GermanDurationParserConfiguration(commonConfiguration)); case DateTimeParsers.Holiday: return new HolidayParserGer(new GermanHolidayParserConfiguration(commonConfiguration)); case DateTimeParsers.Set: return new BaseSetParser(new GermanSetParserConfiguration(commonConfiguration)); case DateTimeParsers.Merged: return new BaseMergedDateTimeParser(new GermanMergedParserConfiguration(commonConfiguration)); } throw new Exception($"Parser '{parserName}' for German not supported"); } public static IDateTimeExtractor GetItalianExtractor(DateTimeExtractors extractorName) { var config = new BaseOptionsConfiguration(); switch (extractorName) { case DateTimeExtractors.Date: return new BaseDateExtractor(new ItalianDateExtractorConfiguration(config)); case DateTimeExtractors.Time: return new BaseTimeExtractor(new ItalianTimeExtractorConfiguration(config)); case DateTimeExtractors.DatePeriod: return new BaseDatePeriodExtractor(new ItalianDatePeriodExtractorConfiguration(config)); case DateTimeExtractors.TimePeriod: return new BaseTimePeriodExtractor(new ItalianTimePeriodExtractorConfiguration(config)); case DateTimeExtractors.DateTime: return new BaseDateTimeExtractor(new ItalianDateTimeExtractorConfiguration(config)); case DateTimeExtractors.DateTimePeriod: return new BaseDateTimePeriodExtractor(new ItalianDateTimePeriodExtractorConfiguration(config)); case DateTimeExtractors.Duration: return new BaseDurationExtractor(new ItalianDurationExtractorConfiguration(config)); case DateTimeExtractors.Holiday: return new BaseHolidayExtractor(new ItalianHolidayExtractorConfiguration(config)); case DateTimeExtractors.Set: return new BaseSetExtractor(new ItalianSetExtractorConfiguration(config)); case DateTimeExtractors.Merged: return new BaseMergedDateTimeExtractor(new ItalianMergedExtractorConfiguration(config)); case DateTimeExtractors.MergedSkipFromTo: return new BaseMergedDateTimeExtractor(new ItalianMergedExtractorConfiguration(config)); case DateTimeExtractors.TimeZone: return new BaseTimeZoneExtractor(new ItalianTimeZoneExtractorConfiguration(config)); } throw new Exception($"Extractor '{extractorName}' for Italian not supported"); } public static IDateTimeParser GetItalianParser(DateTimeParsers parserName) { var commonConfiguration = new ItalianCommonDateTimeParserConfiguration(new BaseOptionsConfiguration()); switch (parserName) { case DateTimeParsers.Date: return new BaseDateParser(new ItalianDateParserConfiguration(commonConfiguration)); case DateTimeParsers.Time: return new DateTime.Italian.TimeParser(new ItalianTimeParserConfiguration(commonConfiguration)); case DateTimeParsers.DatePeriod: return new BaseDatePeriodParser(new ItalianDatePeriodParserConfiguration(commonConfiguration)); case DateTimeParsers.TimePeriod: return new BaseTimePeriodParser(new ItalianTimePeriodParserConfiguration(commonConfiguration)); case DateTimeParsers.DateTime: return new BaseDateTimeParser(new ItalianDateTimeParserConfiguration(commonConfiguration)); case DateTimeParsers.DateTimePeriod: return new BaseDateTimePeriodParser(new ItalianDateTimePeriodParserConfiguration(commonConfiguration)); case DateTimeParsers.Duration: return new BaseDurationParser(new ItalianDurationParserConfiguration(commonConfiguration)); case DateTimeParsers.Holiday: return new BaseHolidayParser(new ItalianHolidayParserConfiguration(commonConfiguration)); case DateTimeParsers.Set: return new BaseSetParser(new ItalianSetParserConfiguration(commonConfiguration)); case DateTimeParsers.Merged: return new BaseMergedDateTimeParser(new ItalianMergedParserConfiguration(commonConfiguration)); } throw new Exception($"Parser '{parserName}' for Italian not supported"); } } }
66.143799
290
0.685861
[ "MIT" ]
Aliandi/Recognizers-Text
.NET/Microsoft.Recognizers.Text.DataDrivenTests/TestContextExtensions.cs
50,139
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApp1 { class Program { static void Main(string[] args) { Persona p1 = new Persona("1234","Roger",30); Persona p2 = new Persona("5678","Javier",50); Trabajador t1 = new Trabajador("1212", "Michael",25,250000); p1.digaNombre(); p2.digaNombre(); p1.darEfectivo(100.0F); p2.darEfectivo(500.0F); p1.presentarse(p2.pasaNombre()); p2.presentarse(p1.pasaNombre()); Console.ReadLine(); } } }
21.25
72
0.560294
[ "MIT" ]
Hikhuj/ULACIT_DisenioAppSoftware
Foro_-_Tarea2_ClasePersona/Foro_-_Tarea2_ClasePersona/Program.cs
682
C#
using Content.Server.Atmos.Monitor.Components; using Content.Server.Atmos.EntitySystems; using Content.Server.Atmos.Piping.EntitySystems; using Content.Server.Atmos.Piping.Components; using Content.Server.DeviceNetwork; using Content.Server.DeviceNetwork.Components; using Content.Server.DeviceNetwork.Systems; using Content.Server.Power.Components; using Content.Server.Power.EntitySystems; using Content.Shared.Atmos; using Content.Shared.Atmos.Monitor; using Robust.Shared.Audio; using Robust.Shared.Player; using Robust.Shared.Prototypes; namespace Content.Server.Atmos.Monitor.Systems { // AtmosMonitorSystem. Grabs all the AtmosAlarmables connected // to it via local APC net, and starts sending updates of the // current atmosphere. Monitors fire (which always triggers as // a danger), and atmos (which triggers based on set thresholds). public sealed class AtmosMonitorSystem : EntitySystem { [Dependency] private readonly AtmosphereSystem _atmosphereSystem = default!; [Dependency] private readonly AtmosDeviceSystem _atmosDeviceSystem = default!; [Dependency] private readonly DeviceNetworkSystem _deviceNetSystem = default!; [Dependency] private readonly IPrototypeManager _prototypeManager = default!; // Commands /// <summary> /// Command to alarm the network that something has happened. /// </summary> public const string AtmosMonitorAlarmCmd = "atmos_monitor_alarm_update"; /// <summary> /// Command to sync this monitor's alarm state with the rest of the network. /// </summary> public const string AtmosMonitorAlarmSyncCmd = "atmos_monitor_alarm_sync"; /// <summary> /// Command to reset all alarms on a network. /// </summary> public const string AtmosMonitorAlarmResetAllCmd = "atmos_monitor_alarm_reset_all"; // Packet data /// <summary> /// Data response that contains the threshold types in an atmos monitor alarm. /// </summary> public const string AtmosMonitorAlarmThresholdTypes = "atmos_monitor_alarm_threshold_types"; /// <summary> /// Data response that contains the source of an atmos alarm. /// </summary> public const string AtmosMonitorAlarmSrc = "atmos_monitor_alarm_source"; /// <summary> /// Data response that contains the maximum alarm in an atmos alarm network. /// </summary> public const string AtmosMonitorAlarmNetMax = "atmos_monitor_alarm_net_max"; public override void Initialize() { SubscribeLocalEvent<AtmosMonitorComponent, ComponentInit>(OnAtmosMonitorInit); SubscribeLocalEvent<AtmosMonitorComponent, ComponentStartup>(OnAtmosMonitorStartup); SubscribeLocalEvent<AtmosMonitorComponent, ComponentShutdown>(OnAtmosMonitorShutdown); SubscribeLocalEvent<AtmosMonitorComponent, AtmosDeviceUpdateEvent>(OnAtmosUpdate); SubscribeLocalEvent<AtmosMonitorComponent, TileFireEvent>(OnFireEvent); SubscribeLocalEvent<AtmosMonitorComponent, PowerChangedEvent>(OnPowerChangedEvent); SubscribeLocalEvent<AtmosMonitorComponent, BeforePacketSentEvent>(BeforePacketRecv); SubscribeLocalEvent<AtmosMonitorComponent, DeviceNetworkPacketEvent>(OnPacketRecv); } private void OnAtmosMonitorInit(EntityUid uid, AtmosMonitorComponent component, ComponentInit args) { if (component.TemperatureThresholdId != null) component.TemperatureThreshold = _prototypeManager.Index<AtmosAlarmThreshold>(component.TemperatureThresholdId); if (component.PressureThresholdId != null) component.PressureThreshold = _prototypeManager.Index<AtmosAlarmThreshold>(component.PressureThresholdId); if (component.GasThresholdIds != null) { component.GasThresholds = new(); foreach (var (gas, id) in component.GasThresholdIds) if (_prototypeManager.TryIndex<AtmosAlarmThreshold>(id, out var gasThreshold)) component.GasThresholds.Add(gas, gasThreshold); } } private void OnAtmosMonitorStartup(EntityUid uid, AtmosMonitorComponent component, ComponentStartup args) { if (!HasComp<ApcPowerReceiverComponent>(uid) && TryComp<AtmosDeviceComponent>(uid, out var atmosDeviceComponent)) { _atmosDeviceSystem.LeaveAtmosphere(atmosDeviceComponent); return; } _checkPos.Add(uid); } private void OnAtmosMonitorShutdown(EntityUid uid, AtmosMonitorComponent component, ComponentShutdown args) { if (_checkPos.Contains(uid)) _checkPos.Remove(uid); } // hackiest shit ever but there's no PostStartup event private HashSet<EntityUid> _checkPos = new(); public override void Update(float frameTime) { foreach (var uid in _checkPos) OpenAirOrReposition(uid); } private void OpenAirOrReposition(EntityUid uid, AtmosMonitorComponent? component = null, AppearanceComponent? appearance = null) { if (!Resolve(uid, ref component, ref appearance)) return; var transform = Transform(component.Owner); // atmos alarms will first attempt to get the air // directly underneath it - if not, then it will // instead place itself directly in front of the tile // it is facing, and then visually shift itself back // via sprite offsets (SS13 style but fuck it) var coords = transform.Coordinates; if (_atmosphereSystem.IsTileAirBlocked(coords)) { var rotPos = transform.LocalRotation.RotateVec(new Vector2(0, -1)); transform.Anchored = false; coords = coords.Offset(rotPos); transform.Coordinates = coords; appearance.SetData("offset", - new Vector2(0, -1)); transform.Anchored = true; } GasMixture? air = _atmosphereSystem.GetTileMixture(coords); component.TileGas = air; _checkPos.Remove(uid); } private void BeforePacketRecv(EntityUid uid, AtmosMonitorComponent component, BeforePacketSentEvent args) { if (!component.NetEnabled) args.Cancel(); } private void OnPacketRecv(EntityUid uid, AtmosMonitorComponent component, DeviceNetworkPacketEvent args) { // sync the internal 'last alarm state' from // the other alarms, so that we can calculate // the highest network alarm state at any time if (!args.Data.TryGetValue(DeviceNetworkConstants.Command, out string? cmd) || !EntityManager.TryGetComponent(uid, out AtmosAlarmableComponent? alarmable) || !EntityManager.TryGetComponent(uid, out DeviceNetworkComponent netConn)) return; // ignore packets from self, ignore from different frequency if (netConn.Address == args.SenderAddress) return; switch (cmd) { // sync on alarm or explicit sync case AtmosMonitorAlarmCmd: case AtmosMonitorAlarmSyncCmd: if (args.Data.TryGetValue(AtmosMonitorAlarmSrc, out string? src) && alarmable.AlarmedByPrototypes.Contains(src) && args.Data.TryGetValue(DeviceNetworkConstants.CmdSetState, out AtmosMonitorAlarmType state) && !component.NetworkAlarmStates.TryAdd(args.SenderAddress, state)) component.NetworkAlarmStates[args.SenderAddress] = state; break; case AtmosMonitorAlarmResetAllCmd: if (args.Data.TryGetValue(AtmosMonitorAlarmSrc, out string? resetSrc) && alarmable.AlarmedByPrototypes.Contains(resetSrc)) { component.LastAlarmState = AtmosMonitorAlarmType.Normal; component.NetworkAlarmStates.Clear(); } break; } if (component.DisplayMaxAlarmInNet) { if (EntityManager.TryGetComponent(component.Owner, out AppearanceComponent? appearanceComponent)) appearanceComponent.SetData("alarmType", component.HighestAlarmInNetwork); if (component.HighestAlarmInNetwork == AtmosMonitorAlarmType.Danger) PlayAlertSound(uid, component); } } private void OnPowerChangedEvent(EntityUid uid, AtmosMonitorComponent component, PowerChangedEvent args) { if (TryComp<AtmosDeviceComponent>(uid, out var atmosDeviceComponent)) { if (!args.Powered) { if (atmosDeviceComponent.JoinedGrid != null) { _atmosDeviceSystem.LeaveAtmosphere(atmosDeviceComponent); component.TileGas = null; } // clear memory when power cycled component.LastAlarmState = AtmosMonitorAlarmType.Normal; component.NetworkAlarmStates.Clear(); } else if (args.Powered) { if (atmosDeviceComponent.JoinedGrid == null) { _atmosDeviceSystem.JoinAtmosphere(atmosDeviceComponent); var coords = Transform(component.Owner).Coordinates; var air = _atmosphereSystem.GetTileMixture(coords); component.TileGas = air; } } } if (EntityManager.TryGetComponent(component.Owner, out AppearanceComponent? appearanceComponent)) { appearanceComponent.SetData("powered", args.Powered); appearanceComponent.SetData("alarmType", component.LastAlarmState); } } private void OnFireEvent(EntityUid uid, AtmosMonitorComponent component, ref TileFireEvent args) { if (!this.IsPowered(uid, EntityManager)) return; // if we're monitoring for atmos fire, then we make it similar to a smoke detector // and just outright trigger a danger event // // somebody else can reset it :sunglasses: if (component.MonitorFire && component.LastAlarmState != AtmosMonitorAlarmType.Danger) Alert(uid, AtmosMonitorAlarmType.Danger, new []{ AtmosMonitorThresholdType.Temperature }, component); // technically??? // only monitor state elevation so that stuff gets alarmed quicker during a fire, // let the atmos update loop handle when temperature starts to reach different // thresholds and different states than normal -> warning -> danger if (component.TemperatureThreshold != null && component.TemperatureThreshold.CheckThreshold(args.Temperature, out var temperatureState) && temperatureState > component.LastAlarmState) Alert(uid, AtmosMonitorAlarmType.Danger, new []{ AtmosMonitorThresholdType.Temperature }, component); } private void OnAtmosUpdate(EntityUid uid, AtmosMonitorComponent component, AtmosDeviceUpdateEvent args) { if (!this.IsPowered(uid, EntityManager)) return; // can't hurt // (in case something is making AtmosDeviceUpdateEvents // outside the typical device loop) if (!TryComp<AtmosDeviceComponent>(uid, out var atmosDeviceComponent) || atmosDeviceComponent.JoinedGrid == null) return; // if we're not monitoring atmos, don't bother if (component.TemperatureThreshold == null && component.PressureThreshold == null && component.GasThresholds == null) return; UpdateState(uid, component.TileGas, component); } // Update checks the current air if it exceeds thresholds of // any kind. // // If any threshold exceeds the other, that threshold // immediately replaces the current recorded state. // // If the threshold does not match the current state // of the monitor, it is set in the Alert call. private void UpdateState(EntityUid uid, GasMixture? air, AtmosMonitorComponent? monitor = null) { if (air == null) return; if (!Resolve(uid, ref monitor)) return; AtmosMonitorAlarmType state = AtmosMonitorAlarmType.Normal; List<AtmosMonitorThresholdType> alarmTypes = new(); if (monitor.TemperatureThreshold != null && monitor.TemperatureThreshold.CheckThreshold(air.Temperature, out var temperatureState) && temperatureState > state) { state = temperatureState; alarmTypes.Add(AtmosMonitorThresholdType.Temperature); } if (monitor.PressureThreshold != null && monitor.PressureThreshold.CheckThreshold(air.Pressure, out var pressureState) && pressureState > state) { state = pressureState; alarmTypes.Add(AtmosMonitorThresholdType.Pressure); } if (monitor.GasThresholds != null) { foreach (var (gas, threshold) in monitor.GasThresholds) { var gasRatio = air.GetMoles(gas) / air.TotalMoles; if (threshold.CheckThreshold(gasRatio, out var gasState) && gasState > state) { state = gasState; alarmTypes.Add(AtmosMonitorThresholdType.Gas); } } } // if the state of the current air doesn't match the last alarm state, // we update the state if (state != monitor.LastAlarmState) { Alert(uid, state, alarmTypes, monitor); } } /// <summary> /// Alerts the network that the state of a monitor has changed. /// </summary> /// <param name="state">The alarm state to set this monitor to.</param> /// <param name="alarms">The alarms that caused this alarm state.</param> public void Alert(EntityUid uid, AtmosMonitorAlarmType state, IEnumerable<AtmosMonitorThresholdType>? alarms = null, AtmosMonitorComponent? monitor = null) { if (!Resolve(uid, ref monitor)) return; monitor.LastAlarmState = state; if (EntityManager.TryGetComponent(monitor.Owner, out AppearanceComponent? appearanceComponent)) appearanceComponent.SetData("alarmType", monitor.LastAlarmState); BroadcastAlertPacket(monitor, alarms); if (state == AtmosMonitorAlarmType.Danger) PlayAlertSound(uid, monitor); if (EntityManager.TryGetComponent(monitor.Owner, out AtmosAlarmableComponent alarmable) && !alarmable.IgnoreAlarms) RaiseLocalEvent(monitor.Owner, new AtmosMonitorAlarmEvent(monitor.LastAlarmState, monitor.HighestAlarmInNetwork)); // TODO: Central system that grabs *all* alarms from wired network } private void PlayAlertSound(EntityUid uid, AtmosMonitorComponent? monitor = null) { if (!Resolve(uid, ref monitor)) return; SoundSystem.Play(Filter.Pvs(uid), monitor.AlarmSound.GetSound(), uid, AudioParams.Default.WithVolume(monitor.AlarmVolume)); } /// <summary> /// Resets a single monitor's alarm. /// </summary> public void Reset(EntityUid uid) => Alert(uid, AtmosMonitorAlarmType.Normal); /// <summary> /// Resets a network's alarms, using this monitor as a source. /// </summary> /// <remarks> /// The resulting packet will have this monitor set as the source, using its prototype ID if it has one - otherwise just sending an empty string. /// </remarks> public void ResetAll(EntityUid uid, AtmosMonitorComponent? monitor = null) { if (!Resolve(uid, ref monitor)) return; var prototype = Prototype(monitor.Owner); var payload = new NetworkPayload { [DeviceNetworkConstants.Command] = AtmosMonitorAlarmResetAllCmd, [AtmosMonitorAlarmSrc] = prototype != null ? prototype.ID : string.Empty }; _deviceNetSystem.QueuePacket(monitor.Owner, null, payload); monitor.NetworkAlarmStates.Clear(); Alert(uid, AtmosMonitorAlarmType.Normal, null, monitor); } // (TODO: maybe just cache monitors in other monitors?) /// <summary> /// Syncs the current state of this monitor to the network (to avoid alerting other monitors). /// </summary> private void Sync(AtmosMonitorComponent monitor) { if (!monitor.NetEnabled) return; var prototype = Prototype(monitor.Owner); var payload = new NetworkPayload { [DeviceNetworkConstants.Command] = AtmosMonitorAlarmSyncCmd, [DeviceNetworkConstants.CmdSetState] = monitor.LastAlarmState, [AtmosMonitorAlarmSrc] = prototype != null ? prototype.ID : string.Empty }; _deviceNetSystem.QueuePacket(monitor.Owner, null, payload); } /// <summary> /// Broadcasts an alert packet to all devices on the network, /// which consists of the current alarm types, /// the highest alarm currently cached by this monitor, /// and the current alarm state of the monitor (so other /// alarms can sync to it). /// </summary> /// <remarks> /// Alarmables use the highest alarm to ensure that a monitor's /// state doesn't override if the alarm is lower. The state /// is synced between monitors the moment a monitor sends out an alarm, /// or if it is explicitly synced (see ResetAll/Sync). /// </remarks> private void BroadcastAlertPacket(AtmosMonitorComponent monitor, IEnumerable<AtmosMonitorThresholdType>? alarms = null) { if (!monitor.NetEnabled) return; string source = string.Empty; if (alarms == null) alarms = new List<AtmosMonitorThresholdType>(); var prototype = Prototype(monitor.Owner); if (prototype != null) source = prototype.ID; var payload = new NetworkPayload { [DeviceNetworkConstants.Command] = AtmosMonitorAlarmCmd, [DeviceNetworkConstants.CmdSetState] = monitor.LastAlarmState, [AtmosMonitorAlarmNetMax] = monitor.HighestAlarmInNetwork, [AtmosMonitorAlarmThresholdTypes] = alarms, [AtmosMonitorAlarmSrc] = source }; _deviceNetSystem.QueuePacket(monitor.Owner, null, payload); } /// <summary> /// Set a monitor's threshold. /// </summary> /// <param name="type">The type of threshold to change.</param> /// <param name="threshold">Threshold data.</param> /// <param name="gas">Gas, if applicable.</param> public void SetThreshold(EntityUid uid, AtmosMonitorThresholdType type, AtmosAlarmThreshold threshold, Gas? gas = null, AtmosMonitorComponent? monitor = null) { if (!Resolve(uid, ref monitor)) return; switch (type) { case AtmosMonitorThresholdType.Pressure: monitor.PressureThreshold = threshold; break; case AtmosMonitorThresholdType.Temperature: monitor.TemperatureThreshold = threshold; break; case AtmosMonitorThresholdType.Gas: if (gas == null || monitor.GasThresholds == null) return; monitor.GasThresholds[(Gas) gas] = threshold; break; } } } public sealed class AtmosMonitorAlarmEvent : EntityEventArgs { public AtmosMonitorAlarmType Type { get; } public AtmosMonitorAlarmType HighestNetworkType { get; } public AtmosMonitorAlarmEvent(AtmosMonitorAlarmType type, AtmosMonitorAlarmType netMax) { Type = type; HighestNetworkType = netMax; } } }
44.189979
166
0.61251
[ "MIT" ]
LittleBuilderJane/space-station-14
Content.Server/Atmos/Monitor/Systems/AtmosMonitoringSystem.cs
21,167
C#
namespace Kesco.Web.Mvc.UI.Grid { using System; public enum EditType { AutoComplete, CheckBox, Custom, DatePicker, DropDown, Password, TextArea, TextBox } }
14
31
0.512605
[ "MIT" ]
Kesco-m/Kesco.App.Web.MVC.Persons
Kesco.Web.Mvc.UI.Controls/Grid/EditType.cs
238
C#
// ------------------------------------------------------------------------------ // <auto-generated> // Generated by Xsd2Code. Version 3.4.0.18239 Microsoft Reciprocal License (Ms-RL) // <NameSpace>Mim.V6301</NameSpace><Collection>Array</Collection><codeType>CSharp</codeType><EnableDataBinding>False</EnableDataBinding><EnableLazyLoading>False</EnableLazyLoading><TrackingChangesEnable>False</TrackingChangesEnable><GenTrackingClasses>False</GenTrackingClasses><HidePrivateFieldInIDE>False</HidePrivateFieldInIDE><EnableSummaryComment>True</EnableSummaryComment><VirtualProp>False</VirtualProp><IncludeSerializeMethod>True</IncludeSerializeMethod><UseBaseClass>False</UseBaseClass><GenBaseClass>False</GenBaseClass><GenerateCloneMethod>True</GenerateCloneMethod><GenerateDataContracts>False</GenerateDataContracts><CodeBaseTag>Net35</CodeBaseTag><SerializeMethodName>Serialize</SerializeMethodName><DeserializeMethodName>Deserialize</DeserializeMethodName><SaveToFileMethodName>SaveToFile</SaveToFileMethodName><LoadFromFileMethodName>LoadFromFile</LoadFromFileMethodName><GenerateXMLAttributes>True</GenerateXMLAttributes><OrderXMLAttrib>False</OrderXMLAttrib><EnableEncoding>False</EnableEncoding><AutomaticProperties>False</AutomaticProperties><GenerateShouldSerialize>False</GenerateShouldSerialize><DisableDebug>False</DisableDebug><PropNameSpecified>Default</PropNameSpecified><Encoder>UTF8</Encoder><CustomUsings></CustomUsings><ExcludeIncludedTypes>True</ExcludeIncludedTypes><EnableInitializeFields>False</EnableInitializeFields> // </auto-generated> // ------------------------------------------------------------------------------ namespace Mim.V6301 { using System; using System.Diagnostics; using System.Xml.Serialization; using System.Collections; using System.Xml.Schema; using System.ComponentModel; using System.IO; using System.Text; [System.CodeDom.Compiler.GeneratedCodeAttribute("Xsd2Code", "3.4.0.18239")] [System.SerializableAttribute()] [System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true, Namespace="urn:hl7-org:v3")] public enum StrucDocColAlign { /// <remarks/> left, /// <remarks/> center, /// <remarks/> right, /// <remarks/> justify, /// <remarks/> @char, } }
61.487179
1,358
0.711426
[ "MIT" ]
Kusnaditjung/MimDms
src/Mim.V6301/Generated/StrucDocColAlign.cs
2,398
C#