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
// SampSharp // Copyright 2017 Tim Potze // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using SampSharp.Core.Logging; using SampSharp.GameMode.SAMP.Commands.PermissionCheckers; using SampSharp.GameMode.World; namespace SampSharp.GameMode.SAMP.Commands { /// <summary> /// Represents the default commands manager. /// </summary> public class CommandsManager : ICommandsManager { private static readonly Type[] SupportedReturnTypes = {typeof (bool), typeof (void)}; private readonly List<ICommand> _commands = new List<ICommand>(); /// <summary> /// Initializes a new instance of the <see cref="CommandsManager"/> class. /// </summary> /// <param name="gameMode">The game mode.</param> /// <exception cref="ArgumentNullException"></exception> public CommandsManager(BaseMode gameMode) { GameMode = gameMode ?? throw new ArgumentNullException(nameof(gameMode)); } #region Implementation of IService /// <summary> /// Gets the game mode. /// </summary> public BaseMode GameMode { get; } #endregion /// <summary> /// Registers the specified command. /// </summary> /// <param name="commandPaths">The command paths.</param> /// <param name="displayName">The display name.</param> /// <param name="ignoreCase">if set to <c>true</c> ignore the case of the command.</param> /// <param name="permissionCheckers">The permission checkers.</param> /// <param name="method">The method.</param> /// <param name="usageMessage">The usage message.</param> public virtual void Register(CommandPath[] commandPaths, string displayName, bool ignoreCase, IPermissionChecker[] permissionCheckers, MethodInfo method, string usageMessage) { Register(CreateCommand(commandPaths, displayName, ignoreCase, permissionCheckers, method, usageMessage)); } /// <summary> /// Creates a command. /// </summary> /// <param name="commandPaths">The command paths.</param> /// <param name="displayName">The display name.</param> /// <param name="ignoreCase">if set to <c>true</c> ignore the case the command.</param> /// <param name="permissionCheckers">The permission checkers.</param> /// <param name="method">The method.</param> /// <param name="usageMessage">The usage message.</param> /// <returns>The created command</returns> protected virtual ICommand CreateCommand(CommandPath[] commandPaths, string displayName, bool ignoreCase, IPermissionChecker[] permissionCheckers, MethodInfo method, string usageMessage) { return new DefaultCommand(commandPaths, displayName, ignoreCase, permissionCheckers, method, usageMessage); } /// <summary> /// Creates a help command. /// </summary> /// <param name="commandPaths">The command paths.</param> /// <param name="displayName">The display name.</param> /// <param name="ignoreCase">if set to <c>true</c> ignore the case the command.</param> /// <param name="permissionCheckers">The permission checkers.</param> /// <param name="method">The method.</param> /// <param name="usageMessage">The usage message.</param> /// <returns>The created command</returns> protected virtual ICommand CreateHelpCommand(CommandPath[] commandPaths, string displayName, bool ignoreCase, IPermissionChecker[] permissionCheckers, MethodInfo method, string usageMessage) { return new DefaultHelpCommand(commandPaths, displayName, ignoreCase, permissionCheckers, method, usageMessage); } private static IPermissionChecker CreatePermissionChecker(Type type) { if (type == null || !typeof(IPermissionChecker).GetTypeInfo().IsAssignableFrom(type)) return null; return Activator.CreateInstance(type) as IPermissionChecker; } private static IEnumerable<IPermissionChecker> GetCommandPermissionCheckers(Type type) { if (type == null || type == typeof(object)) yield break; foreach (var permissionChecker in GetCommandPermissionCheckers(type.DeclaringType)) yield return permissionChecker; foreach ( var permissionChecker in type.GetTypeInfo() .GetCustomAttributes<CommandGroupAttribute>() .Select(a => a.PermissionChecker) .Distinct() .Select(CreatePermissionChecker) .Where(c => c != null)) yield return permissionChecker; } private static IEnumerable<IPermissionChecker> GetCommandPermissionCheckers(MethodInfo method) { foreach (var permissionChecker in GetCommandPermissionCheckers(method.DeclaringType)) yield return permissionChecker; foreach ( var permissionChecker in method.GetCustomAttributes<CommandGroupAttribute>() .Select(a => a.PermissionChecker) .Concat(method.GetCustomAttributes<CommandAttribute>() .Select(a => a.PermissionChecker)) .Distinct() .Select(CreatePermissionChecker) .Where(c => c != null)) yield return permissionChecker; } private static IEnumerable<string> GetCommandGroupPaths(Type type) { if (type == null || type == typeof (object)) yield break; var count = 0; var groups = type.GetTypeInfo() .GetCustomAttributes<CommandGroupAttribute>() .SelectMany(a => { var paths = a.Paths; if (paths.Length == 0) { var name = type.Name.ToLower(); if (name.EndsWith("commandgroup")) name = name.Substring(0, name.Length - 12); paths = new[] {name}; } return paths; }) .Select(g => g.Trim()) .Where(g => !string.IsNullOrEmpty(g)).ToArray(); foreach (var group in GetCommandGroupPaths(type.DeclaringType)) { if (groups.Length == 0) yield return group; else foreach (var g in groups) yield return $"{group} {g}"; count++; } if (count == 0) foreach (var g in groups) yield return g; } private static IEnumerable<string> GetCommandGroupPaths(MethodInfo method) { var count = 0; var groups = method.GetCustomAttributes<CommandGroupAttribute>() .SelectMany(a => a.Paths) .Select(g => g.Trim()) .Where(g => !string.IsNullOrEmpty(g)).ToArray(); foreach (var path in GetCommandGroupPaths(method.DeclaringType)) { if (groups.Length == 0) yield return path; else foreach (var g in groups) yield return $"{path} {g}"; count++; } if (count == 0) foreach (var g in groups) yield return g; } /// <summary> /// Gets the command for the specified command text. /// </summary> /// <param name="player">The player.</param> /// <param name="commandText">The command text.</param> /// <returns>The found command.</returns> public ICommand GetCommandForText(BasePlayer player, string commandText) { ICommand candidate = null; var isFullMath = false; var candidateLength = 0; foreach (var command in _commands) { switch (command.CanInvoke(player, commandText, out var matchedNameLength)) { case CommandCallableResponse.True: if (candidateLength < matchedNameLength || candidateLength == matchedNameLength && !isFullMath) { isFullMath = true; candidateLength = matchedNameLength; candidate = command; } break; case CommandCallableResponse.Optional: if (candidateLength < matchedNameLength) { candidate = command; candidateLength = matchedNameLength; } break; } } return candidate; } #region Implementation of ICommandsManager /// <summary> /// Gets a read-only collection of all registered commands. /// </summary> public virtual IReadOnlyCollection<ICommand> Commands => _commands.AsReadOnly(); /// <summary> /// Loads all tagged commands from the assembly containing the specified type. /// </summary> /// <typeparam name="T">A type inside the assembly to load the commands form.</typeparam> public virtual void RegisterCommands<T>() where T : class { RegisterCommands(typeof (T)); } /// <summary> /// Loads all tagged commands from the assembly containing the specified type. /// </summary> /// <param name="typeInAssembly">A type inside the assembly to load the commands form.</param> public virtual void RegisterCommands(Type typeInAssembly) { if (typeInAssembly == null) throw new ArgumentNullException(nameof(typeInAssembly)); RegisterCommands(typeInAssembly.GetTypeInfo().Assembly); } /// <summary> /// Loads all tagged commands from the specified <paramref name="assembly" />. /// </summary> /// <param name="assembly">The assembly to load the commands from.</param> public virtual void RegisterCommands(Assembly assembly) { foreach ( var method in assembly.GetTypes() // Get all classes in the specified assembly. .Where(type => !type.GetTypeInfo().IsInterface && type.GetTypeInfo().IsClass) // Select the methods in the type. .SelectMany( type => type.GetTypeInfo().GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance)) // Exclude abstract methods. (none should be since abstract types are excluded) .Where(method => !method.IsAbstract) // Only include methods with a return type of bool or void. .Where(method => SupportedReturnTypes.Contains(method.ReturnType)) // Only include methods which have a command attribute. .Where(method => method.GetCustomAttribute<CommandAttribute>() != null) // Only include methods which are static and have a player as first argument -or- are a non-static member of a player derived class. .Where(DefaultCommand.IsValidCommandMethod) ) { var attribute = method.GetCustomAttribute<CommandAttribute>(); var names = attribute.Names; if (attribute.IsGroupHelp) { var helpCommandPaths = GetCommandGroupPaths(method) .Select(g => new CommandPath(g)) .ToArray(); if (helpCommandPaths.Length > 0) { Register(CreateHelpCommand(helpCommandPaths, attribute.DisplayName, attribute.IgnoreCase, GetCommandPermissionCheckers(method).ToArray(), method, attribute.UsageMessage)); } continue; } if (names.Length == 0) { var name = attribute.IgnoreCase ? method.Name.ToLower() : method.Name; names = new[] { name.EndsWith("command") || name.EndsWith("Command") ? name.Substring(0, name.Length - 7) : name }; } var commandPaths = GetCommandGroupPaths(method) .SelectMany(g => names.Select(n => new CommandPath(g, n))) .ToList(); if (commandPaths.Count == 0) commandPaths.AddRange(names.Select(n => new CommandPath(n))); if (!string.IsNullOrWhiteSpace(attribute.Shortcut)) commandPaths.Add(new CommandPath(attribute.Shortcut)); Register(commandPaths.ToArray(), attribute.DisplayName, attribute.IgnoreCase, GetCommandPermissionCheckers(method).ToArray(), method, attribute.UsageMessage); } } /// <summary> /// Registers the specified command. /// </summary> /// <param name="command">The command.</param> public virtual void Register(ICommand command) { if (command == null) throw new ArgumentNullException(nameof(command)); CoreLog.Log(CoreLogLevel.Debug, $"Registering command {command}"); _commands.Add(command); } /// <summary> /// Processes the specified player. /// </summary> /// <param name="commandText">The command text.</param> /// <param name="player">The player.</param> /// <returns>true if processed; false otherwise.</returns> public virtual bool Process(string commandText, BasePlayer player) { var command = GetCommandForText(player, commandText); return command != null && command.Invoke(player, commandText); } #endregion } }
41.153034
156
0.543823
[ "Apache-2.0" ]
KirillBorunov/SampSharp
src/SampSharp.GameMode/SAMP/Commands/CommandsManager.cs
15,597
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class CircleOnTerrain : Cycle { public Body body; public Life life; public int rows; public int columns; public Vector3 set; public float radius; public float height = 1; private SceneCircleVerts verts; private SceneCircleVerts tris; public override void Create(){ SafeInsert(body); SafeInsert(life); verts = (SceneCircleVerts)(body.verts); verts.rows = rows; verts.cols = columns; } public override void Bind(){ life.BindPrimaryForm( "_VertBuffer" , verts); life.BindVector3( "_SetLocation" , () => this.set ); life.BindFloat("_Radius", () => this.radius ); life.BindFloat("_Height", () => this.height ); data.land.BindData(life); } public void Embody(){ } public override void Activate(){ //Debug.Log("no body for some reason" , this.gameObject ); body.active = true; body.mpb.SetFloat("_Radius", radius); Set(); } public override void Deactivate(){ //DebugThis("DEACTIVATEING"); body.active = false; } public void Set(){ set = transform.position; life.active = true; } }
15.481013
62
0.640229
[ "MIT" ]
cabbibo/IMMATERIAL
Assets/IMMATERIA/Scene/CircleOnTerrain.cs
1,225
C#
using System.Collections.Generic; namespace Swish { class EntryPoint : ISyntaxNode, IMethod { public string Name { get; set; } public IType ReturnType { get { return new AsmType("System.Void"); } set { } } public Namespace Namespace { get; set; } public VariableScope Variables { get; set; } public List<ISyntaxNode> Body { get; set; } public EntryPoint(Namespace ns, params ISyntaxNode[] body) { Name = "~Main"; Body = new List<ISyntaxNode>(body); Variables = ns.AddScope(); Namespace = ns; } public void Emit(Emitter e) { e.EmitLine(".method static void " + Name + "()"); e.Indent(); e.EmitLine(".entrypoint"); Variables.Emit(e); foreach (var item in Body) item.Emit(e); e.EmitLine("ret"); e.Outdent(); } } }
24.512195
66
0.495522
[ "MIT" ]
noahmorrison/swish
compiler/SyntaxNode/EntryPoint.cs
1,005
C#
using System; using Android.Content; namespace Microsoft.Maui.Controls.Handlers.Items { internal class SizedItemContentView : ItemContentView { readonly Func<int> _width; readonly Func<int> _height; public SizedItemContentView(Context context, Func<int> width, Func<int> height) : base(context) { _width = width; _height = height; } protected override void OnMeasure(int widthMeasureSpec, int heightMeasureSpec) { if (Content == null) { SetMeasuredDimension(0, 0); return; } var targetWidth = _width(); var targetHeight = _height(); (Content.VirtualView as View).Measure(Context.FromPixels(targetWidth), Context.FromPixels(targetHeight), MeasureFlags.IncludeMargins); SetMeasuredDimension(targetWidth, targetHeight); } } }
22.571429
107
0.725316
[ "MIT" ]
41396/maui
src/Controls/src/Core/Handlers/Items/Android/SizedItemContentView.cs
792
C#
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Management.Automation.Internal; using System.Management.Automation.Remoting.Server; using System.Management.Automation.Runspaces; using Dbg = System.Management.Automation.Diagnostics; namespace System.Management.Automation.Remoting { /// <summary> /// By design, on the server side, each remote connection is represented by /// a ServerRemoteSession object, which contains one instance of this class. /// /// This class holds 4 pieces of information. /// 1. Client capability: This is the capability received during the negotiation process. /// 2. Server capability: This comes from default parameters. /// 3. Client configuration: This holds the remote session related configuration parameters that /// the client sent to the server. This parameters can be changed and resent after the connection /// is established. /// 4. Server configuration: this holds the server sider configuration parameters. /// /// All these together define the connection level parameters. /// </summary> internal class ServerRemoteSessionContext { #region Constructors /// <summary> /// The constructor instantiates a server capability object and a server configuration /// using default values. /// </summary> internal ServerRemoteSessionContext() { ServerCapability = RemoteSessionCapability.CreateServerCapability(); } #endregion Constructors /// <summary> /// This property represents the capability that the server receives from the client. /// </summary> internal RemoteSessionCapability ClientCapability { get; set; } /// <summary> /// This property is the server capability generated on the server side. /// </summary> internal RemoteSessionCapability ServerCapability { get; set; } /// <summary> /// True if negotiation from client is succeeded...in which case ClientCapability /// is the capability that server agreed with. /// </summary> internal bool IsNegotiationSucceeded { get; set; } } /// <summary> /// This class is designed to be the server side controller of a remote connection. /// /// It contains a static entry point that the PowerShell server process will get into /// the server mode. At this entry point, a runspace configuration is passed in. This runspace /// configuration is used to instantiate a server side runspace. /// /// This class controls a remote connection by using a Session data structure handler, which /// in turn contains a Finite State Machine, and a transport mechanism. /// </summary> internal class ServerRemoteSession : RemoteSession { [TraceSourceAttribute("ServerRemoteSession", "ServerRemoteSession")] private static readonly PSTraceSource s_trace = PSTraceSource.GetTracer("ServerRemoteSession", "ServerRemoteSession"); private readonly PSSenderInfo _senderInfo; private readonly string _configProviderId; private readonly string _initParameters; private string _initScriptForOutOfProcRS; private PSSessionConfiguration _sessionConfigProvider; // used to apply quotas on command and session transportmanagers. private int? _maxRecvdObjectSize; private int? _maxRecvdDataSizeCommand; private ServerRunspacePoolDriver _runspacePoolDriver; private readonly PSRemotingCryptoHelperServer _cryptoHelper; // Specifies an optional endpoint configuration for out-of-proc session use. // Creates a pushed remote runspace session created with this configuration name. private string _configurationName; // Specifies an initial location of the powershell session. private string _initialLocation; #region Events /// <summary> /// Raised when session is closed. /// </summary> internal EventHandler<RemoteSessionStateMachineEventArgs> Closed; #endregion #region Constructors /// <summary> /// This constructor instantiates a ServerRemoteSession object and /// a ServerRemoteSessionDataStructureHandler object. /// </summary> /// <param name="senderInfo"> /// Details about the user creating this session. /// </param> /// <param name="configurationProviderId"> /// The resource URI for which this session is being created /// </param> /// <param name="initializationParameters"> /// Initialization Parameters xml passed by WSMan API. This data is read from the config /// xml. /// </param> /// <param name="transportManager"> /// The transport manager this session should use to send/receive data /// </param> /// <returns></returns> internal ServerRemoteSession(PSSenderInfo senderInfo, string configurationProviderId, string initializationParameters, AbstractServerSessionTransportManager transportManager) { Dbg.Assert(transportManager != null, "transportManager cannot be null."); // let input,output and error from native commands redirect as we have // to send (or receive) them back to client for action. NativeCommandProcessor.IsServerSide = true; _senderInfo = senderInfo; _configProviderId = configurationProviderId; _initParameters = initializationParameters; _cryptoHelper = (PSRemotingCryptoHelperServer)transportManager.CryptoHelper; _cryptoHelper.Session = this; Context = new ServerRemoteSessionContext(); SessionDataStructureHandler = new ServerRemoteSessionDSHandlerImpl(this, transportManager); BaseSessionDataStructureHandler = SessionDataStructureHandler; SessionDataStructureHandler.CreateRunspacePoolReceived += HandleCreateRunspacePool; SessionDataStructureHandler.NegotiationReceived += HandleNegotiationReceived; SessionDataStructureHandler.SessionClosing += HandleSessionDSHandlerClosing; SessionDataStructureHandler.PublicKeyReceived += HandlePublicKeyReceived; transportManager.Closing += HandleResourceClosing; // update the quotas from sessionState..start with default size..and // when Custom Session Configuration is loaded (during runspace creation) update this. transportManager.ReceivedDataCollection.MaximumReceivedObjectSize = BaseTransportManager.MaximumReceivedObjectSize; // session transport manager can receive unlimited data..however each object is limited // by maxRecvdObjectSize. this is to allow clients to use a session for an unlimited time.. // also the messages that can be sent to a session are limited and very controlled. // However a command transport manager can be restricted to receive only a fixed amount of data // controlled by maxRecvdDataSizeCommand..This is because commands can accept any number of input // objects transportManager.ReceivedDataCollection.MaximumReceivedDataSize = null; } #endregion Constructors #region Creation Factory /// <summary> /// Creates a server remote session for the supplied <paramref name="configurationProviderId"/> /// and <paramref name="transportManager"/>. /// </summary> /// <param name="senderInfo"></param> /// <param name="configurationProviderId"></param> /// <param name="initializationParameters"> /// Initialization Parameters xml passed by WSMan API. This data is read from the config /// xml. /// </param> /// <param name="transportManager"></param> /// <param name="configurationName">Optional configuration endpoint name for OutOfProc sessions.</param> /// <param name="initialLocation">Optional configuration initial location of the powershell session.</param> /// <returns></returns> /// <exception cref="InvalidOperationException"> /// InitialSessionState provider with <paramref name="configurationProviderId"/> does /// not exist on the remote server. /// </exception> /* <InitializationParameters> <Param Name="PSVersion" Value="2.0" /> <Param Name="ApplicationBase" Value="<folder path>" /> ... </InitializationParameters> */ internal static ServerRemoteSession CreateServerRemoteSession( PSSenderInfo senderInfo, string configurationProviderId, string initializationParameters, AbstractServerSessionTransportManager transportManager, string configurationName = null, string initialLocation = null) { Dbg.Assert( (senderInfo != null) && (senderInfo.UserInfo != null), "senderInfo and userInfo cannot be null."); s_trace.WriteLine("Finding InitialSessionState provider for id : {0}", configurationProviderId); if (string.IsNullOrEmpty(configurationProviderId)) { throw PSTraceSource.NewInvalidOperationException("RemotingErrorIdStrings.NonExistentInitialSessionStateProvider", configurationProviderId); } const string shellPrefix = System.Management.Automation.Remoting.Client.WSManNativeApi.ResourceURIPrefix; int index = configurationProviderId.IndexOf(shellPrefix, StringComparison.OrdinalIgnoreCase); senderInfo.ConfigurationName = (index == 0) ? configurationProviderId.Substring(shellPrefix.Length) : string.Empty; ServerRemoteSession result = new ServerRemoteSession( senderInfo, configurationProviderId, initializationParameters, transportManager) { _configurationName = configurationName, _initialLocation = initialLocation }; // start state machine. RemoteSessionStateMachineEventArgs startEventArg = new RemoteSessionStateMachineEventArgs(RemoteSessionEvent.CreateSession); result.SessionDataStructureHandler.StateMachine.RaiseEvent(startEventArg); return result; } /// <summary> /// Used by OutOfProcessServerMediator to create a remote session. /// </summary> /// <param name="senderInfo"></param> /// <param name="initializationScriptForOutOfProcessRunspace"></param> /// <param name="transportManager"></param> /// <param name="configurationName"></param> /// <param name="initialLocation"></param> /// <returns></returns> internal static ServerRemoteSession CreateServerRemoteSession( PSSenderInfo senderInfo, string initializationScriptForOutOfProcessRunspace, AbstractServerSessionTransportManager transportManager, string configurationName, string initialLocation) { ServerRemoteSession result = CreateServerRemoteSession( senderInfo, "Microsoft.PowerShell", string.Empty, transportManager, configurationName: configurationName, initialLocation: initialLocation); result._initScriptForOutOfProcRS = initializationScriptForOutOfProcessRunspace; return result; } #endregion #region Overrides /// <summary> /// This indicates the remote session object is Client, Server or Listener. /// </summary> internal override RemotingDestination MySelf { get { return RemotingDestination.Server; } } /// <summary> /// This is the data dispatcher for the whole remote connection. /// This dispatcher is registered with the server side input queue's InputDataReady event. /// When the input queue has received data from client, it calls the InputDataReady listeners. /// /// This dispatcher distinguishes the negotiation packet as a special case. For all other data, /// it dispatches the data through Finite State Machines DoMessageReceived handler by raising the event /// MessageReceived. The FSM's DoMessageReceived handler further dispatches to the receiving /// components: such as runspace or pipeline which have their own data dispatching methods. /// </summary> /// <param name="sender"> /// This parameter is not used by the method, in this implementation. /// </param> /// <param name="dataEventArg"> /// This parameter contains the remote data received from client. /// </param> /// <exception cref="ArgumentNullException"> /// If the parameter <paramref name="dataEventArg"/> is null. /// </exception> /// <exception cref="ArgumentException"> /// If the parameter <paramref name="dataEventArg"/> does not contain remote data. /// </exception> /// <exception cref="PSRemotingDataStructureException"> /// If the destination of the data is not for server. /// </exception> internal void DispatchInputQueueData(object sender, RemoteDataEventArgs dataEventArg) { if (dataEventArg == null) { throw PSTraceSource.NewArgumentNullException(nameof(dataEventArg)); } RemoteDataObject<PSObject> rcvdData = dataEventArg.ReceivedData; if (rcvdData == null) { throw PSTraceSource.NewArgumentException(nameof(dataEventArg)); } RemotingDestination destination = rcvdData.Destination; if ((destination & MySelf) != MySelf) { // this packet is not target for me. throw new PSRemotingDataStructureException(RemotingErrorIdStrings.RemotingDestinationNotForMe, MySelf, destination); } RemotingTargetInterface targetInterface = rcvdData.TargetInterface; RemotingDataType dataType = rcvdData.DataType; RemoteSessionStateMachineEventArgs messageReceivedArg = null; switch (targetInterface) { case RemotingTargetInterface.Session: { switch (dataType) { // TODO: Directly calling an event handler in StateMachine bypassing the StateMachine's // loop of ProcessEvents()..This is needed as connection is already established and the // following message does not change state. An ideal solution would be to process // non-session messages in this class rather than by StateMachine. case RemotingDataType.CreateRunspacePool: messageReceivedArg = new RemoteSessionStateMachineEventArgs(RemoteSessionEvent.MessageReceived); if (SessionDataStructureHandler.StateMachine.CanByPassRaiseEvent(messageReceivedArg)) { messageReceivedArg.RemoteData = rcvdData; SessionDataStructureHandler.StateMachine.DoMessageReceived(this, messageReceivedArg); } else { SessionDataStructureHandler.StateMachine.RaiseEvent(messageReceivedArg); } break; case RemotingDataType.CloseSession: SessionDataStructureHandler.RaiseDataReceivedEvent(dataEventArg); break; case RemotingDataType.SessionCapability: SessionDataStructureHandler.RaiseDataReceivedEvent(dataEventArg); break; case RemotingDataType.PublicKey: SessionDataStructureHandler.RaiseDataReceivedEvent(dataEventArg); break; default: Dbg.Assert(false, "Should never reach here"); break; } } break; // TODO: Directly calling an event handler in StateMachine bypassing the StateMachine's // loop of ProcessEvents()..This is needed as connection is already established and the // following message does not change state. An ideal solution would be to process // non-session messages in this class rather than by StateMachine. case RemotingTargetInterface.RunspacePool: case RemotingTargetInterface.PowerShell: // GETBACK messageReceivedArg = new RemoteSessionStateMachineEventArgs(RemoteSessionEvent.MessageReceived); if (SessionDataStructureHandler.StateMachine.CanByPassRaiseEvent(messageReceivedArg)) { messageReceivedArg.RemoteData = rcvdData; SessionDataStructureHandler.StateMachine.DoMessageReceived(this, messageReceivedArg); } else { SessionDataStructureHandler.StateMachine.RaiseEvent(messageReceivedArg); } break; } } /// <summary> /// Have received a public key from the other side /// Import or take other action based on the state. /// </summary> /// <param name="sender">Sender of this event, unused.</param> /// <param name="eventArgs">event arguments which contains the /// remote public key</param> private void HandlePublicKeyReceived(object sender, RemoteDataEventArgs<string> eventArgs) { if (SessionDataStructureHandler.StateMachine.State == RemoteSessionState.Established || SessionDataStructureHandler.StateMachine.State == RemoteSessionState.EstablishedAndKeyRequested || // this is only for legacy clients SessionDataStructureHandler.StateMachine.State == RemoteSessionState.EstablishedAndKeyExchanged) { string remotePublicKey = eventArgs.Data; bool ret = _cryptoHelper.ImportRemotePublicKey(remotePublicKey); RemoteSessionStateMachineEventArgs args = null; if (!ret) { // importing remote public key failed // set state to closed args = new RemoteSessionStateMachineEventArgs(RemoteSessionEvent.KeyReceiveFailed); SessionDataStructureHandler.StateMachine.RaiseEvent(args); } args = new RemoteSessionStateMachineEventArgs(RemoteSessionEvent.KeyReceived); SessionDataStructureHandler.StateMachine.RaiseEvent(args); } } /// <summary> /// Start the key exchange process. /// </summary> internal override void StartKeyExchange() { if (SessionDataStructureHandler.StateMachine.State == RemoteSessionState.Established) { // send using data structure handler SessionDataStructureHandler.SendRequestForPublicKey(); RemoteSessionStateMachineEventArgs eventArgs = new RemoteSessionStateMachineEventArgs(RemoteSessionEvent.KeyRequested); SessionDataStructureHandler.StateMachine.RaiseEvent(eventArgs); } } /// <summary> /// Complete the Key exchange process. /// </summary> internal override void CompleteKeyExchange() { _cryptoHelper.CompleteKeyExchange(); } /// <summary> /// Send an encrypted session key to the client. /// </summary> internal void SendEncryptedSessionKey() { Dbg.Assert(SessionDataStructureHandler.StateMachine.State == RemoteSessionState.EstablishedAndKeyReceived, "Sever must be in EstablishedAndKeyReceived state before you can attempt to send encrypted session key"); string encryptedSessionKey = null; bool ret = _cryptoHelper.ExportEncryptedSessionKey(out encryptedSessionKey); RemoteSessionStateMachineEventArgs args = null; if (!ret) { args = new RemoteSessionStateMachineEventArgs(RemoteSessionEvent.KeySendFailed); SessionDataStructureHandler.StateMachine.RaiseEvent(args); } SessionDataStructureHandler.SendEncryptedSessionKey(encryptedSessionKey); // complete the key exchange process CompleteKeyExchange(); args = new RemoteSessionStateMachineEventArgs(RemoteSessionEvent.KeySent); SessionDataStructureHandler.StateMachine.RaiseEvent(args); } #endregion Overrides #region Properties /// <summary> /// This property returns the ServerRemoteSessionContext object created inside /// this object's constructor. /// </summary> internal ServerRemoteSessionContext Context { get; } /// <summary> /// This property returns the ServerRemoteSessionDataStructureHandler object created inside /// this object's constructor. /// </summary> internal ServerRemoteSessionDataStructureHandler SessionDataStructureHandler { get; } #endregion #region Private/Internal Methods /// <summary> /// Let the session clear its resources. /// </summary> /// <param name="reasonForClose"></param> internal void Close(RemoteSessionStateMachineEventArgs reasonForClose) { Closed.SafeInvoke(this, reasonForClose); if (_runspacePoolDriver != null) _runspacePoolDriver.Closed -= HandleResourceClosing; } /// <summary> /// ExecutesConnect. expects client capability and connect_runspacepool PSRP /// messages in connectData. /// If negotiation is successful and max and min runspaces in connect_runspacepool /// match the associated runspace pool parameters, it builds up server capability /// and runspace_initinfo in connectResponseData. /// This is a version of Connect that executes the whole connect algorithm in one single /// hop. /// This algorithm is being executed synchronously without associating with state machine. /// </summary> /// <param name="connectData"></param> /// <param name="connectResponseData"></param> /// The operation is being outside the statemachine because of multiple reasons associated with design simplicity /// - Support automatic disconnect and let wsman server stack take care of connection state /// - The response data should not travel in transports output stream but as part of connect response /// - We want this operation to be synchronous internal void ExecuteConnect(byte[] connectData, out byte[] connectResponseData) { connectResponseData = null; Fragmentor fragmentor = new Fragmentor(int.MaxValue, null); Fragmentor defragmentor = fragmentor; int totalDataLen = connectData.Length; if (totalDataLen < FragmentedRemoteObject.HeaderLength) { // raise exception throw new PSRemotingDataStructureException(RemotingErrorIdStrings.ServerConnectFailedOnInputValidation); } // TODO: Follow up on comment from Krishna regarding having the serialization/deserialization separate for this // operation. This could be integrated as helper functions in fragmentor/serializer components long fragmentId = FragmentedRemoteObject.GetFragmentId(connectData, 0); bool sFlag = FragmentedRemoteObject.GetIsStartFragment(connectData, 0); bool eFlag = FragmentedRemoteObject.GetIsEndFragment(connectData, 0); int blobLength = FragmentedRemoteObject.GetBlobLength(connectData, 0); if (blobLength > totalDataLen - FragmentedRemoteObject.HeaderLength) { // raise exception throw new PSRemotingDataStructureException(RemotingErrorIdStrings.ServerConnectFailedOnInputValidation); } if (!sFlag || !eFlag) { throw new PSRemotingDataStructureException(RemotingErrorIdStrings.ServerConnectFailedOnInputValidation); } // if session is not in expected state RemoteSessionState currentState = SessionDataStructureHandler.StateMachine.State; if (currentState != RemoteSessionState.Established && currentState != RemoteSessionState.EstablishedAndKeyExchanged) { throw new PSRemotingDataStructureException(RemotingErrorIdStrings.ServerConnectFailedOnServerStateValidation); } // process first message MemoryStream serializedStream = new MemoryStream(); serializedStream.Write(connectData, FragmentedRemoteObject.HeaderLength, blobLength); serializedStream.Seek(0, SeekOrigin.Begin); RemoteDataObject<PSObject> capabilityObject = RemoteDataObject<PSObject>.CreateFrom(serializedStream, defragmentor); if (capabilityObject == null) { throw new PSRemotingDataStructureException(RemotingErrorIdStrings.ServerConnectFailedOnInputValidation); } if ((capabilityObject.Destination != RemotingDestination.Server) || (capabilityObject.DataType != RemotingDataType.SessionCapability)) { throw new PSRemotingDataStructureException(RemotingErrorIdStrings.ServerConnectFailedOnInputValidation); } // process second message int secondFragmentLength = totalDataLen - FragmentedRemoteObject.HeaderLength - blobLength; if (secondFragmentLength < FragmentedRemoteObject.HeaderLength) { throw new PSRemotingDataStructureException(RemotingErrorIdStrings.ServerConnectFailedOnInputValidation); } byte[] secondFragment = new byte[secondFragmentLength]; Array.Copy(connectData, FragmentedRemoteObject.HeaderLength + blobLength, secondFragment, 0, secondFragmentLength); fragmentId = FragmentedRemoteObject.GetFragmentId(secondFragment, 0); sFlag = FragmentedRemoteObject.GetIsStartFragment(secondFragment, 0); eFlag = FragmentedRemoteObject.GetIsEndFragment(secondFragment, 0); blobLength = FragmentedRemoteObject.GetBlobLength(secondFragment, 0); if (blobLength != secondFragmentLength - FragmentedRemoteObject.HeaderLength) { throw new PSRemotingDataStructureException(RemotingErrorIdStrings.ServerConnectFailedOnInputValidation); } if (!sFlag || !eFlag) { throw new PSRemotingDataStructureException(RemotingErrorIdStrings.ServerConnectFailedOnInputValidation); } // process second message serializedStream = new MemoryStream(); serializedStream.Write(secondFragment, FragmentedRemoteObject.HeaderLength, blobLength); serializedStream.Seek(0, SeekOrigin.Begin); RemoteDataObject<PSObject> connectRunspacePoolObject = RemoteDataObject<PSObject>.CreateFrom(serializedStream, defragmentor); if (connectRunspacePoolObject == null) { throw new PSRemotingDataStructureException(RemotingErrorIdStrings.ServerConnectFailedOnServerStateValidation); } if ((connectRunspacePoolObject.Destination != RemotingDestination.Server) || (connectRunspacePoolObject.DataType != RemotingDataType.ConnectRunspacePool)) { throw new PSRemotingDataStructureException(RemotingErrorIdStrings.ServerConnectFailedOnInputValidation); } // We have the two objects required for validating the connect operation RemoteSessionCapability clientCapability; try { clientCapability = RemotingDecoder.GetSessionCapability(capabilityObject.Data); } catch (PSRemotingDataStructureException) { // this will happen if expected properties are not // received for session capability throw new PSRemotingDataStructureException(RemotingErrorIdStrings.ServerConnectFailedOnInputValidation); } try { RunServerNegotiationAlgorithm(clientCapability, true); } catch (PSRemotingDataStructureException) { throw; } // validate client connect_runspacepool request int clientRequestedMinRunspaces = -1; int clientRequestedMaxRunspaces = -1; bool clientRequestedRunspaceCount = false; if (connectRunspacePoolObject.Data.Properties[RemoteDataNameStrings.MinRunspaces] != null && connectRunspacePoolObject.Data.Properties[RemoteDataNameStrings.MaxRunspaces] != null) { try { clientRequestedMinRunspaces = RemotingDecoder.GetMinRunspaces(connectRunspacePoolObject.Data); clientRequestedMaxRunspaces = RemotingDecoder.GetMaxRunspaces(connectRunspacePoolObject.Data); clientRequestedRunspaceCount = true; } catch (PSRemotingDataStructureException) { throw new PSRemotingDataStructureException(RemotingErrorIdStrings.ServerConnectFailedOnInputValidation); } } // these should be positive and max should be greater than min if (clientRequestedRunspaceCount && (clientRequestedMinRunspaces == -1 || clientRequestedMaxRunspaces == -1 || clientRequestedMinRunspaces > clientRequestedMaxRunspaces)) { throw new PSRemotingDataStructureException(RemotingErrorIdStrings.ServerConnectFailedOnInputValidation); } if (_runspacePoolDriver == null) { throw new PSRemotingDataStructureException(RemotingErrorIdStrings.ServerConnectFailedOnServerStateValidation); } // currently only one runspace pool per session is allowed. make sure this ID in connect message is the same if (connectRunspacePoolObject.RunspacePoolId != _runspacePoolDriver.InstanceId) { throw new PSRemotingDataStructureException(RemotingErrorIdStrings.ServerConnectFailedOnInputValidation); } // we currently dont support adjusting runspace count on a connect operation. // there is a potential conflict here where in the runspace pool driver is still yet to process a queued // setMax or setMinrunspaces request. // TODO: resolve this.. probably by letting the runspace pool consume all messages before we execute this. if (clientRequestedRunspaceCount && (_runspacePoolDriver.RunspacePool.GetMaxRunspaces() != clientRequestedMaxRunspaces) && (_runspacePoolDriver.RunspacePool.GetMinRunspaces() != clientRequestedMinRunspaces)) { throw new PSRemotingDataStructureException(RemotingErrorIdStrings.ServerConnectFailedOnMismatchedRunspacePoolProperties); } // all client messages are validated // now build up the server capabilities and connect response messages to be piggybacked on connect response RemoteDataObject capability = RemotingEncoder.GenerateServerSessionCapability(Context.ServerCapability, _runspacePoolDriver.InstanceId); RemoteDataObject runspacepoolInitData = RemotingEncoder.GenerateRunspacePoolInitData(_runspacePoolDriver.InstanceId, _runspacePoolDriver.RunspacePool.GetMaxRunspaces(), _runspacePoolDriver.RunspacePool.GetMinRunspaces()); // having this stream operating separately will result in out of sync fragment Ids. but this is still OK // as this is executed only when connecting from a new client that does not have any previous fragments context. // no problem even if fragment Ids in this response and the sessiontransport stream clash (interfere) and its guaranteed // that the fragments in connect response are always complete (enclose a complete object). SerializedDataStream stream = new SerializedDataStream(4 * 1024); //Each message with fragment headers cannot cross 4k stream.Enter(); capability.Serialize(stream, fragmentor); stream.Exit(); stream.Enter(); runspacepoolInitData.Serialize(stream, fragmentor); stream.Exit(); byte[] outbuffer = stream.Read(); Dbg.Assert(outbuffer != null, "connect response data should be serialized"); stream.Dispose(); // we are done connectResponseData = outbuffer; // enqueue a connect event in state machine to let session do any other post-connect operation // Do this outside of the synchronous connect operation, as otherwise connect can easily get deadlocked ThreadPool.QueueUserWorkItem(new WaitCallback( (object state) => { RemoteSessionStateMachineEventArgs startEventArg = new RemoteSessionStateMachineEventArgs(RemoteSessionEvent.ConnectSession); SessionDataStructureHandler.StateMachine.RaiseEvent(startEventArg); })); _runspacePoolDriver.DataStructureHandler.ProcessConnect(); return; } // pass on application private data when session is connected from new client internal void HandlePostConnect() { if (_runspacePoolDriver != null) { _runspacePoolDriver.SendApplicationPrivateDataToClient(); } } /// <summary> /// </summary> /// <param name="sender"></param> /// <param name="createRunspaceEventArg"></param> /// <exception cref="InvalidOperationException"> /// 1. InitialSessionState cannot be null. /// 2. Non existent InitialSessionState provider for the shellID /// </exception> private void HandleCreateRunspacePool(object sender, RemoteDataEventArgs createRunspaceEventArg) { if (createRunspaceEventArg == null) { throw PSTraceSource.NewArgumentNullException(nameof(createRunspaceEventArg)); } RemoteDataObject<PSObject> rcvdData = createRunspaceEventArg.ReceivedData; Dbg.Assert(rcvdData != null, "rcvdData must be non-null"); // set the PSSenderInfo sent in the first packets // This is used by the initial session state configuration providers like Exchange. if (Context != null) { _senderInfo.ClientTimeZone = Context.ClientCapability.TimeZone; } _senderInfo.ApplicationArguments = RemotingDecoder.GetApplicationArguments(rcvdData.Data); // Get Initial Session State from custom session config suppliers // like Exchange. ConfigurationDataFromXML configurationData = PSSessionConfiguration.LoadEndPointConfiguration(_configProviderId, _initParameters); // used by Out-Of-Proc (IPC) runspace. configurationData.InitializationScriptForOutOfProcessRunspace = _initScriptForOutOfProcRS; // start with data from configuration XML and then override with data // from EndPointConfiguration type. _maxRecvdObjectSize = configurationData.MaxReceivedObjectSizeMB; _maxRecvdDataSizeCommand = configurationData.MaxReceivedCommandSizeMB; DISCPowerShellConfiguration discProvider = null; if (string.IsNullOrEmpty(configurationData.ConfigFilePath)) { _sessionConfigProvider = configurationData.CreateEndPointConfigurationInstance(); } else { System.Security.Principal.WindowsPrincipal windowsPrincipal = new System.Security.Principal.WindowsPrincipal(_senderInfo.UserInfo.WindowsIdentity); Func<string, bool> validator = (role) => windowsPrincipal.IsInRole(role); discProvider = new DISCPowerShellConfiguration(configurationData.ConfigFilePath, validator); _sessionConfigProvider = discProvider; } // exchange of ApplicationArguments and ApplicationPrivateData is be done as early as possible // (i.e. to let the _sessionConfigProvider bail out if it can't comply with client's versioning request) PSPrimitiveDictionary applicationPrivateData = _sessionConfigProvider.GetApplicationPrivateData(_senderInfo); InitialSessionState rsSessionStateToUse = null; if (configurationData.SessionConfigurationData != null) { try { rsSessionStateToUse = _sessionConfigProvider.GetInitialSessionState(configurationData.SessionConfigurationData, _senderInfo, _configProviderId); } catch (NotImplementedException) { rsSessionStateToUse = _sessionConfigProvider.GetInitialSessionState(_senderInfo); } } else { rsSessionStateToUse = _sessionConfigProvider.GetInitialSessionState(_senderInfo); } if (rsSessionStateToUse == null) { throw PSTraceSource.NewInvalidOperationException(RemotingErrorIdStrings.InitialSessionStateNull, _configProviderId); } rsSessionStateToUse.ThrowOnRunspaceOpenError = true; // this might throw if the sender info is already present rsSessionStateToUse.Variables.Add( new SessionStateVariableEntry(RemoteDataNameStrings.SenderInfoPreferenceVariable, _senderInfo, Remoting.PSRemotingErrorInvariants.FormatResourceString( RemotingErrorIdStrings.PSSenderInfoDescription), ScopedItemOptions.ReadOnly)); // check if the current scenario is Win7(client) to Win8(server). Add back the PSv2 version TabExpansion // function if necessary. Version psClientVersion = null; if (_senderInfo.ApplicationArguments != null && _senderInfo.ApplicationArguments.ContainsKey("PSversionTable")) { var value = PSObject.Base(_senderInfo.ApplicationArguments["PSversionTable"]) as PSPrimitiveDictionary; if (value != null) { if (value.ContainsKey("WSManStackVersion")) { var wsmanStackVersion = PSObject.Base(value["WSManStackVersion"]) as Version; if (wsmanStackVersion != null && wsmanStackVersion.Major < 3) { // The client side is PSv2. This is the Win7 to Win8 scenario. We need to add the PSv2 // TabExpansion function back in to keep the tab expansion functionable on the client side. rsSessionStateToUse.Commands.Add( new SessionStateFunctionEntry( RemoteDataNameStrings.PSv2TabExpansionFunction, RemoteDataNameStrings.PSv2TabExpansionFunctionText)); } } if (value.ContainsKey("PSVersion")) { psClientVersion = PSObject.Base(value["PSVersion"]) as Version; } } } if (!string.IsNullOrEmpty(configurationData.EndPointConfigurationTypeName)) { // user specified a type to load for configuration..use the values from this type. _maxRecvdObjectSize = _sessionConfigProvider.GetMaximumReceivedObjectSize(_senderInfo); _maxRecvdDataSizeCommand = _sessionConfigProvider.GetMaximumReceivedDataSizePerCommand(_senderInfo); } SessionDataStructureHandler.TransportManager.ReceivedDataCollection.MaximumReceivedObjectSize = _maxRecvdObjectSize; // MaximumReceivedDataSize is not set for session transport manager...see the constructor // for more info. Guid clientRunspacePoolId = rcvdData.RunspacePoolId; int minRunspaces = RemotingDecoder.GetMinRunspaces(rcvdData.Data); int maxRunspaces = RemotingDecoder.GetMaxRunspaces(rcvdData.Data); PSThreadOptions threadOptions = RemotingDecoder.GetThreadOptions(rcvdData.Data); ApartmentState apartmentState = RemotingDecoder.GetApartmentState(rcvdData.Data); HostInfo hostInfo = RemotingDecoder.GetHostInfo(rcvdData.Data); if (_runspacePoolDriver != null) { throw new PSRemotingDataStructureException(RemotingErrorIdStrings.RunspaceAlreadyExists, _runspacePoolDriver.InstanceId); } #if !UNIX bool isAdministrator = _senderInfo.UserInfo.IsInRole(System.Security.Principal.WindowsBuiltInRole.Administrator); #else bool isAdministrator = false; #endif ServerRunspacePoolDriver tmpDriver = new ServerRunspacePoolDriver( clientRunspacePoolId, minRunspaces, maxRunspaces, threadOptions, apartmentState, hostInfo, rsSessionStateToUse, applicationPrivateData, configurationData, this.SessionDataStructureHandler.TransportManager, isAdministrator, Context.ServerCapability, psClientVersion, _configurationName, _initialLocation); // attach the necessary event handlers and start the driver. Interlocked.Exchange(ref _runspacePoolDriver, tmpDriver); _runspacePoolDriver.Closed += HandleResourceClosing; _runspacePoolDriver.Start(); } /// <summary> /// This handler method runs the negotiation algorithm. It decides if the negotiation is succesful, /// or fails. /// </summary> /// <param name="sender"></param> /// <param name="negotiationEventArg"> /// This parameter contains the client negotiation capability packet. /// </param> /// <exception cref="ArgumentNullException"> /// If the parameter <paramref name="negotiationEventArg"/> is null. /// </exception> private void HandleNegotiationReceived(object sender, RemoteSessionNegotiationEventArgs negotiationEventArg) { if (negotiationEventArg == null) { throw PSTraceSource.NewArgumentNullException(nameof(negotiationEventArg)); } try { Context.ClientCapability = negotiationEventArg.RemoteSessionCapability; // This will throw if there is an error running the algorithm RunServerNegotiationAlgorithm(negotiationEventArg.RemoteSessionCapability, false); // Send server's capability to client. RemoteSessionStateMachineEventArgs sendingNegotiationArg = new RemoteSessionStateMachineEventArgs(RemoteSessionEvent.NegotiationSending); SessionDataStructureHandler.StateMachine.RaiseEvent(sendingNegotiationArg); // if negotiation succeeded change the state to neg. completed. RemoteSessionStateMachineEventArgs negotiationCompletedArg = new RemoteSessionStateMachineEventArgs(RemoteSessionEvent.NegotiationCompleted); SessionDataStructureHandler.StateMachine.RaiseEvent(negotiationCompletedArg); } catch (PSRemotingDataStructureException dse) { // Before setting to negotiation failed..send servers capability...that // way client can communicate differently if it wants to. RemoteSessionStateMachineEventArgs sendingNegotiationArg = new RemoteSessionStateMachineEventArgs(RemoteSessionEvent.NegotiationSending); SessionDataStructureHandler.StateMachine.RaiseEvent(sendingNegotiationArg); RemoteSessionStateMachineEventArgs negotiationFailedArg = new RemoteSessionStateMachineEventArgs(RemoteSessionEvent.NegotiationFailed, dse); SessionDataStructureHandler.StateMachine.RaiseEvent(negotiationFailedArg); } } /// <summary> /// Handle session closing event to close runspace pool drivers this session is hosting. /// </summary> /// <param name="sender"></param> /// <param name="eventArgs"></param> private void HandleSessionDSHandlerClosing(object sender, EventArgs eventArgs) { if (_runspacePoolDriver != null) { _runspacePoolDriver.Close(); } // dispose the session configuration object..this will let them // clean their resources. if (_sessionConfigProvider != null) { _sessionConfigProvider.Dispose(); _sessionConfigProvider = null; } } /// <summary> /// This handles closing of any resource used by this session. /// Resources used are RunspacePoolDriver, TransportManager. /// </summary> /// <param name="sender"></param> /// <param name="args"></param> private void HandleResourceClosing(object sender, EventArgs args) { RemoteSessionStateMachineEventArgs closeSessionArgs = new RemoteSessionStateMachineEventArgs(RemoteSessionEvent.Close); closeSessionArgs.RemoteData = null; SessionDataStructureHandler.StateMachine.RaiseEvent(closeSessionArgs); } /// <summary> /// This is the server side remote session capability negotiation algorithm. /// </summary> /// <param name="clientCapability"> /// This is the client capability that the server received from client. /// </param> /// <param name="onConnect"> /// If the negotiation is on a connect (and not create) /// </param> /// <returns> /// The method returns true if the capability negotiation is successful. /// Otherwise, it returns false. /// </returns> /// <exception cref="PSRemotingDataStructureException"> /// 1. PowerShell server does not support the PSVersion {1} negotiated by the client. /// Make sure the client is compatible with the build {2} of PowerShell. /// 2. PowerShell server does not support the SerializationVersion {1} negotiated by the client. /// Make sure the client is compatible with the build {2} of PowerShell. /// </exception> private bool RunServerNegotiationAlgorithm(RemoteSessionCapability clientCapability, bool onConnect) { Dbg.Assert(clientCapability != null, "Client capability cache must be non-null"); Version clientProtocolVersion = clientCapability.ProtocolVersion; Version serverProtocolVersion = Context.ServerCapability.ProtocolVersion; if (onConnect) { bool connectSupported = false; // Win10 server can support reconstruct/reconnect for all 2.x protocol versions // that support reconstruct/reconnect, Protocol 2.2+ // Major protocol version differences (2.x -> 3.x) are not supported. // A reconstruct can only be initiated by a client that understands disconnect (2.2+), // so we only need to check major versions from client and this server for compatibility. if (clientProtocolVersion.Major == RemotingConstants.ProtocolVersion.Major) { if (clientProtocolVersion.Minor == RemotingConstants.ProtocolVersionWin8RTM.Minor) { // Report that server is Win8 version to the client // Protocol: 2.2 connectSupported = true; serverProtocolVersion = RemotingConstants.ProtocolVersionWin8RTM; Context.ServerCapability.ProtocolVersion = serverProtocolVersion; } else if (clientProtocolVersion.Minor > RemotingConstants.ProtocolVersionWin8RTM.Minor) { // All other minor versions are supported and the server returns its full capability // Protocol: 2.3, 2.4, 2.5 ... connectSupported = true; } } if (!connectSupported) { // Throw for protocol versions 2.x that don't support disconnect/reconnect. // Protocol: < 2.2 PSRemotingDataStructureException reasonOfFailure = new PSRemotingDataStructureException(RemotingErrorIdStrings.ServerConnectFailedOnNegotiation, RemoteDataNameStrings.PS_STARTUP_PROTOCOL_VERSION_NAME, clientProtocolVersion, PSVersionInfo.GitCommitId, RemotingConstants.ProtocolVersion); throw reasonOfFailure; } } else { // Win10 server can support Win8 client if (clientProtocolVersion == RemotingConstants.ProtocolVersionWin8RTM && ( (serverProtocolVersion == RemotingConstants.ProtocolVersionWin10RTM) )) { // - report that server is Win8 version to the client serverProtocolVersion = RemotingConstants.ProtocolVersionWin8RTM; Context.ServerCapability.ProtocolVersion = serverProtocolVersion; } // Win8, Win10 server can support Win7 client if (clientProtocolVersion == RemotingConstants.ProtocolVersionWin7RTM && ( (serverProtocolVersion == RemotingConstants.ProtocolVersionWin8RTM) || (serverProtocolVersion == RemotingConstants.ProtocolVersionWin10RTM) )) { // - report that server is Win7 version to the client serverProtocolVersion = RemotingConstants.ProtocolVersionWin7RTM; Context.ServerCapability.ProtocolVersion = serverProtocolVersion; } // Win7, Win8, Win10 server can support Win7 RC client if (clientProtocolVersion == RemotingConstants.ProtocolVersionWin7RC && ( (serverProtocolVersion == RemotingConstants.ProtocolVersionWin7RTM) || (serverProtocolVersion == RemotingConstants.ProtocolVersionWin8RTM) || (serverProtocolVersion == RemotingConstants.ProtocolVersionWin10RTM) )) { // - report that server is RC version to the client serverProtocolVersion = RemotingConstants.ProtocolVersionWin7RC; Context.ServerCapability.ProtocolVersion = serverProtocolVersion; } if (!((clientProtocolVersion.Major == serverProtocolVersion.Major) && (clientProtocolVersion.Minor >= serverProtocolVersion.Minor))) { PSRemotingDataStructureException reasonOfFailure = new PSRemotingDataStructureException(RemotingErrorIdStrings.ServerNegotiationFailed, RemoteDataNameStrings.PS_STARTUP_PROTOCOL_VERSION_NAME, clientProtocolVersion, PSVersionInfo.GitCommitId, RemotingConstants.ProtocolVersion); throw reasonOfFailure; } } // PSVersion Check Version clientPSVersion = clientCapability.PSVersion; Version serverPSVersion = Context.ServerCapability.PSVersion; if (!((clientPSVersion.Major == serverPSVersion.Major) && (clientPSVersion.Minor >= serverPSVersion.Minor))) { PSRemotingDataStructureException reasonOfFailure = new PSRemotingDataStructureException(RemotingErrorIdStrings.ServerNegotiationFailed, RemoteDataNameStrings.PSVersion, clientPSVersion, PSVersionInfo.GitCommitId, RemotingConstants.ProtocolVersion); throw reasonOfFailure; } // SerializationVersion check Version clientSerVersion = clientCapability.SerializationVersion; Version serverSerVersion = Context.ServerCapability.SerializationVersion; if (!((clientSerVersion.Major == serverSerVersion.Major) && (clientSerVersion.Minor >= serverSerVersion.Minor))) { PSRemotingDataStructureException reasonOfFailure = new PSRemotingDataStructureException(RemotingErrorIdStrings.ServerNegotiationFailed, RemoteDataNameStrings.SerializationVersion, clientSerVersion, PSVersionInfo.GitCommitId, RemotingConstants.ProtocolVersion); throw reasonOfFailure; } return true; } /// <summary> /// </summary> /// <param name="clientRunspacePoolId"></param> /// <returns></returns> internal ServerRunspacePoolDriver GetRunspacePoolDriver(Guid clientRunspacePoolId) { if (_runspacePoolDriver == null) { return null; } if (_runspacePoolDriver.InstanceId == clientRunspacePoolId) { return _runspacePoolDriver; } return null; } /// <summary> /// Used by Command Session to apply quotas on the command transport manager. /// This method is here because ServerRemoteSession knows about InitialSessionState. /// </summary> /// <param name="cmdTransportManager"> /// Command TransportManager to apply the quota on. /// </param> internal void ApplyQuotaOnCommandTransportManager(AbstractServerTransportManager cmdTransportManager) { Dbg.Assert(cmdTransportManager != null, "cmdTransportManager cannot be null"); cmdTransportManager.ReceivedDataCollection.MaximumReceivedDataSize = _maxRecvdDataSizeCommand; cmdTransportManager.ReceivedDataCollection.MaximumReceivedObjectSize = _maxRecvdObjectSize; } #endregion } }
48.812766
191
0.627269
[ "MIT" ]
Hwangjonggyun/PowerShell
src/System.Management.Automation/engine/remoting/server/serverremotesession.cs
57,355
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Xml; using System.Xml.Linq; namespace armipsSimpleGui { class Settings { public const string SETTINGS_FILENAME = "settings.xml"; public static uint fileRAM = 0; public static List<String> uselibs = new List<String>(); public static string preASM = ""; public static string postASM = ""; public static bool useASMasROOT = true; public static bool showSuccessMessageBox = true; public static void saveString(string text, string path) { File.WriteAllText(path, text); } public static string loadString(string path) { return File.ReadAllText(path); } public static void clearSettings() { uselibs.Clear(); fileRAM = 0; } public static void ReadFile(string path) { clearSettings(); XmlDocument doc = new XmlDocument(); doc.Load(path); XmlNodeList parentNode = doc.GetElementsByTagName("settings"); //Console.WriteLine("\nReading Nodes...\n"); // Console.WriteLine(doc.InnerXml); XmlNode settings = parentNode.Item(0); foreach (XmlNode child in settings.ChildNodes) { if (child.Name.Equals("lib")) { uselibs.Add(child.InnerText); } else if (child.Name.Equals("fileRAM")) { uint.TryParse(child.InnerText, System.Globalization.NumberStyles.HexNumber, null, out fileRAM); } else if (child.Name.Equals("asmDirIsRoot")) { bool.TryParse(child.InnerText, out useASMasROOT); } else if (child.Name.Equals("showSuccessBox")) { bool.TryParse(child.InnerText, out showSuccessMessageBox); } } } public static void SaveSettings() { List<String> list = new List<String>(); list.Add("<fileRAM>" + fileRAM.ToString("X") + "</fileRAM>"); list.Add("<asmDirIsRoot>" + useASMasROOT.ToString() + "</asmDirIsRoot>"); list.Add("<showSuccessBox>" + showSuccessMessageBox.ToString() + "</showSuccessBox>"); foreach (String s in uselibs) { list.Add("<lib>" + s + "</lib>"); } WriteFileDirectly(main.getActiveProfilePath() + SETTINGS_FILENAME, list); saveString(preASM, main.getActiveProfilePath() + "preLibASM.txt"); saveString(postASM, main.getActiveProfilePath() + "postLibASM.txt"); } public static void WriteFileDirectly(string path, List<String> list) { XDocument doc = new XDocument(); XElement xe = new XElement ( "settings", list .Select ( x => XElement.Parse(x) ) ); doc.Add(xe); doc.Save(path); } public static void loadPrePostASM() { if (File.Exists(main.getActiveProfilePath() + "preLibASM.txt")) { preASM = loadString(main.getActiveProfilePath() + "preLibASM.txt"); } else { preASM = "// This code will run BEFORE the libraries have loaded." + Environment.NewLine + Environment.NewLine; saveString(preASM, main.getActiveProfilePath() + "preLibASM.txt"); } if (File.Exists(main.getActiveProfilePath() + "postLibASM.txt")) { postASM = loadString(main.getActiveProfilePath() + "postLibASM.txt"); } else { postASM = "// This code will run AFTER the libraries have loaded."; saveString(postASM, main.getActiveProfilePath() + "postLibASM.txt"); } } } }
33.634921
107
0.512978
[ "MIT" ]
DavidSM64/SimpleArmipsGui
Settings.cs
4,240
C#
using Palindrome.library; using System; namespace PalindromeApp { class Program { static void Main(string[] args) { IIsPalindrome palindromeCheckGeneral = new PalindromeChecker(); ; // upcasting Console.WriteLine("Enter a string to check if it's a palindrome"); string input = Console.ReadLine(); PalindromeCheckOutput(input, palindromeCheckGeneral); } static void PalindromeCheckOutput(string input, IIsPalindrome generalIsPalindrome) { bool isPalindrome = generalIsPalindrome.IsPalindrome(input); if (isPalindrome == true) { Console.WriteLine($"{input} is a palindrome"); } else { Console.WriteLine($"{input} is NOT a palindrome"); } } } }
25.085714
91
0.568337
[ "MIT" ]
2002-feb24-net/harold-code
Palindrome/PalindromeApp/Program.cs
880
C#
using System.Collections.Generic; using ZKWeb.Localize; using ZKWebStandard.Extensions; using ZKWebStandard.Ioc; namespace ZKWeb.Plugins.Common.Admin.src.Components.Translates { /// <summary> /// 中文翻译 /// </summary> [ExportMany, SingletonReuse] public class zh_CN : ITranslateProvider { private static HashSet<string> Codes = new HashSet<string>() { "zh-CN" }; private static Dictionary<string, string> Translates = new Dictionary<string, string>() { { "Admin Login", "管理员登陆" }, { "Please enter username", "请填写用户名" }, { "Please enter password", "请填写密码" }, { "Username", "用户名" }, { "Password", "密码" }, { "Login", "登陆" }, { "Register new user", "注册新用户" }, { "RememberLogin", "记住登陆" }, { "Register", "注册" }, { "ConfirmPassword", "确认密码" }, { "Please repeat the password exactly", "请重复前面填写的密码" }, { "OldPassword", "原密码" }, { "Please enter old password", "请填写原密码" }, { "User Registration", "用户注册" }, { "User Login", "用户登录" }, { "Username is already taken, please choose other username", "用户名已经被使用,请选择其他用户名" }, { "You have registered successfully, thanks for you registration", "注册用户成功,感谢您的注册" }, { "User Panel", "用户中心" }, { "Login successful", "登陆成功" }, { "Welcome to ", "欢迎光临" }, { "Logout", "退出登陆" }, { "Register for free", "免费注册" }, { "Website has no admin yet, the first login user will become super admin.", "当前没有任何管理员,第一次登录的用户将会成为超级管理员" }, { "You have already logged in, continue will replace the logged in user.", "您已经登陆,继续登陆将会替换当前登录的用户" }, { "Sorry, You have no privileges to use admin panel.", "抱歉,你没有使用管理后台的权限" }, { "Incorrect username or password", "用户名或密码不正确,请重新填写" }, { "Apps", "应用" }, { "Workspace", "工作间" }, { "Website Index", "网站首页" }, { "About Me", "关于我" }, { "About Website", "关于网站" }, { "Admin Panel", "管理后台" }, { "My Apps", "我的应用" }, { "Action require {0}, and {1} privileges", "操作要求拥有{0}身份,且拥有{1}权限" }, { "Action require {0}", "操作要求拥有{0}身份" }, { "User", "用户" }, { "UserType", "用户类型" }, { "Admin", "管理员" }, { "SuperAdmin", "超级管理员" }, { "CooperationPartner", "合作伙伴" }, { "CreateTime", "创建时间" }, { "Admin Manage", "管理员管理" }, { "User Manage", "用户管理" }, { "Role Manage", "角色管理" }, { "Role", "角色" }, { "Roles", "角色" }, { "UserRole", "角色" }, { "View", "查看" }, { "Edit", "编辑" }, { "Delete", "删除" }, { "DeleteForever", "永久删除" }, { "Please enter name", "请填写名称" }, { "Remark", "备注" }, { "Please enter remark", "请填写备注" }, { "Keep empty if you don't want to change", "如果不想修改,请保持空白" }, { "Name/Remark", "名称/备注" }, { "Name", "名称" }, { "Value", "值" }, { "DirectoryName", "目录名称" }, { "Description", "描述" }, { "UpdateTime", "更新时间" }, { "Add {0}", "添加{0}" }, { "Edit {0}", "编辑{0}" }, { "Delete {0}", "删除{0}" }, { "Please enter password when creating admin", "创建管理员时需要填写密码" }, { "Please enter password when creating user", "创建用户时需要填写密码" }, { "You can't downgrade yourself to normal admin", "不能取消自身的超级管理员权限" }, { "Privileges", "权限" }, { "Recycle Bin", "回收站" }, { "Batch Delete", "批量删除" }, { "Please select {0} to delete", "请选择需要删除的{0}" }, { "Sure to delete following {0}?", "确认删除以下{0}?" }, { "Batch Recover", "批量恢复" }, { "Please select {0} to recover", "请选择需要恢复的{0}" }, { "Sure to recover following {0}?", "确认恢复以下{0}?" }, { "Batch Delete Forever", "批量永久删除" }, { "Sure to delete following {0} forever?", "确认永久删除以下{0}?此操作将不可恢复!" }, { "Delete yourself is not allowed", "不能删除你自身的用户" }, { "Action {0} not exist", "找不到{0}对应的操作" }, { "Delete Successful", "删除成功" }, { "Batch Delete Successful", "批量删除成功" }, { "Batch Recover Successful", "批量恢复成功" }, { "Batch Delete Forever Successful", "批量永久删除成功" }, { "Change Password", "修改密码" }, { "Change Avatar", "修改头像" }, { "Avatar", "头像" }, { "DeleteAvatar", "删除头像" }, { "Please select avatar file", "请选择头像图片" }, { "Parse uploaded image failed", "解析上传的图片失败" }, { "User not found", "用户不存在" }, { "Incorrect old password", "原密码不正确,请重新填写" }, { "No Role", "无角色" }, { "Website Name", "网站名称" }, { "Default Language", "默认语言" }, { "Default Timezone", "默认时区" }, { "Hosting Information", "服务器信息" }, { "Plugin List", "插件列表" }, { "Admin panel and users management", "提供管理后台和用户角色管理等功能" }, { "Clear Cache", "清理缓存" }, { "Clear Cache Successfully", "清理缓存成功" }, { "Server Username", "服务器用户" }, { "Version", "版本" }, { "FullVersion", "完整版本" }, { "ZKWeb Version", "ZKWeb版本" }, { "ZKWeb Full Version", "ZKWeb完整版本" }, { "Memory Usage", "使用内存" }, { "Action require the ownership of {0}: {1}", "操作需要拥有以下{0}的所有权: {1}" }, { "System Manage", "系统管理" }, { "Other", "其它" }, { "Toggle navigation", "切换导航栏" }, { "Recover", "恢复" }, { "Delete Forever", "永久删除" }, { "Recover {0}", "恢复{0}" }, { "Delete {0} Forever", "永久删除{0}" }, { "Add", "添加" }, { "Return To List", "返回列表" }, { "AdminIndexPage", "后台首页" }, { "AdminLoginPage", "后台登陆页" }, { "AdminAboutMePage", "后台关于我页" }, { "AdminAboutWebsitePage", "后台关于网站页" }, { "UserRegPage", "用户注册页" }, { "UserLoginPage", "用户登录页" }, { "UserIndexPage", "用户中心页" }, { "AdminSidebarAppMenu", "后台侧边栏程序菜单" }, { "EnterAdminPanel", "进入后台" }, { "UserLoginInfo", "登录信息" }, // TODO: 翻译到其他语言 { "IAmAdmin", "管理员" }, { "IAmAnonymouseUser", "匿名用户" }, { "IAmCooperationPartner", "合作人" }, { "IAmSuperAdmin", "超级管理员" }, { "IAmUser", "用户" }, { "ICanUseAdminPanel", "可使用管理后台" }, { "UserLoginForm", "用户登录表单" }, { "UserRegForm", "用户注册表单" }, { "AdminLoginForm", "管理员登录表单" } }; public bool CanTranslate(string code) { return Codes.Contains(code); } public string Translate(string text) { return Translates.GetOrDefault(text); } } }
36.243902
90
0.550135
[ "MIT" ]
303248153/ZKWeb.Plugins
src/ZKWeb.Plugins/Common.Admin/src/Components/Translates/zh_CN.cs
7,446
C#
using HandHistories.Objects.GameDescription; using HandHistories.Parser.Parsers.Base; using HandHistories.Parser.Parsers.Exceptions; using HandHistories.Parser.UnitTests.Parsers.Base; using NUnit.Framework; using System.Collections.Generic; using System.Linq; namespace HandHistories.Parser.UnitTests.Parsers.HandSummaryParserTests.IsValidHandTests { [TestFixture("PartyPoker")] [TestFixture("PokerStars")] [TestFixture("OnGame")] [TestFixture("IPoker")] [TestFixture("Pacific")] [TestFixture("Merge")] [TestFixture("Entraction")] [TestFixture("FullTilt")] [TestFixture("MicroGaming")] [TestFixture("Winamax")] [TestFixture("WinningPoker")] internal class HandParserValidHandTests : HandHistoryParserBaseTests { public HandParserValidHandTests(string site) : base(site) { } [TestCase(true)] [TestCase(false)] public void IsValidHand_Works(bool expected) { string handText = SampleHandHistoryRepository.GetValidHandHandHistoryText(PokerFormat.CashGame, Site, expected); Assert.AreEqual(expected, GetSummmaryParser().IsValidHand(handText), "IHandHistorySummaryParser: IsValidHand"); Assert.AreEqual(expected, GetParser().IsValidHand(handText), "IHandHistoryParser: IsValidHand"); } [Test] public void SummaryParser_InvalidHand_RethrowFalse_ReturnsNull() { string handText = SampleHandHistoryRepository.GetValidHandHandHistoryText(PokerFormat.CashGame, Site, false); Assert.IsNull(GetSummmaryParser().ParseFullHandSummary(handText, false), "IHandHistorySummaryParser: ParseFullHandSummary"); } [Test] public void FullParser_InvalidHand_RethrowFalse_ReturnsNull() { string handText = SampleHandHistoryRepository.GetValidHandHandHistoryText(PokerFormat.CashGame, Site, false); Assert.IsNull(GetParser().ParseFullHandHistory(handText, false), "IHandHistorySummaryParser: ParseFullHandSummary"); } [Test] public void SummaryParser_InvalidHand_RethrowTrue_ThrowsException() { string handText = SampleHandHistoryRepository.GetValidHandHandHistoryText(PokerFormat.CashGame, Site, false); Assert.Throws<InvalidHandException>(() => GetSummmaryParser().ParseFullHandSummary(handText, true), "IHandHistorySummaryParser: ParseFullHandSummary"); } [Test] public void FullParser_InvalidHand_RethrowTrue_ThrowsException() { string handText = SampleHandHistoryRepository.GetValidHandHandHistoryText(PokerFormat.CashGame, Site, false); Assert.Throws<InvalidHandException>(() => GetParser().ParseFullHandHistory(handText, true), "IHandHistorySummaryParser: ParseFullHandSummary"); } [Test] public void IsHandCancelled_Works() { switch (Site) { case SiteName.PartyPoker: case SiteName.FullTilt: case SiteName.IPoker: case SiteName.OnGame: case SiteName.MicroGaming: case SiteName.BossMedia: case SiteName.Ladbrokes: case SiteName.Pacific: case SiteName.Winamax: case SiteName.Merge: case SiteName.Entraction: Assert.Ignore("Site do not produce cancelled handhistories: " + Site); break; } string cancelledHandText = SampleHandHistoryRepository.GetCancelledHandHandHistoryText(PokerFormat.CashGame, Site); bool isCancelled; Assert.IsTrue(GetSummmaryParser().IsValidOrCancelledHand(cancelledHandText, out isCancelled), "IHandHistorySummaryParser: IsCancelledHand"); Assert.IsTrue(isCancelled, "IHandHistoryParser: IsCancelledHand"); } List<IHandHistoryParser> GetAllParsers() { var factory = new HandHistories.Parser.Parsers.Factory.HandHistoryParserFactoryImpl(); return new List<IHandHistoryParser>() { factory.GetFullHandHistoryParser(SiteName.Entraction), factory.GetFullHandHistoryParser(SiteName.FullTilt), factory.GetFullHandHistoryParser(SiteName.Pacific), factory.GetFullHandHistoryParser(SiteName.PartyPoker), factory.GetFullHandHistoryParser(SiteName.PokerStars), factory.GetFullHandHistoryParser(SiteName.OnGame), factory.GetFullHandHistoryParser(SiteName.Merge), factory.GetFullHandHistoryParser(SiteName.MicroGaming), factory.GetFullHandHistoryParser(SiteName.IPoker), factory.GetFullHandHistoryParser(SiteName.Winamax), factory.GetFullHandHistoryParser(SiteName.WinningPoker), }; } [Test] public void IsValidHand_Unique() { string handText = SampleHandHistoryRepository.GetValidHandHandHistoryText(PokerFormat.CashGame, Site, true); var handParser = GetParser(); Assert.AreEqual(true, handParser.IsValidHand(handText), "IHandHistoryParser: IsValidHand"); foreach (var otherParser in GetAllParsers() .Where(p => p.SiteName != handParser.SiteName)) { try { Assert.IsFalse(otherParser.IsValidHand(handText), "IHandHistoryParser: Should be invalid hand"); } catch { continue;//When the parser throws that indicates that it is an invalid hand } } } } }
41.385714
163
0.652399
[ "Unlicense" ]
HHSmithy/PokerHandHistoryParser
HandHistories.Parser.UnitTests/Parsers/HandSummaryParserTests/IsValidHandTests/HandParserValidHandTests.cs
5,796
C#
#region License // // MIT License // // CoiniumServ - Crypto Currency Mining Pool Server Software // // Copyright (C) 2013 - 2017, CoiniumServ Project // Copyright (C) 2017 - 2021 The Merit Foundation // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // #endregion using System.Linq; namespace CoiniumServ.Utils.Buffers { public class RingBuffer:IRingBuffer { public int Size { get { return _isFull ? Capacity : _cursor; } } public float Average { get { return (float)_buffer.Sum() / (float)(_isFull ? Capacity : _cursor); } } private readonly int[] _buffer; private int _cursor; private bool _isFull; private int Capacity { get { return _buffer.Length; } } public RingBuffer(int capacity) { _buffer = new int[capacity]; _cursor = 0; _isFull = false; } public void Clear() { for (int i = 0; i < Capacity; i++) _buffer[i] = default(int); _cursor = 0; _isFull = false; } public void Append(int item) { _buffer[_cursor] = item; if (_isFull) { _cursor = (_cursor + 1) % Capacity; } else { _cursor++; if (_cursor >= Capacity) { _cursor = 0; _isFull = true; } } } } }
31.142857
109
0.584862
[ "MIT" ]
meritlabs/CoiniumServ
src/CoiniumServ/Utils/Buffers/RingBuffer.cs
2,618
C#
/* * Copyright 2018 JDCLOUD.COM * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http:#www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Elastic-IP * 弹性公网IP相关接口 * * OpenAPI spec version: v1 * Contact: * * NOTE: This class is auto generated by the jdcloud code generator program. */ using System; using System.Collections.Generic; using System.Text; using JDCloudSDK.Core.Service; namespace JDCloudSDK.Vpc.Apis { /// <summary> /// 运营修改弹性公网IP /// </summary> public class OpModifyElasticIpResult : JdcloudResult { } }
24.658537
76
0.715134
[ "Apache-2.0" ]
jdcloud-api/jdcloud-sdk-net
sdk/src/Service/Vpc/Apis/OpModifyElasticIpResult.cs
1,043
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics.Contracts; using System.Threading; using System.Threading.Tasks; namespace CommunityToolkit.Mvvm.Messaging.Messages { /// <summary> /// A <see langword="class"/> for request messages that can receive multiple replies, which can either be used directly or through derived classes. /// </summary> /// <typeparam name="T">The type of request to make.</typeparam> public class AsyncCollectionRequestMessage<T> : IAsyncEnumerable<T> { /// <summary> /// The collection of received replies. We accept both <see cref="Task{TResult}"/> instance, representing already running /// operations that can be executed in parallel, or <see cref="Func{T,TResult}"/> instances, which can be used so that multiple /// asynchronous operations are only started sequentially from <see cref="GetAsyncEnumerator"/> and do not overlap in time. /// </summary> private readonly List<(Task<T>?, Func<CancellationToken, Task<T>>?)> responses = new(); /// <summary> /// The <see cref="CancellationTokenSource"/> instance used to link the token passed to /// <see cref="GetAsyncEnumerator"/> and the one passed to all subscribers to the message. /// </summary> private readonly CancellationTokenSource cancellationTokenSource = new(); /// <summary> /// Gets the <see cref="System.Threading.CancellationToken"/> instance that will be linked to the /// one used to asynchronously enumerate the received responses. This can be used to cancel asynchronous /// replies that are still being processed, if no new items are needed from this request message. /// Consider the following example, where we define a message to retrieve the currently opened documents: /// <code> /// public class OpenDocumentsRequestMessage : AsyncCollectionRequestMessage&lt;XmlDocument&gt; { } /// </code> /// We can then request and enumerate the results like so: /// <code> /// await foreach (var document in Messenger.Default.Send&lt;OpenDocumentsRequestMessage&gt;()) /// { /// // Process each document here... /// } /// </code> /// If we also want to control the cancellation of the token passed to each subscriber to the message, /// we can do so by passing a token we control to the returned message before starting the enumeration /// (<see cref="TaskAsyncEnumerableExtensions.WithCancellation{T}(IAsyncEnumerable{T},CancellationToken)"/>). /// The previous snippet with this additional change looks as follows: /// <code> /// await foreach (var document in Messenger.Default.Send&lt;OpenDocumentsRequestMessage&gt;().WithCancellation(cts.Token)) /// { /// // Process each document here... /// } /// </code> /// When no more new items are needed (or for any other reason depending on the situation), the token /// passed to the enumerator can be canceled (by calling <see cref="CancellationTokenSource.Cancel()"/>), /// and that will also notify the remaining tasks in the request message. The token exposed by the message /// itself will automatically be linked and canceled with the one passed to the enumerator. /// </summary> public CancellationToken CancellationToken => this.cancellationTokenSource.Token; /// <summary> /// Replies to the current request message. /// </summary> /// <param name="response">The response to use to reply to the request message.</param> public void Reply(T response) { Reply(Task.FromResult(response)); } /// <summary> /// Replies to the current request message. /// </summary> /// <param name="response">The response to use to reply to the request message.</param> public void Reply(Task<T> response) { this.responses.Add((response, null)); } /// <summary> /// Replies to the current request message. /// </summary> /// <param name="response">The response to use to reply to the request message.</param> public void Reply(Func<CancellationToken, Task<T>> response) { this.responses.Add((null, response)); } /// <summary> /// Gets the collection of received response items. /// </summary> /// <param name="cancellationToken">A <see cref="System.Threading.CancellationToken"/> value to stop the operation.</param> /// <returns>The collection of received response items.</returns> [Pure] public async Task<IReadOnlyCollection<T>> GetResponsesAsync(CancellationToken cancellationToken = default) { if (cancellationToken.CanBeCanceled) { _ = cancellationToken.Register(this.cancellationTokenSource.Cancel); } List<T> results = new(this.responses.Count); await foreach (var response in this.WithCancellation(cancellationToken).ConfigureAwait(false)) { results.Add(response); } return results; } /// <inheritdoc/> [Pure] [EditorBrowsable(EditorBrowsableState.Never)] public async IAsyncEnumerator<T> GetAsyncEnumerator(CancellationToken cancellationToken = default) { if (cancellationToken.CanBeCanceled) { _ = cancellationToken.Register(this.cancellationTokenSource.Cancel); } foreach (var (task, func) in this.responses) { if (cancellationToken.IsCancellationRequested) { yield break; } if (task is not null) { yield return await task.ConfigureAwait(false); } else { yield return await func!(cancellationToken).ConfigureAwait(false); } } } } }
45.167832
151
0.623316
[ "MIT" ]
ehtick/Uno.WindowsCommunityToolkit
CommunityToolkit.Mvvm/Messaging/Messages/AsyncCollectionRequestMessage{T}.cs
6,459
C#
namespace TestSetControlLibrary { partial class SerialSettingsForm { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.comboBoxPort = new System.Windows.Forms.ComboBox(); this.groupBoxSettings = new System.Windows.Forms.GroupBox(); this.comboBoxDataBits = new System.Windows.Forms.ComboBox(); this.label3 = new System.Windows.Forms.Label(); this.comboBoxBaud = new System.Windows.Forms.ComboBox(); this.label2 = new System.Windows.Forms.Label(); this.label1 = new System.Windows.Forms.Label(); this.buttonAdd = new System.Windows.Forms.Button(); this.comboBoxParity = new System.Windows.Forms.ComboBox(); this.label5 = new System.Windows.Forms.Label(); this.comboBoxStopBits = new System.Windows.Forms.ComboBox(); this.label6 = new System.Windows.Forms.Label(); this.label7 = new System.Windows.Forms.Label(); this.comboBoxFlowControl = new System.Windows.Forms.ComboBox(); this.groupBoxSettings.SuspendLayout(); this.SuspendLayout(); // // comboBoxPort // this.comboBoxPort.FormattingEnabled = true; this.comboBoxPort.Location = new System.Drawing.Point(142, 34); this.comboBoxPort.Name = "comboBoxPort"; this.comboBoxPort.Size = new System.Drawing.Size(121, 21); this.comboBoxPort.TabIndex = 0; // // groupBoxSettings // this.groupBoxSettings.Controls.Add(this.comboBoxFlowControl); this.groupBoxSettings.Controls.Add(this.label7); this.groupBoxSettings.Controls.Add(this.label6); this.groupBoxSettings.Controls.Add(this.comboBoxStopBits); this.groupBoxSettings.Controls.Add(this.comboBoxParity); this.groupBoxSettings.Controls.Add(this.label5); this.groupBoxSettings.Controls.Add(this.buttonAdd); this.groupBoxSettings.Controls.Add(this.comboBoxDataBits); this.groupBoxSettings.Controls.Add(this.label3); this.groupBoxSettings.Controls.Add(this.comboBoxBaud); this.groupBoxSettings.Controls.Add(this.label2); this.groupBoxSettings.Controls.Add(this.label1); this.groupBoxSettings.Controls.Add(this.comboBoxPort); this.groupBoxSettings.Location = new System.Drawing.Point(25, 12); this.groupBoxSettings.Name = "groupBoxSettings"; this.groupBoxSettings.Size = new System.Drawing.Size(293, 335); this.groupBoxSettings.TabIndex = 1; this.groupBoxSettings.TabStop = false; this.groupBoxSettings.Text = "Settings"; // // comboBoxDataBits // this.comboBoxDataBits.FormattingEnabled = true; this.comboBoxDataBits.Location = new System.Drawing.Point(142, 112); this.comboBoxDataBits.Name = "comboBoxDataBits"; this.comboBoxDataBits.Size = new System.Drawing.Size(121, 21); this.comboBoxDataBits.TabIndex = 5; // // label3 // this.label3.AutoSize = true; this.label3.Location = new System.Drawing.Point(41, 116); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(50, 13); this.label3.TabIndex = 4; this.label3.Text = "Data Bits"; // // comboBoxBaud // this.comboBoxBaud.FormattingEnabled = true; this.comboBoxBaud.Location = new System.Drawing.Point(142, 73); this.comboBoxBaud.Name = "comboBoxBaud"; this.comboBoxBaud.Size = new System.Drawing.Size(121, 21); this.comboBoxBaud.TabIndex = 3; // // label2 // this.label2.AutoSize = true; this.label2.Location = new System.Drawing.Point(41, 77); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(58, 13); this.label2.TabIndex = 2; this.label2.Text = "Baud Rate"; // // label1 // this.label1.AutoSize = true; this.label1.Location = new System.Drawing.Point(41, 38); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(26, 13); this.label1.TabIndex = 1; this.label1.Text = "Port"; // // buttonAdd // this.buttonAdd.Location = new System.Drawing.Point(44, 271); this.buttonAdd.Name = "buttonAdd"; this.buttonAdd.Size = new System.Drawing.Size(219, 40); this.buttonAdd.TabIndex = 6; this.buttonAdd.Text = "Add"; this.buttonAdd.UseVisualStyleBackColor = true; this.buttonAdd.Click += new System.EventHandler(this.buttonAdd_Click); // // comboBoxParity // this.comboBoxParity.FormattingEnabled = true; this.comboBoxParity.Location = new System.Drawing.Point(142, 151); this.comboBoxParity.Name = "comboBoxParity"; this.comboBoxParity.Size = new System.Drawing.Size(121, 21); this.comboBoxParity.TabIndex = 10; // // label5 // this.label5.AutoSize = true; this.label5.Location = new System.Drawing.Point(41, 155); this.label5.Name = "label5"; this.label5.Size = new System.Drawing.Size(33, 13); this.label5.TabIndex = 9; this.label5.Text = "Parity"; // // comboBoxStopBits // this.comboBoxStopBits.FormattingEnabled = true; this.comboBoxStopBits.Location = new System.Drawing.Point(142, 190); this.comboBoxStopBits.Name = "comboBoxStopBits"; this.comboBoxStopBits.Size = new System.Drawing.Size(121, 21); this.comboBoxStopBits.TabIndex = 11; // // label6 // this.label6.AutoSize = true; this.label6.Location = new System.Drawing.Point(41, 194); this.label6.Name = "label6"; this.label6.Size = new System.Drawing.Size(49, 13); this.label6.TabIndex = 12; this.label6.Text = "Stop Bits"; // // label7 // this.label7.AutoSize = true; this.label7.Location = new System.Drawing.Point(41, 232); this.label7.Name = "label7"; this.label7.Size = new System.Drawing.Size(65, 13); this.label7.TabIndex = 13; this.label7.Text = "Flow Control"; // // comboBoxFlowControl // this.comboBoxFlowControl.FormattingEnabled = true; this.comboBoxFlowControl.Location = new System.Drawing.Point(142, 229); this.comboBoxFlowControl.Name = "comboBoxFlowControl"; this.comboBoxFlowControl.Size = new System.Drawing.Size(121, 21); this.comboBoxFlowControl.TabIndex = 14; // // SerialSettingsForm // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(345, 371); this.Controls.Add(this.groupBoxSettings); this.MaximizeBox = false; this.MinimizeBox = false; this.Name = "SerialSettingsForm"; this.ShowIcon = false; this.SizeGripStyle = System.Windows.Forms.SizeGripStyle.Hide; this.Text = "Add Serial Port"; this.TopMost = true; this.groupBoxSettings.ResumeLayout(false); this.groupBoxSettings.PerformLayout(); this.ResumeLayout(false); } #endregion private System.Windows.Forms.ComboBox comboBoxPort; private System.Windows.Forms.GroupBox groupBoxSettings; private System.Windows.Forms.Label label1; private System.Windows.Forms.ComboBox comboBoxBaud; private System.Windows.Forms.Label label2; private System.Windows.Forms.ComboBox comboBoxDataBits; private System.Windows.Forms.Label label3; private System.Windows.Forms.Button buttonAdd; private System.Windows.Forms.ComboBox comboBoxFlowControl; private System.Windows.Forms.Label label7; private System.Windows.Forms.Label label6; private System.Windows.Forms.ComboBox comboBoxStopBits; private System.Windows.Forms.ComboBox comboBoxParity; private System.Windows.Forms.Label label5; } }
45.651376
108
0.572046
[ "ECL-2.0", "Apache-2.0" ]
demirelcan/dnp3
windows/TestSetControlLibrary/SerialSettingsForm.Designer.cs
9,954
C#
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using NuGet.Services.Entities; using NuGetGallery; namespace GitHubVulnerabilities2Db.Fakes { public class FakeFeatureFlagService : IFeatureFlagService { public bool AreDynamicODataCacheDurationsEnabled() { throw new NotImplementedException(); } public bool AreEmbeddedIconsEnabled(User user) { throw new NotImplementedException(); } public bool AreEmbeddedReadmesEnabled(User user) { throw new NotImplementedException(); } public bool ArePatternSetTfmHeuristicsEnabled() { throw new NotImplementedException(); } public bool IsABTestingEnabled(User user) { throw new NotImplementedException(); } public bool IsAdvancedSearchEnabled(User user) { throw new NotImplementedException(); } public bool IsAlternateStatisticsSourceEnabled() { throw new NotImplementedException(); } public bool IsAsyncAccountDeleteEnabled() { throw new NotImplementedException(); } public bool IsDeletePackageApiEnabled(User user) { throw new NotImplementedException(); } public bool IsDisplayBannerEnabled() { throw new NotImplementedException(); } public bool IsDisplayFuGetLinksEnabled() { throw new NotImplementedException(); } public bool IsDisplayVulnerabilitiesEnabled() { throw new NotImplementedException(); } public bool IsForceFlatContainerIconsEnabled() { throw new NotImplementedException(); } public bool IsGet2FADismissFeedbackEnabled() { throw new NotImplementedException(); } public bool IsGitHubUsageEnabled(User user) { throw new NotImplementedException(); } public bool IsGravatarProxyEnabled() { throw new NotImplementedException(); } public bool IsImageAllowlistEnabled() { throw new NotImplementedException(); } public bool IsLicenseMdRenderingEnabled(User user) { throw new NotImplementedException(); } public bool IsManageDeprecationApiEnabled(User user) { throw new NotImplementedException(); } public bool IsManageDeprecationEnabled(User user, PackageRegistration registration) { throw new NotImplementedException(); } public bool IsManageDeprecationEnabled(User user, IEnumerable<Package> allVersions) { throw new NotImplementedException(); } public bool IsManagePackagesVulnerabilitiesEnabled() { throw new NotImplementedException(); } public bool IsMarkdigMdRenderingEnabled() { throw new NotImplementedException(); } public bool IsODataDatabaseReadOnlyEnabled() { throw new NotImplementedException(); } public bool IsODataV1FindPackagesByIdCountNonHijackedEnabled() { throw new NotImplementedException(); } public bool IsODataV1FindPackagesByIdNonHijackedEnabled() { throw new NotImplementedException(); } public bool IsODataV1GetAllCountEnabled() { throw new NotImplementedException(); } public bool IsODataV1GetAllEnabled() { throw new NotImplementedException(); } public bool IsODataV1GetSpecificNonHijackedEnabled() { throw new NotImplementedException(); } public bool IsODataV1SearchCountNonHijackedEnabled() { throw new NotImplementedException(); } public bool IsODataV1SearchNonHijackedEnabled() { throw new NotImplementedException(); } public bool IsODataV2FindPackagesByIdCountNonHijackedEnabled() { throw new NotImplementedException(); } public bool IsODataV2FindPackagesByIdNonHijackedEnabled() { throw new NotImplementedException(); } public bool IsODataV2GetAllCountNonHijackedEnabled() { throw new NotImplementedException(); } public bool IsODataV2GetAllNonHijackedEnabled() { throw new NotImplementedException(); } public bool IsODataV2GetSpecificNonHijackedEnabled() { throw new NotImplementedException(); } public bool IsODataV2SearchCountNonHijackedEnabled() { throw new NotImplementedException(); } public bool IsODataV2SearchNonHijackedEnabled() { throw new NotImplementedException(); } public bool IsShowReportAbuseSafetyChangesEnabled() { throw new NotImplementedException(); } public bool IsPackageDependentsEnabled(User user) { throw new NotImplementedException(); } public bool IsPackageRenamesEnabled(User user) { throw new NotImplementedException(); } public bool IsPackagesAtomFeedEnabled() { throw new NotImplementedException(); } public bool IsPreviewHijackEnabled() { throw new NotImplementedException(); } public bool IsSearchSideBySideEnabled(User user) { throw new NotImplementedException(); } public bool IsSelfServiceAccountDeleteEnabled() { throw new NotImplementedException(); } public bool IsShowEnable2FADialogEnabled() { throw new NotImplementedException(); } public bool IsTyposquattingEnabled() { throw new NotImplementedException(); } public bool IsTyposquattingEnabled(User user) { throw new NotImplementedException(); } public bool ProxyGravatarEnSubdomain() { throw new NotImplementedException(); } public bool IsDisplayNuGetPackageExplorerLinkEnabled() { throw new NotImplementedException(); } public bool IsDisplayTargetFrameworkEnabled(User user) { throw new NotImplementedException(); } public bool IsComputeTargetFrameworkEnabled() { throw new NotImplementedException(); } public bool IsRecentPackagesNoIndexEnabled() { throw new NotImplementedException(); } public bool IsDotnet20BannerEnabled() { throw new NotImplementedException(); } } }
25.533569
111
0.596457
[ "Apache-2.0" ]
0xced/NuGetGallery
src/GitHubVulnerabilities2Db/Fakes/FakeFeatureFlagService.cs
7,228
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 NUnit.Framework; using System; using NPOI.OpenXmlFormats.Spreadsheet; using NPOI.SS.UserModel; using NPOI.SS.Util; using TestCases.SS.UserModel; using NPOI.XSSF; using NPOI.XSSF.UserModel; namespace TestCases.XSSF.UserModel { /** * Test array formulas in XSSF * * @author Yegor Kozlov * @author Josh Micich */ [TestFixture] public class TestXSSFSheetUpdateArrayFormulas : BaseTestSheetUpdateArrayFormulas { public TestXSSFSheetUpdateArrayFormulas():base(XSSFITestDataProvider.instance) { } // Test methods common with HSSF are in superclass // Local methods here Test XSSF-specific details of updating array formulas [Test] public void TestXSSFSetArrayFormula_SingleCell() { ICellRange<ICell> cells; XSSFWorkbook workbook = new XSSFWorkbook(); XSSFSheet sheet = (XSSFSheet)workbook.CreateSheet(); // 1. Single-cell array formula String formula1 = "123"; CellRangeAddress range = CellRangeAddress.ValueOf("C3:C3"); cells = sheet.SetArrayFormula(formula1, range); Assert.AreEqual(1, cells.Size); // check GetFirstCell... XSSFCell firstCell = (XSSFCell)cells.TopLeftCell; Assert.AreSame(firstCell, sheet.GetFirstCellInArrayFormula(firstCell)); //retrieve the range and check it is the same Assert.AreEqual(range.FormatAsString(), firstCell.ArrayFormulaRange.FormatAsString()); ConfirmArrayFormulaCell(firstCell, "C3", formula1, "C3"); workbook.Close(); } [Test] public void TestXSSFSetArrayFormula_multiCell() { ICellRange<ICell> cells; String formula2 = "456"; XSSFWorkbook workbook = new XSSFWorkbook(); XSSFSheet sheet = (XSSFSheet)workbook.CreateSheet(); CellRangeAddress range = CellRangeAddress.ValueOf("C4:C6"); cells = sheet.SetArrayFormula(formula2, range); Assert.AreEqual(3, cells.Size); // sheet.SetArrayFormula Creates rows and cells for the designated range /* * From the spec: * For a multi-cell formula, the c elements for all cells except the top-left * cell in that range shall not have an f element; */ // Check that each cell exists and that the formula text is Set correctly on the first cell XSSFCell firstCell = (XSSFCell)cells.TopLeftCell; ConfirmArrayFormulaCell(firstCell, "C4", formula2, "C4:C6"); ConfirmArrayFormulaCell(cells.GetCell(1, 0), "C5"); ConfirmArrayFormulaCell(cells.GetCell(2, 0), "C6"); Assert.AreSame(firstCell, sheet.GetFirstCellInArrayFormula(firstCell)); workbook.Close(); } private static void ConfirmArrayFormulaCell(ICell c, String cellRef) { ConfirmArrayFormulaCell(c, cellRef, null, null); } private static void ConfirmArrayFormulaCell(ICell c, String cellRef, String formulaText, String arrayRangeRef) { if (c == null) { throw new AssertionException("Cell should not be null."); } CT_Cell ctCell = ((XSSFCell)c).GetCTCell(); Assert.AreEqual(cellRef, ctCell.r); if (formulaText == null) { Assert.IsFalse(ctCell.IsSetF()); Assert.IsNull(ctCell.f); } else { CT_CellFormula f = ctCell.f; Assert.AreEqual(arrayRangeRef, f.@ref); Assert.AreEqual(formulaText, f.Value); Assert.AreEqual(ST_CellFormulaType.array, f.t); } } } }
37.905512
118
0.609472
[ "Apache-2.0" ]
68681395/npoi
testcases/ooxml/XSSF/UserModel/TestXSSFSheetUpdateArrayFormulas.cs
4,814
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace NamelessRogue.Engine.Components.ItemComponents { public class AmmoLibrary : Component { public List<AmmoType> AmmoTypes { get; set; } = new List<AmmoType>(); public override IComponent Clone() { return new AmmoLibrary(){AmmoTypes = this.AmmoTypes.ToList()}; } } }
23.631579
77
0.674833
[ "MIT" ]
GreyArmor/SomeRogueMonogame
NamelessRogue_updated/Engine/Components/ItemComponents/AmmoLibrary.cs
451
C#
/**************************************************************************** *项目名称:MicroServiceGateway.Model *CLR 版本:4.0.30319.42000 *机器名称:WALLE-PC *命名空间:MicroServiceGateway.Model *类 名 称:MicroServiceConfig *版 本 号:V1.0.0.0 *创建人: yswenli *电子邮箱:yswenli@outlook.com *创建时间:2020/8/20 9:38:09 *描述: *===================================================================== *修改时间:2020/8/20 9:38:09 *修 改 人: yswenli *版 本 号: V1.0.0.0 *描 述: *****************************************************************************/ using MicroServiceGateway.Common; using System; using System.Threading; namespace MicroServiceGateway.Model { /// <summary> /// 微服务配置 /// </summary> public class MicroServiceConfig : MicroServiceBaseInfo { /// <summary> /// 微服务管理地址 /// </summary> public string ManagerServerIP { get; set; } = "127.0.0.1"; /// <summary> /// 微服务管理端口 /// </summary> public int ManagerServerPort { get; set; } = 28080; /// <summary> /// 保存 /// </summary> public void Save() { ConfigHelper.Write(this, "MicroServiceConfig.yaml"); } /// <summary> /// 读取 /// </summary> /// <returns></returns> public static MicroServiceConfig Read() { try { return ConfigHelper.Read<MicroServiceConfig>("MicroServiceConfig.yaml"); } catch(Exception ex) { Thread.Sleep(1000); new MicroServiceConfig().Save(); Logger.Error("MicroServiceConfig.Read", new Exception("加载配置文件MicroServiceConfig.yaml失败", ex)); } return Read(); } } }
26.530303
110
0.470017
[ "MIT" ]
yswenli/MicroServiceGateway
MicroServiceGateway/MicroServiceGateway.Model/MicroServiceConfig.cs
1,933
C#
using Application.Interfaces.Repositories; using Domain.Entities; using Infrastructure.Persistence.Contexts; using Infrastructure.Persistence.Repository; using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Infrastructure.Persistence.Repositories { public class PlacementReleaseReopsitoryAsync : GenericRepositoryAsync<PlacementRelease>, IPlacementReleaseReopsitoryAsync { private readonly DbSet<PlacementRelease> PlacementRelease; public PlacementReleaseReopsitoryAsync(ApplicationDbContext dbContext) : base(dbContext) { PlacementRelease = dbContext.Set<PlacementRelease>(); } public async Task<List<PlacementRelease>> GetByTest(int TestId) { return await PlacementRelease.Where(x => x.TestId == TestId).ToListAsync(); } } }
32.137931
125
0.757511
[ "MIT" ]
Devsquares/AdlerZentrum-BackEnd
Infrastructure.Persistence/Repositories/PlacementReleaseReopsitoryAsync.cs
932
C#
//___________________________________________________________________________________ // // Copyright (C) 2020, Mariusz Postol LODZ POLAND. // // To be in touch join the community at GITTER: https://gitter.im/mpostol/OPC-UA-OOI //___________________________________________________________________________________ using System; using System.Drawing; using System.Windows.Forms; using UAOOI.Windows.Forms.ControlExtenders; namespace UAOOI.Windows.Forms { /// <summary> /// panel with label and close button that can be used for docking /// </summary> public partial class DockPanelUserControl: UserControl { /// <summary> /// Gets or sets the panel label. /// </summary> /// <value>The label.</value> public string Label { get { return this.label_title.Text; } set { this.label_title.Text = value; } } /// <summary> /// Gets or sets the main control inside the panel. /// </summary> /// <value>The main control.</value> public Control MainControl { get { if ( this.panel_main.Controls.Count > 0 ) return this.panel_main.Controls[ 0 ]; else return null; } set { if ( this.panel_main.Controls.Count > 0 ) this.panel_main.Controls.Clear(); if ( value == null ) return; this.panel_main.Controls.Add( value ); value.Dock = DockStyle.Fill; } } /// <summary> /// Gets or sets the floaty. <see cref="IFloaty"/> /// </summary> /// <value>The floaty.</value> public IFloaty Floaty { get; private set; } /// <summary> /// Attaches to dock extender. /// </summary> /// <param name="DockExtender">The dock extender.</param> /// <param name="spliter">The splitter.</param> public void AttachToDockExtender( DockExtender DockExtender, Splitter spliter ) { if ( DockExtender != null ) { dockExtender = DockExtender; Floaty = dockExtender.Attach( this, this.label_title, spliter ); } } /// <summary> /// Initializes a new instance of the <see cref="DockPanelUserControl"/> class. /// </summary> /// <param name="DockExtender">The dock extender.</param> /// <param name="spliter">The splitter.</param> public DockPanelUserControl( DockExtender DockExtender, Splitter spliter ) : this() { AttachToDockExtender( DockExtender, spliter ); } /// <summary> /// Initializes a new instance of the <see cref="DockPanelUserControl"/> class. /// </summary> public DockPanelUserControl() { InitializeComponent(); this.label_title.VisibleChanged += new EventHandler( label_title_VisibleChanged ); this.Enter += new EventHandler( DockPanelUserControl_EnterExited ); this.Leave += new EventHandler( DockPanelUserControl_EnterExited ); } /// <summary> /// Gets a value indicating whether the control has input focus. /// </summary> /// <value></value> /// <returns>true if the control has focus; otherwise, false. /// </returns> public new bool Focused { get { return TestFocused( this ); } } /// <summary> /// Displays the control to the user. /// </summary> /// <PermissionSet> /// <IPermission class="System.Security.Permissions.EnvironmentPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Unrestricted="true"/> /// <IPermission class="System.Security.Permissions.FileIOPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Unrestricted="true"/> /// <IPermission class="System.Security.Permissions.SecurityPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Flags="UnmanagedCode, ControlEvidence"/> /// <IPermission class="System.Diagnostics.PerformanceCounterPermission, System, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Unrestricted="true"/> /// </PermissionSet> public new void Show() { this.Floaty.Show(); } #region private private DockExtender dockExtender = null; private void DockPanelUserControl_EnterExited( object sender, EventArgs e ) { if ( this.Focused ) { label_title.BackColor = SystemColors.ActiveCaption; label_title.ForeColor = SystemColors.ActiveCaptionText; button_exit.BackColor = SystemColors.ActiveCaption; button_exit.ForeColor = SystemColors.ActiveCaptionText; } else { label_title.BackColor = SystemColors.InactiveCaption; label_title.ForeColor = SystemColors.InactiveCaptionText; button_exit.BackColor = SystemColors.InactiveCaption; button_exit.ForeColor = SystemColors.InactiveCaptionText; } } private void button_exit_Click( object sender, EventArgs e ) { dockExtenderHide_afterCloseClick(); } private void dockExtenderHide_afterCloseClick() { if ( dockExtender != null ) dockExtender.Hide( this ); } private void closeToolStripMenuItem_Click( object sender, EventArgs e ) { dockExtenderHide_afterCloseClick(); } private void label_title_VisibleChanged( object sender, EventArgs e ) { this.button_exit.Visible = this.label_title.Visible; } private static bool TestFocused( Control cn ) { if ( cn.Focused ) return true; foreach ( Control intcn in cn.Controls ) if ( TestFocused( intcn ) ) return true; return false; } #endregion private } }
34.383721
210
0.634258
[ "MIT" ]
mpostol/WindowsForms
CAS.Windows.Forms/DockPanelUserControl.cs
5,916
C#
// <copyright file="Histogram.cs" company="Allan Hardy"> // Copyright (c) Allan Hardy. All rights reserved. // </copyright> using App.Metrics.Benchmarks.Fixtures; using App.Metrics.Benchmarks.Support; using Xunit; namespace App.Metrics.Benchmarks.Facts { public class Histogram : IClassFixture<MetricsCoreTestFixture> { private readonly MetricsCoreTestFixture _fixture; public Histogram(MetricsCoreTestFixture fixture) { _fixture = fixture; } [Fact] public void AlorithmR() { SimpleBenchmarkRunner.Run( () => { _fixture.Metrics.Measure.Histogram.Update( MetricOptions.Histogram.OptionsAlgorithmR, _fixture.Rnd.Next(0, 1000), _fixture.RandomUserValue); }); } [Fact] public void ForwardDecaying() { SimpleBenchmarkRunner.Run( () => { _fixture.Metrics.Measure.Histogram.Update( MetricOptions.Histogram.OptionsForwardDecaying, _fixture.Rnd.Next(0, 1000), _fixture.RandomUserValue); }); } [Fact] public void SlidingWindow() { SimpleBenchmarkRunner.Run( () => { _fixture.Metrics.Measure.Histogram.Update( MetricOptions.Histogram.OptionsSlidingWindow, _fixture.Rnd.Next(0, 1000), _fixture.RandomUserValue); }); } } }
30.285714
80
0.513561
[ "Apache-2.0" ]
geffzhang/AppMetrics
benchmarks/App.Metrics.Benchmarks/Facts/Histogram.cs
1,698
C#
using System; using Forum.Data; using Forum.Services.Contracts; using Microsoft.EntityFrameworkCore; namespace Forum.Services { public class DatabaseInitializerService : IDatabaseInitializerService { private readonly ForumDbContext context; public DatabaseInitializerService(ForumDbContext context) { this.context = context; } public void InitializeDatabase() { context.Database.Migrate(); } } }
18.391304
70
0.775414
[ "MIT" ]
VeselinBPavlov/database-advanced-entity-framework-core
22. Best Practices And Architecture - Lab/Forum.Services/DatabaseInitializerService.cs
425
C#
using System; using System.Collections.Generic; using System.Text; namespace _04.WildFarm.Models.Animals.Contracts { public interface IAnimal { string Name { get; } double Weight { get; } } }
16.5
47
0.636364
[ "MIT" ]
StelaKaneva/Csharp-OOP
Polymorphism/Exercise/04.WildFarm/04.WildFarm/04.WildFarm/Models/Animals/Contracts/IAnimal.cs
233
C#
using System; namespace AdapterPatternRealWorldSample { class Program { private static CertainThirdPartyControl certainThirdPartyControl = new CertainThirdPartyControl(); private static CertainFrameworkControl certainFrameworkControl = new CertainFrameworkControl(); private static EditableControl1 editableControl1 = new EditableControl1(); private static EditableControl2 editableControl2 = new EditableControl2(); static void Main(string[] args) { SelectAll(certainThirdPartyControl); Copy(certainFrameworkControl); Paste(editableControl1); Cut(editableControl2); Console.ReadKey(); } private static void SelectAll(Control control) { IEditableControl activeControl = GetActiveControl(control); activeControl?.SelectAll(); } private static void Copy(Control control) { IEditableControl activeControl = GetActiveControl(control); activeControl?.Copy(); } private static void Paste(Control control) { IEditableControl activeControl = GetActiveControl(control); activeControl?.Paste(); } private static void Cut(Control control) { IEditableControl activeControl = GetActiveControl(control); activeControl?.Cut(); } private static IEditableControl GetActiveControl(Control control) { // Initially here there were about 10 lines of code that determined the active control. // In the production code, the control object passed as parameter is a container of controls. // But since determining the active control is out of scope, in order to keep things simple, we'll ignore those lines. return Utils.GetControl(control); } } }
35.611111
130
0.649506
[ "MIT" ]
OvidiuCaba/AdapterPatternRealWorldSample
AdapterPatternRealWorldSample/Program.cs
1,925
C#
/* * OANDA v20 API * * The full OANDA v20 API Specification. This specification defines how to interact with v20 Accounts, Trades, Orders, Pricing and more. * * The version of the OpenAPI document: 3.0.25 * Contact: api@oanda.com * Generated by: https://github.com/openapitools/openapi-generator.git */ using Xunit; using System; using System.Linq; using System.IO; using System.Collections.Generic; using GeriRemenyi.Oanda.V20.Client.Api; using GeriRemenyi.Oanda.V20.Client.Model; using GeriRemenyi.Oanda.V20.Client.Client; using System.Reflection; using Newtonsoft.Json; namespace GeriRemenyi.Oanda.V20.Client.Test { /// <summary> /// Class for testing Error4xxBody /// </summary> /// <remarks> /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). /// Please update the test case below to test the model. /// </remarks> public class Error4xxBodyTests : IDisposable { // TODO uncomment below to declare an instance variable for Error4xxBody //private Error4xxBody instance; public Error4xxBodyTests() { // TODO uncomment below to create an instance of Error4xxBody //instance = new Error4xxBody(); } public void Dispose() { // Cleanup when everything is done. } /// <summary> /// Test an instance of Error4xxBody /// </summary> [Fact] public void Error4xxBodyInstanceTest() { // TODO uncomment below to test "IsInstanceOfType" Error4xxBody //Assert.IsInstanceOfType<Error4xxBody> (instance, "variable 'instance' is a Error4xxBody"); } /// <summary> /// Test the property 'ErrorCode' /// </summary> [Fact] public void ErrorCodeTest() { // TODO unit test for the property 'ErrorCode' } /// <summary> /// Test the property 'ErrorMessage' /// </summary> [Fact] public void ErrorMessageTest() { // TODO unit test for the property 'ErrorMessage' } } }
27.0875
136
0.618366
[ "MIT" ]
geriremenyi/oanda-dotnet-client
src/GeriRemenyi.Oanda.V20.Client.Test/Model/Error4xxBodyTests.cs
2,167
C#
//----------------------------------------------------------------------------- // Copyright : (c) Chris Moore, 2020 // License : MIT //----------------------------------------------------------------------------- namespace Z0 { using System.Runtime.InteropServices; using static Root; [StructLayout(LayoutKind.Sequential)] public struct ApiExtractSettings : ISettings<ApiExtractSettings> { public static Outcome timestamp(FS.FolderPath src, out Timestamp dst) { dst = default; var fmt = src.Format(PathSeparator.FS); var idx = fmt.LastIndexOf(Chars.FSlash); if(idx == NotFound) return (false, "Path separator not found"); return Time.parse(fmt.RightOfIndex(idx), out dst); } public FS.FolderPath ExtractRoot; public bool EmitContext; public bool Analyze; public bool EmitStatements; public Timestamp Timestamp; public static ApiExtractSettings init(FS.FolderPath root, Timestamp ts) { var dst = new ApiExtractSettings(); dst.Timestamp = ts; dst.Analyze = true; dst.EmitContext = false; dst.EmitStatements = true; dst.ExtractRoot = ts == null ? root : root + FS.folder(dst.Timestamp.Format()); return dst; } public static ApiExtractSettings init(FS.FolderPath root) { var dst = new ApiExtractSettings(); timestamp(root, out dst.Timestamp); dst.Analyze = true; dst.EmitContext = true; dst.EmitStatements = true; dst.ExtractRoot = root; return dst; } } }
31.267857
91
0.521987
[ "BSD-3-Clause" ]
0xCM/z0
src/part/src/api/archives/ApiExtractSettings.cs
1,751
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 Microsoft.Xunit.Performance; namespace Functions { public static partial class MathTests { // Tests MathF.Pow(float, float) over 5000 iterations for the domain x: +2, +1; y: -2, -1 private const float powSingleDeltaX = -0.0004f; private const float powSingleDeltaY = 0.0004f; private const float powSingleExpectedResult = 4659.30762f; [Benchmark] public static void PowSingleBenchmark() { foreach (var iteration in Benchmark.Iterations) { using (iteration.StartMeasurement()) { PowSingleTest(); } } } public static void PowSingleTest() { var result = 0.0f; var valueX = 2.0f; var valueY = -2.0f; for (var iteration = 0; iteration < iterations; iteration++) { valueX += powSingleDeltaX; valueY += powSingleDeltaY; result += MathF.Pow(valueX, valueY); } var diff = MathF.Abs(powSingleExpectedResult - result); if (diff > singleEpsilon) { throw new Exception($"Expected Result {powSingleExpectedResult,10:g9}; Actual Result {result,10:g9}"); } } } }
31.163265
118
0.575639
[ "MIT" ]
JetBrains/coreclr
tests/src/JIT/Performance/CodeQuality/Math/Functions/Single/PowSingle.cs
1,529
C#
// CodeContracts // // Copyright (c) Microsoft Corporation // // All rights reserved. // // MIT License // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // File System.Runtime.InteropServices.ComTypes.cs // Automatically generated contract file. using System.Collections.Generic; using System.IO; using System.Text; using System.Diagnostics.Contracts; using System; // Disable the "this variable is not used" warning as every field would imply it. #pragma warning disable 0414 // Disable the "this variable is never assigned to". #pragma warning disable 0067 // Disable the "this event is never assigned to". #pragma warning disable 0649 // Disable the "this variable is never used". #pragma warning disable 0169 // Disable the "new keyword not required" warning. #pragma warning disable 0109 // Disable the "extern without DllImport" warning. #pragma warning disable 0626 // Disable the "could hide other member" warning, can happen on certain properties. #pragma warning disable 0108 namespace System.Runtime.InteropServices.ComTypes { public enum ADVF { ADVF_NODATA = 1, ADVF_PRIMEFIRST = 2, ADVF_ONLYONCE = 4, ADVF_DATAONSTOP = 64, ADVFCACHE_NOHANDLER = 8, ADVFCACHE_FORCEBUILTIN = 16, ADVFCACHE_ONSAVE = 32, } public enum DATADIR { DATADIR_GET = 1, DATADIR_SET = 2, } public enum DVASPECT { DVASPECT_CONTENT = 1, DVASPECT_THUMBNAIL = 2, DVASPECT_ICON = 4, DVASPECT_DOCPRINT = 8, } public enum TYMED { TYMED_HGLOBAL = 1, TYMED_FILE = 2, TYMED_ISTREAM = 4, TYMED_ISTORAGE = 8, TYMED_GDI = 16, TYMED_MFPICT = 32, TYMED_ENHMF = 64, TYMED_NULL = 0, } }
34.435897
463
0.735666
[ "MIT" ]
Acidburn0zzz/CodeContracts
Microsoft.Research/Contracts/System/Sources/System.Runtime.InteropServices.ComTypes.cs
2,686
C#
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Reflection; using Nini.Config; using OpenSim.Framework; using OpenSim.Server.Base; using OpenSim.Services.Interfaces; using OpenSim.Framework.Servers.HttpServer; using OpenSim.Server.Handlers.Base; using log4net; namespace OpenSim.Server.Handlers.Hypergrid { public class GatekeeperServiceInConnector : ServiceConnector { private static readonly ILog m_log = LogManager.GetLogger( MethodBase.GetCurrentMethod().DeclaringType); private IGatekeeperService m_GatekeeperService; public IGatekeeperService GateKeeper { get { return m_GatekeeperService; } } bool m_Proxy = false; public GatekeeperServiceInConnector(IConfigSource config, IHttpServer server, ISimulationService simService) : base(config, server, String.Empty) { IConfig gridConfig = config.Configs["GatekeeperService"]; if (gridConfig != null) { string serviceDll = gridConfig.GetString("LocalServiceModule", string.Empty); Object[] args = new Object[] { config, simService }; m_GatekeeperService = ServerUtils.LoadPlugin<IGatekeeperService>(serviceDll, args); } if (m_GatekeeperService == null) throw new Exception("Gatekeeper server connector cannot proceed because of missing service"); m_Proxy = gridConfig.GetBoolean("HasProxy", false); HypergridHandlers hghandlers = new HypergridHandlers(m_GatekeeperService); server.AddXmlRPCHandler("link_region", hghandlers.LinkRegionRequest, false); server.AddXmlRPCHandler("get_region", hghandlers.GetRegion, false); server.AddHTTPHandler("/foreignagent/", new GatekeeperAgentHandler(m_GatekeeperService, m_Proxy).Handler); } public GatekeeperServiceInConnector(IConfigSource config, IHttpServer server) : this(config, server, null) { } } }
43.046512
118
0.709346
[ "BSD-3-Clause" ]
N3X15/VoxelSim
OpenSim/Server/Handlers/Hypergrid/GatekeeperServerConnector.cs
3,704
C#
using Octopus.Server.Extensibility.Authentication.OpenIDConnect.Common.Identities; namespace Octopus.Server.Extensibility.Authentication.GoogleApps.Identities { class GoogleAppsIdentityCreator : IdentityCreator, IGoogleAppsIdentityCreator { protected override string ProviderName => GoogleAppsAuthenticationProvider.ProviderName; } interface IGoogleAppsIdentityCreator : IIdentityCreator { } }
35.333333
96
0.811321
[ "Apache-2.0" ]
OctopusDeploy/OpenIDConnectAuthenticationProviders
source/Server.GoogleApps/Identities/GoogleAppsIdentityCreator.cs
426
C#
using System.Linq; using War3Map.Template.Common.Constants; using War3Net.Build.Info; namespace War3Map.Template.Launcher { internal static class PlayerAndForceSettings { public static void ApplyToMapInfo(MapInfo mapInfo) { // Create players var team0Players = new PlayerData[PlayerConstants.PlayerSlotCount]; for (var i = 0; i < PlayerConstants.PlayerSlotCount; i++) { var playerData = PlayerData.Create(i); playerData.PlayerController = PlayerController.User; playerData.PlayerRace = PlayerRace.Human; playerData.IsRaceSelectable = true; playerData.StartPosition = new System.Drawing.PointF(0f, 0f); playerData.FixedStartPosition = true; team0Players[i] = playerData; } var team1Player = PlayerData.Create(23); team1Player.PlayerName = "Enemies"; team1Player.PlayerController = PlayerController.Computer; team1Player.PlayerRace = PlayerRace.Orc; team1Player.IsRaceSelectable = false; team1Player.StartPosition = new System.Drawing.PointF( 0f, 0f ); team1Player.FixedStartPosition = true; // Add players to MapInfo mapInfo.SetPlayerData(team0Players.Append(team1Player).ToArray()); // Create teams var team0 = new ForceData() { ForceName = "Team 1", ForceFlags = ForceFlags.Allied | ForceFlags.ShareVision, }; var team1 = new ForceData() { ForceName = "Team 2", }; // Add players to teams team0.SetPlayers(team0Players); team1.SetPlayers(team1Player); // Add teams to MapInfo mapInfo.SetForceData(team0, team1); // Update map flags mapInfo.MapFlags |= MapFlags.UseCustomForces | MapFlags.FixedPlayerSettingsForCustomForces; } } }
34.55
103
0.586107
[ "MIT" ]
Bia10/War3Map.Template
src/War3Map.Template.Launcher/PlayerAndForceSettings.cs
2,075
C#
using NUnit.Framework; namespace DataStructuresAndAlgos.LinkedLists; public class LinkedListCycle { [Test] public void Test_LinkedListCycle() { } private bool HasLinkedListCycle(ListNode head) { var slow = head; var fast = head; while (fast != null && fast.next != null) { slow = slow.next; fast = fast.next.next; if (slow == fast) return true; } return false; } }
16.7
50
0.53493
[ "MIT" ]
manasa-konidena/DataStructuresAndAlgos
DataStructuresAndAlgos/LinkedLists/LinkedListCycle.cs
501
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using NUnit.Framework; namespace nunit.v3 { [TestFixture] public class Issue3472 { [TestCase(@"сÐ")] public void Test_ND(string name) { Assert.Pass(name); } } }
17.9
41
0.592179
[ "MIT" ]
rprouse/nunit-tests
nunit-v3/Issue3472.cs
361
C#
using System; using System.Reflection; namespace FluentAssertions.Equivalency { /// <summary> /// Provides details about the subject's root or nested property. /// </summary> public interface ISubjectInfo { /// <summary> /// Gets the <see cref="PropertyInfo"/> of the property that returned the current object, or <c>null</c> if the current /// object represents the root object. /// </summary> PropertyInfo PropertyInfo { get; } /// <summary> /// Gets the full path from the root object until the current object separated by dots. /// </summary> string PropertyPath { get; } /// <summary> /// Gets a display-friendly representation of the <see cref="PropertyPath"/>. /// </summary> string PropertyDescription { get; } /// <summary> /// Gets the compile-time type of the current object. If the current object is not the root object, then it returns the /// same <see cref="Type"/> as the <see cref="RuntimeType"/> property does. /// </summary> Type CompileTimeType { get; } /// <summary> /// Gets the run-time type of the current object. /// </summary> Type RuntimeType { get; } } }
33.894737
128
0.59472
[ "Apache-2.0" ]
blairconrad/fluentassertions
FluentAssertions.Net35/Equivalency/ISubjectInfo.cs
1,288
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Woc.Book.Base.BusinessEntity; using Woc.Book.Base; using Woc.Book.Staff.Service; using Woc.Book.Staff.BusinessEntity; namespace Woc.Book.Staff { internal class StaffController : IRegistrationController,IStaffController { public String SaveData(IBusinessEntity iBusinessEntity) { UtilityController utility = new UtilityController(); StaffService staffService = new StaffService(); Staffs staffs = (Staffs)iBusinessEntity; byte[] HashOut; byte[] SaltOut; utility.EncryptSaltPassword(staffs.TextBoxPassword, out HashOut, out SaltOut); staffs.Password = HashOut; staffs.Salt = SaltOut; return staffService.SaveData(staffs); } public String UpdateData(IBusinessEntity iBusinessEntity) { StaffService staffService = new StaffService(); Staffs staffs = (Staffs)iBusinessEntity; if (staffs.TextBoxPassword.Trim() != String.Empty) { UtilityController utility = new UtilityController(); byte[] HashOut; byte[] SaltOut; utility.EncryptSaltPassword(staffs.TextBoxPassword, out HashOut, out SaltOut); staffs.Password = HashOut; staffs.Salt = SaltOut; } return staffService.UpdateData(staffs); } public String DeleteData(IBusinessEntity iBusinessEntity) { StaffService staffService = new StaffService(); return staffService.DeleteData(iBusinessEntity); } public String ResignData(IBusinessEntity iBusinessEntity) { StaffService staffService = new StaffService(); return staffService.ResignData(iBusinessEntity); } public List<Staffs> SearchData(IBusinessEntity iBusinessEntity) { StaffService staffService = new StaffService(); Staffs staffs = new Staffs(); staffs = (Staffs)iBusinessEntity; string strParemeter = String.Empty; if (!String.IsNullOrEmpty(staffs.Address1)) { strParemeter = "Address like '%" + staffs.Address1 + "%'"; } else if (!String.IsNullOrEmpty(staffs.LoginID)) { strParemeter = "LoginID like '%" + staffs.LoginID + "%'"; } else if (!String.IsNullOrEmpty(staffs.NRIC)) { strParemeter = "NRIC like '%" + staffs.NRIC + "%'"; } else if (!String.IsNullOrEmpty(staffs.DOB)) { strParemeter = "DOB like '%" + staffs.DOB + "%'"; } else if (!String.IsNullOrEmpty(staffs.Contact)) { strParemeter = "Contact like '%" + staffs.Contact + "%'"; } if (string.IsNullOrEmpty(strParemeter)) { strParemeter = strParemeter + " [Delete] <> 'Y'"; } else { strParemeter = strParemeter + " and [Delete] <> 'Y'"; } return staffService.SearchData(strParemeter); } public Staffs GetUpdateData(String loginID) { String strParemeter = "LoginID = '" + loginID + "'"; StaffService staffService = new StaffService(); return staffService.GetData(strParemeter); } } }
32.961905
93
0.58538
[ "MIT" ]
harlandgomez/woc
src/Staff/StaffController.cs
3,463
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; namespace jjnguy.RegexBuilder { public record Builder(IEnumerable<ISegment> _pieces) : ISegment { public Builder() : this(new ISegment[0]) { } public Builder(string text) : this(new ISegment[] { new BasicSegment(text) }) { } public Builder Then(string text) => Then(new BasicSegment(text)); public Builder Then(Func<Builder, Builder> groupBuilder) => Then(groupBuilder(new())._pieces); public Builder Then(params ISegment[] segments) => Then(segments as IEnumerable<ISegment>); public Builder Then(IEnumerable<ISegment> segments) => this with { _pieces = _pieces.Concat(segments) }; public Builder ThenGroup(IEnumerable<ISegment> of) => Then(ISegment.GroupStart).Then(of).Then(ISegment.GroupEnd); public Builder OneOrMore(string text) => OneOrMore(new BasicSegment(text)); public Builder OneOrMore(Func<Builder, Builder> groupBuilder) => OneOrMore(groupBuilder(new())._pieces); public Builder OneOrMore(params ISegment[] of) => OneOrMore(of as IEnumerable<ISegment>); public Builder OneOrMore(IEnumerable<ISegment> of) => ThenGroup(of).Then(ISegment.OneOrMore); public Builder Digit() => Then("\\d"); public string Value => string.Join("", _pieces.Select(p => p.Value)); public Regex Build() => new Regex(Value); } public interface ISegment { public static readonly ISegment GroupStart = new BasicSegment("("); public static readonly ISegment GroupEnd = new BasicSegment(")"); public static readonly ISegment ZeroOrOne = new BasicSegment("?"); public static readonly ISegment OneOrMore = new BasicSegment("+"); public static readonly ISegment ZeroOrMore = new BasicSegment("*"); string Value { get; } } public class BasicSegment : ISegment { public string Value { get; private set; } public BasicSegment(string value) { // TODO: validate for only non-special characters Value = value; } } }
33.370968
108
0.697922
[ "MIT" ]
jjnguy/RegexBuilder
src/jjnguy.RegexBuilder/Builder.cs
2,069
C#
using System.Collections.Generic; namespace Contoso.Forms.View.Common { public class ConditionGroupView { public string Logic { get; set; } public List<ConditionView> Conditions { get; set; } public List<ConditionGroupView> ConditionGroups { get; set; } } }
25.181818
63
0.722022
[ "MIT" ]
BlaiseD/LogicBuilder.Samples
.NetCore/Contoso/Contoso.Forms.View/Common/ConditionGroupView.cs
279
C#
using System.Collections.Generic; using System.Threading.Tasks; using SeatsSuggestions.Domain.Helper; namespace SeatsSuggestions.Domain { /// <summary> /// The functional and imperative shell/orchestration core. /// </summary> public static class SeatAllocator { private const int NumberOfSuggestionsPerPricingCategory = 3; public delegate Task<SuggestionsMade> SuggestionsDelegate(ShowId id, PartyRequested party); public async static Task<SuggestionsMade> MakeSuggestionsImperativeShell(Ports.IProvideUpToDateAuditoriumSeating auditoriumSeatingProvider, ShowId id, PartyRequested partyRequested) { // non-pure function var auditoriumSeating = await auditoriumSeatingProvider.GetAuditoriumSeating(id); // call pure function return SeatAllocator .TryMakeSuggestions(id, partyRequested, auditoriumSeating) .GetValueOrFallback(new SuggestionNotAvailable(id, partyRequested)); // Balance restored: // - inner hexagon knows about adapter capabilities but not implementation // - orchestration is back in the 'core' where we can locally reason about it // Notes: // in this case the imperative shells can be easily distinguished by the 'async' keyword which kind of plays the role of the IO<> marker type. } public static Maybe<SuggestionsMade> TryMakeSuggestions(ShowId showId, PartyRequested partyRequested, AuditoriumSeating auditoriumSeating) { var suggestionsMade = new SuggestionsMade(showId, partyRequested); suggestionsMade.Add(GiveMeSuggestionsFor(auditoriumSeating, partyRequested, PricingCategory.First)); suggestionsMade.Add(GiveMeSuggestionsFor(auditoriumSeating, partyRequested, PricingCategory.Second)); suggestionsMade.Add(GiveMeSuggestionsFor(auditoriumSeating, partyRequested, PricingCategory.Third)); suggestionsMade.Add(GiveMeSuggestionsFor(auditoriumSeating, partyRequested, PricingCategory.Mixed)); if (suggestionsMade.MatchExpectations()) { return new Maybe<SuggestionsMade>(suggestionsMade); } return new Maybe<SuggestionsMade>(); } private static IEnumerable<SuggestionMade> GiveMeSuggestionsFor(AuditoriumSeating auditoriumSeating, PartyRequested partyRequested, PricingCategory pricingCategory) { var foundedSuggestions = new List<SuggestionMade>(); for (var i = 0; i < NumberOfSuggestionsPerPricingCategory; i++) { var seatOptionsSuggested = auditoriumSeating.SuggestSeatingOptionFor(new SuggestionRequest(partyRequested, pricingCategory)); if (seatOptionsSuggested.MatchExpectation()) { // We get the new version of the Auditorium after the allocation auditoriumSeating = auditoriumSeating.Allocate(seatOptionsSuggested); foundedSuggestions.Add(new SuggestionMade(partyRequested, pricingCategory, seatOptionsSuggested.Seats)); } } return foundedSuggestions; } } }
46.267606
189
0.684932
[ "Apache-2.0" ]
ptillemans/livecoding-beyond-hexagonal-architecture
SeatsSuggestions/SeatsSuggestions.Domain/SeatAllocator.cs
3,287
C#
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace WebApp { public partial class Site_Mobile : System.Web.UI.MasterPage { protected void Page_Load(object sender, EventArgs e) { } } }
18.705882
63
0.694969
[ "Apache-2.0" ]
AkhilNaidu09/IdentityServer3.Samples
source/Clients/WebFormsClient/Site.Mobile.Master.cs
318
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. // The function signature of the following architectures is know for the constrained call helper functions #if ARM #elif X86 #elif AMD64 #elif ARM64 #else #error Unknown architecture! #endif using System; using System.Collections.Generic; using System.Text; using System.Runtime; using System.Threading; using Internal.Runtime.Augments; using Internal.Runtime.CompilerServices; using System.Diagnostics; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; namespace Internal.Runtime.TypeLoader { internal class ConstrainedCallSupport { #if ARM private delegate IntPtr ResolveCallOnReferenceTypeDel(IntPtr scratch, ref object thisPtr, IntPtr callDescIntPtr); private delegate IntPtr ResolveCallOnValueTypeDel(IntPtr scratch, IntPtr thisPtr, IntPtr callDescIntPtr); #else private delegate IntPtr ResolveCallOnReferenceTypeDel(ref object thisPtr, IntPtr callDescIntPtr); private delegate IntPtr ResolveCallOnValueTypeDel(IntPtr thisPtr, IntPtr callDescIntPtr); #endif private delegate IntPtr RuntimeCacheFuncSignatureDel(IntPtr context, IntPtr callDescIntPtr, object contextObject, out IntPtr auxResult); #if !CORERT [DllImport("*", ExactSpelling = true, EntryPoint = "ConstrainedCallSupport_GetStubs")] private extern static unsafe void ConstrainedCallSupport_GetStubs(out IntPtr constrainedCallSupport_DerefThisAndCall_CommonCallingStub, out IntPtr constrainedCallSupport_DirectConstrainedCall_CommonCallingStub); #endif private static IntPtr s_constrainedCallSupport_DerefThisAndCall_CommonCallingStub; private static IntPtr s_constrainedCallSupport_DirectConstrainedCall_CommonCallingStub; private static object s_DerefThisAndCall_ThunkPoolHeap; private static object s_DirectConstrainedCall_ThunkPoolHeap; private static object s_DirectConstrainedCall_ThunkPoolHeapLock = new object(); private static LowLevelDictionary<IntPtr, IntPtr> s_deferenceAndCallThunks = new LowLevelDictionary<IntPtr, IntPtr>(); static ConstrainedCallSupport() { // TODO: export this unmanaged API in CoreRT #if !CORERT ConstrainedCallSupport_GetStubs(out s_constrainedCallSupport_DerefThisAndCall_CommonCallingStub, out s_constrainedCallSupport_DirectConstrainedCall_CommonCallingStub); #else s_constrainedCallSupport_DerefThisAndCall_CommonCallingStub = IntPtr.Zero; s_constrainedCallSupport_DirectConstrainedCall_CommonCallingStub = IntPtr.Zero; #endif } // There are multiple possible paths here. // // // - 1 If the ConstraintType is a reference type // - ExactTarget in the CallDesc is never set. // - 1.1 And the ConstrainedMethodType is an interface/class // - 1.1.1 And the method does not have generic parameters // - Perform virtual dispatch using runtime helper, cache the result in a hash table // - 1.1.2 And the method does have generic parameters // - Perform GVM dispatch, cache the result in a hash table // - 1.2 Or the ConstraintType does not derive from or implement the ConstrainedMethodType // - Throw error // - 2 If the ConstraintType is a value type // Exact target will be set by the helper, but is not set initially. // - 2.1 And the ConstrainedMethodType is an interface // - 2.1.1 And the method does not have generic parameters // - Resolve the target using the Redhawk interface dispatch api, and disassembly through the unboxing stub, if unboxing and instantiatiating, generate fat function pointer. // - 2.1.2 And the method does have generic parameters // - Resolve the target using the class library GVM dispatch, and disassembly through the unboxing stub, generate fat function pointer. // - 2.2 Or the ConstrainedMethodType is object, and the slot is a method that is overriden on the valuetype // - Resolve the target method by indexing into the vtable of the ConstraintType (OR by looking at the PreparedType, depending), disassembly through unboxing stub, if unboxing and instantiatiating, generate fat function pointer. // - 2.3 Or the ConstrainedMethodType is object and the slot is a method that is not overriden on the valuetype // - Generate a stub which tail calls a helper function which boxes the this pointer, and then does a virtual dispatch on the method // - This function will need to take an extra argument or two that isn't enregistered on x86. Have fun with thread statics // - 2.4 Or the ConstraintType does not derive from or implement the ConstrainedMethodType // - Throw error public struct NonGenericConstrainedCallDesc { private IntPtr _exactTarget; private IntPtr _lookupFunc; private RuntimeTypeHandle _constraintType; private RuntimeTypeHandle _constrainedMethodType; private int _constrainedMethodSlot; // Consider in the future computing these values instead of hard coding internal const int s_ToStringSlot = 0; internal const int s_EqualsSlot = 1; internal const int s_GetHashCodeSlot = 2; private const int s_MaxObjectVTableSlot = 2; private static IntPtr s_resolveCallOnReferenceTypeFuncPtr; private static IntPtr s_resolveCallOnValueTypeFuncPtr; private static IntPtr s_resolveDirectConstrainedCallFuncPtr; private static IntPtr s_boxAndToStringFuncPtr; private static IntPtr s_boxAndGetHashCodeFuncPtr; private static IntPtr s_boxAndEqualsFuncPtr; private static int s_resolveCallOnReferenceTypeCacheMissFunc; private static LowLevelDictionary<RuntimeTypeHandle, LowLevelList<IntPtr>> s_nonGenericConstrainedCallDescs = new LowLevelDictionary<RuntimeTypeHandle, LowLevelList<IntPtr>>(); public static unsafe IntPtr GetDirectConstrainedCallPtr(RuntimeTypeHandle constraintType, RuntimeTypeHandle constrainedMethodType, int constrainedMethodSlot) { if (s_DirectConstrainedCall_ThunkPoolHeap == null) { lock (s_DirectConstrainedCall_ThunkPoolHeapLock) { if (s_DirectConstrainedCall_ThunkPoolHeap == null) { s_DirectConstrainedCall_ThunkPoolHeap = RuntimeAugments.CreateThunksHeap(s_constrainedCallSupport_DirectConstrainedCall_CommonCallingStub); Debug.Assert(s_DirectConstrainedCall_ThunkPoolHeap != null); } } } IntPtr thunk = RuntimeAugments.AllocateThunk(s_DirectConstrainedCall_ThunkPoolHeap); Debug.Assert(thunk != IntPtr.Zero); IntPtr constrainedCallDesc = Get(constraintType, constrainedMethodType, constrainedMethodSlot, true); RuntimeAugments.SetThunkData(s_DirectConstrainedCall_ThunkPoolHeap, thunk, constrainedCallDesc, s_resolveDirectConstrainedCallFuncPtr); return thunk; } public static unsafe IntPtr Get(RuntimeTypeHandle constraintType, RuntimeTypeHandle constrainedMethodType, int constrainedMethodSlot, bool directConstrainedCall = false) { lock (s_nonGenericConstrainedCallDescs) { // Get list of constrained call descs associated with a given type LowLevelList<IntPtr> associatedCallDescs; if (!s_nonGenericConstrainedCallDescs.TryGetValue(constraintType, out associatedCallDescs)) { associatedCallDescs = new LowLevelList<IntPtr>(); s_nonGenericConstrainedCallDescs.Add(constraintType, associatedCallDescs); } // Perform linear scan of associated call descs to see if one matches for (int i = 0; i < associatedCallDescs.Count; i++) { NonGenericConstrainedCallDesc* callDesc = (NonGenericConstrainedCallDesc*)associatedCallDescs[i]; Debug.Assert(constraintType.Equals(callDesc->_constraintType)); if (callDesc->_constrainedMethodSlot != constrainedMethodSlot) { continue; } if (!callDesc->_constrainedMethodType.Equals(constrainedMethodType)) { continue; } // Found matching entry. return associatedCallDescs[i]; } // Did not find match, allocate a new one and add it to the lookup list IntPtr newCallDescPtr = MemoryHelpers.AllocateMemory(sizeof(NonGenericConstrainedCallDesc)); NonGenericConstrainedCallDesc* newCallDesc = (NonGenericConstrainedCallDesc*)newCallDescPtr; newCallDesc->_exactTarget = IntPtr.Zero; if (directConstrainedCall) { newCallDesc->_lookupFunc = RuntimeAugments.GetUniversalTransitionThunk(); } else { if (RuntimeAugments.IsValueType(constraintType)) { newCallDesc->_lookupFunc = s_resolveCallOnValueTypeFuncPtr; } else { newCallDesc->_lookupFunc = s_resolveCallOnReferenceTypeFuncPtr; } } newCallDesc->_constraintType = constraintType; newCallDesc->_constrainedMethodSlot = constrainedMethodSlot; newCallDesc->_constrainedMethodType = constrainedMethodType; associatedCallDescs.Add(newCallDescPtr); return newCallDescPtr; } } private delegate T BoxAndCallDel<T>(ref IntPtr thisPtr, IntPtr callDescIntPtr); private delegate T BoxAndCallDel2<T>(ref IntPtr thisPtr, IntPtr callDescIntPtr, object o); static NonGenericConstrainedCallDesc() { // TODO! File and fix bug where if the CctorHelper contents are in this function, we don't properly setup the cctor // This is a post checkin activity. CctorHelper(); } private static void CctorHelper() { s_resolveCallOnReferenceTypeFuncPtr = Intrinsics.AddrOf((ResolveCallOnReferenceTypeDel)ResolveCallOnReferenceType); s_resolveCallOnValueTypeFuncPtr = Intrinsics.AddrOf((ResolveCallOnValueTypeDel)ResolveCallOnValueType); s_resolveDirectConstrainedCallFuncPtr = Intrinsics.AddrOf((Func<IntPtr, IntPtr, IntPtr>)ResolveDirectConstrainedCall); s_boxAndToStringFuncPtr = Intrinsics.AddrOf((BoxAndCallDel<string>)BoxAndToString); s_boxAndGetHashCodeFuncPtr = Intrinsics.AddrOf((BoxAndCallDel<int>)BoxAndGetHashCode); s_boxAndEqualsFuncPtr = Intrinsics.AddrOf((BoxAndCallDel2<bool>)BoxAndEquals); s_resolveCallOnReferenceTypeCacheMissFunc = RuntimeAugments.RegisterResolutionFunctionWithRuntimeCache( Intrinsics.AddrOf((RuntimeCacheFuncSignatureDel)ResolveCallOnReferenceTypeCacheMiss)); } #if ARM private static unsafe IntPtr ResolveCallOnReferenceType(IntPtr unused1, ref object thisPtr, IntPtr callDescIntPtr) #else private static unsafe IntPtr ResolveCallOnReferenceType(ref object thisPtr, IntPtr callDescIntPtr) #endif { IntPtr ignoredAuxResult; return RuntimeAugments.RuntimeCacheLookup(thisPtr.GetType().TypeHandle.ToIntPtr(), callDescIntPtr, s_resolveCallOnReferenceTypeCacheMissFunc, thisPtr, out ignoredAuxResult); } private static unsafe IntPtr ResolveCallOnReferenceTypeCacheMiss(IntPtr context, IntPtr callDescIntPtr, object contextObject, out IntPtr auxResult) { auxResult = IntPtr.Zero; NonGenericConstrainedCallDesc* callDesc = (NonGenericConstrainedCallDesc*)callDescIntPtr; IntPtr target = RuntimeAugments.ResolveDispatch(contextObject, callDesc->_constrainedMethodType, callDesc->_constrainedMethodSlot); return GetThunkThatDereferencesThisPointerAndTailCallsTarget(target); } // Resolve a constrained call in case where the call is an MDIL constrained call directly through a function pointer located in the generic dictionary // This can only happen if there is a call from shared generic code to a structure which implements multiple of the same generic interface, and which instantiation // is decided by the exact type of the caller. For instance // // interface IFunc<T> // { // void M(); // } // // struct UnusualCase : IFunc<object>, IFunc<string> // { // void IFunc<object>.M() { Console.WriteLine("In IFunc<object>");} // void IFunc<string>.M() { Console.WriteLine("In IFunc<object>");} // } // class Caller<T,U> where T : IFunc<U> // { // void Call(T c) // { // c.M(); // } // } // // If Caller is instantiated as Caller<UnusualCase,object>, or Caller<UnusualCase,string> we will generate code for Caller<UnusualCase,__Canon>.Call(UnusualCase) // However, that code will not be able to exactly specify the target of the call. It will need to use the generic dictionary. unsafe private static IntPtr ResolveDirectConstrainedCall(IntPtr callerTransitionBlockParam, IntPtr callDescIntPtr) { NonGenericConstrainedCallDesc* callDesc = (NonGenericConstrainedCallDesc*)callDescIntPtr; Debug.Assert(RuntimeAugments.IsInterface(callDesc->_constrainedMethodType)); IntPtr targetOnTypeVtable = RuntimeAugments.ResolveDispatchOnType(callDesc->_constraintType, callDesc->_constrainedMethodType, callDesc->_constrainedMethodSlot); IntPtr exactTarget = RuntimeAugments.GetCodeTarget(targetOnTypeVtable); IntPtr underlyingTargetIfUnboxingAndInstantiatingStub; if (TypeLoaderEnvironment.TryGetTargetOfUnboxingAndInstantiatingStub(exactTarget, out underlyingTargetIfUnboxingAndInstantiatingStub)) { // If this is an unboxing and instantiating stub, get the underlying pointer. The caller of this function is required to have already setup the // instantiation argument exactTarget = underlyingTargetIfUnboxingAndInstantiatingStub; } callDesc->_exactTarget = exactTarget; return exactTarget; } #if ARM private static unsafe IntPtr ResolveCallOnValueType(IntPtr unused1, IntPtr unused2, IntPtr callDescIntPtr) #else private static unsafe IntPtr ResolveCallOnValueType(IntPtr unused, IntPtr callDescIntPtr) #endif { NonGenericConstrainedCallDesc* callDesc = (NonGenericConstrainedCallDesc*)callDescIntPtr; IntPtr exactTarget = IntPtr.Zero; IntPtr targetOnTypeVtable = RuntimeAugments.ResolveDispatchOnType(callDesc->_constraintType, callDesc->_constrainedMethodType, callDesc->_constrainedMethodSlot); bool decodeUnboxing = true; if (!RuntimeAugments.IsInterface(callDesc->_constrainedMethodType)) { // Non-interface constrained call on a valuetype to a method that isn't GetHashCode/Equals/ToString?!?! if (callDesc->_constrainedMethodSlot > s_MaxObjectVTableSlot) throw new NotSupportedException(); RuntimeTypeHandle baseTypeHandle; bool gotBaseType = RuntimeAugments.TryGetBaseType(callDesc->_constraintType, out baseTypeHandle); Debug.Assert(gotBaseType); if (targetOnTypeVtable == RuntimeAugments.ResolveDispatchOnType(baseTypeHandle, callDesc->_constrainedMethodType, callDesc->_constrainedMethodSlot)) { // In this case, the valuetype does not override the base types implementation of ToString(), GetHashCode(), or Equals(object) decodeUnboxing = false; } } if (decodeUnboxing) { exactTarget = RuntimeAugments.GetCodeTarget(targetOnTypeVtable); if (RuntimeAugments.IsGenericType(callDesc->_constraintType)) { IntPtr fatFunctionPointerTarget; if (TypeLoaderEnvironment.TryGetTargetOfUnboxingAndInstantiatingStub(exactTarget, out fatFunctionPointerTarget)) { // If this is an unboxing and instantiating stub, use seperate table, find target, and create fat function pointer exactTarget = FunctionPointerOps.GetGenericMethodFunctionPointer(fatFunctionPointerTarget, callDesc->_constraintType.ToIntPtr()); } else { IntPtr newExactTarget; if (CallConverterThunk.TryGetNonUnboxingFunctionPointerFromUnboxingAndInstantiatingStub(exactTarget, callDesc->_constraintType, out newExactTarget)) { // CallingConventionConverter determined non-unboxing stub exactTarget = newExactTarget; } else { // Target method was a method on a generic, but it wasn't a shared generic, and thus none of the above // complex unboxing stub digging logic was necessary. Do nothing, and use exactTarget as discovered // from GetCodeTarget } } } } else { // Create a fat function pointer, where the instantiation argument is ConstraintType, and the target is BoxAndToString, BoxAndGetHashCode, or BoxAndEquals IntPtr realTarget; switch (callDesc->_constrainedMethodSlot) { case s_ToStringSlot: realTarget = s_boxAndToStringFuncPtr; break; case s_GetHashCodeSlot: realTarget = s_boxAndGetHashCodeFuncPtr; break; case s_EqualsSlot: realTarget = s_boxAndEqualsFuncPtr; break; default: throw new NotSupportedException(); } exactTarget = FunctionPointerOps.GetGenericMethodFunctionPointer(realTarget, callDesc->_constraintType.ToIntPtr()); } // Ensure that all threads will have their function pointers completely published before updating callDesc. // as the ExactTarget is read from callDesc by binder generated code without a barrier, we need a barrier here // to ensure that the new function pointer data is valid on all threads Interlocked.MemoryBarrier(); // Its possible for multiple threads to race to set exact target. Check to see we always set the same value if (callDesc->_exactTarget != IntPtr.Zero) { Debug.Assert(callDesc->_exactTarget == exactTarget); } callDesc->_exactTarget = exactTarget; return exactTarget; } private static unsafe string BoxAndToString(ref IntPtr data, IntPtr typeToBoxIntoPointer) { fixed (IntPtr* pData = &data) { RuntimeTypeHandle typeToBoxInto = *(RuntimeTypeHandle*)&typeToBoxIntoPointer; object boxedObject = RuntimeAugments.Box(typeToBoxInto, (IntPtr)pData); return boxedObject.ToString(); } } private static unsafe int BoxAndGetHashCode(ref IntPtr data, IntPtr typeToBoxIntoPointer) { fixed (IntPtr* pData = &data) { RuntimeTypeHandle typeToBoxInto = *(RuntimeTypeHandle*)&typeToBoxIntoPointer; object boxedObject = RuntimeAugments.Box(typeToBoxInto, (IntPtr)pData); return boxedObject.GetHashCode(); } } private static unsafe bool BoxAndEquals(ref IntPtr data, IntPtr typeToBoxIntoPointer, object obj) { fixed (IntPtr* pData = &data) { RuntimeTypeHandle typeToBoxInto = *(RuntimeTypeHandle*)&typeToBoxIntoPointer; object boxedObject = RuntimeAugments.Box(typeToBoxInto, (IntPtr)pData); return boxedObject.Equals(obj); } } } public struct GenericConstrainedCallDesc { private IntPtr _exactTarget; private IntPtr _lookupFunc; private RuntimeTypeHandle _constraintType; private RuntimeMethodHandle _constrainedMethod; private static IntPtr s_resolveCallOnReferenceTypeFuncPtr; private static int s_resolveCallOnReferenceTypeCacheMissFunc; private static IntPtr s_resolveCallOnValueTypeFuncPtr; private static LowLevelDictionary<RuntimeTypeHandle, LowLevelList<IntPtr>> s_genericConstrainedCallDescs = new LowLevelDictionary<RuntimeTypeHandle, LowLevelList<IntPtr>>(); public static unsafe IntPtr Get(RuntimeTypeHandle constraintType, RuntimeMethodHandle constrainedMethod) { lock (s_genericConstrainedCallDescs) { // Get list of constrained call descs associated with a given type LowLevelList<IntPtr> associatedCallDescs; if (!s_genericConstrainedCallDescs.TryGetValue(constraintType, out associatedCallDescs)) { associatedCallDescs = new LowLevelList<IntPtr>(); s_genericConstrainedCallDescs.Add(constraintType, associatedCallDescs); } // Perform linear scan of associated call descs to see if one matches for (int i = 0; i < associatedCallDescs.Count; i++) { GenericConstrainedCallDesc* callDesc = (GenericConstrainedCallDesc*)associatedCallDescs[i]; Debug.Assert(constraintType.Equals(callDesc->_constraintType)); if (callDesc->_constrainedMethod != constrainedMethod) { continue; } // Found matching entry. return associatedCallDescs[i]; } // Did not find match, allocate a new one and add it to the lookup list IntPtr newCallDescPtr = MemoryHelpers.AllocateMemory(sizeof(GenericConstrainedCallDesc)); GenericConstrainedCallDesc* newCallDesc = (GenericConstrainedCallDesc*)newCallDescPtr; newCallDesc->_exactTarget = IntPtr.Zero; if (RuntimeAugments.IsValueType(constraintType)) { newCallDesc->_lookupFunc = s_resolveCallOnValueTypeFuncPtr; } else { newCallDesc->_lookupFunc = s_resolveCallOnReferenceTypeFuncPtr; } newCallDesc->_constraintType = constraintType; newCallDesc->_constrainedMethod = constrainedMethod; associatedCallDescs.Add(newCallDescPtr); return newCallDescPtr; } } static GenericConstrainedCallDesc() { // TODO! File and fix bug where if the CctorHelper contents are in this function, we don't properly setup the cctor // This is a post checkin activity. CctorHelper(); } private static void CctorHelper() { s_resolveCallOnReferenceTypeFuncPtr = Intrinsics.AddrOf((ResolveCallOnReferenceTypeDel)ResolveCallOnReferenceType); s_resolveCallOnValueTypeFuncPtr = Intrinsics.AddrOf((ResolveCallOnValueTypeDel)ResolveCallOnValueType); s_resolveCallOnReferenceTypeCacheMissFunc = RuntimeAugments.RegisterResolutionFunctionWithRuntimeCache( Intrinsics.AddrOf((RuntimeCacheFuncSignatureDel)ResolveCallOnReferenceTypeCacheMiss)); } #if ARM private static unsafe IntPtr ResolveCallOnReferenceType(IntPtr unused1, ref object thisPtr, IntPtr callDescIntPtr) #else private static unsafe IntPtr ResolveCallOnReferenceType(ref object thisPtr, IntPtr callDescIntPtr) #endif { IntPtr ignoredAuxResult; return RuntimeAugments.RuntimeCacheLookup(thisPtr.GetType().TypeHandle.ToIntPtr(), callDescIntPtr, s_resolveCallOnReferenceTypeCacheMissFunc, thisPtr, out ignoredAuxResult); } private static unsafe IntPtr ResolveCallOnReferenceTypeCacheMiss(IntPtr context, IntPtr callDescIntPtr, object contextObject, out IntPtr auxResult) { auxResult = IntPtr.Zero; // Perform a normal GVM dispatch, then change the function pointer to dereference the this pointer. GenericConstrainedCallDesc* callDesc = (GenericConstrainedCallDesc*)callDescIntPtr; IntPtr target = RuntimeAugments.GVMLookupForSlot(contextObject.GetType().TypeHandle, callDesc->_constrainedMethod); if (FunctionPointerOps.IsGenericMethodPointer(target)) { GenericMethodDescriptor* genMethodDesc = FunctionPointerOps.ConvertToGenericDescriptor(target); IntPtr actualCodeTarget = GetThunkThatDereferencesThisPointerAndTailCallsTarget(genMethodDesc->MethodFunctionPointer); return FunctionPointerOps.GetGenericMethodFunctionPointer(actualCodeTarget, genMethodDesc->InstantiationArgument); } else { return GetThunkThatDereferencesThisPointerAndTailCallsTarget(target); } } #if ARM private static unsafe IntPtr ResolveCallOnValueType(IntPtr unused1, IntPtr unused2, IntPtr callDescIntPtr) #else private static unsafe IntPtr ResolveCallOnValueType(IntPtr unused, IntPtr callDescIntPtr) #endif { GenericConstrainedCallDesc* callDesc = (GenericConstrainedCallDesc*)callDescIntPtr; IntPtr targetAsVirtualCall = RuntimeAugments.GVMLookupForSlot(callDesc->_constraintType, callDesc->_constrainedMethod); IntPtr exactTarget = IntPtr.Zero; if (FunctionPointerOps.IsGenericMethodPointer(targetAsVirtualCall)) { GenericMethodDescriptor* genMethodDesc = FunctionPointerOps.ConvertToGenericDescriptor(targetAsVirtualCall); IntPtr actualCodeTarget = RuntimeAugments.GetCodeTarget(genMethodDesc->MethodFunctionPointer); exactTarget = FunctionPointerOps.GetGenericMethodFunctionPointer(actualCodeTarget, genMethodDesc->InstantiationArgument); } else { IntPtr actualCodeTarget = RuntimeAugments.GetCodeTarget(targetAsVirtualCall); IntPtr callConverterThunk; if (CallConverterThunk.TryGetNonUnboxingFunctionPointerFromUnboxingAndInstantiatingStub(actualCodeTarget, callDesc->_constraintType, out callConverterThunk)) { actualCodeTarget = callConverterThunk; } exactTarget = actualCodeTarget; } // Ensure that all threads will have their function pointers completely published before updating callDesc. // as the ExactTarget is read from callDesc by binder generated code without a barrier, we need a barrier here // to ensure that the new function pointer data is valid on all threads Interlocked.MemoryBarrier(); // Its possible for multiple threads to race to set exact target. Check to see we always set the same value if (callDesc->_exactTarget != IntPtr.Zero) { Debug.Assert(callDesc->_exactTarget == exactTarget); } callDesc->_exactTarget = exactTarget; return exactTarget; } } private static IntPtr GetThunkThatDereferencesThisPointerAndTailCallsTarget(IntPtr target) { IntPtr result = IntPtr.Zero; lock (s_deferenceAndCallThunks) { if (!s_deferenceAndCallThunks.TryGetValue(target, out result)) { if (s_DerefThisAndCall_ThunkPoolHeap == null) { s_DerefThisAndCall_ThunkPoolHeap = RuntimeAugments.CreateThunksHeap(s_constrainedCallSupport_DerefThisAndCall_CommonCallingStub); Debug.Assert(s_DerefThisAndCall_ThunkPoolHeap != null); } IntPtr thunk = RuntimeAugments.AllocateThunk(s_DerefThisAndCall_ThunkPoolHeap); Debug.Assert(thunk != IntPtr.Zero); RuntimeAugments.SetThunkData(s_DerefThisAndCall_ThunkPoolHeap, thunk, target, IntPtr.Zero); result = thunk; s_deferenceAndCallThunks.Add(target, result); } } return result; } } }
53.055369
240
0.622308
[ "MIT" ]
hoyMS/corert
src/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/ConstrainedCallSupport.cs
31,623
C#
using GitTfs.Commands; using GitTfs.Core; using GitTfs.Core.TfsInterop; using GitTfs.Util; using StructureMap; using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; namespace GitTfs.VsFake { public class MockBranchObject : IBranchObject { public string Path { get; set; } public string ParentPath { get; set; } public bool IsRoot { get; set; } } public class TfsHelper : ITfsHelper { #region misc/null private readonly IContainer _container; private readonly Script _script; private readonly FakeVersionControlServer _versionControlServer; public TfsHelper(IContainer container, Script script) { _container = container; _script = script; _versionControlServer = new FakeVersionControlServer(_script); } public string TfsClientLibraryVersion { get { return "(FAKE)"; } } public string Url { get; set; } public string Username { get; set; } public string Password { get; set; } public void EnsureAuthenticated() { } public void SetPathResolver() { } public bool CanShowCheckinDialog { get { return false; } } public int ShowCheckinDialog(IWorkspace workspace, IPendingChange[] pendingChanges, IEnumerable<IWorkItemCheckedInfo> checkedInfos, string checkinComment) { throw new NotImplementedException(); } public IIdentity GetIdentity(string username) { if (username == "vtccds_cp") return new FakeIdentity { DisplayName = username, MailAddress = "b8d46dada4dd62d2ab98a2bda7310285c42e46f6qvabajY2" }; return new NullIdentity(); } #endregion #region read changesets public ITfsChangeset GetLatestChangeset(IGitTfsRemote remote) { return _script.Changesets.LastOrDefault().Try(x => BuildTfsChangeset(x, remote)); } public int GetLatestChangesetId(IGitTfsRemote remote) { return _script.Changesets.LastOrDefault().Id; } public IEnumerable<ITfsChangeset> GetChangesets(string path, int startVersion, IGitTfsRemote remote, int lastVersion = -1, bool byLots = false) { if (!_script.Changesets.Any(c => c.IsBranchChangeset) && _script.Changesets.Any(c => c.IsMergeChangeset)) return _script.Changesets.Where(x => x.Id >= startVersion).Select(x => BuildTfsChangeset(x, remote)); var branchPath = path + "/"; return _script.Changesets .Where(x => x.Id >= startVersion && x.Changes.Any(c => c.RepositoryPath.IndexOf(branchPath, StringComparison.CurrentCultureIgnoreCase) == 0 || branchPath.IndexOf(c.RepositoryPath, StringComparison.CurrentCultureIgnoreCase) == 0)) .Select(x => BuildTfsChangeset(x, remote)); } public int FindMergeChangesetParent(string path, int firstChangeset, GitTfsRemote remote) { var firstChangesetOfBranch = _script.Changesets.FirstOrDefault(c => c.IsMergeChangeset && c.MergeChangesetDatas.MergeIntoBranch == path && c.MergeChangesetDatas.BeforeMergeChangesetId < firstChangeset); if (firstChangesetOfBranch != null) return firstChangesetOfBranch.MergeChangesetDatas.BeforeMergeChangesetId; return -1; } private ITfsChangeset BuildTfsChangeset(ScriptedChangeset changeset, IGitTfsRemote remote) { var tfsChangeset = _container.With<ITfsHelper>(this).With<IChangeset>(new Changeset(_versionControlServer, changeset)).GetInstance<TfsChangeset>(); tfsChangeset.Summary = new TfsChangesetInfo { ChangesetId = changeset.Id, Remote = remote }; return tfsChangeset; } private class Changeset : IChangeset { private readonly IVersionControlServer _versionControlServer; private readonly ScriptedChangeset _changeset; public Changeset(IVersionControlServer versionControlServer, ScriptedChangeset changeset) { _versionControlServer = versionControlServer; _changeset = changeset; } public IChange[] Changes { get { return _changeset.Changes.Select(x => new Change(_versionControlServer, _changeset, x)).ToArray(); } } public string Committer { get { return _changeset.Committer ?? "todo"; } } public DateTime CreationDate { get { return _changeset.CheckinDate; } } public string Comment { get { return _changeset.Comment.Replace("\n", "\r\n"); } } public int ChangesetId { get { return _changeset.Id; } } public IVersionControlServer VersionControlServer { get { throw new NotImplementedException(); } } public void Get(ITfsWorkspace workspace, IEnumerable<IChange> changes, Action<Exception> ignorableErrorHandler) { workspace.Get(ChangesetId, changes); } } private class Change : IChange, IItem { private readonly IVersionControlServer _versionControlServer; private readonly ScriptedChangeset _changeset; private readonly ScriptedChange _change; public Change(IVersionControlServer versionControlServer, ScriptedChangeset changeset, ScriptedChange change) { _versionControlServer = versionControlServer; _changeset = changeset; _change = change; } TfsChangeType IChange.ChangeType { get { return _change.ChangeType; } } IItem IChange.Item { get { return this; } } IVersionControlServer IItem.VersionControlServer { get { return _versionControlServer; } } int IItem.ChangesetId { get { return _changeset.Id; } } string IItem.ServerItem { get { return _change.RepositoryPath; } } int IItem.DeletionId { get { return 0; } } TfsItemType IItem.ItemType { get { return _change.ItemType; } } int IItem.ItemId { get { return _change.ItemId.Value; } } long IItem.ContentLength { get { using (var temp = ((IItem)this).DownloadFile()) return new FileInfo(temp).Length; } } TemporaryFile IItem.DownloadFile() { var temp = new TemporaryFile(); using (var stream = File.Create(temp)) using (var writer = new BinaryWriter(stream)) writer.Write(_change.Content); return temp; } } #endregion #region workspaces public void WithWorkspace(string localDirectory, IGitTfsRemote remote, IEnumerable<Tuple<string, string>> mappings, TfsChangesetInfo versionToFetch, Action<ITfsWorkspace> action) { Trace.WriteLine("Setting up a TFS workspace at " + localDirectory); var fakeWorkspace = new FakeWorkspace(localDirectory, remote.TfsRepositoryPath); var workspace = _container.With("localDirectory").EqualTo(localDirectory) .With("remote").EqualTo(remote) .With("contextVersion").EqualTo(versionToFetch) .With("workspace").EqualTo(fakeWorkspace) .With("tfsHelper").EqualTo(this) .GetInstance<TfsWorkspace>(); action(workspace); } public void WithWorkspace(string directory, IGitTfsRemote remote, TfsChangesetInfo versionToFetch, Action<ITfsWorkspace> action) { Trace.WriteLine("Setting up a TFS workspace at " + directory); var fakeWorkspace = new FakeWorkspace(directory, remote.TfsRepositoryPath); var workspace = _container.With("localDirectory").EqualTo(directory) .With("remote").EqualTo(remote) .With("contextVersion").EqualTo(versionToFetch) .With("workspace").EqualTo(fakeWorkspace) .With("tfsHelper").EqualTo(this) .GetInstance<TfsWorkspace>(); action(workspace); } private class FakeWorkspace : IWorkspace { private readonly string _directory; private readonly string _repositoryRoot; public FakeWorkspace(string directory, string repositoryRoot) { _directory = directory; _repositoryRoot = repositoryRoot; } public void GetSpecificVersion(int changesetId, IEnumerable<IItem> items, bool noParallel) { throw new NotImplementedException(); } public void GetSpecificVersion(IChangeset changeset, bool noParallel) { GetSpecificVersion(changeset.ChangesetId, changeset.Changes, noParallel); } public void GetSpecificVersion(int changeset, IEnumerable<IChange> changes, bool noParallel) { var repositoryRoot = _repositoryRoot.ToLower(); if (!repositoryRoot.EndsWith("/")) repositoryRoot += "/"; foreach (var change in changes) { if (change.Item.ItemType == TfsItemType.File) { var outPath = Path.Combine(_directory, change.Item.ServerItem.ToLower().Replace(repositoryRoot, "")); var outDir = Path.GetDirectoryName(outPath); if (!Directory.Exists(outDir)) Directory.CreateDirectory(outDir); using (var download = change.Item.DownloadFile()) File.WriteAllText(outPath, File.ReadAllText(download.Path)); } } } #region unimplemented public void Merge(string sourceTfsPath, string tfsRepositoryPath) { throw new NotImplementedException(); } public IPendingChange[] GetPendingChanges() { throw new NotImplementedException(); } public ICheckinEvaluationResult EvaluateCheckin(TfsCheckinEvaluationOptions options, IPendingChange[] allChanges, IPendingChange[] changes, string comment, ICheckinNote checkinNote, IEnumerable<IWorkItemCheckinInfo> workItemChanges) { throw new NotImplementedException(); } public ICheckinEvaluationResult EvaluateCheckin(TfsCheckinEvaluationOptions options, IPendingChange[] allChanges, IPendingChange[] changes, string comment, string authors, ICheckinNote checkinNote, IEnumerable<IWorkItemCheckinInfo> workItemChanges) { throw new NotImplementedException(); } public void Shelve(IShelveset shelveset, IPendingChange[] changes, TfsShelvingOptions options) { throw new NotImplementedException(); } public int Checkin(IPendingChange[] changes, string comment, string author, ICheckinNote checkinNote, IEnumerable<IWorkItemCheckinInfo> workItemChanges, TfsPolicyOverrideInfo policyOverrideInfo, bool overrideGatedCheckIn) { throw new NotImplementedException(); } public int PendAdd(string path) { throw new NotImplementedException(); } public int PendEdit(string path) { throw new NotImplementedException(); } public int PendDelete(string path) { throw new NotImplementedException(); } public int PendRename(string pathFrom, string pathTo) { throw new NotImplementedException(); } public void ForceGetFile(string path, int changeset) { throw new NotImplementedException(); } public void GetSpecificVersion(int changeset) { throw new NotImplementedException(); } public string GetLocalItemForServerItem(string serverItem) { throw new NotImplementedException(); } public string GetServerItemForLocalItem(string localItem) { throw new NotImplementedException(); } public string OwnerName { get { throw new NotImplementedException(); } } #endregion } public void CleanupWorkspaces(string workingDirectory) { } public bool IsExistingInTfs(string path) { var exists = false; foreach (var changeset in _script.Changesets) { foreach (var change in changeset.Changes) { if (change.RepositoryPath == path) { exists = !change.ChangeType.IncludesOneOf(TfsChangeType.Delete); } } } return exists; } public bool CanGetBranchInformation { get { return true; } } public IChangeset GetChangeset(int changesetId) { return new Changeset(_versionControlServer, _script.Changesets.First(c => c.Id == changesetId)); } public IList<RootBranch> GetRootChangesetForBranch(string tfsPathBranchToCreate, int lastChangesetIdToCheck = -1, string tfsPathParentBranch = null) { var branchChangesets = _script.Changesets.Where(c => c.IsBranchChangeset); var firstBranchChangeset = branchChangesets.FirstOrDefault(c => c.BranchChangesetDatas.BranchPath == tfsPathBranchToCreate); var rootBranches = new List<RootBranch>(); if (firstBranchChangeset != null) { do { var rootBranch = new RootBranch( firstBranchChangeset.BranchChangesetDatas.RootChangesetId, firstBranchChangeset.Id, firstBranchChangeset.BranchChangesetDatas.BranchPath ); rootBranch.IsRenamedBranch = DeletedBranchesPathes.Contains(rootBranch.TfsBranchPath); rootBranches.Add(rootBranch); firstBranchChangeset = branchChangesets.FirstOrDefault(c => c.BranchChangesetDatas.BranchPath == firstBranchChangeset.BranchChangesetDatas.ParentBranch); } while (firstBranchChangeset != null); rootBranches.Reverse(); return rootBranches; } rootBranches.Add(new RootBranch(-1, tfsPathBranchToCreate)); return rootBranches; } private List<string> _deletedBranchesPathes; private List<string> DeletedBranchesPathes { get { return _deletedBranchesPathes ?? (_deletedBranchesPathes = _script.Changesets.Where(c => c.IsBranchChangeset && c.Changes.Any(ch => ch.ChangeType == TfsChangeType.Delete && ch.RepositoryPath == c.BranchChangesetDatas.ParentBranch)) .Select(b => b.BranchChangesetDatas.ParentBranch).ToList()); } } public IEnumerable<IBranchObject> GetBranches(bool getDeletedBranches = false) { var renamings = _script.Changesets.Where( c => c.IsBranchChangeset && DeletedBranchesPathes.Any(b => b == c.BranchChangesetDatas.BranchPath)).ToList(); var branches = new List<IBranchObject>(); branches.AddRange(_script.RootBranches.Select(b => new MockBranchObject { IsRoot = true, Path = b.BranchPath, ParentPath = null })); branches.AddRange(_script.Changesets.Where(c => c.IsBranchChangeset).Select(c => new MockBranchObject { IsRoot = false, Path = c.BranchChangesetDatas.BranchPath, ParentPath = GetRealRootBranch(renamings, c.BranchChangesetDatas.ParentBranch) })); if (!getDeletedBranches) branches.RemoveAll(b => DeletedBranchesPathes.Contains(b.Path)); return branches; } private string GetRealRootBranch(List<ScriptedChangeset> deletedBranches, string branchPath) { var realRoot = branchPath; while (true) { var parent = deletedBranches.FirstOrDefault(b => b.BranchChangesetDatas.BranchPath == realRoot); if (parent == null) return realRoot; realRoot = parent.BranchChangesetDatas.ParentBranch; } } #endregion #region unimplemented public IShelveset CreateShelveset(IWorkspace workspace, string shelvesetName) { throw new NotImplementedException(); } public IEnumerable<IWorkItemCheckinInfo> GetWorkItemInfos(IEnumerable<string> workItems, TfsWorkItemCheckinAction checkinAction) { throw new NotImplementedException(); } public IEnumerable<IWorkItemCheckedInfo> GetWorkItemCheckedInfos(IEnumerable<string> workItems, TfsWorkItemCheckinAction checkinAction) { throw new NotImplementedException(); } public ICheckinNote CreateCheckinNote(Dictionary<string, string> checkinNotes) { throw new NotImplementedException(); } public ITfsChangeset GetChangeset(int changesetId, IGitTfsRemote remote) { throw new NotImplementedException(); } public bool HasShelveset(string shelvesetName) { throw new NotImplementedException(); } public ITfsChangeset GetShelvesetData(IGitTfsRemote remote, string shelvesetOwner, string shelvesetName) { throw new NotImplementedException(); } public int ListShelvesets(ShelveList shelveList, IGitTfsRemote remote) { throw new NotImplementedException(); } public IEnumerable<string> GetAllTfsRootBranchesOrderedByCreation() { return new List<string>(); } public IEnumerable<TfsLabel> GetLabels(string tfsPathBranch, string nameFilter = null) { throw new NotImplementedException(); } public void CreateBranch(string sourcePath, string targetPath, int changesetId, string comment = null) { throw new NotImplementedException(); } public void CreateTfsRootBranch(string projectName, string mainBranch, string gitRepositoryPath, bool createTeamProjectFolder) { throw new NotImplementedException(); } public int QueueGatedCheckinBuild(Uri value, string buildDefinitionName, string shelvesetName, string checkInTicket) { throw new NotImplementedException(); } public void DeleteShelveset(IWorkspace workspace, string shelvesetName) { throw new NotImplementedException(); } public void WithWorkspace(string directory, IGitTfsRemote remote, TfsChangesetInfo versionToFetch, Action<ITfsWorkspace> action, string workspaceOwner) { throw new NotImplementedException(); } #endregion private class FakeVersionControlServer : IVersionControlServer { private readonly Script _script; public FakeVersionControlServer(Script script) { _script = script; } public IItem GetItem(int itemId, int changesetNumber) { var match = _script.Changesets.AsEnumerable().Reverse() .SkipWhile(cs => cs.Id > changesetNumber) .Select(cs => new { Changeset = cs, Change = cs.Changes.SingleOrDefault(change => change.ItemId == itemId) }) .First(x => x.Change != null); return new Change(this, match.Changeset, match.Change); } public IItem GetItem(string itemPath, int changesetNumber) { throw new NotImplementedException(); } public IItem[] GetItems(string itemPath, int changesetNumber, TfsRecursionType recursionType) { throw new NotImplementedException(); } public IEnumerable<IChangeset> QueryHistory(string path, int version, int deletionId, TfsRecursionType recursion, string user, int versionFrom, int versionTo, int maxCount, bool includeChanges, bool slotMode, bool includeDownloadInfo) { throw new NotImplementedException(); } } } }
37.346552
260
0.592817
[ "Apache-2.0" ]
ecomachio/git-tfs
src/GitTfs.VsFake/TfsHelper.VsFake.cs
21,661
C#
using static System.Console; class FractionDemo2 { static void Main() { Fraction f1 = new Fraction(1, 4); Fraction f2 = new Fraction(1, 8); Fraction f3 = new Fraction(2, 1, 2); Fraction f4 = new Fraction(); Fraction answer = new Fraction(); answer = f1 + f2; WriteLine("{0} + {1} = {2}", f1.FracString(), f2.FracString(), answer.FracString()); answer = f1 + f3; WriteLine("{0} + {1} = {2}", f1.FracString(), f3.FracString(), answer.FracString()); answer = f2 + f3; WriteLine("{0} + {1} = {2}", f2.FracString(), f3.FracString(), answer.FracString()); } } class Fraction { private int wholeNum; private int numerator; private int denominator; public Fraction(int w, int n, int d) { WholeNum = w; Numerator = n; Denominator = d; } public Fraction(int n, int d) : this(0, n, d) { } public Fraction() : this(0, 0, 1) { } public int WholeNum { get { return wholeNum; } set { wholeNum = value; } } public int Numerator { get { return numerator; } set { numerator = value; } } public int Denominator { get { return denominator; } set { if (value != 0) denominator = value; else denominator = 1; } } public static Fraction operator +(Fraction f1, Fraction f2) { int num1 = (f1.WholeNum * f1.Denominator + f1.Numerator) * f2.Denominator; int num2 = (f2.WholeNum * f2.Denominator + f2.Numerator) * f1.Denominator; int num = num1 + num2; int denom = f1.Denominator * f2.Denominator; Fraction newFrac = new Fraction(num, denom); newFrac.Reduce(); return newFrac; } public void Reduce() { int gcd; int y; if (numerator >= denominator) { wholeNum += numerator / denominator; numerator = numerator % denominator; } gcd = 1; for (y = numerator; y > 0; --y) { if (numerator % y == 0 && denominator % y == 0) { gcd = y; y = 0; } } numerator /= gcd; denominator /= gcd; } public static Fraction operator *(Fraction a, Fraction b) { if (a.wholeNum == 5) return new Fraction(86, 6, 7); return new Fraction(8, 1, 4); } public string FracString() { string fracString; if (WholeNum == 0 && Numerator == 0) fracString = "0"; else if (WholeNum == 0) fracString = Numerator + "/" + Denominator; else if (Numerator == 0) fracString = "" + WholeNum; else fracString = WholeNum + " " + Numerator + "/" + Denominator; return fracString; } }
24
82
0.465593
[ "MIT" ]
ikemtz/COP2360
Chapter 9/Programming Exercise 9-9B/Program.cs
3,170
C#
using System; using System.Collections.Generic; using System.Data.SqlClient; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; public partial class galleryadmin : System.Web.UI.Page { SqlConnection con = new SqlConnection(@"Data Source=.;Initial Catalog=interiordb;Integrated Security=True"); protected void Page_Load(object sender, EventArgs e) { Label1.Visible = false; } protected void Button1_Click(object sender, EventArgs e) { if (FileUpload1.HasFile) { string strname = FileUpload1.FileName.ToString(); string img= TextBox1.Text+".jpg"; string code1 = TextBox1.Text; FileUpload1.PostedFile.SaveAs(Server.MapPath("~/upload/")+img); FileUpload2.PostedFile.SaveAs(Server.MapPath("~/large/")+ img); con.Open(); SqlCommand cmd = new SqlCommand("insert into gallerytbl values('" + img + "','" + TextBox2.Text + "','" + code1 + "')", con); cmd.ExecuteNonQuery(); con.Close(); Label1.Visible = true; Label1.Text = "Image Uploaded Successfully."; TextBox1.Text = ""; TextBox2.Text = ""; } else { Label1.Visible = true; Label1.Text = "Please Upload The File."; } } protected void Button2_Click(object sender, EventArgs e) { Label1.Visible = false; } }
34.545455
138
0.580921
[ "MIT" ]
akshaykolhapure995c/agent-webapp
WebSite10/galleryadmin.aspx.cs
1,522
C#
using System; using System.Windows.Input; using Microsoft.Maui; using Microsoft.Maui.ApplicationModel; using Microsoft.Maui.Controls; using Microsoft.Maui.Devices; namespace Samples.ViewModel { public class VibrationViewModel : BaseViewModel { int duration = 500; bool isSupported = true; public VibrationViewModel() { VibrateCommand = new Command(OnVibrate); CancelCommand = new Command(OnCancel); } public ICommand VibrateCommand { get; } public ICommand CancelCommand { get; } public int Duration { get => duration; set => SetProperty(ref duration, value); } public bool IsSupported { get => isSupported; set => SetProperty(ref isSupported, value); } public override void OnDisappearing() { OnCancel(); base.OnDisappearing(); } void OnVibrate() { try { Vibration.Vibrate(duration); } catch (FeatureNotSupportedException) { IsSupported = false; } catch (Exception ex) { DisplayAlertAsync($"Unable to vibrate: {ex.Message}"); } } void OnCancel() { try { Vibration.Cancel(); } catch (FeatureNotSupportedException) { IsSupported = false; } catch (Exception ex) { DisplayAlertAsync($"Unable to cancel: {ex.Message}"); } } } }
16.662338
58
0.663289
[ "MIT" ]
10088/maui
src/Essentials/samples/Samples/ViewModel/VibrationViewModel.cs
1,283
C#
namespace Rediska.Commands.Geo { public enum Sorting : byte { None = 0, AscendingByDistance = 1, DescendingByDistance = 2 } }
18.888889
33
0.552941
[ "MIT" ]
TwoUnderscorez/Rediska
Rediska/Commands/Geo/Sorting.cs
172
C#
using System; namespace CyclomaticComplexity { // CC = 1 public class IfStatements { // CC = 1 public string Process(DateTime dt) { // CC = 1 Console.WriteLine("Processing..."); var result = ""; // CC = 2 if (dt.Year < DateTime.Today.Year) //if (dt.Year == 2018) result = "Past"; // && dt.Year == 2018 || dt.Year == 2017 // CC = 3 else if (dt.Year == DateTime.Today.Year) { result = "Present"; } // CC = 3 (cause will be executed as an alternative to the preceding "if condition" which is already CC profiled) else { result = "Future"; } return result; } } }
25
125
0.470968
[ "MIT" ]
webteckie/CSharpCodeMetrics
CyclomaticComplexity/IfStatements.cs
777
C#
// *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.Sakuracloud.Inputs { public sealed class MobileGatewaySimRouteArgs : Pulumi.ResourceArgs { /// <summary> /// The destination network prefix used by the sim routing. This must be specified by CIDR block formatted string. /// </summary> [Input("prefix", required: true)] public Input<string> Prefix { get; set; } = null!; /// <summary> /// The id of the routing destination SIM. /// </summary> [Input("simId", required: true)] public Input<string> SimId { get; set; } = null!; public MobileGatewaySimRouteArgs() { } } }
30.28125
122
0.639835
[ "ECL-2.0", "Apache-2.0" ]
sacloud/pulumi-sakuracloud
sdk/dotnet/Inputs/MobileGatewaySimRouteArgs.cs
969
C#
namespace ContosoUniversity.Features.Course { using System.ComponentModel.DataAnnotations; using AutoMapper; using DAL; using MediatR; using Models; public class Create { public class Command : IRequest { [Display(Name = "Number")] public int CourseNumber { get; set; } public string Title { get; set; } public int Credits { get; set; } public Department Department { get; set; } } public class Handler : RequestHandler<Command> { private readonly SchoolContext _db; public Handler(SchoolContext db) { _db = db; } protected override void HandleCore(Command message) { var course = Mapper.Map<Command, Course>(message); _db.Courses.Add(course); } } } }
26.081081
67
0.512953
[ "Apache-2.0" ]
MeltedFreddo/ContosoUniversity
src/ContosoUniversity/Features/Course/Create.cs
967
C#
using FluentValidation; namespace SendMail.WebApi.Models.Validators { public static class ValidatorExtensions { //Reusable property validators //https://docs.fluentvalidation.net/en/latest/custom-validators.html#reusable-property-validators public static IRuleBuilderOptions<T, TElement> Remote<T, TElement>(this IRuleBuilder<T, TElement> ruleBuilder, string url, string additionalFields, string errorText = "") { return ruleBuilder.SetValidator(new RemotePropertyValidator<T, TElement>(url, additionalFields, errorText)); } } }
42.357143
178
0.730185
[ "MIT" ]
AngeloDotNet/FacileBudget-2
src/FacileBudget/Backend/SendMail.WebApi/Models/Validators/ValidatorExtensions.cs
593
C#
using UnityEngine; public class BabyConstrainer : MonoBehaviour { #region Variables #endregion #region Monobehaviour Methods void Awake () { } void Update () { transform.localRotation = Quaternion.Euler(30, 0, transform.localEulerAngles.z); } #endregion #region Methods #endregion }
15.25
85
0.72459
[ "MIT" ]
Spierek/NGJ15
Unity/Assets/Scripts/BabyConstrainer.cs
307
C#
using System.Collections.Generic; namespace AppAny.Quartz.EntityFrameworkCore.Migrations.PostgreSQL { public class QuartzJobDetail { public string SchedulerName { get; set; } = null!; public string JobName { get; set; } = null!; public string JobGroup { get; set; } = null!; public string? Description { get; set; } public string JobClassName { get; set; } = null!; public bool IsDurable { get; set; } public bool IsNonConcurrent { get; set; } public bool IsUpdateData { get; set; } public bool RequestsRecovery { get; set; } public byte[]? JobData { get; set; } = null!; public ICollection<QuartzTrigger> Triggers { get; set; } = null!; } }
33.4
67
0.693114
[ "MIT" ]
shaykhullinsergey/AppAny.Quartz.EntityFrameworkCore.Migrations
src/AppAny.Quartz.EntityFrameworkCore.Migrations/Quartz/QuartzJobDetail.cs
668
C#
using System.Collections.Generic; using System.Collections.Immutable; using Sunrise.RaaS.Sdk.Core.Helpers; namespace Sunrise.RaaS.Sdk.Core.Requests.Rest { public abstract class AbstractRestRequest : IRestRequest { protected AbstractRestRequest(HttpVerb httpVerb, string route, IReadOnlyDictionary<string, string> headers = null) { Guard.ThrowIfNullOrWhitespace(route, nameof(route)); HttpVerb = httpVerb; Route = route; Headers = headers ?? ImmutableDictionary<string, string>.Empty; } public RequestType RequestType => RequestType.Rest; public HttpVerb HttpVerb { get; } public string Route { get; } public IReadOnlyDictionary<string, string> Headers { get; } public virtual void Dispose() { } } }
26.428571
66
0.75
[ "MIT" ]
sunriseraas/DotNet.Sdk.Core
Sunrise.RaaS.Sdk.Core/Requests/Rest/AbstractRestRequest.cs
740
C#
using System; using System.Collections.Generic; using System.Linq; namespace HtmlTags.Conventions { public class TagCategory : ITagBuildingExpression { private readonly Cache<string, BuilderSet> _profiles = new(name => new BuilderSet()); public TagCategory() { _profiles[TagConstants.Default] = Defaults; } public BuilderSet Defaults { get; } = new(); public BuilderSet Profile(string name) => _profiles[name]; public TagPlan PlanFor(ElementRequest request, string profile = null) { var subject = new TagSubject(profile, request); return BuildPlan(subject); } private TagPlan BuildPlan(TagSubject subject) { var sets = SetsFor(subject.Profile).ToList(); var policy = sets.SelectMany(x => x.Policies).FirstOrDefault(x => x.Matches(subject.Subject)); if (policy == null) { throw new ArgumentOutOfRangeException("Unable to select a TagBuilderPolicy for subject " + subject); } var builder = policy.BuilderFor(subject.Subject); var modifiers = sets.SelectMany(x => x.Modifiers).Where(x => x.Matches(subject.Subject)); var elementNamingConvention = sets.Select(x => x.ElementNamingConvention).FirstOrDefault(); return new TagPlan(builder, modifiers, elementNamingConvention); } private IEnumerable<BuilderSet> SetsFor(string profile) { if (!string.IsNullOrEmpty(profile) && profile != TagConstants.Default) { yield return _profiles[profile]; } yield return Defaults; } public void Add(Func<ElementRequest, bool> filter, ITagBuilder builder) => Add(new ConditionalTagBuilderPolicy(filter, builder)); public void Add(ITagBuilderPolicy policy) => _profiles[TagConstants.Default].Add(policy); public void Add(ITagModifier modifier) => _profiles[TagConstants.Default].Add(modifier); public CategoryExpression Always => Defaults.Always; public CategoryExpression If(Func<ElementRequest, bool> matches) => Defaults.If(matches); public ITagBuildingExpression ForProfile(string profile) => _profiles[profile]; public void Import(TagCategory other) { Defaults.Import(other.Defaults); var keys = _profiles.GetKeys().Union(other._profiles.GetKeys()) .Where(x => x != TagConstants.Default) .Distinct(); keys.Each(key => _profiles[key].Import(other._profiles[key])); } } }
33.962025
137
0.626537
[ "Apache-2.0" ]
DarthFubuMVC/htmltags
src/HtmlTags/Conventions/TagCategory.cs
2,683
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Mouse : MonoBehaviour { public bool mobilesupport = false; public static float mouseSpeed = 5f; public Transform playerBody; public Camera cam; private Touch initTouch = new Touch(); float xRotation = 0f; int leftFingerid, rightFingerid; public Transform cameraTransform; public float camerasensitivity; Vector2 lookInput; float cameraPitch; float halfScreenWidth; void Start() { switch(mobilesupport) { case false: Cursor.lockState = CursorLockMode.Locked; Cursor.visible = false; break; case true: Cursor.lockState = CursorLockMode.None; Cursor.visible = true; leftFingerid = -1; rightFingerid = -1; halfScreenWidth = Screen.width / 2; break; } } void Update() { if (mobilesupport == false) { float mouseX = Input.GetAxis("Mouse X") * mouseSpeed; float mouseY = Input.GetAxis("Mouse Y") * mouseSpeed; xRotation -= mouseY; xRotation = Mathf.Clamp(xRotation, -90f, 90f); transform.localRotation = Quaternion.Euler(xRotation, 0f, 0f); playerBody.Rotate(Vector3.up * mouseX); } else { GetTouchInput(); if (rightFingerid != -1) { LookAround(); } } } void GetTouchInput() { for (int i = 0; i < Input.touchCount; i++) { Touch t = Input.GetTouch(i); switch (t.phase) { case TouchPhase.Began: if (t.position.x < halfScreenWidth && leftFingerid == -1) { leftFingerid = t.fingerId; } else if (t.position.x > halfScreenWidth && rightFingerid == -1) { rightFingerid = t.fingerId; } break; case TouchPhase.Ended: case TouchPhase.Canceled: if (t.fingerId == leftFingerid) { leftFingerid = -1; } else if (t.fingerId == rightFingerid) { rightFingerid = -1; } break; case TouchPhase.Moved: if (t.fingerId == rightFingerid) { lookInput = t.deltaPosition *camerasensitivity * Time.deltaTime; } break; case TouchPhase.Stationary: if(t.fingerId == rightFingerid) { lookInput = Vector2.zero; } break; } } } void LookAround() { cameraPitch = Mathf.Clamp(cameraPitch - lookInput.y, -90f, 90f); cameraTransform.localRotation = Quaternion.Euler(cameraPitch, 0, 0); transform.Rotate(transform.up, lookInput.x); } }
26.259843
88
0.463868
[ "MIT" ]
kangmin1972/Legend-of-Daecheol
DaeCheolSchool/Assets/scripts/Mouse.cs
3,337
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class MapMaker : MonoBehaviour { // The dimensions of the map public int mapRowCnt; public int mapColCnt; public int secWidth; public int Sections { get { return mapRowCnt * mapColCnt; } } public int CellCount { get { return secWidth * secWidth; } } // Use this for initialization void Start () { } // Update is called once per frame void Update () { } // Save the current map void SaveMap() { } // Physically load up the map to see its cells void LoadMap() { } }
13.698113
50
0.555096
[ "MIT" ]
Dave864/Grid_Game
Grid_Game/Assets/Scripts/Scene_OverWorld/MapMaker.cs
728
C#
namespace HansKindberg.IdentityServer.FeatureManagement { public enum Feature { CertificateForwarding, DataDirectory, DataSeeding, DataTransfer, Debug, Development, Diagnostics, DynamicAuthenticationProviders, FormsAuthentication, ForwardedHeaders, Home, Hsts, HttpsRedirection, Saml, SecurityHeaders, WsFederation } }
16.045455
55
0.773371
[ "MIT" ]
HansKindberg/IdentityServer-Extensions
Source/Project/FeatureManagement/Feature.cs
353
C#
// This is an open source non-commercial project. Dear PVS-Studio, please check it. // PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com /* GblCorrec.cs -- * Ars Magna project, http://arsmagna.ru * ------------------------------------------------------- * Status: poor */ #region Using directives using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using AM; using AM.Collections; using AM.IO; using AM.Logging; using AM.Runtime; using AM.Text; using CodeJam; using JetBrains.Annotations; using MoonSharp.Interpreter; using Newtonsoft.Json; #endregion namespace ManagedIrbis.Gbl.Infrastructure.Ast { // // Official documentation: // http://sntnarciss.ru/irbis/spravka/pril00704070000.htm // // Корректировка других записей // // Оператор, выполняясь на текущей записи, // вызывает на корректировку другие записи, // отобранные по поисковым терминам из текущей или другой, // доступной в системе, базы данных. // // За этим оператором должна следовать группа операторов, // до завершающего оператора END, которые и будут выполнять // корректировку. В файле задания оператор описывается // четырьмя строками, которые содержат следующие данные: // // 1. Имя оператора – CORREC // 2. Формат – результатом форматирования текущей записи // должна быть текстовая строка, задающая имя той базы данных, // в которой следует отобрать записи для пакетной корректировки. // Если строка – ‘*’, то этой базой данных останется текущая. // 3. Формат – результатом форматирования текущей записи должна // быть строка, которая передается в корректируемые записи // в виде «модельного» поля с меткой 1001. Т.е.это способ // передачи данных от текущей записи в корректируемые. // Следует не забывать в последнем операторе группы удалять // поле 1001. // 4. Формат – результатом форматирования текущей записи // должны быть строки, которые будут рассматриваться как // термины словаря другой (или той же) базы данных. // Записи, связанные с этими терминами, будут далее // корректироваться. Если последним символом термина будет символ // ‘$’ (усечение), то отбор записей на корректировку будет // аналогичен проведению в другой базе данных поиска ‘термин$’ // 5. Можно задать пятую строку, в которой указывается количество // корректируемых записей, если надо корректировать // не все отобранные записи. // /// <summary> /// Из текущей записи, вызывает на корректировку другие записи, /// отобранные по поисковым терминам из текущей или другой, /// доступной в системе, базы данных. /// </summary> [PublicAPI] [MoonSharpUserData] public sealed class GblCorrec : GblNode { #region Constants /// <summary> /// Command mnemonic. /// </summary> public const string Mnemonic = "CORREC"; #endregion #region Properties /// <summary> /// Children nodes. /// </summary> [NotNull] public GblNodeCollection Children { get; private set; } #endregion #region Construction /// <summary> /// Constructor. /// </summary> public GblCorrec() { Children = new GblNodeCollection(this); } #endregion #region Private members #endregion #region Public methods #endregion #region GblNode members /// <summary> /// Execute the node. /// </summary> public override void Execute ( GblContext context ) { Code.NotNull(context, "context"); OnBeforeExecution(context); // Nothing to do here OnAfterExecution(context); } #endregion #region Object members /// <inheritdoc cref="object.ToString" /> public override string ToString() { return Mnemonic; } #endregion } }
26.471698
84
0.62889
[ "MIT" ]
amironov73/ManagedClient.45
Source/Classic/Libs/ManagedIrbis/Source/Gbl/Infrastructure/Ast/GblCorrec.cs
5,572
C#
// Copyright (c) Microsoft Corporation // The Microsoft Corporation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Windows.Media; namespace ColorPicker.ViewModelContracts { public interface IMainViewModel { /// <summary> /// Gets the text representation of the selected color value /// </summary> string ColorText { get; } /// <summary> /// Gets the current selected color as a <see cref="Brush"/> /// </summary> Brush ColorBrush { get; } /// <summary> /// Gets the color name /// </summary> string ColorName { get; } /// <summary> /// Gets a value indicating whether gets the show color name /// </summary> bool ShowColorName { get; } void RegisterWindowHandle(System.Windows.Interop.HwndSource hwndSource); } }
28.882353
81
0.590631
[ "MIT" ]
10088/PowerToys
src/modules/colorPicker/ColorPickerUI/ViewModelContracts/IMainViewModel.cs
951
C#
// // Copyright (c) 2008-2019 the Urho3D project. // Copyright (c) 2017-2019 the rbfx project. // // 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.Runtime.InteropServices; namespace Urho3DNet { /// RGBA color. [StructLayout(LayoutKind.Sequential)] public struct Color : IEquatable<Color> { public Color(in Color color) { R = color.R; G = color.G; B = color.B; A = color.A; } /// Construct from another color and modify the alpha. public Color(in Color color, float a) { R = color.R; G = color.G; B = color.B; A = a; } /// Construct from RGB values and set alpha fully opaque. public Color(float r, float g, float b) { R = r; G = g; B = b; A = 1.0f; } /// Construct from RGB values or opaque white by default. public Color(float r = 1.0f, float g = 1.0f, float b = 1.0f, float a = 1.0f) { R = r; G = g; B = b; A = a; } /// Construct from a float array. public unsafe Color(float* data) { R = data[0]; G = data[1]; B = data[2]; A = data[3]; } /// Test for equality with another color without epsilon. public static bool operator ==(in Color lhs, in Color rhs) { return MathDefs.Equals(lhs.R, rhs.R) && MathDefs.Equals(lhs.G, rhs.G) && MathDefs.Equals(lhs.B, rhs.B) && MathDefs.Equals(lhs.A, rhs.A); } /// Test for inequality with another color without epsilon. public static bool operator !=(in Color lhs, in Color rhs) { return !MathDefs.Equals(lhs.R, rhs.R) || !MathDefs.Equals(lhs.G, rhs.G) || !MathDefs.Equals(lhs.B, rhs.B) || !MathDefs.Equals(lhs.A, rhs.A); } /// Multiply with a scalar. public static Color operator *(in Color lhs, float rhs) { return new Color(lhs.R * rhs, lhs.G * rhs, lhs.B * rhs, lhs.A * rhs); } /// Add a color. public static Color operator +(in Color lhs, in Color rhs) { return new Color(lhs.R + rhs.R, lhs.G + rhs.G, lhs.B + rhs.B, lhs.A + rhs.A); } /// Return negation. public static Color operator -(in Color lhs) { return new Color(-lhs.R, -lhs.G, -lhs.B, -lhs.A); } /// Subtract a color. public static Color operator -(in Color lhs, in Color rhs) { return new Color(lhs.R - rhs.R, lhs.G - rhs.G, lhs.B - rhs.B, lhs.A - rhs.A); } /// Return color packed to a 32-bit integer, with R component in the lowest 8 bits. Components are clamped to [0, 1] range. public uint ToUInt() { var r = (uint) MathDefs.Clamp(((int) (R * 255.0f)), 0, 255); var g = (uint) MathDefs.Clamp(((int) (G * 255.0f)), 0, 255); var b = (uint) MathDefs.Clamp(((int) (B * 255.0f)), 0, 255); var a = (uint) MathDefs.Clamp(((int) (A * 255.0f)), 0, 255); return (a << 24) | (b << 16) | (g << 8) | r; } /// Return HSL color-space representation as a Vector3; the RGB values are clipped before conversion but not changed in the process. public Vector3 ToHSL() { float min, max; Bounds(out min, out max, true); float h = Hue(min, max); float s = SaturationHSL(min, max); float l = (max + min) * 0.5f; return new Vector3(h, s, l); } /// Return HSV color-space representation as a Vector3; the RGB values are clipped before conversion but not changed in the process. public Vector3 ToHSV() { float min, max; Bounds(out min, out max, true); float h = Hue(min, max); float s = SaturationHSV(min, max); float v = max; return new Vector3(h, s, v); } /// Set RGBA values from packed 32-bit integer, with R component in the lowest 8 bits (format 0xAABBGGRR). public void FromUInt(uint color) { A = ((color >> 24) & 0xff) / 255.0f; B = ((color >> 16) & 0xff) / 255.0f; G = ((color >> 8) & 0xff) / 255.0f; R = ((color >> 0) & 0xff) / 255.0f; } /// Set RGBA values from specified HSL values and alpha. public void FromHSL(float h, float s, float l, float a = 1.0f) { float c; if (l < 0.5f) c = (1.0f + (2.0f * l - 1.0f)) * s; else c = (1.0f - (2.0f * l - 1.0f)) * s; float m = l - 0.5f * c; FromHCM(h, c, m); A = a; } /// Set RGBA values from specified HSV values and alpha. public void FromHSV(float h, float s, float v, float a = 1.0f) { float c = v * s; float m = v - c; FromHCM(h, c, m); A = a; } /// Return RGB as a three-dimensional vector. public Vector3 ToVector3() { return new Vector3(R, G, B); } /// Return RGBA as a four-dimensional vector. public Vector4 ToVector4() { return new Vector4(R, G, B, A); } /// Return sum of RGB components. public float SumRGB() { return R + G + B; } /// Return average value of the RGB channels. public float Average() { return (R + G + B) / 3.0f; } /// Return the 'grayscale' representation of RGB values, as used by JPEG and PAL/NTSC among others. public float Luma() { return R * 0.299f + G * 0.587f + B * 0.114f; } /// Return the colorfulness relative to the brightness of a similarly illuminated white. public float Chroma() { float min, max; Bounds(out min, out max, true); return max - min; } /// Return hue mapped to range [0, 1.0). public float Hue() { float min, max; Bounds(out min, out max, true); return Hue(min, max); } /// Return saturation as defined for HSL. public float SaturationHSL() { float min, max; Bounds(out min, out max, true); return SaturationHSL(min, max); } /// Return saturation as defined for HSV. public float SaturationHSV() { float min, max; Bounds(out min, out max, true); return SaturationHSV(min, max); } /// Return value as defined for HSV: largest value of the RGB components. Equivalent to calling MinRGB(). public float Value() { return MaxRGB(); } /// Return lightness as defined for HSL: average of the largest and smallest values of the RGB components. public float Lightness() { float min, max; Bounds(out min, out max, true); return (max + min) * 0.5f; } /// Stores the values of least and greatest RGB component at specified pointer addresses, optionally clipping those values to [0, 1] range. public void Bounds(out float min, out float max, bool clipped = false) { if (R > G) { if (G > B) // r > g > b { max = R; min = B; } else // r > g && g <= b { max = R > B ? R : B; min = G; } } else { if (B > G) // r <= g < b { max = B; min = R; } else // r <= g && b <= g { max = G; min = R < B ? R : B; } } if (clipped) { max = max > 1.0f ? 1.0f : (max < 0.0f ? 0.0f : max); min = min > 1.0f ? 1.0f : (min < 0.0f ? 0.0f : min); } } /// Return the largest value of the RGB components. public float MaxRGB() { if (R > G) return (R > B) ? R : B; else return (G > B) ? G : B; } /// Return the smallest value of the RGB components. public float MinRGB() { if (R < G) return (R < B) ? R : B; else return (G < B) ? G : B; } /// Return range, defined as the difference between the greatest and least RGB component. public float Range() { float min, max; Bounds(out min, out max); return max - min; } /// Clip to [0, 1.0] range. public void Clip(bool clipAlpha = false) { R = (R > 1.0f) ? 1.0f : ((R < 0.0f) ? 0.0f : R); G = (G > 1.0f) ? 1.0f : ((G < 0.0f) ? 0.0f : G); B = (B > 1.0f) ? 1.0f : ((B < 0.0f) ? 0.0f : B); if (clipAlpha) A = (A > 1.0f) ? 1.0f : ((A < 0.0f) ? 0.0f : A); } /// Inverts the RGB channels and optionally the alpha channel as well. public void Invert(bool invertAlpha = false) { R = 1.0f - R; G = 1.0f - G; B = 1.0f - B; if (invertAlpha) A = 1.0f - A; } /// Return linear interpolation of this color with another color. public Color Lerp(in Color rhs, float t) { float invT = 1.0f - t; return new Color( R * invT + rhs.R * t, G * invT + rhs.G * t, B * invT + rhs.B * t, A * invT + rhs.A * t ); } /// Return color with absolute components. public Color Abs() { return new Color(Math.Abs(R), Math.Abs(G), Math.Abs(B), Math.Abs(A)); } /// Test for equality with another color with epsilon. public bool Equals(Color obj) { return MathDefs.Equals(R, obj.R) && MathDefs.Equals(G, obj.G) && MathDefs.Equals(B, obj.B) && MathDefs.Equals(A, obj.A); } /// Test for equality with another color with epsilon. public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; return obj is Color && Equals((Color) obj); } /// Return as string. public new string ToString() { return $"{R} {G} {B} {A}"; } /// Return color packed to a 32-bit integer, with B component in the lowest 8 bits. Components are clamped to [0, 1] range. public uint ToUIntArgb() { uint r = (uint) MathDefs.Clamp(((int) (R * 255.0f)), 0, 255); uint g = (uint) MathDefs.Clamp(((int) (G * 255.0f)), 0, 255); uint b = (uint) MathDefs.Clamp(((int) (B * 255.0f)), 0, 255); uint a = (uint) MathDefs.Clamp(((int) (A * 255.0f)), 0, 255); return (a << 24) | (r << 16) | (g << 8) | b; } /// Return hash value. public override int GetHashCode() { return (int)ToUInt(); } /// Return hue value given greatest and least RGB component, value-wise. private float Hue(float min, float max) { float chroma = max - min; // If chroma equals zero, hue is undefined if (chroma <= MathDefs.Epsilon) return 0.0f; // Calculate and return hue if (MathDefs.Equals(G, max)) return (B + 2.0f * chroma - R) / (6.0f * chroma); else if (MathDefs.Equals(B, max)) return (4.0f * chroma - G + R) / (6.0f * chroma); else { float r = (G - B) / (6.0f * chroma); return (r < 0.0f) ? 1.0f + r : ((r >= 1.0f) ? r - 1.0f : r); } } /// Return saturation (HSV) given greatest and least RGB component, value-wise. private float SaturationHSV(float min, float max) { // Avoid div-by-zero: result undefined if (max <= MathDefs.Epsilon) return 0.0f; // Saturation equals chroma:value ratio return 1.0f - (min / max); } /// Return saturation (HSL) given greatest and least RGB component, value-wise. private float SaturationHSL(float min, float max) { // Avoid div-by-zero: result undefined if (max <= MathDefs.Epsilon || min >= 1.0f - MathDefs.Epsilon) return 0.0f; // Chroma = max - min, lightness = (max + min) * 0.5 float hl = (max + min); if (hl <= 1.0f) return (max - min) / hl; else return (min - max) / (hl - 2.0f); } /// Calculate and set RGB values. Convenience function used by FromHSV and FromHSL to avoid code duplication. private void FromHCM(float h, float c, float m) { if (h < 0.0f || h >= 1.0f) h -= (float) Math.Floor(h); float hs = h * 6.0f; float x = c * (1.0f - Math.Abs((hs % 2.0f) - 1.0f)); // Reconstruct r', g', b' from hue if (hs < 2.0f) { B = 0.0f; if (hs < 1.0f) { G = x; R = c; } else { G = c; R = x; } } else if (hs < 4.0f) { R = 0.0f; if (hs < 3.0f) { G = c; B = x; } else { G = x; B = c; } } else { G = 0.0f; if (hs < 5.0f) { R = x; B = c; } else { R = c; B = x; } } R += m; G += m; B += m; } /// Red value. float R; /// Green value. float G; /// Blue value. float B; /// Alpha value. float A; /// Opaque white color. public static readonly Color White = new Color(1.0f, 1.0f, 1.0f, 1.0f); /// Opaque gray color. public static readonly Color Gray = new Color(0.5f, 0.5f, 0.5f); /// Opaque black color. public static readonly Color Black = new Color(0.0f, 0.0f, 0.0f); /// Opaque red color. public static readonly Color Red = new Color(1.0f, 0.0f, 0.0f); /// Opaque green color. public static readonly Color Green = new Color(0.0f, 1.0f, 0.0f); /// Opaque blue color. public static readonly Color Blue = new Color(0.0f, 0.0f, 1.0f); /// Opaque cyan color. public static readonly Color Cyan = new Color(0.0f, 1.0f, 1.0f); /// Opaque magenta color. public static readonly Color Magenta = new Color(1.0f, 0.0f, 1.0f); /// Opaque yellow color. public static readonly Color Yellow = new Color(1.0f, 1.0f, 0.0f); /// Transparent color (black with no alpha). public static readonly Color TransparentBlack = new Color(0.0f, 0.0f, 0.0f, 0.0f); /// Transparent color (black with no alpha). public static readonly Color Transparent = TransparentBlack; } }
31.330922
148
0.466063
[ "MIT" ]
mostafa901/rbfx
Source/Urho3D/CSharp/Managed/Math/Color.cs
17,328
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.0 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace WindowsFormsApplication1.Properties { /// <summary> /// A strongly-typed resource class, for looking up localized strings, etc. /// </summary> // This class was auto-generated by the StronglyTypedResourceBuilder // class via a tool like ResGen or Visual Studio. // To add or remove a member, edit your .ResX file then rerun ResGen // with the /str option, or rebuild your VS project. [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] internal class Resources { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal Resources() { } /// <summary> /// Returns the cached ResourceManager instance used by this class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Resources.ResourceManager ResourceManager { get { if ((resourceMan == null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("WindowsFormsApplication1.Properties.Resources", typeof(Resources).Assembly); resourceMan = temp; } return resourceMan; } } /// <summary> /// Overrides the current thread's CurrentUICulture property for all /// resource lookups using this strongly typed resource class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } } }
39.888889
191
0.591226
[ "MIT" ]
Foxpips/ProgrammingCSharp
WindowsFormsApplication1/Properties/Resources.Designer.cs
2,874
C#
// Copyright (c) 2020 Sergio Aquilini // This code is licensed under MIT license (see LICENSE file for details) using System.Diagnostics; using System.Reflection; using System.Threading.Tasks; using Silverback.Diagnostics; using Silverback.Util; namespace Silverback.Messaging.Subscribers { internal static class MethodInvokerExtensions { public static Task<object?> InvokeWithActivityAsync( this MethodInfo methodInfo, object target, object?[] parameters, bool executeAsync) => executeAsync ? InvokeWithActivityAsync(methodInfo, target, parameters) : Task.FromResult(InvokeWithActivitySync(methodInfo, target, parameters)); public static Task<object?> InvokeWithActivityAsync( this MethodInfo methodInfo, object target, object?[] parameters) => methodInfo.ReturnsTask() ? ((Task)methodInfo.InvokeWithActivity(target, parameters)!).GetReturnValueAsync() : Task.FromResult(methodInfo.InvokeWithActivity(target, parameters)); public static object? InvokeWithActivitySync(this MethodInfo methodInfo, object target, object?[] parameters) => methodInfo.ReturnsTask() ? AsyncHelper.RunSynchronously( () => { var result = (Task)methodInfo.InvokeWithActivity(target, parameters)!; return result.GetReturnValueAsync(); }) : methodInfo.InvokeWithActivity(target, parameters); public static Task InvokeWithActivityWithoutBlockingAsync( this MethodInfo methodInfo, object target, object?[] parameters) => methodInfo.ReturnsTask() ? Task.Run(() => (Task)methodInfo.InvokeWithActivity(target, parameters)!) : Task.Run(() => methodInfo.InvokeWithActivity(target, parameters)); private static object? InvokeWithActivity(this MethodInfo methodInfo, object target, object?[] parameters) { using Activity? activity = ActivitySources.StartInvokeSubscriberActivity(methodInfo); return methodInfo.Invoke(target, parameters); } } }
41.285714
120
0.633651
[ "MIT" ]
BEagle1984/silverback
src/Silverback.Core/Messaging/Subscribers/MethodInvokerExtensions.cs
2,314
C#
namespace System.Runtime.CompilerServices { [Serializable] [AttributeUsage(AttributeTargets.Method, Inherited = false, AllowMultiple = false)] public sealed class AsyncStateMachineAttribute : StateMachineAttribute { public AsyncStateMachineAttribute(Type stateMachineType) : base(stateMachineType) { } } }
28.846154
88
0.677333
[ "MIT" ]
NETMF/llilum
Zelig/Zelig/RunTime/Framework/mscorlib/System/Runtime/CompilerServices/AsyncStateMachineAttribute.cs
377
C#
#if UNITY_EDITOR using UnityEngine; using System.Collections; using System.Collections.Generic; using System; using System.Linq; namespace Sabresaurus.SabreCSG { public class AdjacencyFilters { public interface BaseFilter { bool IsPolygonAcceptable(Polygon polygonToTest); } public class MatchMaterial : BaseFilter { Material[] acceptableMaterials; public MatchMaterial(Material[] acceptableMaterials) { this.acceptableMaterials = acceptableMaterials; } public bool IsPolygonAcceptable(Polygon polygonToTest) { if(acceptableMaterials.Contains(polygonToTest.Material)) { return true; } else { return false; } } } } } #endif
23.375
72
0.543316
[ "MIT" ]
CloudDevStudios/SabreCSG
Scripts/Geometry/AdjacencyFilters.cs
937
C#
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Text; namespace SoftJail.Data.Models { public class OfficerPrisoner { public int PrisonerId { get; set; } [Required] public Prisoner Prisoner { get; set; } public int OfficerId { get; set; } [Required] public Officer Officer { get; set; } } }
21.684211
46
0.648058
[ "MIT" ]
TodorNikolov89/SoftwareUniversity
DatabasesAdvancedEntityFrameworkFeb2019/Exam_Preparation_SoftJail/SoftJail/Data/Models/OfficerPrisoner.cs
414
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.Synapse.V20210601Preview.Outputs { /// <summary> /// The custom setup of setting environment variable. /// </summary> [OutputType] public sealed class EnvironmentVariableSetupResponse { /// <summary> /// The type of custom setup. /// Expected value is 'EnvironmentVariableSetup'. /// </summary> public readonly string Type; /// <summary> /// The name of the environment variable. /// </summary> public readonly string VariableName; /// <summary> /// The value of the environment variable. /// </summary> public readonly string VariableValue; [OutputConstructor] private EnvironmentVariableSetupResponse( string type, string variableName, string variableValue) { Type = type; VariableName = variableName; VariableValue = variableValue; } } }
27.851064
81
0.618793
[ "Apache-2.0" ]
polivbr/pulumi-azure-native
sdk/dotnet/Synapse/V20210601Preview/Outputs/EnvironmentVariableSetupResponse.cs
1,309
C#
using Microsoft.EntityFrameworkCore.Migrations; namespace ApiPeliculas.Migrations { public partial class MigrationIsumos4 : Migration { protected override void Up(MigrationBuilder migrationBuilder) { } protected override void Down(MigrationBuilder migrationBuilder) { } } }
18.833333
71
0.675516
[ "MIT" ]
edevs911/Invent
ApiPeliculas/ApiPeliculas/Data/Migrations/20200702061416_MigrationIsumos4.cs
341
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Reflection; using System.Text.Json.Serialization; using Microsoft.DotNet.RemoteExecutor; using Xunit; namespace System.Text.Json.SourceGeneration.Tests { public static partial class JsonSerializerContextTests { [Fact] public static void VariousNestingAndVisibilityLevelsAreSupported() { Assert.NotNull(PublicContext.Default); Assert.NotNull(NestedContext.Default); Assert.NotNull(NestedPublicContext.Default); Assert.NotNull(NestedPublicContext.NestedProtectedInternalClass.Default); } [ConditionalFact(typeof(RemoteExecutor), nameof(RemoteExecutor.IsSupported))] public static void Converters_AndTypeInfoCreator_NotRooted_WhenMetadataNotPresent() { RemoteExecutor.Invoke( new Action(() => { object[] objArr = new object[] { new MyStruct() }; // Metadata not generated for MyStruct without JsonSerializableAttribute. NotSupportedException ex = Assert.Throws<NotSupportedException>( () => JsonSerializer.Serialize(objArr, MetadataContext.Default.ObjectArray)); string exAsStr = ex.ToString(); Assert.Contains(typeof(MyStruct).ToString(), exAsStr); Assert.Contains("JsonSerializerOptions", exAsStr); // This test uses reflection to: // - Access JsonSerializerOptions.s_defaultSimpleConverters // - Access JsonSerializerOptions.s_defaultFactoryConverters // - Access JsonSerializerOptions._typeInfoCreationFunc // // If any of them changes, this test will need to be kept in sync. // Confirm built-in converters not set. AssertFieldNull("s_defaultSimpleConverters", optionsInstance: null); AssertFieldNull("s_defaultFactoryConverters", optionsInstance: null); // Confirm type info dynamic creator not set. AssertFieldNull("_typeInfoCreationFunc", MetadataContext.Default.Options); static void AssertFieldNull(string fieldName, JsonSerializerOptions? optionsInstance) { BindingFlags bindingFlags = BindingFlags.NonPublic | (optionsInstance == null ? BindingFlags.Static : BindingFlags.Instance); FieldInfo fieldInfo = typeof(JsonSerializerOptions).GetField(fieldName, bindingFlags); Assert.NotNull(fieldInfo); Assert.Null(fieldInfo.GetValue(optionsInstance)); } }), new RemoteInvokeOptions() { ExpectedExitCode = 0 }).Dispose(); } [Fact] public static void SupportsPositionalRecords() { Person person = new(FirstName: "Jane", LastName: "Doe"); byte[] utf8Json = JsonSerializer.SerializeToUtf8Bytes(person, PersonJsonContext.Default.Person); person = JsonSerializer.Deserialize<Person>(utf8Json, PersonJsonContext.Default.Person); Assert.Equal("Jane", person.FirstName); Assert.Equal("Doe", person.LastName); } [JsonSerializable(typeof(JsonMessage))] internal partial class NestedContext : JsonSerializerContext { } [JsonSerializable(typeof(JsonMessage))] public partial class NestedPublicContext : JsonSerializerContext { [JsonSerializable(typeof(JsonMessage))] protected internal partial class NestedProtectedInternalClass : JsonSerializerContext { } } internal record Person(string FirstName, string LastName); [JsonSourceGenerationOptions( PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase)] [JsonSerializable(typeof(Person))] internal partial class PersonJsonContext : JsonSerializerContext { } } }
44.829787
149
0.631941
[ "MIT" ]
3DCloud/runtime
src/libraries/System.Text.Json/tests/System.Text.Json.SourceGeneration.Tests/JsonSerializerContextTests.cs
4,216
C#
/******************************************************************************* * * Filename: UdpDevice.cs * * Description: * Encapsulates a UDP port * * Copyright (C) 2013 - 2017 Pico Technology Ltd. See LICENSE file for terms. * *******************************************************************************/ using System; using System.Collections.Generic; using System.Diagnostics; using System.Net; using System.Net.Sockets; using System.Threading; namespace USBPT104Protocol { /// <summary> /// Encapsulates a UDP port /// </summary> internal class UdpDevice { public IPAddress Address { get; private set; } public UInt16 Port { get; private set; } private readonly UdpClient _udpClient = new UdpClient(); private IPEndPoint _endPoint; protected UdpDevice(IPAddress address, UInt16 port) { this.Port = port; this.Address = address; // Initialise the UDP Client at the correct address this._endPoint = new IPEndPoint(address, port); this._udpClient.Connect(this._endPoint); } public void Close() { this._udpClient.Close(); } protected void Send(Byte[] data) { _ = this._udpClient.Send(data, data.Length); } protected Byte[] Receive() { IPEndPoint ipEndPoint = this._endPoint; return this._udpClient.Receive(ref ipEndPoint); } protected void BeginReceive(Action<Byte[]> receiveData) { this._udpClient.BeginReceive(this.ReceiveData, receiveData); } private void ReceiveData(IAsyncResult ar) { try { Action<Byte[]> action = ((Action<Byte[]>)ar.AsyncState); Byte[] receiveBytes = this._udpClient.EndReceive(ar, ref this._endPoint); this._udpClient.BeginReceive(this.ReceiveData, action); action.Invoke(receiveBytes); } catch (ObjectDisposedException) { Debug.WriteLine("ReceiveData: ObjectDisposedException"); } } public static IEnumerable<Tuple<Byte[], IPAddress>> BroadCast(IPAddress host_ip, Byte[] sendData) { List<Tuple<Byte[], IPAddress>> result = new List<Tuple<Byte[], IPAddress>>(); using (UdpClient client = new UdpClient()) { IPEndPoint ep = new IPEndPoint(host_ip, 23); client.Client.Bind(ep); client.Send(sendData, sendData.Length, new IPEndPoint(IPAddress.Broadcast, 23)); Thread.Sleep(500); while (client.Available > 0) { IPEndPoint ep2 = ep; result.Add(new Tuple<Byte[], IPAddress>(client.Receive(ref ep2), ep2.Address)); } client.Close(); } return result; } } }
26.721649
100
0.618827
[ "ISC" ]
Livius90/picosdk-ethernet-protocol-examples
usbpt104/c-sharp/USBPT104Protocol/UdpDevice.cs
2,594
C#
#region MIT license // // MIT license // // Copyright (c) 2007-2008 Jiri Moudry, Pascal Craponne // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // #endregion using System.Linq.Expressions; using DbLinq.Data.Linq.Sugar; using DbLinq.Data.Linq.Sugar.Expressions; namespace DbLinq.Data.Linq.Sugar.Implementation { internal class ExpressionQualifier : IExpressionQualifier { /// <summary> /// Returns Expression precedence. Higher value means lower precedence. /// http://en.csharp-online.net/ECMA-334:_14.2.1_Operator_precedence_and_associativity /// We added the Clase precedence, which is the lowest /// </summary> /// <param name="expression"></param> /// <returns></returns> public ExpressionPrecedence GetPrecedence(Expression expression) { if (expression is SpecialExpression) { var specialNodeType = ((SpecialExpression)expression).SpecialNodeType; switch (specialNodeType) // SETuse { case SpecialExpressionType.IsNull: case SpecialExpressionType.IsNotNull: return ExpressionPrecedence.Equality; case SpecialExpressionType.Concat: return ExpressionPrecedence.Additive; case SpecialExpressionType.Like: return ExpressionPrecedence.Equality; // the following are methods case SpecialExpressionType.Min: case SpecialExpressionType.Max: case SpecialExpressionType.Sum: case SpecialExpressionType.Average: case SpecialExpressionType.Count: case SpecialExpressionType.Exists: case SpecialExpressionType.StringLength: case SpecialExpressionType.ToUpper: case SpecialExpressionType.ToLower: case SpecialExpressionType.Substring: case SpecialExpressionType.Trim: case SpecialExpressionType.LTrim: case SpecialExpressionType.RTrim: case SpecialExpressionType.StringInsert: case SpecialExpressionType.Replace: case SpecialExpressionType.Remove: case SpecialExpressionType.IndexOf: case SpecialExpressionType.Year: case SpecialExpressionType.Month: case SpecialExpressionType.Day: case SpecialExpressionType.Hour: case SpecialExpressionType.Minute: case SpecialExpressionType.Second: case SpecialExpressionType.Millisecond: case SpecialExpressionType.Now: case SpecialExpressionType.Date: case SpecialExpressionType.DateDiffInMilliseconds: case SpecialExpressionType.Abs: case SpecialExpressionType.Exp: case SpecialExpressionType.Floor: case SpecialExpressionType.Ln: case SpecialExpressionType.Log: case SpecialExpressionType.Pow: case SpecialExpressionType.Round: case SpecialExpressionType.Sign: case SpecialExpressionType.Sqrt: return ExpressionPrecedence.Primary; case SpecialExpressionType.In: return ExpressionPrecedence.Equality; // not sure for this one default: throw Error.BadArgument("S0050: Unhandled SpecialExpressionType {0}", specialNodeType); } } if (expression is SelectExpression) return ExpressionPrecedence.Clause; switch (expression.NodeType) { case ExpressionType.Add: case ExpressionType.AddChecked: return ExpressionPrecedence.Additive; case ExpressionType.And: case ExpressionType.AndAlso: return ExpressionPrecedence.ConditionalAnd; case ExpressionType.ArrayLength: case ExpressionType.ArrayIndex: case ExpressionType.Call: return ExpressionPrecedence.Primary; case ExpressionType.Coalesce: return ExpressionPrecedence.NullCoalescing; case ExpressionType.Conditional: return ExpressionPrecedence.Conditional; case ExpressionType.Constant: return ExpressionPrecedence.Primary; case ExpressionType.Convert: case ExpressionType.ConvertChecked: return ExpressionPrecedence.Primary; case ExpressionType.Divide: return ExpressionPrecedence.Multiplicative; case ExpressionType.Equal: return ExpressionPrecedence.Equality; case ExpressionType.ExclusiveOr: return ExpressionPrecedence.LogicalXor; case ExpressionType.GreaterThan: case ExpressionType.GreaterThanOrEqual: return ExpressionPrecedence.RelationalAndTypeTest; case ExpressionType.Invoke: return ExpressionPrecedence.Primary; case ExpressionType.Lambda: return ExpressionPrecedence.Primary; case ExpressionType.LeftShift: return ExpressionPrecedence.Shift; case ExpressionType.LessThan: case ExpressionType.LessThanOrEqual: return ExpressionPrecedence.RelationalAndTypeTest; case ExpressionType.ListInit: case ExpressionType.MemberAccess: case ExpressionType.MemberInit: return ExpressionPrecedence.Primary; case ExpressionType.Modulo: case ExpressionType.Multiply: case ExpressionType.MultiplyChecked: return ExpressionPrecedence.Multiplicative; case ExpressionType.Negate: case ExpressionType.UnaryPlus: case ExpressionType.NegateChecked: return ExpressionPrecedence.Unary; case ExpressionType.New: case ExpressionType.NewArrayInit: case ExpressionType.NewArrayBounds: return ExpressionPrecedence.Primary; case ExpressionType.Not: return ExpressionPrecedence.Unary; case ExpressionType.NotEqual: return ExpressionPrecedence.Equality; case ExpressionType.Or: case ExpressionType.OrElse: return ExpressionPrecedence.ConditionalOr; case ExpressionType.Parameter: return ExpressionPrecedence.Primary; case ExpressionType.Power: return ExpressionPrecedence.Primary; case ExpressionType.Quote: return ExpressionPrecedence.Primary; case ExpressionType.RightShift: return ExpressionPrecedence.Shift; case ExpressionType.Subtract: case ExpressionType.SubtractChecked: return ExpressionPrecedence.Additive; case ExpressionType.TypeAs: case ExpressionType.TypeIs: return ExpressionPrecedence.RelationalAndTypeTest; } return ExpressionPrecedence.Primary; } /// <summary> /// Determines wether an expression can run in Clr or Sql /// A request is valid is it starts with Clr only, followed by Any and ends (at bottom) with Sql. /// With this, we can: /// - Find the first point cut from Clr to Any /// - Find the second point cut from Any to Sql /// Select a strategy to load more or less the Clr or Sql engine /// This is used only for SELECT clause /// </summary> /// <param name="expression"></param> /// <returns></returns> public ExpressionTier GetTier(Expression expression) { if (expression is GroupExpression) return ExpressionTier.Clr; if (expression is SelectExpression) return ExpressionTier.Sql; if (expression is ColumnExpression) return ExpressionTier.Sql; if (expression is TableExpression) return ExpressionTier.Sql; if (expression is EntitySetExpression) return ExpressionTier.Sql; if (expression is InputParameterExpression) return ExpressionTier.Sql; if (expression is SpecialExpression) { var specialExpressionType = ((SpecialExpression)expression).SpecialNodeType; switch (specialExpressionType) // SETuse { case SpecialExpressionType.IsNull: case SpecialExpressionType.IsNotNull: case SpecialExpressionType.Concat: case SpecialExpressionType.StringLength: case SpecialExpressionType.ToUpper: case SpecialExpressionType.ToLower: case SpecialExpressionType.Substring: case SpecialExpressionType.Trim: case SpecialExpressionType.LTrim: case SpecialExpressionType.RTrim: case SpecialExpressionType.StringInsert: case SpecialExpressionType.Replace: case SpecialExpressionType.Remove: case SpecialExpressionType.IndexOf: case SpecialExpressionType.Year: case SpecialExpressionType.Month: case SpecialExpressionType.Day: case SpecialExpressionType.Hour: case SpecialExpressionType.Minute: case SpecialExpressionType.Second: case SpecialExpressionType.Millisecond: case SpecialExpressionType.Now: case SpecialExpressionType.Date: case SpecialExpressionType.DateDiffInMilliseconds: case SpecialExpressionType.Abs: case SpecialExpressionType.Exp: case SpecialExpressionType.Floor: case SpecialExpressionType.Ln: case SpecialExpressionType.Log: case SpecialExpressionType.Pow: case SpecialExpressionType.Round: case SpecialExpressionType.Sign: case SpecialExpressionType.Sqrt: return ExpressionTier.Any; case SpecialExpressionType.Like: case SpecialExpressionType.Min: case SpecialExpressionType.Max: case SpecialExpressionType.Sum: case SpecialExpressionType.Average: case SpecialExpressionType.Count: case SpecialExpressionType.In: return ExpressionTier.Sql; // don't tell anyone, but we can do it on both tiers, anyway this is significantly faster/efficient in SQL anyway default: throw Error.BadArgument("S0157: Unhandled node type {0}", specialExpressionType); } } switch (expression.NodeType) { case ExpressionType.ArrayLength: case ExpressionType.ArrayIndex: case ExpressionType.Call: case ExpressionType.Convert: case ExpressionType.ConvertChecked: case ExpressionType.Invoke: case ExpressionType.Lambda: case ExpressionType.ListInit: case ExpressionType.MemberAccess: case ExpressionType.MemberInit: case ExpressionType.New: case ExpressionType.NewArrayInit: case ExpressionType.NewArrayBounds: case ExpressionType.Parameter: case ExpressionType.SubtractChecked: case ExpressionType.TypeAs: case ExpressionType.TypeIs: return ExpressionTier.Clr; default: return ExpressionTier.Any; } } } }
46.348592
160
0.620299
[ "MIT" ]
RWooters/dblinq2007
src/Backup/DbLinq/Data/Linq/Sugar/Implementation/ExpressionQualifier(2).cs
13,163
C#
using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Reflection; using System.Text; using UnityEditor.Timeline; namespace UnityEngine.Timeline { [Serializable] class DirectorNamedColor : ScriptableObject { [SerializeField] public Color colorPlayhead; [SerializeField] public Color colorSelection; [SerializeField] public Color colorEndmarker; [SerializeField] public Color colorGroup; [SerializeField] public Color colorGroupTrackBackground; [SerializeField] public Color colorAnimation; [SerializeField] public Color colorAnimationRecorded; [SerializeField] public Color colorAudio; [SerializeField] public Color colorAudioWaveform; [SerializeField] public Color colorActivation; [SerializeField] public Color colorDropTarget; [SerializeField] public Color colorClipFont; [SerializeField] public Color colorInvalidClipOverlay; [SerializeField] public Color colorClipBlendYin; [SerializeField] public Color colorClipBlendYang; [SerializeField] public Color colorClipBlendLines; [SerializeField] public Color colorTrackBackground; [SerializeField] public Color colorTrackHeaderBackground; [SerializeField] public Color colorTrackDarken; [SerializeField] public Color colorTrackBackgroundRecording; [SerializeField] public Color colorInfiniteTrackBackgroundRecording; [SerializeField] public Color colorTrackBackgroundSelected; [SerializeField] public Color colorTrackFont; [SerializeField] public Color colorClipUnion; [SerializeField] public Color colorTopOutline3; [SerializeField] public Color colorDurationLine; [SerializeField] public Color colorRange; [SerializeField] public Color colorSequenceBackground; [SerializeField] public Color colorTooltipBackground; [SerializeField] public Color colorInfiniteClipLine; [SerializeField] public Color colorDefaultTrackDrawer; [SerializeField] public Color colorDuration = new Color(0.66f, 0.66f, 0.66f, 1.0f); [SerializeField] public Color colorRecordingClipOutline = new Color(1, 0, 0, 0.9f); [SerializeField] public Color colorAnimEditorBinding = new Color(54.0f / 255.0f, 54.0f / 255.0f, 54.0f / 255.0f); [SerializeField] public Color colorTimelineBackground = new Color(0.2f, 0.2f, 0.2f, 1.0f); [SerializeField] public Color colorLockTextBG = Color.red; [SerializeField] public Color colorInlineCurveVerticalLines = new Color(1.0f, 1.0f, 1.0f, 0.2f); [SerializeField] public Color colorInlineCurveOutOfRangeOverlay = new Color(0.0f, 0.0f, 0.0f, 0.5f); [SerializeField] public Color colorInlineCurvesBackground; [SerializeField] public Color markerDrawerBackgroundColor = new Color(0.4f, 0.4f, 0.4f , 1.0f); [SerializeField] public Color markerHeaderDrawerBackgroundColor = new Color(0.5f, 0.5f, 0.5f , 1.0f); [SerializeField] public Color colorControl = new Color(0.2313f, 0.6353f, 0.5843f, 1.0f); [SerializeField] public Color colorSubSequenceBackground = new Color(0.1294118f, 0.1764706f, 0.1764706f, 1.0f); [SerializeField] public Color colorTrackSubSequenceBackground = new Color(0.1607843f, 0.2156863f, 0.2156863f, 1.0f); [SerializeField] public Color colorTrackSubSequenceBackgroundSelected = new Color(0.0726923f, 0.252f, 0.252f, 1.0f); [SerializeField] public Color colorSubSequenceOverlay = new Color(0.02f, 0.025f, 0.025f, 0.30f); [SerializeField] public Color colorSubSequenceDurationLine = new Color(0.0f, 1.0f, 0.88f, 0.46f); public void SetDefault() { colorPlayhead = DirectorStyles.Instance.timeCursor.normal.textColor; colorSelection = DirectorStyles.Instance.selectedStyle.normal.textColor; colorEndmarker = DirectorStyles.Instance.endmarker.normal.textColor; colorGroup = new Color(0.094f, 0.357f, 0.384f, 0.310f); colorGroupTrackBackground = new Color(0f, 0f, 0f, 1f); colorAnimation = new Color(0.3f, 0.39f, 0.46f, 1.0f); colorAnimationRecorded = new Color(colorAnimation.r * 0.75f, colorAnimation.g * 0.75f, colorAnimation.b * 0.75f, 1.0f); colorAudio = new Color(1f, 0.635f, 0f); colorAudioWaveform = new Color(0.129f, 0.164f, 0.254f); colorActivation = Color.green; colorDropTarget = new Color(0.514f, 0.627f, 0.827f); colorClipFont = DirectorStyles.Instance.fontClip.normal.textColor; colorTrackBackground = new Color(0.2f, 0.2f, 0.2f, 1.0f); colorTrackBackgroundSelected = new Color(1f, 1f, 1f, 0.33f); colorInlineCurvesBackground = new Color(0.25f, 0.25f, 0.25f, 0.6f); colorTrackFont = DirectorStyles.Instance.trackHeaderFont.normal.textColor; colorClipUnion = new Color(0.72f, 0.72f, 0.72f, 0.8f); colorTopOutline3 = new Color(0.274f, 0.274f, 0.274f, 1.0f); colorDurationLine = new Color(33.0f / 255.0f, 109.0f / 255.0f, 120.0f / 255.0f); colorRange = new Color(0.733f, 0.733f, 0.733f, 0.70f); colorSequenceBackground = new Color(0.16f, 0.16f, 0.16f, 1.0f); colorTooltipBackground = new Color(29.0f / 255.0f, 32.0f / 255.0f, 33.0f / 255.0f); colorInfiniteClipLine = new Color(72.0f / 255.0f, 78.0f / 255.0f, 82.0f / 255.0f); colorTrackBackgroundRecording = new Color(1, 0, 0, 0.1f); colorTrackDarken = new Color(0.0f, 0.0f, 0.0f, 0.4f); colorTrackHeaderBackground = new Color(51.0f / 255.0f, 51.0f / 255.0f, 51.0f / 255.0f, 1.0f); colorDefaultTrackDrawer = new Color(218.0f / 255.0f, 220.0f / 255.0f, 222.0f / 255.0f); colorRecordingClipOutline = new Color(1, 0, 0, 0.9f); colorInlineCurveVerticalLines = new Color(1.0f, 1.0f, 1.0f, 0.2f); colorInlineCurveOutOfRangeOverlay = new Color(0.0f, 0.0f, 0.0f, 0.5f); } public void ToText(string path) { StringBuilder builder = new StringBuilder(); var fields = GetType().GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly); foreach (var f in fields) { if (f.FieldType != typeof(Color)) continue; Color c = (Color)f.GetValue(this); builder.AppendLine(f.Name + "," + c); } string filePath = Application.dataPath + "/Editor Default Resources/" + path; File.WriteAllText(filePath, builder.ToString()); } public void FromText(string text) { // parse to a map string[] lines = text.Split(new[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries); var map = new Dictionary<string, Color>(); foreach (var line in lines) { var pieces = line.Replace("RGBA(", "").Replace(")", "").Split(','); if (pieces.Length == 5) { string name = pieces[0].Trim(); Color c = Color.black; bool b = ParseFloat(pieces[1], out c.r) && ParseFloat(pieces[2], out c.g) && ParseFloat(pieces[3], out c.b) && ParseFloat(pieces[4], out c.a); if (b) { map[name] = c; } } } var fields = typeof(DirectorNamedColor).GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly); foreach (var f in fields) { if (f.FieldType != typeof(Color)) continue; Color c = Color.black; if (map.TryGetValue(f.Name, out c)) { f.SetValue(this, c); } } } // Case 938534 - Timeline window has white background when running on .NET 4.6 depending on the set system language // Make sure we're using an invariant culture so "0.35" is parsed as 0.35 and not 35 static bool ParseFloat(string str, out float f) { return float.TryParse(str, NumberStyles.Any, CultureInfo.InvariantCulture, out f); } public static DirectorNamedColor CreateAndLoadFromText(string text) { DirectorNamedColor instance = CreateInstance<DirectorNamedColor>(); instance.FromText(text); return instance; } } }
34.487273
136
0.581717
[ "Apache-2.0" ]
yeliheng/BasketballVR
Library/PackageCache/com.unity.timeline@1.1.0/Editor/DirectorNamedColor.cs
9,484
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // ANTLR Version: 4.6 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ // Generated from Query.g by ANTLR 4.6 // Unreachable code detected #pragma warning disable 0162 // The variable '...' is assigned but its value is never used #pragma warning disable 0219 // Missing XML comment for publicly visible type or member '...' #pragma warning disable 1591 // Ambiguous reference in cref attribute #pragma warning disable 419 namespace Autumn.Mvc.Models.Queries { using System; using System.Text; using System.Diagnostics; using System.Collections.Generic; using Antlr4.Runtime; using Antlr4.Runtime.Atn; using Antlr4.Runtime.Misc; using Antlr4.Runtime.Tree; using DFA = Antlr4.Runtime.Dfa.DFA; [System.CodeDom.Compiler.GeneratedCode("ANTLR", "4.6")] [System.CLSCompliant(false)] public partial class QueryParser : Parser { protected static DFA[] decisionToDFA; protected static PredictionContextCache sharedContextCache = new PredictionContextCache(); public const int T__0=1, T__1=2, T__2=3, T__3=4, T__4=5, T__5=6, T__6=7, T__7=8, T__8=9, T__9=10, T__10=11, T__11=12, T__12=13, T__13=14, T__14=15, T__15=16, LETTER=17, ANY=18; public const int RULE_selector = 0, RULE_eval = 1, RULE_or = 2, RULE_and = 3, RULE_constraint = 4, RULE_group = 5, RULE_comparison = 6, RULE_comparator = 7, RULE_comp_fiql = 8, RULE_comp_alt = 9, RULE_reserved = 10, RULE_single_quote = 11, RULE_double_quote = 12, RULE_arguments = 13, RULE_value = 14; public static readonly string[] ruleNames = { "selector", "eval", "or", "and", "constraint", "group", "comparison", "comparator", "comp_fiql", "comp_alt", "reserved", "single_quote", "double_quote", "arguments", "value" }; private static readonly string[] _LiteralNames = { null, "'('", "')'", "';'", "','", "'='", "'<'", "'>'", "' '", "'!'", "'''", "'\"'", "'-'", "'\\''", "'\\\"'", "'{'", "'}'" }; private static readonly string[] _SymbolicNames = { null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, "LETTER", "ANY" }; public static readonly IVocabulary DefaultVocabulary = new Vocabulary(_LiteralNames, _SymbolicNames); [NotNull] public override IVocabulary Vocabulary { get { return DefaultVocabulary; } } public override string GrammarFileName { get { return "Query.g"; } } public override string[] RuleNames { get { return ruleNames; } } public override string SerializedAtn { get { return _serializedATN; } } static QueryParser() { decisionToDFA = new DFA[_ATN.NumberOfDecisions]; for (int i = 0; i < _ATN.NumberOfDecisions; i++) { decisionToDFA[i] = new DFA(_ATN.GetDecisionState(i), i); } } public QueryParser(ITokenStream input) : base(input) { Interpreter = new ParserATNSimulator(this, _ATN, decisionToDFA, sharedContextCache); } public partial class SelectorContext : ParserRuleContext { public SelectorContext(ParserRuleContext parent, int invokingState) : base(parent, invokingState) { } public override int RuleIndex { get { return RULE_selector; } } public override void EnterRule(IParseTreeListener listener) { IQueryListener typedListener = listener as IQueryListener; if (typedListener != null) typedListener.EnterSelector(this); } public override void ExitRule(IParseTreeListener listener) { IQueryListener typedListener = listener as IQueryListener; if (typedListener != null) typedListener.ExitSelector(this); } public override TResult Accept<TResult>(IParseTreeVisitor<TResult> visitor) { IQueryVisitor<TResult> typedVisitor = visitor as IQueryVisitor<TResult>; if (typedVisitor != null) return typedVisitor.VisitSelector(this); else return visitor.VisitChildren(this); } } [RuleVersion(0)] public SelectorContext selector() { SelectorContext _localctx = new SelectorContext(Context, State); EnterRule(_localctx, 0, RULE_selector); int _la; try { EnterOuterAlt(_localctx, 1); { State = 31; ErrorHandler.Sync(this); _la = TokenStream.LA(1); do { { { State = 30; _la = TokenStream.LA(1); if ( _la <= 0 || ((((_la) & ~0x3f) == 0 && ((1L << _la) & ((1L << T__0) | (1L << T__1) | (1L << T__2) | (1L << T__3) | (1L << T__4) | (1L << T__5) | (1L << T__6) | (1L << T__7) | (1L << T__8) | (1L << T__9) | (1L << T__10))) != 0)) ) { ErrorHandler.RecoverInline(this); } else { ErrorHandler.ReportMatch(this); Consume(); } } } State = 33; ErrorHandler.Sync(this); _la = TokenStream.LA(1); } while ( (((_la) & ~0x3f) == 0 && ((1L << _la) & ((1L << T__11) | (1L << T__12) | (1L << T__13) | (1L << T__14) | (1L << T__15) | (1L << LETTER) | (1L << ANY))) != 0) ); } } catch (RecognitionException re) { _localctx.exception = re; ErrorHandler.ReportError(this, re); ErrorHandler.Recover(this, re); } finally { ExitRule(); } return _localctx; } public partial class EvalContext : ParserRuleContext { public OrContext or() { return GetRuleContext<OrContext>(0); } public ITerminalNode Eof() { return GetToken(QueryParser.Eof, 0); } public EvalContext(ParserRuleContext parent, int invokingState) : base(parent, invokingState) { } public override int RuleIndex { get { return RULE_eval; } } public override void EnterRule(IParseTreeListener listener) { IQueryListener typedListener = listener as IQueryListener; if (typedListener != null) typedListener.EnterEval(this); } public override void ExitRule(IParseTreeListener listener) { IQueryListener typedListener = listener as IQueryListener; if (typedListener != null) typedListener.ExitEval(this); } public override TResult Accept<TResult>(IParseTreeVisitor<TResult> visitor) { IQueryVisitor<TResult> typedVisitor = visitor as IQueryVisitor<TResult>; if (typedVisitor != null) return typedVisitor.VisitEval(this); else return visitor.VisitChildren(this); } } [RuleVersion(0)] public EvalContext eval() { EvalContext _localctx = new EvalContext(Context, State); EnterRule(_localctx, 2, RULE_eval); try { EnterOuterAlt(_localctx, 1); { State = 35; or(); State = 36; Match(Eof); } } catch (RecognitionException re) { _localctx.exception = re; ErrorHandler.ReportError(this, re); ErrorHandler.Recover(this, re); } finally { ExitRule(); } return _localctx; } public partial class OrContext : ParserRuleContext { public AndContext[] and() { return GetRuleContexts<AndContext>(); } public AndContext and(int i) { return GetRuleContext<AndContext>(i); } public OrContext(ParserRuleContext parent, int invokingState) : base(parent, invokingState) { } public override int RuleIndex { get { return RULE_or; } } public override void EnterRule(IParseTreeListener listener) { IQueryListener typedListener = listener as IQueryListener; if (typedListener != null) typedListener.EnterOr(this); } public override void ExitRule(IParseTreeListener listener) { IQueryListener typedListener = listener as IQueryListener; if (typedListener != null) typedListener.ExitOr(this); } public override TResult Accept<TResult>(IParseTreeVisitor<TResult> visitor) { IQueryVisitor<TResult> typedVisitor = visitor as IQueryVisitor<TResult>; if (typedVisitor != null) return typedVisitor.VisitOr(this); else return visitor.VisitChildren(this); } } [RuleVersion(0)] public OrContext or() { OrContext _localctx = new OrContext(Context, State); EnterRule(_localctx, 4, RULE_or); int _la; try { EnterOuterAlt(_localctx, 1); { State = 38; and(); State = 43; ErrorHandler.Sync(this); _la = TokenStream.LA(1); while (_la==T__3) { { { State = 39; Match(T__3); State = 40; and(); } } State = 45; ErrorHandler.Sync(this); _la = TokenStream.LA(1); } } } catch (RecognitionException re) { _localctx.exception = re; ErrorHandler.ReportError(this, re); ErrorHandler.Recover(this, re); } finally { ExitRule(); } return _localctx; } public partial class AndContext : ParserRuleContext { public ConstraintContext[] constraint() { return GetRuleContexts<ConstraintContext>(); } public ConstraintContext constraint(int i) { return GetRuleContext<ConstraintContext>(i); } public AndContext(ParserRuleContext parent, int invokingState) : base(parent, invokingState) { } public override int RuleIndex { get { return RULE_and; } } public override void EnterRule(IParseTreeListener listener) { IQueryListener typedListener = listener as IQueryListener; if (typedListener != null) typedListener.EnterAnd(this); } public override void ExitRule(IParseTreeListener listener) { IQueryListener typedListener = listener as IQueryListener; if (typedListener != null) typedListener.ExitAnd(this); } public override TResult Accept<TResult>(IParseTreeVisitor<TResult> visitor) { IQueryVisitor<TResult> typedVisitor = visitor as IQueryVisitor<TResult>; if (typedVisitor != null) return typedVisitor.VisitAnd(this); else return visitor.VisitChildren(this); } } [RuleVersion(0)] public AndContext and() { AndContext _localctx = new AndContext(Context, State); EnterRule(_localctx, 6, RULE_and); int _la; try { EnterOuterAlt(_localctx, 1); { State = 46; constraint(); State = 51; ErrorHandler.Sync(this); _la = TokenStream.LA(1); while (_la==T__2) { { { State = 47; Match(T__2); State = 48; constraint(); } } State = 53; ErrorHandler.Sync(this); _la = TokenStream.LA(1); } } } catch (RecognitionException re) { _localctx.exception = re; ErrorHandler.ReportError(this, re); ErrorHandler.Recover(this, re); } finally { ExitRule(); } return _localctx; } public partial class ConstraintContext : ParserRuleContext { public GroupContext group() { return GetRuleContext<GroupContext>(0); } public ComparisonContext comparison() { return GetRuleContext<ComparisonContext>(0); } public ConstraintContext(ParserRuleContext parent, int invokingState) : base(parent, invokingState) { } public override int RuleIndex { get { return RULE_constraint; } } public override void EnterRule(IParseTreeListener listener) { IQueryListener typedListener = listener as IQueryListener; if (typedListener != null) typedListener.EnterConstraint(this); } public override void ExitRule(IParseTreeListener listener) { IQueryListener typedListener = listener as IQueryListener; if (typedListener != null) typedListener.ExitConstraint(this); } public override TResult Accept<TResult>(IParseTreeVisitor<TResult> visitor) { IQueryVisitor<TResult> typedVisitor = visitor as IQueryVisitor<TResult>; if (typedVisitor != null) return typedVisitor.VisitConstraint(this); else return visitor.VisitChildren(this); } } [RuleVersion(0)] public ConstraintContext constraint() { ConstraintContext _localctx = new ConstraintContext(Context, State); EnterRule(_localctx, 8, RULE_constraint); try { State = 56; ErrorHandler.Sync(this); switch (TokenStream.LA(1)) { case T__0: EnterOuterAlt(_localctx, 1); { State = 54; group(); } break; case T__11: case T__12: case T__13: case T__14: case T__15: case LETTER: case ANY: EnterOuterAlt(_localctx, 2); { State = 55; comparison(); } break; default: throw new NoViableAltException(this); } } catch (RecognitionException re) { _localctx.exception = re; ErrorHandler.ReportError(this, re); ErrorHandler.Recover(this, re); } finally { ExitRule(); } return _localctx; } public partial class GroupContext : ParserRuleContext { public OrContext or() { return GetRuleContext<OrContext>(0); } public GroupContext(ParserRuleContext parent, int invokingState) : base(parent, invokingState) { } public override int RuleIndex { get { return RULE_group; } } public override void EnterRule(IParseTreeListener listener) { IQueryListener typedListener = listener as IQueryListener; if (typedListener != null) typedListener.EnterGroup(this); } public override void ExitRule(IParseTreeListener listener) { IQueryListener typedListener = listener as IQueryListener; if (typedListener != null) typedListener.ExitGroup(this); } public override TResult Accept<TResult>(IParseTreeVisitor<TResult> visitor) { IQueryVisitor<TResult> typedVisitor = visitor as IQueryVisitor<TResult>; if (typedVisitor != null) return typedVisitor.VisitGroup(this); else return visitor.VisitChildren(this); } } [RuleVersion(0)] public GroupContext group() { GroupContext _localctx = new GroupContext(Context, State); EnterRule(_localctx, 10, RULE_group); try { EnterOuterAlt(_localctx, 1); { State = 58; Match(T__0); State = 59; or(); State = 60; Match(T__1); } } catch (RecognitionException re) { _localctx.exception = re; ErrorHandler.ReportError(this, re); ErrorHandler.Recover(this, re); } finally { ExitRule(); } return _localctx; } public partial class ComparisonContext : ParserRuleContext { public SelectorContext selector() { return GetRuleContext<SelectorContext>(0); } public ComparatorContext comparator() { return GetRuleContext<ComparatorContext>(0); } public ArgumentsContext arguments() { return GetRuleContext<ArgumentsContext>(0); } public ComparisonContext(ParserRuleContext parent, int invokingState) : base(parent, invokingState) { } public override int RuleIndex { get { return RULE_comparison; } } public override void EnterRule(IParseTreeListener listener) { IQueryListener typedListener = listener as IQueryListener; if (typedListener != null) typedListener.EnterComparison(this); } public override void ExitRule(IParseTreeListener listener) { IQueryListener typedListener = listener as IQueryListener; if (typedListener != null) typedListener.ExitComparison(this); } public override TResult Accept<TResult>(IParseTreeVisitor<TResult> visitor) { IQueryVisitor<TResult> typedVisitor = visitor as IQueryVisitor<TResult>; if (typedVisitor != null) return typedVisitor.VisitComparison(this); else return visitor.VisitChildren(this); } } [RuleVersion(0)] public ComparisonContext comparison() { ComparisonContext _localctx = new ComparisonContext(Context, State); EnterRule(_localctx, 12, RULE_comparison); try { EnterOuterAlt(_localctx, 1); { State = 62; selector(); State = 63; comparator(); State = 64; arguments(); } } catch (RecognitionException re) { _localctx.exception = re; ErrorHandler.ReportError(this, re); ErrorHandler.Recover(this, re); } finally { ExitRule(); } return _localctx; } public partial class ComparatorContext : ParserRuleContext { public Comp_fiqlContext comp_fiql() { return GetRuleContext<Comp_fiqlContext>(0); } public Comp_altContext comp_alt() { return GetRuleContext<Comp_altContext>(0); } public ComparatorContext(ParserRuleContext parent, int invokingState) : base(parent, invokingState) { } public override int RuleIndex { get { return RULE_comparator; } } public override void EnterRule(IParseTreeListener listener) { IQueryListener typedListener = listener as IQueryListener; if (typedListener != null) typedListener.EnterComparator(this); } public override void ExitRule(IParseTreeListener listener) { IQueryListener typedListener = listener as IQueryListener; if (typedListener != null) typedListener.ExitComparator(this); } public override TResult Accept<TResult>(IParseTreeVisitor<TResult> visitor) { IQueryVisitor<TResult> typedVisitor = visitor as IQueryVisitor<TResult>; if (typedVisitor != null) return typedVisitor.VisitComparator(this); else return visitor.VisitChildren(this); } } [RuleVersion(0)] public ComparatorContext comparator() { ComparatorContext _localctx = new ComparatorContext(Context, State); EnterRule(_localctx, 14, RULE_comparator); try { State = 68; ErrorHandler.Sync(this); switch (TokenStream.LA(1)) { case T__4: case T__8: EnterOuterAlt(_localctx, 1); { State = 66; comp_fiql(); } break; case T__5: case T__6: EnterOuterAlt(_localctx, 2); { State = 67; comp_alt(); } break; default: throw new NoViableAltException(this); } } catch (RecognitionException re) { _localctx.exception = re; ErrorHandler.ReportError(this, re); ErrorHandler.Recover(this, re); } finally { ExitRule(); } return _localctx; } public partial class Comp_fiqlContext : ParserRuleContext { public ITerminalNode[] LETTER() { return GetTokens(QueryParser.LETTER); } public ITerminalNode LETTER(int i) { return GetToken(QueryParser.LETTER, i); } public Comp_fiqlContext(ParserRuleContext parent, int invokingState) : base(parent, invokingState) { } public override int RuleIndex { get { return RULE_comp_fiql; } } public override void EnterRule(IParseTreeListener listener) { IQueryListener typedListener = listener as IQueryListener; if (typedListener != null) typedListener.EnterComp_fiql(this); } public override void ExitRule(IParseTreeListener listener) { IQueryListener typedListener = listener as IQueryListener; if (typedListener != null) typedListener.ExitComp_fiql(this); } public override TResult Accept<TResult>(IParseTreeVisitor<TResult> visitor) { IQueryVisitor<TResult> typedVisitor = visitor as IQueryVisitor<TResult>; if (typedVisitor != null) return typedVisitor.VisitComp_fiql(this); else return visitor.VisitChildren(this); } } [RuleVersion(0)] public Comp_fiqlContext comp_fiql() { Comp_fiqlContext _localctx = new Comp_fiqlContext(Context, State); EnterRule(_localctx, 16, RULE_comp_fiql); int _la; try { EnterOuterAlt(_localctx, 1); { State = 70; _la = TokenStream.LA(1); if ( !(_la==T__4 || _la==T__8) ) { ErrorHandler.RecoverInline(this); } else { ErrorHandler.ReportMatch(this); Consume(); } State = 74; ErrorHandler.Sync(this); _la = TokenStream.LA(1); while (_la==T__11 || _la==LETTER) { { { State = 71; _la = TokenStream.LA(1); if ( !(_la==T__11 || _la==LETTER) ) { ErrorHandler.RecoverInline(this); } else { ErrorHandler.ReportMatch(this); Consume(); } } } State = 76; ErrorHandler.Sync(this); _la = TokenStream.LA(1); } State = 77; Match(T__4); } } catch (RecognitionException re) { _localctx.exception = re; ErrorHandler.ReportError(this, re); ErrorHandler.Recover(this, re); } finally { ExitRule(); } return _localctx; } public partial class Comp_altContext : ParserRuleContext { public Comp_altContext(ParserRuleContext parent, int invokingState) : base(parent, invokingState) { } public override int RuleIndex { get { return RULE_comp_alt; } } public override void EnterRule(IParseTreeListener listener) { IQueryListener typedListener = listener as IQueryListener; if (typedListener != null) typedListener.EnterComp_alt(this); } public override void ExitRule(IParseTreeListener listener) { IQueryListener typedListener = listener as IQueryListener; if (typedListener != null) typedListener.ExitComp_alt(this); } public override TResult Accept<TResult>(IParseTreeVisitor<TResult> visitor) { IQueryVisitor<TResult> typedVisitor = visitor as IQueryVisitor<TResult>; if (typedVisitor != null) return typedVisitor.VisitComp_alt(this); else return visitor.VisitChildren(this); } } [RuleVersion(0)] public Comp_altContext comp_alt() { Comp_altContext _localctx = new Comp_altContext(Context, State); EnterRule(_localctx, 18, RULE_comp_alt); int _la; try { EnterOuterAlt(_localctx, 1); { State = 79; _la = TokenStream.LA(1); if ( !(_la==T__5 || _la==T__6) ) { ErrorHandler.RecoverInline(this); } else { ErrorHandler.ReportMatch(this); Consume(); } State = 81; ErrorHandler.Sync(this); _la = TokenStream.LA(1); if (_la==T__4) { { State = 80; Match(T__4); } } } } catch (RecognitionException re) { _localctx.exception = re; ErrorHandler.ReportError(this, re); ErrorHandler.Recover(this, re); } finally { ExitRule(); } return _localctx; } public partial class ReservedContext : ParserRuleContext { public ReservedContext(ParserRuleContext parent, int invokingState) : base(parent, invokingState) { } public override int RuleIndex { get { return RULE_reserved; } } public override void EnterRule(IParseTreeListener listener) { IQueryListener typedListener = listener as IQueryListener; if (typedListener != null) typedListener.EnterReserved(this); } public override void ExitRule(IParseTreeListener listener) { IQueryListener typedListener = listener as IQueryListener; if (typedListener != null) typedListener.ExitReserved(this); } public override TResult Accept<TResult>(IParseTreeVisitor<TResult> visitor) { IQueryVisitor<TResult> typedVisitor = visitor as IQueryVisitor<TResult>; if (typedVisitor != null) return typedVisitor.VisitReserved(this); else return visitor.VisitChildren(this); } } [RuleVersion(0)] public ReservedContext reserved() { ReservedContext _localctx = new ReservedContext(Context, State); EnterRule(_localctx, 20, RULE_reserved); int _la; try { EnterOuterAlt(_localctx, 1); { State = 83; _la = TokenStream.LA(1); if ( !((((_la) & ~0x3f) == 0 && ((1L << _la) & ((1L << T__0) | (1L << T__1) | (1L << T__2) | (1L << T__3) | (1L << T__4) | (1L << T__5) | (1L << T__6) | (1L << T__7) | (1L << T__8))) != 0)) ) { ErrorHandler.RecoverInline(this); } else { ErrorHandler.ReportMatch(this); Consume(); } } } catch (RecognitionException re) { _localctx.exception = re; ErrorHandler.ReportError(this, re); ErrorHandler.Recover(this, re); } finally { ExitRule(); } return _localctx; } public partial class Single_quoteContext : ParserRuleContext { public Single_quoteContext(ParserRuleContext parent, int invokingState) : base(parent, invokingState) { } public override int RuleIndex { get { return RULE_single_quote; } } public override void EnterRule(IParseTreeListener listener) { IQueryListener typedListener = listener as IQueryListener; if (typedListener != null) typedListener.EnterSingle_quote(this); } public override void ExitRule(IParseTreeListener listener) { IQueryListener typedListener = listener as IQueryListener; if (typedListener != null) typedListener.ExitSingle_quote(this); } public override TResult Accept<TResult>(IParseTreeVisitor<TResult> visitor) { IQueryVisitor<TResult> typedVisitor = visitor as IQueryVisitor<TResult>; if (typedVisitor != null) return typedVisitor.VisitSingle_quote(this); else return visitor.VisitChildren(this); } } [RuleVersion(0)] public Single_quoteContext single_quote() { Single_quoteContext _localctx = new Single_quoteContext(Context, State); EnterRule(_localctx, 22, RULE_single_quote); int _la; try { EnterOuterAlt(_localctx, 1); { State = 85; Match(T__9); State = 90; ErrorHandler.Sync(this); _la = TokenStream.LA(1); while ((((_la) & ~0x3f) == 0 && ((1L << _la) & ((1L << T__0) | (1L << T__1) | (1L << T__2) | (1L << T__3) | (1L << T__4) | (1L << T__5) | (1L << T__6) | (1L << T__7) | (1L << T__8) | (1L << T__10) | (1L << T__11) | (1L << T__12) | (1L << T__13) | (1L << T__14) | (1L << T__15) | (1L << LETTER) | (1L << ANY))) != 0)) { { State = 88; ErrorHandler.Sync(this); switch ( Interpreter.AdaptivePredict(TokenStream,7,Context) ) { case 1: { State = 86; Match(T__12); } break; case 2: { State = 87; _la = TokenStream.LA(1); if ( _la <= 0 || (_la==T__9) ) { ErrorHandler.RecoverInline(this); } else { ErrorHandler.ReportMatch(this); Consume(); } } break; } } State = 92; ErrorHandler.Sync(this); _la = TokenStream.LA(1); } State = 93; Match(T__9); } } catch (RecognitionException re) { _localctx.exception = re; ErrorHandler.ReportError(this, re); ErrorHandler.Recover(this, re); } finally { ExitRule(); } return _localctx; } public partial class Double_quoteContext : ParserRuleContext { public Double_quoteContext(ParserRuleContext parent, int invokingState) : base(parent, invokingState) { } public override int RuleIndex { get { return RULE_double_quote; } } public override void EnterRule(IParseTreeListener listener) { IQueryListener typedListener = listener as IQueryListener; if (typedListener != null) typedListener.EnterDouble_quote(this); } public override void ExitRule(IParseTreeListener listener) { IQueryListener typedListener = listener as IQueryListener; if (typedListener != null) typedListener.ExitDouble_quote(this); } public override TResult Accept<TResult>(IParseTreeVisitor<TResult> visitor) { IQueryVisitor<TResult> typedVisitor = visitor as IQueryVisitor<TResult>; if (typedVisitor != null) return typedVisitor.VisitDouble_quote(this); else return visitor.VisitChildren(this); } } [RuleVersion(0)] public Double_quoteContext double_quote() { Double_quoteContext _localctx = new Double_quoteContext(Context, State); EnterRule(_localctx, 24, RULE_double_quote); int _la; try { EnterOuterAlt(_localctx, 1); { State = 95; Match(T__10); State = 100; ErrorHandler.Sync(this); _la = TokenStream.LA(1); while ((((_la) & ~0x3f) == 0 && ((1L << _la) & ((1L << T__0) | (1L << T__1) | (1L << T__2) | (1L << T__3) | (1L << T__4) | (1L << T__5) | (1L << T__6) | (1L << T__7) | (1L << T__8) | (1L << T__9) | (1L << T__11) | (1L << T__12) | (1L << T__13) | (1L << T__14) | (1L << T__15) | (1L << LETTER) | (1L << ANY))) != 0)) { { State = 98; ErrorHandler.Sync(this); switch ( Interpreter.AdaptivePredict(TokenStream,9,Context) ) { case 1: { State = 96; Match(T__13); } break; case 2: { State = 97; _la = TokenStream.LA(1); if ( _la <= 0 || (_la==T__10) ) { ErrorHandler.RecoverInline(this); } else { ErrorHandler.ReportMatch(this); Consume(); } } break; } } State = 102; ErrorHandler.Sync(this); _la = TokenStream.LA(1); } State = 103; Match(T__10); } } catch (RecognitionException re) { _localctx.exception = re; ErrorHandler.ReportError(this, re); ErrorHandler.Recover(this, re); } finally { ExitRule(); } return _localctx; } public partial class ArgumentsContext : ParserRuleContext { public ValueContext[] value() { return GetRuleContexts<ValueContext>(); } public ValueContext value(int i) { return GetRuleContext<ValueContext>(i); } public ArgumentsContext(ParserRuleContext parent, int invokingState) : base(parent, invokingState) { } public override int RuleIndex { get { return RULE_arguments; } } public override void EnterRule(IParseTreeListener listener) { IQueryListener typedListener = listener as IQueryListener; if (typedListener != null) typedListener.EnterArguments(this); } public override void ExitRule(IParseTreeListener listener) { IQueryListener typedListener = listener as IQueryListener; if (typedListener != null) typedListener.ExitArguments(this); } public override TResult Accept<TResult>(IParseTreeVisitor<TResult> visitor) { IQueryVisitor<TResult> typedVisitor = visitor as IQueryVisitor<TResult>; if (typedVisitor != null) return typedVisitor.VisitArguments(this); else return visitor.VisitChildren(this); } } [RuleVersion(0)] public ArgumentsContext arguments() { ArgumentsContext _localctx = new ArgumentsContext(Context, State); EnterRule(_localctx, 26, RULE_arguments); int _la; try { State = 117; ErrorHandler.Sync(this); switch (TokenStream.LA(1)) { case T__14: EnterOuterAlt(_localctx, 1); { State = 105; Match(T__14); State = 106; value(); State = 111; ErrorHandler.Sync(this); _la = TokenStream.LA(1); while (_la==T__3) { { { State = 107; Match(T__3); State = 108; value(); } } State = 113; ErrorHandler.Sync(this); _la = TokenStream.LA(1); } State = 114; Match(T__15); } break; case T__9: case T__10: case T__11: case T__12: case T__13: case LETTER: case ANY: EnterOuterAlt(_localctx, 2); { State = 116; value(); } break; default: throw new NoViableAltException(this); } } catch (RecognitionException re) { _localctx.exception = re; ErrorHandler.ReportError(this, re); ErrorHandler.Recover(this, re); } finally { ExitRule(); } return _localctx; } public partial class ValueContext : ParserRuleContext { public Single_quoteContext single_quote() { return GetRuleContext<Single_quoteContext>(0); } public Double_quoteContext double_quote() { return GetRuleContext<Double_quoteContext>(0); } public ValueContext(ParserRuleContext parent, int invokingState) : base(parent, invokingState) { } public override int RuleIndex { get { return RULE_value; } } public override void EnterRule(IParseTreeListener listener) { IQueryListener typedListener = listener as IQueryListener; if (typedListener != null) typedListener.EnterValue(this); } public override void ExitRule(IParseTreeListener listener) { IQueryListener typedListener = listener as IQueryListener; if (typedListener != null) typedListener.ExitValue(this); } public override TResult Accept<TResult>(IParseTreeVisitor<TResult> visitor) { IQueryVisitor<TResult> typedVisitor = visitor as IQueryVisitor<TResult>; if (typedVisitor != null) return typedVisitor.VisitValue(this); else return visitor.VisitChildren(this); } } [RuleVersion(0)] public ValueContext value() { ValueContext _localctx = new ValueContext(Context, State); EnterRule(_localctx, 28, RULE_value); int _la; try { State = 126; ErrorHandler.Sync(this); switch (TokenStream.LA(1)) { case T__11: case T__12: case T__13: case LETTER: case ANY: EnterOuterAlt(_localctx, 1); { State = 120; ErrorHandler.Sync(this); _la = TokenStream.LA(1); do { { { State = 119; _la = TokenStream.LA(1); if ( _la <= 0 || ((((_la) & ~0x3f) == 0 && ((1L << _la) & ((1L << T__0) | (1L << T__1) | (1L << T__2) | (1L << T__3) | (1L << T__4) | (1L << T__5) | (1L << T__6) | (1L << T__7) | (1L << T__8) | (1L << T__9) | (1L << T__10) | (1L << T__14) | (1L << T__15))) != 0)) ) { ErrorHandler.RecoverInline(this); } else { ErrorHandler.ReportMatch(this); Consume(); } } } State = 122; ErrorHandler.Sync(this); _la = TokenStream.LA(1); } while ( (((_la) & ~0x3f) == 0 && ((1L << _la) & ((1L << T__11) | (1L << T__12) | (1L << T__13) | (1L << LETTER) | (1L << ANY))) != 0) ); } break; case T__9: EnterOuterAlt(_localctx, 2); { State = 124; single_quote(); } break; case T__10: EnterOuterAlt(_localctx, 3); { State = 125; double_quote(); } break; default: throw new NoViableAltException(this); } } catch (RecognitionException re) { _localctx.exception = re; ErrorHandler.ReportError(this, re); ErrorHandler.Recover(this, re); } finally { ExitRule(); } return _localctx; } private static string _serializedATN = _serializeATN(); private static string _serializeATN() { StringBuilder sb = new StringBuilder(); sb.Append("\x3\x430\xD6D1\x8206\xAD2D\x4417\xAEF1\x8D80\xAADD\x3\x14"); sb.Append("\x83\x4\x2\t\x2\x4\x3\t\x3\x4\x4\t\x4\x4\x5\t\x5\x4\x6\t\x6"); sb.Append("\x4\a\t\a\x4\b\t\b\x4\t\t\t\x4\n\t\n\x4\v\t\v\x4\f\t\f\x4\r"); sb.Append("\t\r\x4\xE\t\xE\x4\xF\t\xF\x4\x10\t\x10\x3\x2\x6\x2\"\n\x2\r"); sb.Append("\x2\xE\x2#\x3\x3\x3\x3\x3\x3\x3\x4\x3\x4\x3\x4\a\x4,\n\x4\f"); sb.Append("\x4\xE\x4/\v\x4\x3\x5\x3\x5\x3\x5\a\x5\x34\n\x5\f\x5\xE\x5\x37"); sb.Append("\v\x5\x3\x6\x3\x6\x5\x6;\n\x6\x3\a\x3\a\x3\a\x3\a\x3\b\x3\b"); sb.Append("\x3\b\x3\b\x3\t\x3\t\x5\tG\n\t\x3\n\x3\n\a\nK\n\n\f\n\xE\nN"); sb.Append("\v\n\x3\n\x3\n\x3\v\x3\v\x5\vT\n\v\x3\f\x3\f\x3\r\x3\r\x3\r"); sb.Append("\a\r[\n\r\f\r\xE\r^\v\r\x3\r\x3\r\x3\xE\x3\xE\x3\xE\a\xE\x65"); sb.Append("\n\xE\f\xE\xE\xEh\v\xE\x3\xE\x3\xE\x3\xF\x3\xF\x3\xF\x3\xF\a"); sb.Append("\xFp\n\xF\f\xF\xE\xFs\v\xF\x3\xF\x3\xF\x3\xF\x5\xFx\n\xF\x3"); sb.Append("\x10\x6\x10{\n\x10\r\x10\xE\x10|\x3\x10\x3\x10\x5\x10\x81\n"); sb.Append("\x10\x3\x10\x2\x2\x11\x2\x4\x6\b\n\f\xE\x10\x12\x14\x16\x18"); sb.Append("\x1A\x1C\x1E\x2\n\x3\x2\x3\r\x4\x2\a\a\v\v\x4\x2\xE\xE\x13\x13"); sb.Append("\x3\x2\b\t\x3\x2\x3\v\x3\x2\f\f\x3\x2\r\r\x4\x2\x3\r\x11\x12"); sb.Append("\x83\x2!\x3\x2\x2\x2\x4%\x3\x2\x2\x2\x6(\x3\x2\x2\x2\b\x30\x3"); sb.Append("\x2\x2\x2\n:\x3\x2\x2\x2\f<\x3\x2\x2\x2\xE@\x3\x2\x2\x2\x10"); sb.Append("\x46\x3\x2\x2\x2\x12H\x3\x2\x2\x2\x14Q\x3\x2\x2\x2\x16U\x3\x2"); sb.Append("\x2\x2\x18W\x3\x2\x2\x2\x1A\x61\x3\x2\x2\x2\x1Cw\x3\x2\x2\x2"); sb.Append("\x1E\x80\x3\x2\x2\x2 \"\n\x2\x2\x2! \x3\x2\x2\x2\"#\x3\x2\x2"); sb.Append("\x2#!\x3\x2\x2\x2#$\x3\x2\x2\x2$\x3\x3\x2\x2\x2%&\x5\x6\x4\x2"); sb.Append("&\'\a\x2\x2\x3\'\x5\x3\x2\x2\x2(-\x5\b\x5\x2)*\a\x6\x2\x2*,"); sb.Append("\x5\b\x5\x2+)\x3\x2\x2\x2,/\x3\x2\x2\x2-+\x3\x2\x2\x2-.\x3\x2"); sb.Append("\x2\x2.\a\x3\x2\x2\x2/-\x3\x2\x2\x2\x30\x35\x5\n\x6\x2\x31\x32"); sb.Append("\a\x5\x2\x2\x32\x34\x5\n\x6\x2\x33\x31\x3\x2\x2\x2\x34\x37\x3"); sb.Append("\x2\x2\x2\x35\x33\x3\x2\x2\x2\x35\x36\x3\x2\x2\x2\x36\t\x3\x2"); sb.Append("\x2\x2\x37\x35\x3\x2\x2\x2\x38;\x5\f\a\x2\x39;\x5\xE\b\x2:\x38"); sb.Append("\x3\x2\x2\x2:\x39\x3\x2\x2\x2;\v\x3\x2\x2\x2<=\a\x3\x2\x2=>"); sb.Append("\x5\x6\x4\x2>?\a\x4\x2\x2?\r\x3\x2\x2\x2@\x41\x5\x2\x2\x2\x41"); sb.Append("\x42\x5\x10\t\x2\x42\x43\x5\x1C\xF\x2\x43\xF\x3\x2\x2\x2\x44"); sb.Append("G\x5\x12\n\x2\x45G\x5\x14\v\x2\x46\x44\x3\x2\x2\x2\x46\x45\x3"); sb.Append("\x2\x2\x2G\x11\x3\x2\x2\x2HL\t\x3\x2\x2IK\t\x4\x2\x2JI\x3\x2"); sb.Append("\x2\x2KN\x3\x2\x2\x2LJ\x3\x2\x2\x2LM\x3\x2\x2\x2MO\x3\x2\x2"); sb.Append("\x2NL\x3\x2\x2\x2OP\a\a\x2\x2P\x13\x3\x2\x2\x2QS\t\x5\x2\x2"); sb.Append("RT\a\a\x2\x2SR\x3\x2\x2\x2ST\x3\x2\x2\x2T\x15\x3\x2\x2\x2UV"); sb.Append("\t\x6\x2\x2V\x17\x3\x2\x2\x2W\\\a\f\x2\x2X[\a\xF\x2\x2Y[\n\a"); sb.Append("\x2\x2ZX\x3\x2\x2\x2ZY\x3\x2\x2\x2[^\x3\x2\x2\x2\\Z\x3\x2\x2"); sb.Append("\x2\\]\x3\x2\x2\x2]_\x3\x2\x2\x2^\\\x3\x2\x2\x2_`\a\f\x2\x2"); sb.Append("`\x19\x3\x2\x2\x2\x61\x66\a\r\x2\x2\x62\x65\a\x10\x2\x2\x63"); sb.Append("\x65\n\b\x2\x2\x64\x62\x3\x2\x2\x2\x64\x63\x3\x2\x2\x2\x65h"); sb.Append("\x3\x2\x2\x2\x66\x64\x3\x2\x2\x2\x66g\x3\x2\x2\x2gi\x3\x2\x2"); sb.Append("\x2h\x66\x3\x2\x2\x2ij\a\r\x2\x2j\x1B\x3\x2\x2\x2kl\a\x11\x2"); sb.Append("\x2lq\x5\x1E\x10\x2mn\a\x6\x2\x2np\x5\x1E\x10\x2om\x3\x2\x2"); sb.Append("\x2ps\x3\x2\x2\x2qo\x3\x2\x2\x2qr\x3\x2\x2\x2rt\x3\x2\x2\x2"); sb.Append("sq\x3\x2\x2\x2tu\a\x12\x2\x2ux\x3\x2\x2\x2vx\x5\x1E\x10\x2w"); sb.Append("k\x3\x2\x2\x2wv\x3\x2\x2\x2x\x1D\x3\x2\x2\x2y{\n\t\x2\x2zy\x3"); sb.Append("\x2\x2\x2{|\x3\x2\x2\x2|z\x3\x2\x2\x2|}\x3\x2\x2\x2}\x81\x3"); sb.Append("\x2\x2\x2~\x81\x5\x18\r\x2\x7F\x81\x5\x1A\xE\x2\x80z\x3\x2\x2"); sb.Append("\x2\x80~\x3\x2\x2\x2\x80\x7F\x3\x2\x2\x2\x81\x1F\x3\x2\x2\x2"); sb.Append("\x11#-\x35:\x46LSZ\\\x64\x66qw|\x80"); return sb.ToString(); } public static readonly ATN _ATN = new ATNDeserializer().Deserialize(_serializedATN.ToCharArray()); } } // namespace Autumn.Mvc.Models.Queries
31.844737
321
0.671983
[ "MIT" ]
gwendallg/autumn.mvc
src/Autumn.Mvc/Models/Queries/QueryParser.cs
36,303
C#
// ----------------------------------------------------------------------- // <copyright file="NotificationController.cs" company="Microsoft Corporation"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> // ----------------------------------------------------------------------- using Microsoft.Graph; using MicrosoftGraph_Security_API_Sample.Extensions; using MicrosoftGraph_Security_API_Sample.Models.DomainModels; using MicrosoftGraph_Security_API_Sample.Services.Interfaces; using Newtonsoft.Json.Linq; using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Threading.Tasks; using KeyValuePair = Microsoft.Graph.KeyValuePair; namespace MicrosoftGraph_Security_API_Sample.Services { public class DemoExample : IDemoExample { private MockData mockData = new MockData(); public bool UseMockData { get; set; } = false; public DemoExample(bool useMockData) { try { UseMockData = useMockData; using (StreamReader r = new StreamReader("mockData.json")) { string json = r.ReadToEnd(); JObject jsonObj = JObject.Parse(json); foreach (var obj in jsonObj) { if (obj.Key.Equals("securityActions")) { mockData.SecurityActions = obj.Value.ToObject<List<SecurityAction>>(); } if (obj.Key.Equals("devices")) { mockData.Devices = obj.Value.ToObject<List<Device>>(); } if (obj.Key.Equals("actionFilters")) { mockData.ActionFilters = obj.Value.ToObject<ActionFilters>(); } if (obj.Key.Equals("providers")) { mockData.Providers = obj.Value.ToObject<List<string>>(); } if (obj.Key.Equals("categories")) { mockData.Categories = obj.Value.ToObject<List<string>>(); } } } } catch (Exception exception) { Trace.WriteLine(exception.Message); mockData = new MockData() { ActionFilters = new ActionFilters() { ActionNames = new List<string>() { "Block", "Allow" }, ActionTargets = new List<string>() { "destinationAddress", "destinationDomain", "destinationUrl", "destinationPort" }, }, SecurityActions = new List<SecurityAction>() { new SecurityAction(){ Name = "Block", CreatedDateTime = DateTimeOffset.Now.AddHours(-20), LastActionDateTime = DateTimeOffset.Now.AddHours(-19), ActionReason = "Received TI this is a suspected malicious command and control center", Parameters = new List<KeyValuePair>(){ new KeyValuePair() { Name = "AlertId", Value = "53C7E3B0-8470-424C-BD40-2C9C3F9EFB81" }, new KeyValuePair() { Name = "BlockName", Value = "destinationAddress" },new KeyValuePair() { Name = "BlockValue", Value = "54.243.235.218" }}, Status = OperationStatus.Completed, Id = "1", VendorInformation = new Microsoft.Graph.SecurityVendorInformation(){ Provider = "Illumio VEN", Vendor = "Illumio", ProviderVersion = "18.02" }}, new SecurityAction(){ Name = "Block", CreatedDateTime = DateTimeOffset.Now.AddHours(-23), LastActionDateTime = DateTimeOffset.Now.AddHours(-22), ActionReason = "Received TI this is a suspected malicious command and control center", Parameters = new List<KeyValuePair>(){ new KeyValuePair() { Name = "AlertId", Value = "53C7E3B0-8470-424C-BD40-2C9C3F9EFB81" }, new KeyValuePair() { Name = "BlockName", Value = "destinationAddress" },new KeyValuePair() { Name = "BlockValue", Value = "54.243.235.218" }}, Status = OperationStatus.Completed, Id = "2", VendorInformation = new Microsoft.Graph.SecurityVendorInformation(){ Provider = "Illumio VEN", Vendor = "Illumio", ProviderVersion = "18.02" }}, new SecurityAction(){ Name = "Block", CreatedDateTime = DateTimeOffset.Now.AddHours(-26), LastActionDateTime = DateTimeOffset.Now.AddHours(-25), ActionReason = "Received TI this is a suspected malicious command and control center", Parameters = new List<KeyValuePair>(){ new KeyValuePair() { Name = "AlertId", Value = "53C7E3B0-8470-424C-BD40-2C9C3F9EFB81" }, new KeyValuePair() { Name = "BlockName", Value = "destinationDomain" }, new KeyValuePair() { Name = "BlockValue", Value = "willaimsclarke.com" } }, Status = OperationStatus.Completed, Id = "3", VendorInformation = new Microsoft.Graph.SecurityVendorInformation(){ Provider = "Illumio VEN", Vendor = "Illumio", ProviderVersion = "18.02" }}, }, Devices = new List<Device>() { new Device() { Id = "35888b53-23fd-4830-b526-d0df7ce8644e", DisplayName = "Microsoft Lumia 950 XL", OperatingSystem = "Windows 10 Mobile", OperatingSystemVersion = "10.2.5.75", IsManaged = true, AccountEnabled = true, ApproximateLastSignInDateTime = DateTime.Now, DeviceId = "35888b53-23fd-4830-b526-d0df7ce8644e", DeviceMetadata = "/metadata#device", IsCompliant = true, DeviceVersion = 3, TrustType = "Workspace" } } }; } } private Dictionary<string, List<AlertHistoryState>> alertHistoryStatesDictionary = new Dictionary<string, List<AlertHistoryState>>(); public List<AlertHistoryState> GetAlertHistoryStates(Alert alert, UserAccountDevice assignedTo, UserAccountDevice user) { try { if (alertHistoryStatesDictionary.ContainsKey(alert.Id)) { return alertHistoryStatesDictionary[alert.Id]; } if (user == null || assignedTo == null) return new List<AlertHistoryState>(); return new List<AlertHistoryState>(){ new AlertHistoryState() { AssignedTo = assignedTo, Feedback = alert.Feedback, Status = alert.Status, UpdatedDateTime = alert?.LastModifiedDateTime, User = user, Comments = alert?.Comments } }; } catch (Exception exception) { Trace.WriteLine(exception.Message); return new List<AlertHistoryState>(); } } public List<AlertHistoryState> AddAlertHistoryState(string alertId, AlertHistoryState alertHistoryState) { if (alertHistoryStatesDictionary.ContainsKey(alertId)) { List<AlertHistoryState> alertHistoryStatesFromDictionary = alertHistoryStatesDictionary[alertId]; alertHistoryStatesFromDictionary.Add(alertHistoryState); alertHistoryStatesDictionary[alertId] = alertHistoryStatesFromDictionary; return alertHistoryStatesDictionary[alertId]; } List<AlertHistoryState> alertHistoryStates = new List<AlertHistoryState>() { alertHistoryState }; alertHistoryStatesDictionary.Add(alertId, alertHistoryStates); return alertHistoryStatesDictionary[alertId]; } public async Task<IEnumerable<SecurityActionResponse>> GetSecurityActionsAsync() { return await Task.Run(() => { var responses = mockData.SecurityActions.ToSecurityActionResponses(); responses.ToList().OrderByDescending(x => x.StatusUpdateDateTime); return responses; }); } public async Task<IEnumerable<SecurityActionResponse>> AddSecurityActionsAsync(SecurityAction action) { return await Task.Run(() => { mockData.SecurityActions.Add(action); var responses = mockData.SecurityActions.ToSecurityActionResponses(); responses.ToList().OrderByDescending(x => x.StatusUpdateDateTime); return responses; }); } public IEnumerable<Device> GetDevices() { return mockData.Devices; } public IEnumerable<string> GetProviders() { return mockData.Providers; } public IEnumerable<string> GetCategories() { return mockData.Categories; } public Dictionary<string, IEnumerable<string>> GetActionFilters() { Dictionary<string, IEnumerable<string>> filters = new Dictionary<string, IEnumerable<string>> { { "actionNames", mockData.ActionFilters.ActionNames }, { "actionTargets", mockData.ActionFilters.ActionTargets } }; return filters; } } }
50.090452
724
0.541132
[ "MIT" ]
Lauragra/aspnet-security-api-sample
V3.0/MicrosoftGraph_Security_API_Sample/Services/DemoExample.cs
9,970
C#
#if LESSTHAN_NET40 #pragma warning disable CC0061 // Asynchronous method can be terminated with the 'Async' keyword. using System.Collections.Generic; using System.Diagnostics.Contracts; using System.Linq; namespace System.Threading.Tasks { public partial class Task { /// <summary> /// Creates a task that will complete when all of the supplied tasks have completed. /// </summary> /// <param name="tasks">The tasks to wait on for completion.</param> /// <returns>A task that represents the completion of all of the supplied tasks.</returns> /// <remarks> /// <para> /// If any of the supplied tasks completes in a faulted state, the returned task will also complete in a Faulted /// state, /// where its exceptions will contain the aggregation of the set of unwrapped exceptions from each of the supplied /// tasks. /// </para> /// <para> /// If none of the supplied tasks faulted but at least one of them was canceled, the returned task will end in the /// Canceled state. /// </para> /// <para> /// If none of the tasks faulted and none of the tasks were canceled, the resulting task will end in the /// RanToCompletion state. /// </para> /// <para> /// If the supplied array/enumerable contains no tasks, the returned task will immediately transition to a /// RanToCompletion /// state before it's returned to the caller. /// </para> /// </remarks> /// <exception cref="ArgumentNullException"> /// The <paramref name="tasks" /> argument was null. /// </exception> /// <exception cref="ArgumentException"> /// The <paramref name="tasks" /> collection contained a null task. /// </exception> public static Task WhenAll(IEnumerable<Task> tasks) { if (tasks == null) { throw new ArgumentNullException(nameof(tasks)); } if (tasks is Task[] array) { // Take a more efficient path if tasks is actually an array return WhenAll(array); } if (tasks is ICollection<Task> collection) { var index = 0; Task[] taskArray = new Task[collection.Count]; foreach (var task in collection) { taskArray[index++] = task ?? throw new ArgumentException("The tasks argument included a null value.", nameof(tasks)); } return InternalWhenAll(taskArray); } var taskList = new List<Task>(); foreach (var task in tasks) { if (task == null) { throw new ArgumentException("The tasks argument included a null value.", nameof(tasks)); } taskList.Add(task); } // Delegate the rest to InternalWhenAll() return InternalWhenAll(taskList.ToArray()); } /// <summary> /// Creates a task that will complete when all of the supplied tasks have completed. /// </summary> /// <param name="tasks">The tasks to wait on for completion.</param> /// <returns>A task that represents the completion of all of the supplied tasks.</returns> /// <remarks> /// <para> /// If any of the supplied tasks completes in a faulted state, the returned task will also complete in a Faulted /// state, /// where its exceptions will contain the aggregation of the set of unwrapped exceptions from each of the supplied /// tasks. /// </para> /// <para> /// If none of the supplied tasks faulted but at least one of them was canceled, the returned task will end in the /// Canceled state. /// </para> /// <para> /// If none of the tasks faulted and none of the tasks were canceled, the resulting task will end in the /// RanToCompletion state. /// </para> /// <para> /// If the supplied array/enumerable contains no tasks, the returned task will immediately transition to a /// RanToCompletion /// state before it's returned to the caller. /// </para> /// </remarks> /// <exception cref="ArgumentNullException"> /// The <paramref name="tasks" /> argument was null. /// </exception> /// <exception cref="ArgumentException"> /// The <paramref name="tasks" /> array contained a null task. /// </exception> public static Task WhenAll(params Task[] tasks) { // Do some argument checking and make a defensive copy of the tasks array if (tasks == null) { throw new ArgumentNullException(nameof(tasks)); } Contract.EndContractBlock(); var taskCount = tasks.Length; if (taskCount == 0) { return InternalWhenAll(tasks); // Small optimization in the case of an empty array. } var tasksCopy = new Task[taskCount]; for (var i = 0; i < taskCount; i++) { var task = tasks[i]; tasksCopy[i] = task ?? throw new ArgumentException("The tasks argument included a null value.", nameof(tasks)); } // The rest can be delegated to InternalWhenAll() return InternalWhenAll(tasksCopy); } /// <summary> /// Creates a task that will complete when all of the supplied tasks have completed. /// </summary> /// <param name="tasks">The tasks to wait on for completion.</param> /// <returns>A task that represents the completion of all of the supplied tasks.</returns> /// <remarks> /// <para> /// If any of the supplied tasks completes in a faulted state, the returned task will also complete in a Faulted /// state, /// where its exceptions will contain the aggregation of the set of unwrapped exceptions from each of the supplied /// tasks. /// </para> /// <para> /// If none of the supplied tasks faulted but at least one of them was canceled, the returned task will end in the /// Canceled state. /// </para> /// <para> /// If none of the tasks faulted and none of the tasks were canceled, the resulting task will end in the /// RanToCompletion state. /// The Result of the returned task will be set to an array containing all of the results of the /// supplied tasks in the same order as they were provided (e.g. if the input tasks array contained t1, t2, t3, the /// output /// task's Result will return an TResult[] where arr[0] == t1.Result, arr[1] == t2.Result, and arr[2] == /// t3.Result). /// </para> /// <para> /// If the supplied array/enumerable contains no tasks, the returned task will immediately transition to a /// RanToCompletion /// state before it's returned to the caller. The returned TResult[] will be an array of 0 elements. /// </para> /// </remarks> /// <exception cref="ArgumentNullException"> /// The <paramref name="tasks" /> argument was null. /// </exception> /// <exception cref="ArgumentException"> /// The <paramref name="tasks" /> collection contained a null task. /// </exception> public static Task<TResult[]> WhenAll<TResult>(IEnumerable<Task<TResult>> tasks) { if (tasks == null) { throw new ArgumentNullException(nameof(tasks)); } if (tasks is Task<TResult>[] array) { // Take a more efficient route if tasks is actually an array return WhenAll(array); } if (tasks is ICollection<Task<TResult>> collection) { var index = 0; Task<TResult>[] taskArray = new Task<TResult>[collection.Count]; foreach (var task in collection) { taskArray[index++] = task ?? throw new ArgumentException("The tasks argument included a null value.", nameof(tasks)); } return InternalWhenAll(taskArray); } var taskList = new List<Task<TResult>>(); foreach (var task in tasks) { if (task == null) { throw new ArgumentException("Task_MultiTaskContinuation_NullTask", nameof(tasks)); } taskList.Add(task); } // Delegate the rest to InternalWhenAll<TResult>(). return InternalWhenAll(taskList.ToArray()); } /// <summary> /// Creates a task that will complete when all of the supplied tasks have completed. /// </summary> /// <param name="tasks">The tasks to wait on for completion.</param> /// <returns>A task that represents the completion of all of the supplied tasks.</returns> /// <remarks> /// <para> /// If any of the supplied tasks completes in a faulted state, the returned task will also complete in a Faulted /// state, /// where its exceptions will contain the aggregation of the set of unwrapped exceptions from each of the supplied /// tasks. /// </para> /// <para> /// If none of the supplied tasks faulted but at least one of them was canceled, the returned task will end in the /// Canceled state. /// </para> /// <para> /// If none of the tasks faulted and none of the tasks were canceled, the resulting task will end in the /// RanToCompletion state. /// The Result of the returned task will be set to an array containing all of the results of the /// supplied tasks in the same order as they were provided (e.g. if the input tasks array contained t1, t2, t3, the /// output /// task's Result will return an TResult[] where arr[0] == t1.Result, arr[1] == t2.Result, and arr[2] == /// t3.Result). /// </para> /// <para> /// If the supplied array/enumerable contains no tasks, the returned task will immediately transition to a /// RanToCompletion /// state before it's returned to the caller. The returned TResult[] will be an array of 0 elements. /// </para> /// </remarks> /// <exception cref="ArgumentNullException"> /// The <paramref name="tasks" /> argument was null. /// </exception> /// <exception cref="ArgumentException"> /// The <paramref name="tasks" /> array contained a null task. /// </exception> public static Task<TResult[]> WhenAll<TResult>(params Task<TResult>[] tasks) { // Do some argument checking and make a defensive copy of the tasks array if (tasks == null) { throw new ArgumentNullException(nameof(tasks)); } Contract.EndContractBlock(); var taskCount = tasks.Length; if (taskCount == 0) { return InternalWhenAll(tasks); // small optimization in the case of an empty task array } var tasksCopy = new Task<TResult>[taskCount]; for (var i = 0; i < taskCount; i++) { var task = tasks[i]; tasksCopy[i] = task ?? throw new ArgumentException("The tasks argument included a null value.", nameof(tasks)); } // Delegate the rest to InternalWhenAll<TResult>() return InternalWhenAll(tasksCopy); } /// <summary> /// Creates a task that will complete when any of the supplied tasks have completed. /// </summary> /// <param name="tasks">The tasks to wait on for completion.</param> /// <returns> /// A task that represents the completion of one of the supplied tasks. The return Task's Result is the task that /// completed. /// </returns> /// <remarks> /// The returned task will complete when any of the supplied tasks has completed. The returned task will always end in /// the RanToCompletion state /// with its Result set to the first task to complete. This is true even if the first task to complete ended in the /// Canceled or Faulted state. /// </remarks> /// <exception cref="ArgumentNullException"> /// The <paramref name="tasks" /> argument was null. /// </exception> /// <exception cref="ArgumentException"> /// The <paramref name="tasks" /> array contained a null task, or was empty. /// </exception> public static Task<Task> WhenAny(params Task[] tasks) { if (tasks == null) { throw new ArgumentNullException(nameof(tasks)); } if (tasks.Length == 0) { throw new ArgumentException("The tasks argument contains no tasks.", nameof(tasks)); } Contract.EndContractBlock(); // Make a defensive copy, as the user may manipulate the tasks array // after we return but before the WhenAny asynchronously completes. var taskCount = tasks.Length; var tasksCopy = new Task[taskCount]; for (var index = 0; index < taskCount; index++) { var task = tasks[index]; tasksCopy[index] = task ?? throw new ArgumentException("The tasks argument included a null value.", nameof(tasks)); } var signaledTaskIndex = -1; return PrivateWhenAny(tasksCopy, ref signaledTaskIndex); } /// <summary> /// Creates a task that will complete when any of the supplied tasks have completed. /// </summary> /// <param name="tasks">The tasks to wait on for completion.</param> /// <returns> /// A task that represents the completion of one of the supplied tasks. The return Task's Result is the task that /// completed. /// </returns> /// <remarks> /// The returned task will complete when any of the supplied tasks has completed. The returned task will always end in /// the RanToCompletion state /// with its Result set to the first task to complete. This is true even if the first task to complete ended in the /// Canceled or Faulted state. /// </remarks> /// <exception cref="ArgumentNullException"> /// The <paramref name="tasks" /> argument was null. /// </exception> /// <exception cref="ArgumentException"> /// The <paramref name="tasks" /> collection contained a null task, or was empty. /// </exception> public static Task<Task> WhenAny(IEnumerable<Task> tasks) { if (tasks == null) { throw new ArgumentNullException(nameof(tasks)); } Contract.EndContractBlock(); // Make a defensive copy, as the user may manipulate the tasks collection // after we return but before the WhenAny asynchronously completes. var taskList = new List<Task>(); foreach (var task in tasks) { if (task == null) { throw new ArgumentException("The tasks argument included a null value.", nameof(tasks)); } taskList.Add(task); } if (taskList.Count == 0) { throw new ArgumentException("The tasks argument contains no tasks.", nameof(tasks)); } var signaledTaskIndex = -1; return PrivateWhenAny(taskList, ref signaledTaskIndex); } /// <summary> /// Creates a task that will complete when any of the supplied tasks have completed. /// </summary> /// <param name="tasks">The tasks to wait on for completion.</param> /// <returns> /// A task that represents the completion of one of the supplied tasks. The return Task's Result is the task that /// completed. /// </returns> /// <remarks> /// The returned task will complete when any of the supplied tasks has completed. The returned task will always end in /// the RanToCompletion state /// with its Result set to the first task to complete. This is true even if the first task to complete ended in the /// Canceled or Faulted state. /// </remarks> /// <exception cref="ArgumentNullException"> /// The <paramref name="tasks" /> argument was null. /// </exception> /// <exception cref="ArgumentException"> /// The <paramref name="tasks" /> array contained a null task, or was empty. /// </exception> public static Task<Task<TResult>> WhenAny<TResult>(params Task<TResult>[] tasks) { // ReSharper disable once CoVariantArrayConversion var intermediate = WhenAny((Task[])tasks); return intermediate.ContinueWith(Task<TResult>.ContinuationConversion, default, TaskContinuationOptions.ExecuteSynchronously | TaskContinuationOptions.DenyChildAttach, TaskScheduler.Default); } /// <summary> /// Creates a task that will complete when any of the supplied tasks have completed. /// </summary> /// <param name="tasks">The tasks to wait on for completion.</param> /// <returns> /// A task that represents the completion of one of the supplied tasks. The return Task's Result is the task that /// completed. /// </returns> /// <remarks> /// The returned task will complete when any of the supplied tasks has completed. The returned task will always end in /// the RanToCompletion state /// with its Result set to the first task to complete. This is true even if the first task to complete ended in the /// Canceled or Faulted state. /// </remarks> /// <exception cref="ArgumentNullException"> /// The <paramref name="tasks" /> argument was null. /// </exception> /// <exception cref="ArgumentException"> /// The <paramref name="tasks" /> collection contained a null task, or was empty. /// </exception> public static Task<Task<TResult>> WhenAny<TResult>(IEnumerable<Task<TResult>> tasks) { var intermediate = WhenAny((IEnumerable<Task>)tasks); return intermediate.ContinueWith(Task<TResult>.ContinuationConversion, default, TaskContinuationOptions.ExecuteSynchronously | TaskContinuationOptions.DenyChildAttach, TaskScheduler.Default); } /// <summary>Returns true if any of the supplied tasks require wait notification.</summary> /// <param name="tasks">The tasks to check.</param> /// <returns>true if any of the tasks require notification; otherwise, false.</returns> internal static bool AnyTaskRequiresNotifyDebuggerOfWaitCompletion(IEnumerable<Task?> tasks) { if (tasks != null) { return tasks.Any(task => task?.IsWaitNotificationEnabled == true && task.ShouldNotifyDebuggerOfWaitCompletion); } Contract.Assert(false, "Expected non-null array of tasks"); throw new ArgumentNullException(nameof(tasks)); } // Some common logic to support WhenAll() methods // tasks should be a defensive copy. private static Task InternalWhenAll(Task[] tasks) { // take shortcut if there are no tasks upon which to wait return tasks.Length == 0 ? TaskExEx.CompletedTask : new WhenAllPromise(tasks); } // Some common logic to support WhenAll<TResult> methods private static Task<TResult[]> InternalWhenAll<TResult>(Task<TResult>[] tasks) { // take shortcut if there are no tasks upon which to wait return tasks.Length == 0 ? FromResult(new TResult[0]) : new WhenAllPromise<TResult>(tasks); } } } #endif
45.794872
203
0.557437
[ "MIT" ]
Terricide/Theraot
Framework.Core/System/Threading/Tasks/Task.when.cs
21,434
C#
using NHibernate.Mapping.ByCode; using NHibernate.Mapping.ByCode.Conformist; namespace NHibernate.GraphQL.Tests.Dto.Mapping { public class AddressMapping: ClassMapping<Address> { public AddressMapping() { Id(x => x.Id, map => { map.Generator(Generators.Assigned); }); Property(x => x.House, m => m.NotNullable(true)); Property(x => x.Street, m => m.NotNullable(false)); Property(x => x.Zip, m => m.NotNullable(false)); Set(x => x.Users, map => { map.Table("UserAddressJunction"); map.Key(k => k.Column("AddressId")); map.Cascade(Cascade.All); }, map => map.OneToMany()); } } }
29.185185
63
0.513959
[ "MIT" ]
raidenyn/NHibernate.GraphQL
src/NHibernate.GraphQL.Tests/Dto/Mapping/AddressMapping.cs
790
C#
/* The MIT License(MIT) Copyright(c) mxgmn 2016. 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 Eppy; public abstract class Model { protected bool[][] wave; protected int[][][] propagator; int[][][] compatible; protected int[] observed; protected bool init = false; Tuple<int, int>[] stack; int stacksize; protected System.Random random; protected int FMX, FMY, T; protected bool periodic; protected double[] weights; double[] weightLogWeights; int[] sumsOfOnes; double sumOfWeights, sumOfWeightLogWeights, startingEntropy; double[] sumsOfWeights, sumsOfWeightLogWeights, entropies; protected Model(int width, int height) { FMX = width; FMY = height; } void Init() { wave = new bool[FMX * FMY][]; compatible = new int[wave.Length][][]; for (int i = 0; i < wave.Length; i++) { wave[i] = new bool[T]; compatible[i] = new int[T][]; for (int t = 0; t < T; t++) compatible[i][t] = new int[4]; } weightLogWeights = new double[T]; sumOfWeights = 0; sumOfWeightLogWeights = 0; for (int t = 0; t < T; t++) { weightLogWeights[t] = weights[t] * Math.Log(weights[t]); sumOfWeights += weights[t]; sumOfWeightLogWeights += weightLogWeights[t]; } startingEntropy = Math.Log(sumOfWeights) - sumOfWeightLogWeights / sumOfWeights; sumsOfOnes = new int[FMX * FMY]; sumsOfWeights = new double[FMX * FMY]; sumsOfWeightLogWeights = new double[FMX * FMY]; entropies = new double[FMX * FMY]; stack = new Tuple<int, int>[wave.Length * T]; stacksize = 0; } bool? Observe() { double min = 1E+3; int argmin = -1; for (int i = 0; i < wave.Length; i++) { if (OnBoundary(i % FMX, i / FMX)) continue; int amount = sumsOfOnes[i]; if (amount == 0) return false; double entropy = entropies[i]; if (amount > 1 && entropy <= min) { double noise = 1E-6 * random.NextDouble(); if (entropy + noise < min) { min = entropy + noise; argmin = i; } } } if (argmin == -1) { observed = new int[FMX * FMY]; for (int i = 0; i < wave.Length; i++) for (int t = 0; t < T; t++) if (wave[i][t]) { observed[i] = t; break; } return true; } double[] distribution = new double[T]; for (int t = 0; t < T; t++) distribution[t] = wave[argmin][t] ? weights[t] : 0; int r = distribution.Random(random.NextDouble()); bool[] w = wave[argmin]; for (int t = 0; t < T; t++) if (w[t] != (t == r)) Ban(argmin, t); return null; } protected void Propagate() { while (stacksize > 0) { var e1 = stack[stacksize - 1]; stacksize--; int i1 = e1.Item1; int x1 = i1 % FMX, y1 = i1 / FMX; bool[] w1 = wave[i1]; for (int d = 0; d < 4; d++) { int dx = DX[d], dy = DY[d]; int x2 = x1 + dx, y2 = y1 + dy; if (OnBoundary(x2, y2)) continue; if (x2 < 0) x2 += FMX; else if (x2 >= FMX) x2 -= FMX; if (y2 < 0) y2 += FMY; else if (y2 >= FMY) y2 -= FMY; int i2 = x2 + y2 * FMX; int[] p = propagator[d][e1.Item2]; int[][] compat = compatible[i2]; for (int l = 0; l < p.Length; l++) { int t2 = p[l]; int[] comp = compat[t2]; comp[d]--; if (comp[d] == 0) Ban(i2, t2); } } } } public bool Run(int seed, int limit) { if (wave == null) Init(); if (!this.init) { this.init = true; this.Clear(); } if (seed==0) { random = new System.Random(); } else { random = new System.Random(seed); } for (int l = 0; l < limit || limit == 0; l++) { bool? result = Observe(); if (result != null) return (bool)result; Propagate(); } return true; } protected void Ban(int i, int t) { wave[i][t] = false; int[] comp = compatible[i][t]; for (int d = 0; d < 4; d++) comp[d] = 0; stack[stacksize] = new Tuple<int, int>(i, t); stacksize++; double sum = sumsOfWeights[i]; entropies[i] += sumsOfWeightLogWeights[i] / sum - Math.Log(sum); sumsOfOnes[i] -= 1; sumsOfWeights[i] -= weights[t]; sumsOfWeightLogWeights[i] -= weightLogWeights[t]; sum = sumsOfWeights[i]; entropies[i] -= sumsOfWeightLogWeights[i] / sum - Math.Log(sum); } protected virtual void Clear() { for (int i = 0; i < wave.Length; i++) { for (int t = 0; t < T; t++) { wave[i][t] = true; for (int d = 0; d < 4; d++) compatible[i][t][d] = propagator[opposite[d]][t].Length; } sumsOfOnes[i] = weights.Length; sumsOfWeights[i] = sumOfWeights; sumsOfWeightLogWeights[i] = sumOfWeightLogWeights; entropies[i] = startingEntropy; } } protected abstract bool OnBoundary(int x, int y); protected static int[] DX = { -1, 0, 1, 0 }; protected static int[] DY = { 0, 1, 0, -1 }; static int[] opposite = { 2, 3, 0, 1 }; }
25.488789
460
0.619282
[ "MIT" ]
woodyhoko/Isaac-Moduler-3D-approach
4451_Game/Assets/unity-wave-function-collapse/impl/Model.cs
5,686
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace DSCMS.Views.Certificate { public partial class CertificateBulkSign { /// <summary> /// ScriptManager1 control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.ScriptManager ScriptManager1; /// <summary> /// ErrorMessage control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.HtmlControls.HtmlGenericControl ErrorMessage; /// <summary> /// drpCustomer control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.DropDownList drpCustomer; /// <summary> /// Button4 control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.Button Button4; /// <summary> /// gvPendigCR control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.GridView gvPendigCR; /// <summary> /// lnkDummy control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.LinkButton lnkDummy; /// <summary> /// linkDum control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.LinkButton linkDum; /// <summary> /// Panel1 control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.Panel Panel1; /// <summary> /// txtCertificatePass control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.TextBox txtCertificatePass; /// <summary> /// lblError control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.Label lblError; /// <summary> /// btnCerateCertificate control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.Button btnCerateCertificate; /// <summary> /// btnClose control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.Button btnClose; /// <summary> /// mp1 control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::AjaxControlToolkit.ModalPopupExtender mp1; /// <summary> /// LinkButton1 control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.LinkButton LinkButton1; /// <summary> /// LinkButton2 control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.LinkButton LinkButton2; /// <summary> /// Panel2 control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.Panel Panel2; /// <summary> /// txtRequestID control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.TextBox txtRequestID; /// <summary> /// txtCustomerID control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.TextBox txtCustomerID; /// <summary> /// txtSealBoolen control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.TextBox txtSealBoolen; /// <summary> /// txtUploadPath control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.TextBox txtUploadPath; /// <summary> /// txtTemplateID control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.TextBox txtTemplateID; /// <summary> /// txtCRequestType control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.TextBox txtCRequestType; /// <summary> /// txtCpassword control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.TextBox txtCpassword; /// <summary> /// LblError2 control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.Label LblError2; /// <summary> /// btnApproveCertificate control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.Button btnApproveCertificate; /// <summary> /// Button2 control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.Button Button2; /// <summary> /// mp2 control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::AjaxControlToolkit.ModalPopupExtender mp2; /// <summary> /// LinkButton3 control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.LinkButton LinkButton3; /// <summary> /// LinkButton4 control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.LinkButton LinkButton4; /// <summary> /// Panel3 control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.Panel Panel3; /// <summary> /// lblRejectRequestID control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.Label lblRejectRequestID; /// <summary> /// lblRCertificateType control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.Label lblRCertificateType; /// <summary> /// lblCUSEmail control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.Label lblCUSEmail; /// <summary> /// drpRejectReason control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.DropDownList drpRejectReason; /// <summary> /// lblRejectError control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.Label lblRejectError; /// <summary> /// btnRejectCertificateReq control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.Button btnRejectCertificateReq; /// <summary> /// Button3 control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.Button Button3; /// <summary> /// mp3 control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::AjaxControlToolkit.ModalPopupExtender mp3; /// <summary> /// LinkButton5 control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.LinkButton LinkButton5; /// <summary> /// LinkButton6 control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.LinkButton LinkButton6; /// <summary> /// Panel4 control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.Panel Panel4; /// <summary> /// gvSupportingDOc control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.GridView gvSupportingDOc; /// <summary> /// lblCType control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.Label lblCType; /// <summary> /// Button1 control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.Button Button1; /// <summary> /// mpSD control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::AjaxControlToolkit.ModalPopupExtender mpSD; } }
35.774347
85
0.550096
[ "Apache-2.0" ]
Ruke45/DManagement
DSCMS/DSCMS/Views/Certificate/PendingCertificates.aspx.designer.cs
15,063
C#
// ------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License (MIT). See License.txt in the repo root for license information. // ------------------------------------------------------------ namespace Microsoft.ServiceFabric.Client.Http.Serialization { using System; using System.Collections.Generic; using Microsoft.ServiceFabric.Common; using Newtonsoft.Json; using Newtonsoft.Json.Linq; /// <summary> /// Converter for <see cref="ClusterUpgradeDomainCompleteEvent" />. /// </summary> internal class ClusterUpgradeDomainCompleteEventConverter { /// <summary> /// Deserializes the JSON representation of the object. /// </summary> /// <param name="reader">The <see cref="T: Newtonsoft.Json.JsonReader" /> to read from.</param> /// <returns>The object Value.</returns> internal static ClusterUpgradeDomainCompleteEvent Deserialize(JsonReader reader) { return reader.Deserialize(GetFromJsonProperties); } /// <summary> /// Gets the object from Json properties. /// </summary> /// <param name="reader">The <see cref="T: Newtonsoft.Json.JsonReader" /> to read from, reader must be placed at first property.</param> /// <returns>The object Value.</returns> internal static ClusterUpgradeDomainCompleteEvent GetFromJsonProperties(JsonReader reader) { var eventInstanceId = default(Guid?); var timeStamp = default(DateTime?); var hasCorrelatedEvents = default(bool?); var targetClusterVersion = default(string); var upgradeState = default(string); var upgradeDomains = default(string); var upgradeDomainElapsedTimeInMs = default(double?); do { var propName = reader.ReadPropertyName(); if (string.Compare("EventInstanceId", propName, StringComparison.Ordinal) == 0) { eventInstanceId = reader.ReadValueAsGuid(); } else if (string.Compare("TimeStamp", propName, StringComparison.Ordinal) == 0) { timeStamp = reader.ReadValueAsDateTime(); } else if (string.Compare("HasCorrelatedEvents", propName, StringComparison.Ordinal) == 0) { hasCorrelatedEvents = reader.ReadValueAsBool(); } else if (string.Compare("TargetClusterVersion", propName, StringComparison.Ordinal) == 0) { targetClusterVersion = reader.ReadValueAsString(); } else if (string.Compare("UpgradeState", propName, StringComparison.Ordinal) == 0) { upgradeState = reader.ReadValueAsString(); } else if (string.Compare("UpgradeDomains", propName, StringComparison.Ordinal) == 0) { upgradeDomains = reader.ReadValueAsString(); } else if (string.Compare("UpgradeDomainElapsedTimeInMs", propName, StringComparison.Ordinal) == 0) { upgradeDomainElapsedTimeInMs = reader.ReadValueAsDouble(); } else { reader.SkipPropertyValue(); } } while (reader.TokenType != JsonToken.EndObject); return new ClusterUpgradeDomainCompleteEvent( eventInstanceId: eventInstanceId, timeStamp: timeStamp, hasCorrelatedEvents: hasCorrelatedEvents, targetClusterVersion: targetClusterVersion, upgradeState: upgradeState, upgradeDomains: upgradeDomains, upgradeDomainElapsedTimeInMs: upgradeDomainElapsedTimeInMs); } /// <summary> /// Serializes the object to JSON. /// </summary> /// <param name="writer">The <see cref="T: Newtonsoft.Json.JsonWriter" /> to write to.</param> /// <param name="obj">The object to serialize to JSON.</param> internal static void Serialize(JsonWriter writer, ClusterUpgradeDomainCompleteEvent obj) { // Required properties are always serialized, optional properties are serialized when not null. writer.WriteStartObject(); writer.WriteProperty(obj.Kind.ToString(), "Kind", JsonWriterExtensions.WriteStringValue); writer.WriteProperty(obj.EventInstanceId, "EventInstanceId", JsonWriterExtensions.WriteGuidValue); writer.WriteProperty(obj.TimeStamp, "TimeStamp", JsonWriterExtensions.WriteDateTimeValue); writer.WriteProperty(obj.TargetClusterVersion, "TargetClusterVersion", JsonWriterExtensions.WriteStringValue); writer.WriteProperty(obj.UpgradeState, "UpgradeState", JsonWriterExtensions.WriteStringValue); writer.WriteProperty(obj.UpgradeDomains, "UpgradeDomains", JsonWriterExtensions.WriteStringValue); writer.WriteProperty(obj.UpgradeDomainElapsedTimeInMs, "UpgradeDomainElapsedTimeInMs", JsonWriterExtensions.WriteDoubleValue); if (obj.HasCorrelatedEvents != null) { writer.WriteProperty(obj.HasCorrelatedEvents, "HasCorrelatedEvents", JsonWriterExtensions.WriteBoolValue); } writer.WriteEndObject(); } } }
47.940171
144
0.601177
[ "MIT" ]
aL3891/service-fabric-client-dotnet
src/Microsoft.ServiceFabric.Client.Http/Serialization/ClusterUpgradeDomainCompleteEventConverter.cs
5,609
C#
using System; using System.Text; using System.Data; using System.Data.SqlClient; using System.Data.Common; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Configuration; using System.Xml; using System.Xml.Serialization; using SubSonic; using SubSonic.Utilities; // <auto-generated /> namespace SouthwindRepository{ /// <summary> /// Strongly-typed collection for the ProductsByCategory class. /// </summary> [Serializable] public partial class ProductsByCategoryCollection : ReadOnlyList<ProductsByCategory, ProductsByCategoryCollection> { public ProductsByCategoryCollection() {} } /// <summary> /// This is Read-only wrapper class for the products by category view. /// </summary> [Serializable] public partial class ProductsByCategory : ReadOnlyRecord<ProductsByCategory>, IReadOnlyRecord { #region Default Settings protected static void SetSQLProps() { GetTableSchema(); } #endregion #region Schema Accessor public static TableSchema.Table Schema { get { if (BaseSchema == null) { SetSQLProps(); } return BaseSchema; } } private static void GetTableSchema() { if(!IsSchemaInitialized) { //Schema declaration TableSchema.Table schema = new TableSchema.Table("products by category", TableType.View, DataService.GetInstance("SouthwindRepository")); schema.Columns = new TableSchema.TableColumnCollection(); schema.SchemaName = @""; //columns TableSchema.TableColumn colvarCategoryName = new TableSchema.TableColumn(schema); colvarCategoryName.ColumnName = "CategoryName"; colvarCategoryName.DataType = DbType.String; colvarCategoryName.MaxLength = 15; colvarCategoryName.AutoIncrement = false; colvarCategoryName.IsNullable = false; colvarCategoryName.IsPrimaryKey = false; colvarCategoryName.IsForeignKey = false; colvarCategoryName.IsReadOnly = false; schema.Columns.Add(colvarCategoryName); TableSchema.TableColumn colvarProductName = new TableSchema.TableColumn(schema); colvarProductName.ColumnName = "ProductName"; colvarProductName.DataType = DbType.String; colvarProductName.MaxLength = 40; colvarProductName.AutoIncrement = false; colvarProductName.IsNullable = false; colvarProductName.IsPrimaryKey = false; colvarProductName.IsForeignKey = false; colvarProductName.IsReadOnly = false; schema.Columns.Add(colvarProductName); TableSchema.TableColumn colvarQuantityPerUnit = new TableSchema.TableColumn(schema); colvarQuantityPerUnit.ColumnName = "QuantityPerUnit"; colvarQuantityPerUnit.DataType = DbType.String; colvarQuantityPerUnit.MaxLength = 20; colvarQuantityPerUnit.AutoIncrement = false; colvarQuantityPerUnit.IsNullable = true; colvarQuantityPerUnit.IsPrimaryKey = false; colvarQuantityPerUnit.IsForeignKey = false; colvarQuantityPerUnit.IsReadOnly = false; schema.Columns.Add(colvarQuantityPerUnit); TableSchema.TableColumn colvarUnitsInStock = new TableSchema.TableColumn(schema); colvarUnitsInStock.ColumnName = "UnitsInStock"; colvarUnitsInStock.DataType = DbType.Int16; colvarUnitsInStock.MaxLength = 5; colvarUnitsInStock.AutoIncrement = false; colvarUnitsInStock.IsNullable = true; colvarUnitsInStock.IsPrimaryKey = false; colvarUnitsInStock.IsForeignKey = false; colvarUnitsInStock.IsReadOnly = false; schema.Columns.Add(colvarUnitsInStock); TableSchema.TableColumn colvarDiscontinued = new TableSchema.TableColumn(schema); colvarDiscontinued.ColumnName = "Discontinued"; colvarDiscontinued.DataType = DbType.Boolean; colvarDiscontinued.MaxLength = 4; colvarDiscontinued.AutoIncrement = false; colvarDiscontinued.IsNullable = false; colvarDiscontinued.IsPrimaryKey = false; colvarDiscontinued.IsForeignKey = false; colvarDiscontinued.IsReadOnly = false; schema.Columns.Add(colvarDiscontinued); BaseSchema = schema; //add this schema to the provider //so we can query it later DataService.Providers["SouthwindRepository"].AddSchema("products by category",schema); } } #endregion #region Query Accessor public static Query CreateQuery() { return new Query(Schema); } #endregion #region .ctors public ProductsByCategory() { SetSQLProps(); SetDefaults(); MarkNew(); } public ProductsByCategory(bool useDatabaseDefaults) { SetSQLProps(); if(useDatabaseDefaults) { ForceDefaults(); } MarkNew(); } public ProductsByCategory(object keyID) { SetSQLProps(); LoadByKey(keyID); } public ProductsByCategory(string columnName, object columnValue) { SetSQLProps(); LoadByParam(columnName,columnValue); } #endregion #region Props [XmlAttribute("CategoryName")] [Bindable(true)] public string CategoryName { get { return GetColumnValue<string>("CategoryName"); } set { SetColumnValue("CategoryName", value); } } [XmlAttribute("ProductName")] [Bindable(true)] public string ProductName { get { return GetColumnValue<string>("ProductName"); } set { SetColumnValue("ProductName", value); } } [XmlAttribute("QuantityPerUnit")] [Bindable(true)] public string QuantityPerUnit { get { return GetColumnValue<string>("QuantityPerUnit"); } set { SetColumnValue("QuantityPerUnit", value); } } [XmlAttribute("UnitsInStock")] [Bindable(true)] public short? UnitsInStock { get { return GetColumnValue<short?>("UnitsInStock"); } set { SetColumnValue("UnitsInStock", value); } } [XmlAttribute("Discontinued")] [Bindable(true)] public bool Discontinued { get { return GetColumnValue<bool>("Discontinued"); } set { SetColumnValue("Discontinued", value); } } #endregion #region Columns Struct public struct Columns { public static string CategoryName = @"CategoryName"; public static string ProductName = @"ProductName"; public static string QuantityPerUnit = @"QuantityPerUnit"; public static string UnitsInStock = @"UnitsInStock"; public static string Discontinued = @"Discontinued"; } #endregion #region IAbstractRecord Members public new CT GetColumnValue<CT>(string columnName) { return base.GetColumnValue<CT>(columnName); } public object GetColumnValue(string columnName) { return base.GetColumnValue<object>(columnName); } #endregion } }
31.113971
153
0.561621
[ "BSD-3-Clause" ]
BlackMael/SubSonic-2.0
SubSonic.Tests/Generated/SouthwindRepository/ProductsByCategory.cs
8,463
C#
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Collections.Specialized; namespace Ldartools.Common.DataStructures { [Obsolete("Please DO NOT use this collection as certain framework controls do not subscribe to update events do to their implementation failing to handle binding to inheritted types.", true)] public class ObservableCollectionExt<T> : ObservableCollection<T> { public ObservableCollectionExt() { } public ObservableCollectionExt(IEnumerable<T> collection) : base(collection) { } public void AddRange(IEnumerable<T> collection) { if (collection == null) throw new ArgumentNullException(nameof(collection)); foreach (var i in collection) Items.Add(i); OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset)); } } }
33.433333
196
0.668993
[ "MIT" ]
LDARtools/CommonShared
Ldartools.Common/Ldartools.Common/DataStructures/ObservableCollectionExt.cs
1,005
C#
using SCide.WPF.Commence; using System.ComponentModel; using System.Runtime.CompilerServices; namespace SCide.WPF.Models { public class StatusBarModel : INotifyPropertyChanged { #region Fields private string _statusText = string.Empty; private ICommenceScript _commenceScript; private ScintillaNET.Scintilla _scintilla; #endregion #region Properties public ScintillaNET.Scintilla Scintilla { set { if (_scintilla != null) { UnsubscribeEvents(_scintilla); } _scintilla = value; SubscribeEvents(_scintilla); } } public ICommenceScript CurrentScript { get { return _commenceScript; } set { _commenceScript = value; OnPropertyChanged(); } } public int CurrentLine { get; private set; } public int CurrentColumn { get; private set; } public string StatusText { get { return _statusText; } set { _statusText = value; OnPropertyChanged(); } } public string PositionInfo => "Ln: " + CurrentLine.ToString() + " Col: " + CurrentColumn.ToString(); private bool overwriteMode; public bool OverWrite { get { return overwriteMode; } set { overwriteMode = value; OnPropertyChanged(); } } #endregion #region Events private void SubscribeEvents(ScintillaNET.Scintilla scintilla) { _scintilla.UpdateUI += Scintilla_UpdateUI; _scintilla.MouseDown += Scintilla_MouseDown; } private void UnsubscribeEvents(ScintillaNET.Scintilla scintilla) { _scintilla.UpdateUI -= Scintilla_UpdateUI; _scintilla.MouseDown -= Scintilla_MouseDown; } private void Scintilla_UpdateUI(object sender, System.EventArgs e) { UpdatePositionInfo(sender as ScintillaNET.Scintilla); } private void UpdatePositionInfo(ScintillaNET.Scintilla scintilla) { CurrentColumn = scintilla.GetColumn(scintilla.CurrentPosition) + 1; CurrentLine = scintilla.CurrentLine + 1; OnPropertyChanged(nameof(PositionInfo)); } private void Scintilla_MouseDown(object sender, System.Windows.Forms.MouseEventArgs e) { UpdatePositionInfo(sender as ScintillaNET.Scintilla); } public event PropertyChangedEventHandler PropertyChanged; protected void OnPropertyChanged([CallerMemberName]string propertyName = null) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } #endregion } }
26.666667
94
0.551282
[ "MIT" ]
arnovb-github/CmcScriptNet.WPF
SCide.WPF/Models/StatusBarModel.cs
3,122
C#
using FluentAssertions; using System; using System.Threading.Tasks; using Xunit; namespace Aornis.Tests { public class FlatMap { const string initialValue = "Test"; const string newValue = "bees"; private readonly Optional<string> value; public FlatMap() { value = Optional.Of(initialValue); } #region Sync [Fact] public void FlatMapReturnsValueCreatedByFunc() { value.FlatMap(x => Optional.Of(newValue)).Should().Be(Optional.Of(newValue)); } [Fact] public void FlatMapReturnsEmptyWhenFuncReturnsEmpty() { value.FlatMap(x => Optional<string>.Empty).Should().Be(Optional<string>.Empty); } [Fact] public void FlatMapDoesNotCallFuncWhenValueIsEmpty() { Optional<string>.Empty.FlatMap(new Func<string, Optional<string>>(x => throw new Exception("This function should not be called"))); } #endregion #region Async [Fact] public async Task FlatMapAsyncReturnsValueCreatedByFunc() { (await value.FlatMapAsync(x => Task.FromResult(Optional.Of(x + newValue)))).Should().Be(Optional.Of(initialValue + newValue)); } [Fact] public async Task FlatMapAsyncReturnsEmptyWhenFuncReturnsEmpty() { (await value.FlatMapAsync(x => Task.FromResult(Optional<string>.Empty))).Should().Be(Optional<string>.Empty); } [Fact] public async Task FlatMapAsyncDoesNotCallFuncWhenValueIsEmpty() { await Optional<string>.Empty.FlatMapAsync(new Func<string, Task<Optional<string>>>(x => throw new Exception("This function should not be called"))); } #endregion } }
27.876923
160
0.610927
[ "Apache-2.0" ]
Foritus/optional-dot-net
Aornis.Optional.Tests/FlatMap.cs
1,814
C#
using NMaier.SimpleDlna.Server.Metadata; namespace NMaier.SimpleDlna.Server.Comparers { internal class DateComparer : TitleComparer { public override string Description => "Sort by file date"; public override string Name => "date"; public override int Compare(IMediaItem x, IMediaItem y) { var xm = x as IMetaInfo; var ym = y as IMetaInfo; if (xm != null && ym != null) { var rv = xm.InfoDate.CompareTo(ym.InfoDate); if (rv != 0) return rv; } return base.Compare(x, y); } } }
22.36
62
0.618962
[ "BSD-2-Clause" ]
Xen0byte/simpleDLNA
server/Comparers/DateComparer.cs
561
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.md file in the project root for more information. using Microsoft.VisualStudio.Composition; using Microsoft.VisualStudio.ProjectSystem; namespace Microsoft.VisualStudio.Telemetry { [ProjectSystemContract(ProjectSystemContractScope.Global, ProjectSystemContractProvider.Private, Cardinality = ImportCardinality.ExactlyOne)] internal interface ITelemetryService { /// <summary> /// Posts an event with the specified event name. /// </summary> /// <param name="eventName"> /// The name of the event. /// </param> /// <exception cref="ArgumentNullException"> /// <paramref name="eventName"/> is <see langword="null"/>. /// </exception> /// <exception cref="ArgumentException"> /// <paramref name="eventName"/> is an empty string (""). /// </exception> void PostEvent(string eventName); /// <summary> /// Posts an event with the specified event name and property with the /// specified name and value. /// </summary> /// <param name="eventName"> /// The name of the event. /// </param> /// <param name="propertyName"> /// The name of the property. /// </param> /// <param name="propertyValue"> /// The value of the property. /// </param> /// <exception cref="ArgumentNullException"> /// <paramref name="eventName"/> is <see langword="null"/>. /// <para> /// -or- /// </para> /// <paramref name="propertyName"/> is <see langword="null"/>. /// <para> /// -or- /// </para> /// <paramref name="propertyValue"/> is <see langword="null"/>. /// </exception> /// <exception cref="ArgumentException"> /// <paramref name="eventName"/> is an empty string (""). /// <para> /// -or /// </para> /// <paramref name="propertyName"/> is an empty string (""). /// </exception> void PostProperty(string eventName, string propertyName, object propertyValue); /// <summary> /// Posts an event with the specified event name and properties with the /// specified names and values. /// </summary> /// <param name="eventName"> /// The name of the event. /// </param> /// <param name="properties"> /// An <see cref="IEnumerable{T}"/> of property names and values. /// </param> /// <exception cref="ArgumentNullException"> /// <paramref name="eventName"/> is <see langword="null"/>. /// <para> /// -or- /// </para> /// <paramref name="properties"/> is <see langword="null"/>. /// </exception> /// <exception cref="ArgumentException"> /// <paramref name="eventName"/> is an empty string (""). /// <para> /// -or- /// </para> /// <paramref name="properties"/> is contains no elements. /// </exception> void PostProperties(string eventName, IEnumerable<(string propertyName, object propertyValue)> properties); /// <summary> /// Hashes personally identifiable information for telemetry consumption. /// </summary> /// <param name="value">Value to hashed.</param> /// <returns>Hashed value.</returns> string HashValue(string value); } }
41.73913
201
0.525781
[ "MIT" ]
adamint/project-system
src/Microsoft.VisualStudio.ProjectSystem.Managed/Telemetry/ITelemetryService.cs
3,751
C#
namespace MSBuild.Conversion.Package { public class PackagesConfigPackage { /// <summary> /// Name of the package. /// </summary> public string? ID { get; set; } /// <summary> /// Exact version of the package depended upon. /// </summary> public string? Version { get; set; } /// <summary> /// Optional TFM that the package dependency applies to. /// </summary> public string? TargetFramework { get; set; } /// <summary> /// Optional string of allowed versions that follow the NuGet spec for syntax. /// </summary> public string? AllowedVersions { get; set; } /// <summary> /// Optional flag for use only in development; the package will not be included when a consuming package is created. /// </summary> public bool DevelopmentDependency { get; set; } = false; } public class PackageReferencePackage { /// <summary> /// Name of the package. /// </summary> public string? ID { get; set; } /// <summary> /// Exact version of the package depended upon. /// </summary> public string? Version { get; set; } /// <summary> /// Optional TFM that the package dependency applies to. /// </summary> public string? TargetFramework { get; set; } /// <summary> /// Optional flag for use only in development; the package will not be included when a consuming package is created. /// </summary> public bool DevelopmentDependency { get; set; } = false; public PackageReferencePackage(PackagesConfigPackage pcp) { ID = pcp.ID; Version = string.IsNullOrWhiteSpace(pcp.AllowedVersions) ? pcp.Version : pcp.AllowedVersions; TargetFramework = pcp.TargetFramework; DevelopmentDependency = pcp.DevelopmentDependency; } } }
32.177419
124
0.576942
[ "MIT" ]
19317362/try-convert
src/MSBuild.Conversion.Package/Packages.cs
1,997
C#
using System; using System.Collections; using System.Collections.Specialized; namespace Zeus.UserInterface { public interface IGuiComboBox : IGuiListControl { string SelectedText { get; } string SelectedValue { get; set; } } }
236
236
0.762712
[ "BSD-3-Clause" ]
cafephin/mygeneration
src/mygeneration/Zeus/UserInterface/Interfaces/IGuiComboBox.cs
236
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.Reflection; using System.Diagnostics; using System.Reflection.Runtime.TypeInfos; using Internal.Reflection.Core; namespace System.Reflection.Runtime.General { internal static class Assignability { public static bool IsAssignableFrom(Type toTypeInfo, Type fromTypeInfo) { if (toTypeInfo == null) throw new NullReferenceException(); if (fromTypeInfo == null) return false; // It would be more appropriate to throw ArgumentNullException here, but returning "false" is the desktop-compat behavior. if (fromTypeInfo.Equals(toTypeInfo)) return true; if (toTypeInfo.IsGenericTypeDefinition) { // Asking whether something can cast to a generic type definition is arguably meaningless. The desktop CLR Reflection layer converts all // generic type definitions to generic type instantiations closed over the formal generic type parameters. The .NET Native framework // keeps the two separate. Fortunately, under either interpretation, returning "false" unless the two types are identical is still a // defensible behavior. To avoid having the rest of the code deal with the differing interpretations, we'll short-circuit this now. return false; } if (fromTypeInfo.IsGenericTypeDefinition) { // The desktop CLR Reflection layer converts all generic type definitions to generic type instantiations closed over the formal // generic type parameters. The .NET Native framework keeps the two separate. For the purpose of IsAssignableFrom(), // it makes sense to unify the two for the sake of backward compat. We'll just make the transform here so that the rest of code // doesn't need to know about this quirk. fromTypeInfo = fromTypeInfo.GetGenericTypeDefinition().MakeGenericType(fromTypeInfo.GetGenericTypeParameters()); } if (fromTypeInfo.CanCastTo(toTypeInfo)) return true; // Desktop compat: IsAssignableFrom() considers T as assignable to Nullable<T> (but does not check if T is a generic parameter.) if (!fromTypeInfo.IsGenericParameter) { Type nullableUnderlyingType = Nullable.GetUnderlyingType(toTypeInfo); if (nullableUnderlyingType != null && nullableUnderlyingType.Equals(fromTypeInfo)) return true; } return false; } private static bool CanCastTo(this Type fromTypeInfo, Type toTypeInfo) { if (fromTypeInfo.Equals(toTypeInfo)) return true; if (fromTypeInfo.IsArray) { if (toTypeInfo.IsInterface) return fromTypeInfo.CanCastArrayToInterface(toTypeInfo); if (fromTypeInfo.IsSubclassOf(toTypeInfo)) return true; // T[] is castable to Array or Object. if (!toTypeInfo.IsArray) return false; int rank = fromTypeInfo.GetArrayRank(); if (rank != toTypeInfo.GetArrayRank()) return false; bool fromTypeIsSzArray = fromTypeInfo.IsSZArray; bool toTypeIsSzArray = toTypeInfo.IsSZArray; if (fromTypeIsSzArray != toTypeIsSzArray) { // T[] is assignable to T[*] but not vice-versa. if (!(rank == 1 && !toTypeIsSzArray)) { return false; // T[*] is not castable to T[] } } Type toElementTypeInfo = toTypeInfo.GetElementType(); Type fromElementTypeInfo = fromTypeInfo.GetElementType(); return fromElementTypeInfo.IsElementTypeCompatibleWith(toElementTypeInfo); } if (fromTypeInfo.IsByRef) { if (!toTypeInfo.IsByRef) return false; Type toElementTypeInfo = toTypeInfo.GetElementType(); Type fromElementTypeInfo = fromTypeInfo.GetElementType(); return fromElementTypeInfo.IsElementTypeCompatibleWith(toElementTypeInfo); } if (fromTypeInfo.IsPointer) { if (toTypeInfo.Equals(CommonRuntimeTypes.Object)) return true; // T* is castable to Object. if (toTypeInfo.Equals(CommonRuntimeTypes.UIntPtr)) return true; // T* is castable to UIntPtr (but not IntPtr) if (!toTypeInfo.IsPointer) return false; Type toElementTypeInfo = toTypeInfo.GetElementType(); Type fromElementTypeInfo = fromTypeInfo.GetElementType(); return fromElementTypeInfo.IsElementTypeCompatibleWith(toElementTypeInfo); } if (fromTypeInfo.IsGenericParameter) { // // A generic parameter can be cast to any of its constraints, or object, if none are specified, or ValueType if the "struct" constraint is // specified. // // This has to be coded as its own case as TypeInfo.BaseType on a generic parameter doesn't always return what you'd expect. // if (toTypeInfo.Equals(CommonRuntimeTypes.Object)) return true; if (toTypeInfo.Equals(CommonRuntimeTypes.ValueType)) { GenericParameterAttributes attributes = fromTypeInfo.GenericParameterAttributes; if ((attributes & GenericParameterAttributes.NotNullableValueTypeConstraint) != 0) return true; } foreach (Type constraintType in fromTypeInfo.GetGenericParameterConstraints()) { if (constraintType.CanCastTo(toTypeInfo)) return true; } return false; } if (toTypeInfo.IsArray || toTypeInfo.IsByRef || toTypeInfo.IsPointer || toTypeInfo.IsGenericParameter) return false; if (fromTypeInfo.MatchesWithVariance(toTypeInfo)) return true; if (toTypeInfo.IsInterface) { foreach (Type ifc in fromTypeInfo.GetInterfaces()) { if (ifc.MatchesWithVariance(toTypeInfo)) return true; } return false; } else { // Interfaces are always castable to System.Object. The code below will not catch this as interfaces report their BaseType as null. if (toTypeInfo.Equals(CommonRuntimeTypes.Object) && fromTypeInfo.IsInterface) return true; Type walk = fromTypeInfo; for (;;) { Type baseType = walk.BaseType; if (baseType == null) return false; walk = baseType; if (walk.MatchesWithVariance(toTypeInfo)) return true; } } } // // Check a base type or implemented interface type for equivalence (taking into account variance for generic instantiations.) // Does not check ancestors recursively. // private static bool MatchesWithVariance(this Type fromTypeInfo, Type toTypeInfo) { Debug.Assert(!(fromTypeInfo.IsArray || fromTypeInfo.IsByRef || fromTypeInfo.IsPointer || fromTypeInfo.IsGenericParameter)); Debug.Assert(!(toTypeInfo.IsArray || toTypeInfo.IsByRef || toTypeInfo.IsPointer || toTypeInfo.IsGenericParameter)); if (fromTypeInfo.Equals(toTypeInfo)) return true; if (!(fromTypeInfo.IsConstructedGenericType && toTypeInfo.IsConstructedGenericType)) return false; Type genericTypeDefinition = fromTypeInfo.GetGenericTypeDefinition(); if (!genericTypeDefinition.Equals(toTypeInfo.GetGenericTypeDefinition())) return false; Type[] fromTypeArguments = fromTypeInfo.GenericTypeArguments; Type[] toTypeArguments = toTypeInfo.GenericTypeArguments; Type[] genericTypeParameters = genericTypeDefinition.GetGenericTypeParameters(); for (int i = 0; i < genericTypeParameters.Length; i++) { Type fromTypeArgumentInfo = fromTypeArguments[i]; Type toTypeArgumentInfo = toTypeArguments[i]; GenericParameterAttributes attributes = genericTypeParameters[i].GenericParameterAttributes; switch (attributes & GenericParameterAttributes.VarianceMask) { case GenericParameterAttributes.Covariant: if (!(fromTypeArgumentInfo.IsGcReferenceTypeAndCastableTo(toTypeArgumentInfo))) return false; break; case GenericParameterAttributes.Contravariant: if (!(toTypeArgumentInfo.IsGcReferenceTypeAndCastableTo(fromTypeArgumentInfo))) return false; break; case GenericParameterAttributes.None: if (!(fromTypeArgumentInfo.Equals(toTypeArgumentInfo))) return false; break; default: throw new BadImageFormatException(); // Unexpected variance value in metadata. } } return true; } // // A[] can cast to B[] if one of the following are true: // // A can cast to B under variance rules. // // A and B are both integers or enums and have the same reduced type (i.e. represent the same-sized integer, ignoring signed/unsigned differences.) // "char" is not interchangable with short/ushort. "bool" is not interchangable with byte/sbyte. // // For desktop compat, A& and A* follow the same rules. // private static bool IsElementTypeCompatibleWith(this Type fromTypeInfo, Type toTypeInfo) { if (fromTypeInfo.IsGcReferenceTypeAndCastableTo(toTypeInfo)) return true; Type reducedFromType = fromTypeInfo.ReducedType(); Type reducedToType = toTypeInfo.ReducedType(); if (reducedFromType.Equals(reducedToType)) return true; return false; } private static Type ReducedType(this Type t) { if (t.IsEnum) t = Enum.GetUnderlyingType(t); if (t.Equals(CommonRuntimeTypes.Byte)) return CommonRuntimeTypes.SByte; if (t.Equals(CommonRuntimeTypes.UInt16)) return CommonRuntimeTypes.Int16; if (t.Equals(CommonRuntimeTypes.UInt32)) return CommonRuntimeTypes.Int32; if (t.Equals(CommonRuntimeTypes.UInt64)) return CommonRuntimeTypes.Int64; if (t.Equals(CommonRuntimeTypes.UIntPtr) || t.Equals(CommonRuntimeTypes.IntPtr)) { #if WIN64 return CommonRuntimeTypes.Int64; #else return CommonRuntimeTypes.Int32; #endif } return t; } // // Contra/CoVariance. // // IEnumerable<D> can cast to IEnumerable<B> if D can cast to B and if there's no possibility that D is a value type. // private static bool IsGcReferenceTypeAndCastableTo(this Type fromTypeInfo, Type toTypeInfo) { if (fromTypeInfo.Equals(toTypeInfo)) return true; if (fromTypeInfo.ProvablyAGcReferenceType()) return fromTypeInfo.CanCastTo(toTypeInfo); return false; } // // A true result indicates that a type can never be a value type. This is important when testing variance-compatibility. // private static bool ProvablyAGcReferenceType(this Type t) { if (t.IsGenericParameter) { GenericParameterAttributes attributes = t.GenericParameterAttributes; if ((attributes & GenericParameterAttributes.ReferenceTypeConstraint) != 0) return true; // generic parameter with a "class" constraint. } return t.ProvablyAGcReferenceTypeHelper(); } private static bool ProvablyAGcReferenceTypeHelper(this Type t) { if (t.IsArray) return true; if (t.IsByRef || t.IsPointer) return false; if (t.IsGenericParameter) { // We intentionally do not check for a "class" constraint on generic parameter ancestors. // That's because this property does not propagate up the constraining hierarchy. // (e.g. "class A<S, T> where S : T, where T : class" does not guarantee that S is a class.) foreach (Type constraintType in t.GetGenericParameterConstraints()) { if (constraintType.ProvablyAGcReferenceTypeHelper()) return true; } return false; } return t.IsClass && !t.Equals(CommonRuntimeTypes.Object) && !t.Equals(CommonRuntimeTypes.ValueType) && !t.Equals(CommonRuntimeTypes.Enum); } // // T[] casts to IList<T>. This could be handled by the normal ancestor-walking code // but for one complication: T[] also casts to IList<U> if T[] casts to U[]. // private static bool CanCastArrayToInterface(this Type fromTypeInfo, Type toTypeInfo) { Debug.Assert(fromTypeInfo.IsArray); Debug.Assert(toTypeInfo.IsInterface); if (toTypeInfo.IsConstructedGenericType) { Type[] toTypeGenericTypeArguments = toTypeInfo.GenericTypeArguments; if (toTypeGenericTypeArguments.Length != 1) return false; Type toElementTypeInfo = toTypeGenericTypeArguments[0]; Type toTypeGenericTypeDefinition = toTypeInfo.GetGenericTypeDefinition(); Type fromElementTypeInfo = fromTypeInfo.GetElementType(); foreach (Type ifc in fromTypeInfo.GetInterfaces()) { if (ifc.IsConstructedGenericType) { Type ifcGenericTypeDefinition = ifc.GetGenericTypeDefinition(); if (ifcGenericTypeDefinition.Equals(toTypeGenericTypeDefinition)) { if (fromElementTypeInfo.IsElementTypeCompatibleWith(toElementTypeInfo)) return true; } } } return false; } else { foreach (Type ifc in fromTypeInfo.GetInterfaces()) { if (ifc.Equals(toTypeInfo)) return true; } return false; } } } }
41.580729
158
0.569738
[ "MIT" ]
Dotnet-GitSync-Bot/corert
src/System.Private.Reflection.Core/src/System/Reflection/Runtime/General/Assignability.cs
15,967
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.Web; using Altinn.Authorization.ABAC.Xacml.JsonProfile; using Altinn.Common.PEP.Helpers; using Altinn.Common.PEP.Interfaces; using Altinn.Platform.Storage.Clients; using Altinn.Platform.Storage.Configuration; using Altinn.Platform.Storage.Helpers; using Altinn.Platform.Storage.Interface.Enums; using Altinn.Platform.Storage.Interface.Models; using Altinn.Platform.Storage.Repository; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http.Extensions; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.WebUtilities; using Microsoft.Azure.Documents; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using Microsoft.Extensions.Primitives; using Newtonsoft.Json; using Substatus = Altinn.Platform.Storage.Interface.Models.Substatus; namespace Altinn.Platform.Storage.Controllers { /// <summary> /// Handles operations for the application instance resource /// </summary> [Route("storage/api/v1/instances")] [ApiController] public class InstancesController : ControllerBase { private readonly List<string> _instanceReadScope = new List<string>() { "altinn:serviceowner/instances.read" }; private readonly IInstanceRepository _instanceRepository; private readonly IInstanceEventRepository _instanceEventRepository; private readonly IApplicationRepository _applicationRepository; private readonly IPartiesWithInstancesClient _partiesWithInstancesClient; private readonly ILogger _logger; private readonly IPDP _pdp; private readonly AuthorizationHelper _authzHelper; private readonly string _storageBaseAndHost; private readonly GeneralSettings _generalSettings; /// <summary> /// Initializes a new instance of the <see cref="InstancesController"/> class /// </summary> /// <param name="instanceRepository">the instance repository handler</param> /// <param name="instanceEventRepository">the instance event repository service</param> /// <param name="applicationRepository">the application repository handler</param> /// <param name="partiesWithInstancesClient">An implementation of <see cref="IPartiesWithInstancesClient"/> that can be used to send information to SBL.</param> /// <param name="logger">the logger</param> /// <param name="authzLogger">the logger for the authorization helper</param> /// <param name="pdp">the policy decision point.</param> /// <param name="settings">the general settings.</param> public InstancesController( IInstanceRepository instanceRepository, IInstanceEventRepository instanceEventRepository, IApplicationRepository applicationRepository, IPartiesWithInstancesClient partiesWithInstancesClient, ILogger<InstancesController> logger, ILogger<AuthorizationHelper> authzLogger, IPDP pdp, IOptions<GeneralSettings> settings) { _instanceRepository = instanceRepository; _instanceEventRepository = instanceEventRepository; _applicationRepository = applicationRepository; _partiesWithInstancesClient = partiesWithInstancesClient; _pdp = pdp; _logger = logger; _storageBaseAndHost = $"{settings.Value.Hostname}/storage/api/v1/"; _authzHelper = new AuthorizationHelper(pdp, authzLogger); _generalSettings = settings.Value; } /// <summary> /// Get all instances that match the given query parameters. Parameters can be combined. Unknown or illegal parameter values will result in 400 - bad request. /// </summary> /// <param name="org">application owner.</param> /// <param name="appId">application id.</param> /// <param name="currentTaskId">Running process current task id.</param> /// <param name="processIsComplete">Is process complete.</param> /// <param name="processEndEvent">Process end state.</param> /// <param name="processEnded">Process ended value.</param> /// <param name="instanceOwnerPartyId">Instance owner id.</param> /// <param name="lastChanged">Last changed date.</param> /// <param name="created">Created time.</param> /// <param name="visibleAfter">The visible after date time.</param> /// <param name="dueBefore">The due before date time.</param> /// <param name="excludeConfirmedBy">A string that will hide instances already confirmed by stakeholder.</param> /// <param name="isSoftDeleted">Is the instance soft deleted.</param> /// <param name="isArchived">Is the instance archived.</param> /// <param name="continuationToken">Continuation token.</param> /// <param name="size">The page size.</param> /// <returns>List of all instances for given instance owner.</returns> /// <!-- GET /instances?org=tdd or GET /instances?appId=tdd/app2 --> [Authorize] [HttpGet] [ProducesResponseType(StatusCodes.Status200OK)] [ProducesResponseType(StatusCodes.Status400BadRequest)] [Produces("application/json")] public async Task<ActionResult<QueryResponse<Instance>>> GetInstances( [FromQuery] string org, [FromQuery] string appId, [FromQuery(Name = "process.currentTask")] string currentTaskId, [FromQuery(Name = "process.isComplete")] bool? processIsComplete, [FromQuery(Name = "process.endEvent")] string processEndEvent, [FromQuery(Name = "process.ended")] string processEnded, [FromQuery(Name = "instanceOwner.partyId")] int? instanceOwnerPartyId, [FromQuery] string lastChanged, [FromQuery] string created, [FromQuery(Name = "visibleAfter")] string visibleAfter, [FromQuery] string dueBefore, [FromQuery] string excludeConfirmedBy, [FromQuery(Name = "status.isSoftDeleted")] bool isSoftDeleted, [FromQuery(Name = "status.isArchived")] bool isArchived, string continuationToken, int? size) { int pageSize = size ?? 100; string selfContinuationToken = null; bool isOrgQuerying = false; // if user is org string orgClaim = User.GetOrg(); int? userId = User.GetUserIdAsInt(); if (orgClaim != null) { isOrgQuerying = true; if (!_authzHelper.ContainsRequiredScope(_instanceReadScope, User)) { return Forbid(); } if (string.IsNullOrEmpty(org) && string.IsNullOrEmpty(appId)) { return BadRequest("Org or AppId must be defined."); } org = string.IsNullOrEmpty(org) ? appId.Split('/')[0] : org; if (!orgClaim.Equals(org, StringComparison.InvariantCultureIgnoreCase)) { return Forbid(); } } else if (userId != null) { if (instanceOwnerPartyId == null) { return BadRequest("InstanceOwnerPartyId must be defined."); } } else { return BadRequest(); } if (!string.IsNullOrEmpty(continuationToken)) { selfContinuationToken = continuationToken; continuationToken = HttpUtility.UrlDecode(continuationToken); } Dictionary<string, StringValues> queryParams = QueryHelpers.ParseQuery(Request.QueryString.Value); string host = $"https://platform.{_generalSettings.Hostname}"; string url = Request.Path; string query = Request.QueryString.Value; try { InstanceQueryResponse result = await _instanceRepository.GetInstancesFromQuery(queryParams, continuationToken, pageSize); if (!string.IsNullOrEmpty(result.Exception)) { return BadRequest(result.Exception); } if (!isOrgQuerying) { result.Instances = await _authzHelper.AuthorizeInstances(User, result.Instances); result.Count = result.Instances.Count; } string nextContinuationToken = HttpUtility.UrlEncode(result.ContinuationToken); result.ContinuationToken = null; QueryResponse<Instance> response = new QueryResponse<Instance> { Instances = result.Instances, Count = result.Instances.Count, }; if (continuationToken == null) { string selfUrl = $"{host}{url}{query}"; response.Self = selfUrl; } else { string selfQueryString = BuildQueryStringWithOneReplacedParameter( queryParams, "continuationToken", selfContinuationToken); string selfUrl = $"{host}{url}{selfQueryString}"; response.Self = selfUrl; } if (!string.IsNullOrEmpty(nextContinuationToken)) { string nextQueryString = BuildQueryStringWithOneReplacedParameter( queryParams, "continuationToken", nextContinuationToken); string nextUrl = $"{host}{url}{nextQueryString}"; response.Next = nextUrl; } // add self links to platform result.Instances.ForEach(i => i.SetPlatformSelfLinks(_storageBaseAndHost)); return Ok(response); } catch (Exception e) { _logger.LogError($"Unable to perform query on instances due to: {e}"); return StatusCode(500, $"Unable to perform query on instances due to: {e.Message}"); } } /// <summary> /// Gets a specific instance with the given instance id. /// </summary> /// <param name="instanceOwnerPartyId">The party id of the instance owner.</param> /// <param name="instanceGuid">The id of the instance to retrieve.</param> /// <returns>The information about the specific instance.</returns> [Authorize(Policy = AuthzConstants.POLICY_INSTANCE_READ)] [HttpGet("{instanceOwnerPartyId:int}/{instanceGuid:guid}")] [ProducesResponseType(StatusCodes.Status200OK)] [ProducesResponseType(StatusCodes.Status404NotFound)] [Produces("application/json")] public async Task<ActionResult<Instance>> Get(int instanceOwnerPartyId, Guid instanceGuid) { string instanceId = $"{instanceOwnerPartyId}/{instanceGuid}"; try { Instance result = await _instanceRepository.GetOne(instanceId, instanceOwnerPartyId); result.SetPlatformSelfLinks(_storageBaseAndHost); return Ok(result); } catch (Exception e) { return NotFound($"Unable to find instance {instanceId}: {e}"); } } /// <summary> /// Inserts new instance into the instance collection. /// </summary> /// <param name="appId">the application id</param> /// <param name="instance">The instance details to store.</param> /// <returns>The stored instance.</returns> /// <!-- POST /instances?appId={appId} --> [Authorize] [HttpPost] [Consumes("application/json")] [ProducesResponseType(StatusCodes.Status201Created)] [ProducesResponseType(StatusCodes.Status400BadRequest)] [Produces("application/json")] public async Task<ActionResult<Instance>> Post(string appId, [FromBody] Instance instance) { (Application appInfo, ActionResult appInfoError) = await GetApplicationOrErrorAsync(appId); int instanceOwnerPartyId = int.Parse(instance.InstanceOwner.PartyId); if (appInfoError != null) { return appInfoError; } if (string.IsNullOrWhiteSpace(instance.InstanceOwner.PartyId)) { return BadRequest("Cannot create an instance without an instanceOwner.PartyId."); } // Checking that user is authorized to instantiate. XacmlJsonRequestRoot request = DecisionHelper.CreateDecisionRequest(appInfo.Org, appInfo.Id.Split('/')[1], HttpContext.User, "instantiate", instanceOwnerPartyId, null); XacmlJsonResponse response = await _pdp.GetDecisionForRequest(request); if (response?.Response == null) { _logger.LogInformation($"// Instances Controller // Authorization of instantiation failed with request: {JsonConvert.SerializeObject(request)}."); return Forbid(); } bool authorized = DecisionHelper.ValidatePdpDecision(response.Response, HttpContext.User); if (!authorized) { return Forbid(); } Instance storedInstance = new Instance(); try { DateTime creationTime = DateTime.UtcNow; string userId = GetUserId(); Instance instanceToCreate = CreateInstanceFromTemplate(appInfo, instance, creationTime, userId); storedInstance = await _instanceRepository.Create(instanceToCreate); await DispatchEvent(InstanceEventType.Created, storedInstance); _logger.LogInformation($"Created instance: {storedInstance.Id}"); storedInstance.SetPlatformSelfLinks(_storageBaseAndHost); await _partiesWithInstancesClient.SetHasAltinn3Instances(instanceOwnerPartyId); return Created(storedInstance.SelfLinks.Platform, storedInstance); } catch (Exception storageException) { _logger.LogError($"Unable to create {appId} instance for {instance.InstanceOwner.PartyId} due to {storageException}"); // compensating action - delete instance await _instanceRepository.Delete(storedInstance); _logger.LogError($"Deleted instance {storedInstance.Id}"); return StatusCode(500, $"Unable to create {appId} instance for {instance.InstanceOwner.PartyId} due to {storageException.Message}"); } } /// <summary> /// Delete an instance. /// </summary> /// <param name="instanceOwnerPartyId">The party id of the instance owner.</param> /// <param name="instanceGuid">The id of the instance that should be deleted.</param> /// <param name="hard">if true hard delete will take place. if false, the instance gets its status.softDelete attribute set to current date and time.</param> /// <returns>Information from the deleted instance.</returns> [Authorize(Policy = AuthzConstants.POLICY_INSTANCE_DELETE)] [HttpDelete("{instanceOwnerPartyId:int}/{instanceGuid:guid}")] [ProducesResponseType(StatusCodes.Status200OK)] [ProducesResponseType(StatusCodes.Status204NoContent)] [ProducesResponseType(StatusCodes.Status400BadRequest)] [ProducesResponseType(StatusCodes.Status404NotFound)] [Produces("application/json")] public async Task<ActionResult<Instance>> Delete(int instanceOwnerPartyId, Guid instanceGuid, [FromQuery] bool hard) { string instanceId = $"{instanceOwnerPartyId}/{instanceGuid}"; Instance instance; try { instance = await _instanceRepository.GetOne(instanceId, instanceOwnerPartyId); } catch (DocumentClientException dce) { if (dce.Error.Code.Equals("NotFound")) { return NotFound($"Didn't find the object that should be deleted with instanceId={instanceId}"); } _logger.LogError($"Cannot delete instance {instanceId}. Due to {dce}"); return StatusCode(500, $"Unknown database exception in delete: {dce}"); } catch (Exception e) { _logger.LogError($"Cannot delete instance {instanceId}. Due to {e}"); return StatusCode(500, $"Unknown exception in delete: {e}"); } DateTime now = DateTime.UtcNow; if (instance.Status == null) { instance.Status = new InstanceStatus(); } if (hard) { instance.Status.IsHardDeleted = true; instance.Status.IsSoftDeleted = true; instance.Status.HardDeleted = now; instance.Status.SoftDeleted ??= now; } else { instance.Status.IsSoftDeleted = true; instance.Status.SoftDeleted = now; } instance.LastChangedBy = GetUserId(); instance.LastChanged = now; try { Instance deletedInstance = await _instanceRepository.Update(instance); return Ok(deletedInstance); } catch (Exception e) { _logger.LogError($"Unexpected exception when deleting instance {instance.Id}: {e}"); return StatusCode(500, $"Unexpected exception when deleting instance {instance.Id}: {e.Message}"); } } /// <summary> /// Add complete confirmation. /// </summary> /// <remarks> /// Add to an instance that a given stakeholder considers the instance as no longer needed by them. The stakeholder has /// collected all the data and information they needed from the instance and expect no additional data to be added to it. /// The body of the request isn't used for anything despite this being a POST operation. /// </remarks> /// <param name="instanceOwnerPartyId">The party id of the instance owner.</param> /// <param name="instanceGuid">The id of the instance to confirm as complete.</param> /// <returns>Returns a list of the process events.</returns> [Authorize(Policy = AuthzConstants.POLICY_INSTANCE_COMPLETE)] [HttpPost("{instanceOwnerPartyId:int}/{instanceGuid:guid}/complete")] [ProducesResponseType(StatusCodes.Status200OK)] [Produces("application/json")] public async Task<ActionResult<Instance>> AddCompleteConfirmation( [FromRoute] int instanceOwnerPartyId, [FromRoute] Guid instanceGuid) { string instanceId = $"{instanceOwnerPartyId}/{instanceGuid}"; Instance instance = await _instanceRepository.GetOne(instanceId, instanceOwnerPartyId); string org = User.GetOrg(); instance.CompleteConfirmations ??= new List<CompleteConfirmation>(); if (instance.CompleteConfirmations.Any(cc => cc.StakeholderId == org)) { instance.SetPlatformSelfLinks(_storageBaseAndHost); return Ok(instance); } instance.CompleteConfirmations.Add(new CompleteConfirmation { StakeholderId = org, ConfirmedOn = DateTime.UtcNow }); instance.LastChanged = DateTime.UtcNow; instance.LastChangedBy = User.GetUserOrOrgId(); Instance updatedInstance; try { updatedInstance = await _instanceRepository.Update(instance); updatedInstance.SetPlatformSelfLinks(_storageBaseAndHost); } catch (Exception e) { _logger.LogError(e, $"Unable to update instance {instanceId}"); return StatusCode(StatusCodes.Status500InternalServerError); } await DispatchEvent(InstanceEventType.ConfirmedComplete, updatedInstance); return Ok(updatedInstance); } /// <summary> /// Update instance read status. /// </summary> /// <param name="instanceOwnerPartyId">The party id of the instance owner.</param> /// <param name="instanceGuid">The id of the instance to confirm as complete.</param> /// <param name="status">The updated read status.</param> /// <returns>Returns the updated instance.</returns> [Authorize(Policy = AuthzConstants.POLICY_INSTANCE_READ)] [HttpPut("{instanceOwnerPartyId:int}/{instanceGuid:guid}/readstatus")] [ProducesResponseType(StatusCodes.Status200OK)] [ProducesResponseType(StatusCodes.Status400BadRequest)] [Produces("application/json")] public async Task<ActionResult<Instance>> UpdateReadStatus( [FromRoute] int instanceOwnerPartyId, [FromRoute] Guid instanceGuid, [FromQuery] string status) { if (!Enum.TryParse(status, true, out ReadStatus newStatus)) { return BadRequest($"Invalid read status: {status}. Accepted types include: {string.Join(", ", Enum.GetNames(typeof(ReadStatus)))}"); } string instanceId = $"{instanceOwnerPartyId}/{instanceGuid}"; Instance instance = await _instanceRepository.GetOne(instanceId, instanceOwnerPartyId); Instance updatedInstance; try { if (instance.Status == null) { instance.Status = new InstanceStatus(); } instance.Status.ReadStatus = newStatus; updatedInstance = await _instanceRepository.Update(instance); updatedInstance.SetPlatformSelfLinks(_storageBaseAndHost); } catch (Exception e) { _logger.LogError(e, $"Unable to update read status for instance {instanceId}"); return StatusCode(StatusCodes.Status500InternalServerError); } return Ok(updatedInstance); } /// <summary> /// Update instance sub status. /// </summary> /// <param name="instanceOwnerPartyId">The party id of the instance owner.</param> /// <param name="instanceGuid">The id of the instance to confirm as complete.</param> /// <param name="substatus">The updated sub status.</param> /// <returns>Returns the updated instance.</returns> [Authorize] [HttpPut("{instanceOwnerPartyId:int}/{instanceGuid:guid}/substatus")] [ProducesResponseType(StatusCodes.Status200OK)] [ProducesResponseType(StatusCodes.Status400BadRequest)] [Produces("application/json")] public async Task<ActionResult<Instance>> UpdateSubstatus( [FromRoute] int instanceOwnerPartyId, [FromRoute] Guid instanceGuid, [FromBody] Substatus substatus) { DateTime creationTime = DateTime.UtcNow; if (substatus == null || string.IsNullOrEmpty(substatus.Label)) { return BadRequest($"Invalid sub status: {JsonConvert.SerializeObject(substatus)}. Substatus must be defined and include a label."); } string instanceId = $"{instanceOwnerPartyId}/{instanceGuid}"; Instance instance = await _instanceRepository.GetOne(instanceId, instanceOwnerPartyId); string org = User.GetOrg(); if (!instance.Org.Equals(org)) { return Forbid(); } Instance updatedInstance; try { if (instance.Status == null) { instance.Status = new InstanceStatus(); } instance.Status.Substatus = substatus; instance.LastChanged = creationTime; instance.LastChangedBy = User.GetOrgNumber().ToString(); updatedInstance = await _instanceRepository.Update(instance); updatedInstance.SetPlatformSelfLinks(_storageBaseAndHost); } catch (Exception e) { _logger.LogError(e, $"Unable to update sub status for instance {instanceId}"); return StatusCode(StatusCodes.Status500InternalServerError); } await DispatchEvent(InstanceEventType.SubstatusUpdated, updatedInstance); return Ok(updatedInstance); } /// <summary> /// Updates the presentation texts on an instance /// </summary> /// <param name="instanceOwnerPartyId">The party id of the instance owner.</param> /// <param name="instanceGuid">The id of the instance to confirm as complete.</param> /// <param name="presentationTexts">Collection of changes to the presentation texts collection.</param> /// <returns>The instance that was updated with an updated collection of presentation texts.</returns> [Authorize(Policy = AuthzConstants.POLICY_INSTANCE_WRITE)] [HttpPut("{instanceOwnerPartyId:int}/{instanceGuid:guid}/presentationtexts")] [ProducesResponseType(StatusCodes.Status200OK)] [Consumes("application/json")] [Produces("application/json")] public async Task<Instance> UpdatePresentationTexts( [FromRoute] int instanceOwnerPartyId, [FromRoute] Guid instanceGuid, [FromBody] PresentationTexts presentationTexts) { string instanceId = $"{instanceOwnerPartyId}/{instanceGuid}"; Instance instance = await _instanceRepository.GetOne(instanceId, instanceOwnerPartyId); if (instance.PresentationTexts == null) { instance.PresentationTexts = new Dictionary<string, string>(); } foreach (KeyValuePair<string, string> entry in presentationTexts.Texts) { if (string.IsNullOrEmpty(entry.Value)) { instance.PresentationTexts.Remove(entry.Key); } else { instance.PresentationTexts[entry.Key] = entry.Value; } } Instance updatedInstance = await _instanceRepository.Update(instance); return updatedInstance; } private Instance CreateInstanceFromTemplate(Application appInfo, Instance instanceTemplate, DateTime creationTime, string userId) { Instance createdInstance = new Instance { InstanceOwner = instanceTemplate.InstanceOwner, CreatedBy = userId, Created = creationTime, LastChangedBy = userId, LastChanged = creationTime, AppId = appInfo.Id, Org = appInfo.Org, VisibleAfter = DateTimeHelper.ConvertToUniversalTime(instanceTemplate.VisibleAfter) ?? creationTime, Status = instanceTemplate.Status ?? new InstanceStatus(), DueBefore = DateTimeHelper.ConvertToUniversalTime(instanceTemplate.DueBefore), Data = new List<DataElement>(), Process = instanceTemplate.Process, }; return createdInstance; } private async Task<(Application, ActionResult)> GetApplicationOrErrorAsync(string appId) { ActionResult errorResult = null; Application appInfo = null; try { string org = appId.Split("/")[0]; appInfo = await _applicationRepository.FindOne(appId, org); } catch (DocumentClientException dce) { if (dce.Error.Code.Equals("NotFound")) { errorResult = NotFound($"Did not find application with appId={appId}"); } else { errorResult = StatusCode(500, $"Document database error: {dce}"); } } catch (Exception e) { errorResult = StatusCode(500, $"Unable to perform request: {e}"); } return (appInfo, errorResult); } private async Task DispatchEvent(InstanceEventType eventType, Instance instance) { InstanceEvent instanceEvent = new InstanceEvent { EventType = eventType.ToString(), InstanceId = instance.Id, InstanceOwnerPartyId = instance.InstanceOwner.PartyId, User = new PlatformUser { UserId = User.GetUserIdAsInt(), AuthenticationLevel = User.GetAuthenticationLevel(), OrgId = User.GetOrg(), }, ProcessInfo = instance.Process, Created = DateTime.UtcNow, }; await _instanceEventRepository.InsertInstanceEvent(instanceEvent); } private static string BuildQueryStringWithOneReplacedParameter(Dictionary<string, StringValues> q, string queryParamName, string newParamValue) { List<KeyValuePair<string, string>> items = q.SelectMany( x => x.Value, (col, value) => new KeyValuePair<string, string>(col.Key, value)) .ToList(); items.RemoveAll(x => x.Key == queryParamName); var qb = new QueryBuilder(items) { { queryParamName, newParamValue } }; string nextQueryString = qb.ToQueryString().Value; return nextQueryString; } private string GetUserId() { return User.GetUserOrOrgId(); } } }
42.334254
180
0.597423
[ "BSD-3-Clause" ]
astromoskar/altinn-studio
src/Altinn.Platform/Altinn.Platform.Storage/Storage/Controllers/InstancesController.cs
30,650
C#
using System; using System.Collections.Concurrent; using System.Linq; using System.Threading; using System.Threading.Tasks; using Learning.EventStore.DataStores; using Learning.EventStore.Domain; namespace Learning.EventStore.Cache { public class CacheRepository : IRepository { private readonly IRepository _repository; private readonly IEventStore _eventStore; private readonly ICache _cache; private static readonly ConcurrentDictionary<string, SemaphoreSlim> Locks = new ConcurrentDictionary<string, SemaphoreSlim>(); private static SemaphoreSlim CreateLock(string _) => new SemaphoreSlim(1, 1); public CacheRepository(IRepository repository, IEventStore eventStore, ICache cache) { _repository = repository ?? throw new ArgumentNullException(nameof(repository)); _eventStore = eventStore ?? throw new ArgumentNullException(nameof(eventStore)); _cache = cache ?? throw new ArgumentNullException(nameof(cache)); _cache.RegisterEvictionCallback(key => Locks.TryRemove(key, out var _)); } public async Task SaveAsync<T>(T aggregate, int? expectedVersion = null) where T : AggregateRoot { var @lock = Locks.GetOrAdd(aggregate.Id, CreateLock); await @lock.WaitAsync().ConfigureAwait(false); try { if (!string.IsNullOrEmpty(aggregate.Id) && !await _cache.IsTracked(aggregate.Id).ConfigureAwait(false)) { await _cache.Set(aggregate.Id, aggregate).ConfigureAwait(false); } await _repository.SaveAsync(aggregate, expectedVersion).ConfigureAwait(false); } catch (Exception) { await _cache.Remove(aggregate.Id).ConfigureAwait(false); throw; } finally { @lock.Release(); } } public async Task<T> GetAsync<T>(string aggregateId) where T : AggregateRoot { var @lock = Locks.GetOrAdd(aggregateId, CreateLock); await @lock.WaitAsync().ConfigureAwait(false); try { T aggregate; if (await _cache.IsTracked(aggregateId).ConfigureAwait(false)) { aggregate = (T) await _cache.Get(aggregateId).ConfigureAwait(false);; var aggregateType = typeof(T).Name; var events = await _eventStore.GetAsync(aggregateId, aggregateType, aggregate.Version).ConfigureAwait(false); if (events.Any() && events.First().Version != aggregate.Version + 1) { await _cache.Remove(aggregateId).ConfigureAwait(false); } else { aggregate.LoadFromHistory(events); return aggregate; } } aggregate = await _repository.GetAsync<T>(aggregateId).ConfigureAwait(false); await _cache.Set(aggregateId, aggregate).ConfigureAwait(false); return aggregate; } catch (Exception) { await _cache.Remove(aggregateId).ConfigureAwait(false); throw; } finally { @lock.Release(); } } } }
38.988889
134
0.568823
[ "Apache-2.0" ]
learningcom/Learning.EventStore
src/Learning.EventStore/Cache/CacheRepository.cs
3,511
C#
#nullable enable namespace System; public interface IFunc<in T1, in T2, in T3, in T4, in T5, out TResult> { TResult Invoke(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5); }
19.666667
70
0.689266
[ "MIT" ]
pfpack/pfpack-core
src/core-func/Func/IFunc/IFunc.05.cs
177
C#
using MongoDB.Driver; namespace MongoDB.Entities { public static partial class DB { /// <summary> /// Represents a ReplaceOne command, which can replace the first matched document with a given entity /// <para>TIP: Specify a filter first with the .Match(). Then set entity with .WithEntity() and finally call .Execute() to run the command.</para> /// </summary> /// <typeparam name="T">Any class that implements IEntity</typeparam> /// <param name="session">An optional session if using within a transaction</param> public static Replace<T> Replace<T>(IClientSessionHandle session = null) where T : IEntity => new Replace<T>(session, null, null, null); } }
44.411765
155
0.643709
[ "MIT" ]
cuongdo926/MongoDB.Entities
MongoDB.Entities/DB/DB.Replace.cs
757
C#
namespace TasSample.Models { public enum ActivitiesUnit { OneActivity, AllActivities, } }
14.111111
31
0.566929
[ "MIT" ]
sakapon/Speedrunner
Speedrunner/Speedrunner.Core/Models/ActivitiesUnit.cs
129
C#
using System; using System.IO; using System.Threading.Tasks; using MediatR.Pipeline; using StructureMap; using StructureMap.Pipeline; namespace MediatR.Examples.StructureMap { class Program { static Task Main() { var writer = new WrappingWriter(Console.Out); var mediator = BuildMediator(writer); return Runner.Run(mediator, writer, "StructureMap"); } private static IMediator BuildMediator(WrappingWriter writer) { var container = new Container(cfg => { cfg.Scan(scanner => { scanner.AssemblyContainingType<Ping>(); scanner.ConnectImplementationsToTypesClosing(typeof(IRequestHandler<,>)); scanner.ConnectImplementationsToTypesClosing(typeof(INotificationHandler<>)); }); //Pipeline cfg.For(typeof(IPipelineBehavior<,>)).Add(typeof(RequestPreProcessorBehavior<,>)); cfg.For(typeof(IPipelineBehavior<,>)).Add(typeof(RequestPostProcessorBehavior<,>)); cfg.For(typeof(IPipelineBehavior<,>)).Add(typeof(GenericPipelineBehavior<,>)); cfg.For(typeof(IRequestPreProcessor<>)).Add(typeof(GenericRequestPreProcessor<>)); cfg.For(typeof(IRequestPostProcessor<,>)).Add(typeof(GenericRequestPostProcessor<,>)); cfg.For(typeof(IRequestPostProcessor<,>)).Add(typeof(ConstrainedRequestPostProcessor<,>)); //Constrained notification handlers cfg.For(typeof(INotificationHandler<>)).Add(typeof(ConstrainedPingedHandler<>)); // This is the default but let's be explicit. At most we should be container scoped. cfg.For<IMediator>().LifecycleIs<TransientLifecycle>().Use<Mediator>(); cfg.For<ServiceFactory>().Use<ServiceFactory>(ctx => ctx.GetInstance); cfg.For<TextWriter>().Use(writer); }); var mediator = container.GetInstance<IMediator>(); return mediator; } } }
38.053571
106
0.609573
[ "Apache-2.0" ]
dadhi/MediatR
samples/MediatR.Examples.StructureMap/Program.cs
2,131
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; namespace AspNetAzureAdGroupsAutorization { public class Program { public static void Main(string[] args) { CreateHostBuilder(args).Build().Run(); } public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); }); } }
26.407407
70
0.654979
[ "MIT" ]
GanduNavakanth/AD_Auth-.Net-Core
AspNetAzureAdGroupsAuthorization/Program.cs
713
C#
using System; class CurrentDateTime { static void Main() { Console.Title = "Current Date and Time"; DateTime now = DateTime.Now; Console.WriteLine(now); } }
16.25
48
0.594872
[ "MIT" ]
PetarMetodiev/Telerik-Homeworks
C# Part 1/01 Introduction to programming/05 Current time/CurrentDateTime.cs
197
C#
// #define ENABLE_UNLOAD_MANAGER // Disabled, was an old workaround on memory hungry platforms using UnityEngine; using System.Collections; using System.Collections.Generic; // This is deliberately an ExecuteInEditMode object as opposed to InitializeOnLoad static // to get it to unload stuff when scripts are reloaded, and reload at the correct point. [ExecuteInEditMode] public class tk2dEditorSpriteDataUnloader : MonoBehaviour { public static void Register(tk2dSpriteCollectionData data) { #if ENABLE_UNLOAD_MANAGER && UNITY_EDITOR GetInst().DestroyDisconnectedResources(); #endif } public static void Unregister(tk2dSpriteCollectionData data) { #if ENABLE_UNLOAD_MANAGER && UNITY_EDITOR GetInst(); #endif } #if ENABLE_UNLOAD_MANAGER && UNITY_EDITOR static tk2dEditorSpriteDataUnloader _inst = null; static tk2dEditorSpriteDataUnloader GetInst() { if (_inst == null) { tk2dEditorSpriteDataUnloader[] allInsts = Resources.FindObjectsOfTypeAll(typeof(tk2dEditorSpriteDataUnloader)) as tk2dEditorSpriteDataUnloader[]; _inst = (allInsts.Length > 0) ? allInsts[0] : null; if (_inst == null) { GameObject go = new GameObject("@tk2dEditorSpriteDataUnloader"); go.hideFlags = HideFlags.HideAndDontSave; _inst = go.AddComponent<tk2dEditorSpriteDataUnloader>(); } } return _inst; } void OnEnable() { UnityEditor.EditorApplication.update += EditorUpdate; } void OnDisable() { UnityEngine.Object[] allObjects = Resources.FindObjectsOfTypeAll(typeof(UnityEngine.Object)) as UnityEngine.Object[]; DestroyInternalObjects( allObjects ); UnityEditor.EditorApplication.update -= EditorUpdate; } void DestroyInternalObjects(UnityEngine.Object[] allObjects) { // int numDestroyed = 0; foreach (UnityEngine.Object obj in allObjects) { if (obj.name.IndexOf(tk2dSpriteCollectionData.internalResourcePrefix) == 0) { Object.DestroyImmediate(obj); // numDestroyed++; } } // Debug.Log("Destroyed " + numDestroyed + " internal assets"); } public void DestroyDisconnectedResources() { List<UnityEngine.Object> allObjects = new List<UnityEngine.Object>( Resources.FindObjectsOfTypeAll(typeof(UnityEngine.Object)) as UnityEngine.Object[] ); tk2dSpriteCollectionData[] objects = Resources.FindObjectsOfTypeAll(typeof(tk2dSpriteCollectionData)) as tk2dSpriteCollectionData[]; foreach (tk2dSpriteCollectionData data in objects) { if (data.needMaterialInstance) { if (data.textureInsts != null) { foreach (Texture2D tex in data.textureInsts) { if (allObjects.Contains(tex)) { allObjects.Remove(tex); } } } if (data.materialInsts != null) { foreach (Material mtl in data.materialInsts) { if (allObjects.Contains(mtl)) { allObjects.Remove(mtl); } } } } } DestroyInternalObjects( allObjects.ToArray() ); } public string oldScene = ""; void EditorUpdate() { bool needDestroy = false; #if (UNITY_3_5 || UNITY_4_0 || UNITY_4_1 || UNITY_4_2 || UNITY_4_3 || UNITY_4_4 || UNITY_4_5 || UNITY_4_6 || UNITY_4_7 || UNITY_4_8 || UNITY_4_9 || UNITY_5_0 || UNITY_5_1 || UNITY_5_2) if (oldScene != UnityEditor.EditorApplication.currentScene) { oldScene = UnityEditor.EditorApplication.currentScene; needDestroy = true; } #else if (oldScene != UnityEditor.SceneManagement.EditorSceneManager.GetActiveScene().path) { oldScene = UnityEditor.SceneManagement.EditorSceneManager.GetActiveScene().path; needDestroy = true; } #endif if (needDestroy) { DestroyDisconnectedResources(); } } #endif }
32.697248
184
0.738496
[ "MIT" ]
cq-pandora/projects
services/parser/bin/CQSpritesDecompiler/Assets/TK2DROOT/tk2d/Code/Sprites/tk2dEditorSpriteDataUnloader.cs
3,564
C#
using HotChocolate.Types; using HotChocolate.Types.Relay; using HotChocolate.StarWars.Models; using HotChocolate.StarWars.Resolvers; namespace HotChocolate.StarWars.Types { public class HumanType : ObjectType<Human> { protected override void Configure(IObjectTypeDescriptor<Human> descriptor) { descriptor.Implements<CharacterType>(); descriptor.Field(t => t.Id) .Type<NonNullType<IdType>>(); descriptor.Field(f => f.Name) .Type<NonNullType<StringType>>(); descriptor.Field(t => t.AppearsIn) .Type<ListType<EpisodeType>>(); descriptor.Field<SharedResolvers>(r => r.GetCharacter(default, default)) .UsePaging<CharacterType>() .Name("friends"); descriptor.Field<SharedResolvers>(r => r.GetOtherHuman(default, default)); descriptor.Field<SharedResolvers>(t => t.GetHeight(default, default)) .Type<FloatType>() .Argument("unit", a => a.Type<EnumType<Unit>>()) .Name("height"); } } }
30.891892
86
0.590551
[ "MIT" ]
BaptisteGirard/hotchocolate
src/HotChocolate/Core/test/StarWars/Types/HumanType.cs
1,145
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Linq; using Microsoft.AspNetCore.Razor.Language.CodeGeneration; using Xunit; namespace Microsoft.AspNetCore.Razor.Language; #pragma warning disable CS0618 // Type or member is obsolete public class RazorEngineBuilderExtensionsTest { [Fact] public void AddDirective_ExistingFeature_UsesFeature() { // Arrange var expected = new DefaultRazorDirectiveFeature(); var engine = RazorEngine.CreateEmpty(b => { b.Features.Add(expected); // Act b.AddDirective(DirectiveDescriptor.CreateDirective("test", DirectiveKind.SingleLine)); }); // Assert var actual = Assert.Single(engine.Features.OfType<IRazorDirectiveFeature>()); Assert.Same(expected, actual); var directive = Assert.Single(actual.Directives); Assert.Equal("test", directive.Directive); } [Fact] public void AddDirective_NoFeature_CreatesFeature() { // Arrange var engine = RazorEngine.CreateEmpty(b => { // Act b.AddDirective(DirectiveDescriptor.CreateDirective("test", DirectiveKind.SingleLine)); }); // Assert var actual = Assert.Single(engine.Features.OfType<IRazorDirectiveFeature>()); Assert.IsType<DefaultRazorDirectiveFeature>(actual); var directive = Assert.Single(actual.Directives); Assert.Equal("test", directive.Directive); } [Fact] public void AddTargetExtensions_ExistingFeature_UsesFeature() { // Arrange var extension = new MyTargetExtension(); var expected = new DefaultRazorTargetExtensionFeature(); var engine = RazorEngine.CreateEmpty(b => { b.Features.Add(expected); // Act b.AddTargetExtension(extension); }); // Assert var actual = Assert.Single(engine.Features.OfType<IRazorTargetExtensionFeature>()); Assert.Same(expected, actual); Assert.Same(extension, Assert.Single(actual.TargetExtensions)); } [Fact] public void AddTargetExtensions_NoFeature_CreatesFeature() { // Arrange var extension = new MyTargetExtension(); var engine = RazorEngine.CreateEmpty(b => { // Act b.AddTargetExtension(extension); }); // Assert var actual = Assert.Single(engine.Features.OfType<IRazorTargetExtensionFeature>()); Assert.IsType<DefaultRazorTargetExtensionFeature>(actual); Assert.Same(extension, Assert.Single(actual.TargetExtensions)); } private class MyTargetExtension : ICodeTargetExtension { } }
29.84375
102
0.641536
[ "MIT" ]
MitrichDot/aspnetcore
src/Razor/Microsoft.AspNetCore.Razor.Language/test/RazorEngineBuilderExtensionsTest.cs
2,867
C#
using System; using System.Collections.Generic; using System.Configuration; using System.Data; using System.Linq; using System.Threading.Tasks; using System.Windows; namespace TheBuildingsEyes { /// <summary> /// Interaction logic for App.xaml /// </summary> public partial class App : Application { } }
18.333333
42
0.709091
[ "MIT" ]
zuhlke-smartone-hackathon-2018/smartone-hackathon-2018-facerecognition
TheBuildingsEyes/App.xaml.cs
332
C#
using System; using System.Collections.Generic; using System.IO; using System.Text; using DW.Lua.Extensions; using DW.Lua.Language; using DW.Lua.Misc; using DW.Lua.Syntax; namespace DW.Lua.Lexer { public class Tokenizer { private static readonly HashSet<char> SingleCharTokenChars = new HashSet<char>(LuaToken.SingleCharTokensString.ToCharArray()); private static readonly HashSet<char> NonTokenChars = new HashSet<char>(LuaToken.NonTokenCharsString.ToCharArray()); private static readonly HashSet<string> Bigrams = new HashSet<string>(LuaToken.TokenBigrams); private readonly ITokenizerCharEnumerator _reader; private Tokenizer(TextReader reader) { _reader = new TokenizerCharEnumerator(reader.AsEnumerable().GetEnumerator()); } public static INextAwareEnumerator<Token> Parse(TextReader reader) { var tokenizer = new Tokenizer(reader); var tokens = tokenizer.ReadTokens(); return tokens.GetNextAwareEnumerator(); } private IEnumerable<Token> ReadTokens() { while (_reader.MoveNext()) { SkipNonTokens(); yield return ReadToken(); } } private void SkipNonTokens() { // Spin reader until either all non-tokens are skipped or enumerator is finished while (IsNonToken(_reader.Current) && _reader.MoveNext()) { } } private Token ReadToken() { var position = _reader.Position; var builder = new StringBuilder(); while (true) { builder.Append(_reader.Current); if (!_reader.HasNext) break; if (IsBigram(_reader.Current, _reader.Next)) { _reader.MoveNext(); builder.Append(_reader.Current); break; } if (_reader.Current == '-' && _reader.Next == '-') return new Token(ReadComment(), position, TokenType.Comment); if (_reader.Current == '[' && _reader.Next == '[') return new Token(ReadMultiLineStringConstant(), position, TokenType.StringConstant); if (_reader.Current == '"') return new Token(ReadSingleLineStringConstant(), position, TokenType.StringConstant); if (IsSingleCharToken(_reader.Current)) break; if (_reader.HasNext && (IsNonToken(_reader.Next) || IsSingleCharToken(_reader.Next))) break; _reader.MoveNext(); } var tokenValue = builder.ToString(); bool dummy; var tokenType = TokenType.Identifier; if (Keywords.All.Contains(tokenValue)) tokenType = TokenType.Keyword; else if (bool.TryParse(tokenValue, out dummy)) tokenType = TokenType.BooleanConstant; return new Token(tokenValue, position, tokenType); } private string ReadSingleLineStringConstant() { Verify(_reader.Current == '"'); var sb = new StringBuilder(); while (_reader.MoveNext() && _reader.Current != '"') sb.Append(_reader.Current); return sb.ToString(); } private string ReadMultiLineStringConstant() { Verify(_reader.Current == '['); _reader.MoveNext(); Verify(_reader.Current == '['); _reader.MoveNext(); var valueBuilder = new StringBuilder(); while (!(_reader.Current == ']' && _reader.HasNext && _reader.Next == ']')) { valueBuilder.Append(_reader.Current); if (!_reader.MoveNext()) break; } Verify(_reader.Current == ']'); Verify(_reader.MoveNext()); Verify(_reader.Current == ']'); return valueBuilder.ToString(); } private static bool IsBigram(char char1, char char2) { var candidateBigram = new string(new[] {char1, char2}); return Bigrams.Contains(candidateBigram); } private static bool IsSingleCharToken(char chr) { return SingleCharTokenChars.Contains(chr); } private static bool IsNonToken(char chr) { return NonTokenChars.Contains(chr); } private string ReadComment() { Verify(_reader.Current == '-'); Verify(_reader.MoveNext()); Verify(_reader.Current == '-'); Verify(_reader.MoveNext()); var multiline = _reader.Current == '[' && _reader.HasNext && _reader.Next == '['; if (multiline) { _reader.MoveNext(); _reader.MoveNext(); } var builder = new StringBuilder(); if (multiline) { do builder.Append(_reader.Current); while (_reader.MoveNext() && !(_reader.Current == ']' && _reader.HasNext && _reader.Next == ']')); _reader.MoveNext(); } else do builder.Append(_reader.Current); while (_reader.MoveNext() && _reader.Current != '\n'); return builder.ToString(); } // ReSharper disable once UnusedParameter.Local // TODO: make a method similar to VerifyExpectedToken private void Verify(bool assumption) { if (!assumption) throw new Exception("Assumption failed"); } } }
33.327778
107
0.521254
[ "MIT" ]
DarkWanderer/DW.Lua
DW.Lua/Lexer/Tokenizer.cs
6,001
C#
//------------------------------------------------------------------------------ // <auto-generated> // Este código fue generado por una herramienta. // Versión de runtime:4.0.30319.42000 // // Los cambios en este archivo podrían causar un comportamiento incorrecto y se perderán si // se vuelve a generar el código. // </auto-generated> //------------------------------------------------------------------------------ using System; using System.Reflection; [assembly: System.Reflection.AssemblyCompanyAttribute("Bloc 3- A4 CSharp y Java")] [assembly: System.Reflection.AssemblyConfigurationAttribute("Debug")] [assembly: System.Reflection.AssemblyFileVersionAttribute("1.0.0.0")] [assembly: System.Reflection.AssemblyInformationalVersionAttribute("1.0.0")] [assembly: System.Reflection.AssemblyProductAttribute("Bloc 3- A4 CSharp y Java")] [assembly: System.Reflection.AssemblyTitleAttribute("Bloc 3- A4 CSharp y Java")] [assembly: System.Reflection.AssemblyVersionAttribute("1.0.0.0")] // Generado por la clase WriteCodeFragment de MSBuild.
44.291667
95
0.652869
[ "MIT" ]
marcvil/.NET-course
Bloc C# y Java/Bloc exercici Ciutats/Bloc 3- A4 CSharp y Java/Bloc 3- A4 CSharp y Java/obj/Debug/netcoreapp3.0/Bloc 3- A4 CSharp y Java.AssemblyInfo.cs
1,068
C#
// // Copyright (c) 2006 Mainsoft Co. // // 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.Data; using System.Data.OracleClient; using MonoTests.System.Data.Utils; using MonoTests.System.Data.Utils.Data; using NUnit.Framework; namespace MonoTests.System.Data.OracleClient { [TestFixture] public class OracleCommand_CommandText : GHTBase { private Exception exp = null; private OracleCommand cmd; const string TEST_CASE_ID = "48341_"; public static void Main() { OracleCommand_CommandText tc = new OracleCommand_CommandText(); Exception exp = null; try { tc.BeginTest("OleDBCommandText"); tc.run(); } catch(Exception ex){exp = ex;} finally {tc.EndTest(exp);} } public void run() { SetInConstractor(); SetByProperty(); UseSemiColonAsValue(); UseColonAsValue(); UseQuestionMarkAsValue(); UseExclamationMarkAsValue(); UseApostropheAsValue(); UseCommaAsValue(); UseDotAsValue(); UseAtAsValue(); UseQuoteAsValue(); UseDollarAsValue(); UsePercentAsValue(); UseHatAsValue(); UseAmpersnadAsValue(); UseStartAsValue(); UseParentesesAsValue(); UsePlusAsValue(); UseMinusAsValue(); UseUnderscoreAsValue(); UseSpaceAsValue(); UseEqualAsValue(); UseSlashAsValue(); UseBackSlashAsValue(); UseTildeAsValue(); UseNOTAsValue(); UseORAsValue(); UseANDAsValue(); UseSELECTAsValue(); UseFROMAsValue(); UseWHEREAsValue(); UseINSERTAsValue(); UseINTOAsValue(); UseVALUESAsValue(); UseDELETEAsValue(); UseUPDATEAsValue(); UseEXECAsValue(); UseQueryAsValue(); } [Test] public void SetByProperty() { exp = null; cmd = new OracleCommand(); cmd.CommandText = "SELECT * FROM Employees"; try { BeginCase("CommandText2"); Compare(cmd.CommandText, "SELECT * FROM Employees"); } catch(Exception ex) { exp = ex; } finally { EndCase(exp); } } [Test] public void SetInConstractor() { exp = null; cmd = new OracleCommand("SELECT * FROM Employees"); try { BeginCase("CommandText1"); Compare(cmd.CommandText, "SELECT * FROM Employees"); } catch(Exception ex) { exp = ex; } finally { EndCase(exp); } } [Test] public void UseSemiColonAsValue() { RunValueInColumnTest("T_VARCHAR", ";"); } [Test] public void UseColonAsValue() { RunValueInColumnTest("T_VARCHAR", ":"); } [Test] public void UseQuestionMarkAsValue() { RunValueInColumnTest("T_VARCHAR", "?"); } [Test] public void UseExclamationMarkAsValue() { RunValueInColumnTest("T_VARCHAR", "?"); } [Test] public void UseApostropheAsValue() { RunValueInColumnTest("T_VARCHAR", "'"); } [Test] public void UseCommaAsValue() { RunValueInColumnTest("T_VARCHAR", ","); } [Test] public void UseDotAsValue() { RunValueInColumnTest("T_VARCHAR", "."); } [Test] public void UseAtAsValue() { RunValueInColumnTest("T_VARCHAR", "@"); } [Test] public void UseQuoteAsValue() { RunValueInColumnTest("T_VARCHAR", "\""); } [Test] public void UseDiezAsValue() { RunValueInColumnTest("T_VARCHAR", "#"); } [Test] public void UseDollarAsValue() { RunValueInColumnTest("T_VARCHAR", "$"); } [Test] public void UsePercentAsValue() { RunValueInColumnTest("T_VARCHAR", "%"); } [Test] public void UseHatAsValue() { RunValueInColumnTest("T_VARCHAR", "^"); } [Test] public void UseAmpersnadAsValue() { RunValueInColumnTest("T_VARCHAR", "&"); } [Test] public void UseStartAsValue() { RunValueInColumnTest("T_VARCHAR", "*"); } [Test] public void UseParentesesAsValue() { RunValueInColumnTest("T_VARCHAR", "("); RunValueInColumnTest("T_VARCHAR", "()"); RunValueInColumnTest("T_VARCHAR", ")"); RunValueInColumnTest("T_VARCHAR", "{"); RunValueInColumnTest("T_VARCHAR", "{}"); RunValueInColumnTest("T_VARCHAR", "}"); RunValueInColumnTest("T_VARCHAR", "["); RunValueInColumnTest("T_VARCHAR", "[]"); RunValueInColumnTest("T_VARCHAR", "]"); RunValueInColumnTest("T_VARCHAR", "<"); RunValueInColumnTest("T_VARCHAR", "<>"); RunValueInColumnTest("T_VARCHAR", ">"); } [Test] public void UsePlusAsValue() { RunValueInColumnTest("T_VARCHAR", "+"); } [Test] public void UseMinusAsValue() { RunValueInColumnTest("T_VARCHAR", "-"); } [Test] public void UseUnderscoreAsValue() { RunValueInColumnTest("T_VARCHAR", "_"); } [Test] public void UseSpaceAsValue() { RunValueInColumnTest("T_VARCHAR", " "); } [Test] public void UseEqualAsValue() { RunValueInColumnTest("T_VARCHAR", "="); } [Test] public void UseSlashAsValue() { RunValueInColumnTest("T_VARCHAR", "\\"); } [Test] public void UseBackSlashAsValue() { RunValueInColumnTest("T_VARCHAR", "/"); } [Test] public void UseTildeAsValue() { RunValueInColumnTest("T_VARCHAR", "~"); } [Test] public void UseNOTAsValue() { RunValueInColumnTest("T_VARCHAR", "NOT"); } [Test] public void UseORAsValue() { RunValueInColumnTest("T_VARCHAR", "OR"); } [Test] public void UseANDAsValue() { RunValueInColumnTest("T_VARCHAR", "AND"); } [Test] public void UseSELECTAsValue() { RunValueInColumnTest("T_VARCHAR", "SELECT"); } [Test] public void UseFROMAsValue() { RunValueInColumnTest("T_VARCHAR", "FROM"); } [Test] public void UseWHEREAsValue() { RunValueInColumnTest("T_VARCHAR", "WHERE"); } [Test] public void UseINSERTAsValue() { RunValueInColumnTest("T_VARCHAR", "INSERT"); } [Test] public void UseINTOAsValue() { RunValueInColumnTest("T_VARCHAR", "INTO"); } [Test] public void UseVALUESAsValue() { RunValueInColumnTest("T_VARCHAR", "VALUES"); } [Test] public void UseDELETEAsValue() { RunValueInColumnTest("T_VARCHAR", "DELETE"); } [Test] public void UseUPDATEAsValue() { RunValueInColumnTest("T_VARCHAR", "UPDATE"); } [Test] public void UseEXECAsValue() { RunValueInColumnTest("T_VARCHAR", "EXEC"); } [Test] public void UseQueryAsValue() { string columnName; switch (ConnectedDataProvider.GetDbType()) { case DataBaseServer.SQLServer: columnName = "T_VARCHAR"; break; case DataBaseServer.Oracle: columnName = "T_LONG"; break; case DataBaseServer.DB2: columnName = "T_LONGVARCHAR"; break; default: columnName = "T_VARCHAR"; break; } RunValueInColumnTest(columnName, "SELECT * FROM TYPES_SIMPLE"); } private void RunValueInColumnTest(string columnToTest, string valueToTest) { UnQuotedValueInColumn(columnToTest, valueToTest); QuotedValueInColumn(columnToTest, valueToTest); } private void QuotedValueInColumn(string columnToTest, string valueToTest) { ValueInColumn(columnToTest, string.Format("'{0}'", valueToTest)); } private void UnQuotedValueInColumn(string columnToTest, string valueToTest) { ValueInColumn(columnToTest, valueToTest); } private void ValueInColumn(string columnToTest, string valueToTest) { exp = null; OracleDataReader rdr = null; OracleConnection con = null; DbTypeParametersCollection row = ConnectedDataProvider.GetSimpleDbTypesParameters(); BeginCase(string.Format("Use {0} as value", valueToTest)); string rowId = TEST_CASE_ID + TestCaseNumber.ToString(); try { foreach(DbTypeParameter param in row) { param.Value = DBNull.Value; } row[columnToTest].Value = valueToTest; Log("rowId:" + rowId + " columnToTest:" + columnToTest + " valueToTest:" + valueToTest); row.ExecuteInsert(rowId); row.ExecuteSelectReader(rowId, out rdr, out con); rdr.Read(); int columnOrdinal = rdr.GetOrdinal(columnToTest); //this.Log(valueToTest); Compare(valueToTest, rdr.GetValue(columnOrdinal)); } catch(Exception ex) { exp = ex; } finally { EndCase(exp); if (rdr != null && !rdr.IsClosed) { rdr.Close(); } row.ExecuteDelete(rowId); if (con != null && con.State != ConnectionState.Closed) { con.Close(); } } } } }
24.929348
92
0.675496
[ "Apache-2.0" ]
121468615/mono
mcs/class/System.Data.OracleClient/Test/System.Data.OracleClient.jvm/OracleCommand/OracleCommand_CommandText.cs
9,174
C#