content
stringlengths
5
1.04M
avg_line_length
float64
1.75
12.9k
max_line_length
int64
2
244k
alphanum_fraction
float64
0
0.98
licenses
list
repository_name
stringlengths
7
92
path
stringlengths
3
249
size
int64
5
1.04M
lang
stringclasses
2 values
using System; using System.Linq.Expressions; namespace FlowModel.Presenter.ParentInterfaces { public interface IContainer { void Register<TService, TImplementation>() where TImplementation : TService; void Register<TService>(); void RegisterInstance<TInstance>(TInstance instance); TService Resolve<TService>(); bool IsRegistered<TService>(); void Register<TService, TArgument>(Expression<Func<TArgument, TService>> factory); } }
26.142857
90
0.63388
[ "MIT" ]
Grischenkov/FlowModel
FlowModel.Presenter/ParentInterfaces/IContainer.cs
551
C#
#region Using Directives using System; #endregion Using Directives namespace ScintillaNET { /// <summary> /// Provides data for the StyleChanged event /// </summary> /// <remarks> /// StyleChangedEventHandler is used for the StyleChanged Event which is also used as /// a more specific abstraction around the SCN_MODIFIED notification message. /// </remarks> public class StyleChangedEventArgs : ModifiedEventArgs { #region Fields private int _length; private int _position; #endregion Fields #region Properties /// <summary> /// Returns how many characters have changed /// </summary> public int Length { get { return _length; } } /// <summary> /// Returns the starting document position where the style has been changed /// </summary> public int Position { get { return _position; } } #endregion Properties #region Constructors internal StyleChangedEventArgs(int position, int length, int modificationType) : base(modificationType) { _position = position; _length = length; } #endregion Constructors } }
21.151515
111
0.550143
[ "Unlicense" ]
itlezy/ITLezyTools
ScintillaNET-2.6/StyleChangedEventArgs.cs
1,398
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator 1.0.1.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.StreamAnalytics.Models { using Microsoft.Azure; using Microsoft.Azure.Management; using Microsoft.Azure.Management.StreamAnalytics; /// <summary> /// Defines values for EventsOutOfOrderPolicy. /// </summary> public static class EventsOutOfOrderPolicy { public const string Adjust = "Adjust"; public const string Drop = "Drop"; } }
30.833333
74
0.717568
[ "MIT" ]
azure-keyvault/azure-sdk-for-net
src/SDKs/StreamAnalytics/Management.StreamAnalytics/Generated/Models/EventsOutOfOrderPolicy.cs
740
C#
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; namespace EasyTcp3.Actions { /// <summary> /// Contains the core elements of the action system /// /// Protocol of the action system: /// (ushort: [data length + action id length(4)]) [int: action id] [data] /// </summary> public static class ActionsCore { /// <summary> /// Delegate of an EasyTcp action /// See it as an template /// </summary> /// <param name="sender">EasyTcpClient or EasyTcpServer as object</param> /// <param name="message">received message</param> public delegate void EasyTcpActionDelegate(object sender, Message message); /// <summary> /// Get all methods with the EasyTcpAction attribute /// </summary> /// <param name="assembly">assembly with EasyTcpActions</param> /// <param name="nameSpace">filter for namespace with EasyTcpActions. /// All actions in this namespace will be added, other will be ignored. /// Filter is ignored when null</param> /// <returns>all EasyTcpAction functions within an assembly</returns> /// <exception cref="Exception">could not find any EasyTcpActions</exception> internal static Dictionary<int, EasyTcpActionDelegate> GetActions(Assembly assembly, string nameSpace = null) { try { var actions = assembly.GetTypes() // Get all classes in assembly // Filter on namespace but pass everything if nameSpace is null .Where(t => string.IsNullOrEmpty(nameSpace) || (t.Namespace ?? "").StartsWith(nameSpace)) // Get methods from classes .SelectMany(t => t.GetMethods()) // Get valid action methods .Where(IsValidMethod) // Cast methods to dictionary .ToDictionary(k => k.GetCustomAttributes().OfType<EasyTcpAction>().First().ActionCode, v => (EasyTcpActionDelegate) Delegate.CreateDelegate(typeof(EasyTcpActionDelegate), v)); if (!actions.Any()) throw new Exception("Could not find any EasyTcpActions"); return actions; } catch (ArgumentException ex) { throw new Exception( "Could not load actions: multiple methods found with the same actionCode or method does not match EasyTcpActionDelegate", ex); } } /// <summary> /// Determines whether a method is a valid action method /// </summary> /// <param name="m">method</param> /// <returns>true if method is valid</returns> private static bool IsValidMethod(MethodInfo m) { if (!m.GetCustomAttributes().OfType<EasyTcpAction>().Any() || !m.IsStatic) return false; var parameters = m.GetParameters(); if (parameters.Length != 2 || parameters[0].ParameterType != typeof(object) || parameters[1].ParameterType != typeof(Message)) return false; return true; } /// <summary> /// Execute a received action /// </summary> /// <param name="actions">dictionary with all available actions</param> /// <param name="interceptor">Function that gets called before action is executed. /// If function returns false discard action. Ignore parameter when null</param> /// <param name="onUnknownAction">action that gets triggered when an unknown action is received</param> /// <param name="sender">EasyTcpClient or EasyTcpServer as object</param> /// <param name="message">received data [int: action id] [data]</param> internal static void ExecuteAction(this Dictionary<int, EasyTcpActionDelegate> actions, Func<int, Message, bool> interceptor, Action<Message> onUnknownAction, object sender, Message message) { var actionCode = BitConverter.ToInt32(message.Data, 0); // Get action code as int actions.TryGetValue(actionCode, out var action); // Get delegate if (action == null) { onUnknownAction?.Invoke(message); return; } // Remove action code from message byte[] data = null; if (message.Data.Length > 4) { #if !NETSTANDARD2_1 data = message.Data[4..]; #else data = new byte[message.Data.Length - 4]; Buffer.BlockCopy(message.Data, 4, data, 0, data.Length); #endif } // Execute action var m = new Message(data, message.Client); if (interceptor?.Invoke(actionCode, m) != false) action.Invoke(sender, m); } /// <summary> /// Convert a string to an actionCode by using the djb2a hashing algorithm /// ! Collision are surely possible, but this shouldn't be a problem here (for example: haggadot & loathsomenesses) /// http://www.cse.yorku.ca/~oz/hash.html /// </summary> /// <param name="str">action id as string</param> /// <returns>action id as int</returns> public static int ToActionCode(this string str) { int hash = 5381; foreach (var t in str) hash = ((hash << 5) + hash) ^ (byte) t; return hash; } } }
43.708661
141
0.581517
[ "MIT" ]
AndreiBlizorukov/EasyTcp
EasyTcp3/EasyTcp3.Actions/ActionsCore.cs
5,551
C#
using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Diagnostics; namespace RefactoringEssentials.CSharp.Diagnostics { [DiagnosticAnalyzer(LanguageNames.CSharp)] [NotPortedYet] public class NonReadonlyReferencedInGetHashCodeAnalyzer : DiagnosticAnalyzer { static readonly DiagnosticDescriptor descriptor = new DiagnosticDescriptor( CSharpDiagnosticIDs.NonReadonlyReferencedInGetHashCodeAnalyzerID, GettextCatalog.GetString("Non-readonly field referenced in 'GetHashCode()'"), GettextCatalog.GetString("Non-readonly field referenced in 'GetHashCode()'"), DiagnosticAnalyzerCategories.CodeQualityIssues, DiagnosticSeverity.Warning, isEnabledByDefault: true, helpLinkUri: HelpLink.CreateFor(CSharpDiagnosticIDs.NonReadonlyReferencedInGetHashCodeAnalyzerID) ); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(descriptor); public override void Initialize(AnalysisContext context) { context.RegisterSyntaxNodeAction( (nodeContext) => { IEnumerable<Diagnostic> diagnostics; if (TryGetDiagnostic(nodeContext, out diagnostics)) foreach (var diagnostic in diagnostics) nodeContext.ReportDiagnostic(diagnostic); }, SyntaxKind.MethodDeclaration ); } static bool TryGetDiagnostic(SyntaxNodeAnalysisContext nodeContext, out IEnumerable<Diagnostic> diagnostic) { diagnostic = default(IEnumerable<Diagnostic>); var node = nodeContext.Node as MethodDeclarationSyntax; IMethodSymbol method = nodeContext.SemanticModel.GetDeclaredSymbol(node); if (method == null || method.Name != "GetHashCode" || !method.IsOverride || method.Parameters.Count() > 0) return false; if (method.ReturnType.SpecialType != SpecialType.System_Int32) return false; diagnostic = node .DescendantNodes() .OfType<IdentifierNameSyntax>() .Where(n => IsNonReadonlyField(nodeContext.SemanticModel, n)) .Select(n => Diagnostic.Create(descriptor, n.GetLocation())); return true; } static bool IsNonReadonlyField(SemanticModel semanticModel, SyntaxNode node) { var symbol = semanticModel.GetSymbolInfo(node).Symbol as IFieldSymbol; return symbol != null && !symbol.IsReadOnly && !symbol.IsConst; } } }
44.107692
119
0.66097
[ "MIT" ]
Wagnerp/RefactoringEssentials
RefactoringEssentials/CSharp/Diagnostics/Synced/CodeQuality/NonReadonlyReferencedInGetHashCodeAnalyzer.cs
2,867
C#
using CommandsService.Models; using Microsoft.EntityFrameworkCore; namespace CommandsService.Data { public class AppDbContext: DbContext { public AppDbContext(DbContextOptions<AppDbContext> opts): base(opts) { } public DbSet<Platform> Platforms { get; set; } public DbSet<Command> Commands { get; set; } protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity<Platform>() .HasMany(p => p.Commands) .WithOne(p => p.Platform!) .HasForeignKey(p => p.PlatformId); modelBuilder.Entity<Command>() .HasOne(c => c.Platform) .WithMany(c => c.Commands!) .HasForeignKey(c => c.PlatformId); } } }
27.333333
76
0.57561
[ "MIT" ]
mahrncic/.NET-microservices
CommandsService/CommandsService/Data/AppDbContext.cs
822
C#
using System; namespace App_master.Models { public class Item { public string Id { get; set; } public string Text { get; set; } public string Description { get; set; } } }
19
47
0.583732
[ "MIT" ]
Shaw6157/SOFT803_Xamarin
App_master/App_master/App_master/Models/Item.cs
211
C#
/* * DocuSign REST API * * The DocuSign REST API provides you with a powerful, convenient, and simple Web services API for interacting with DocuSign. * * OpenAPI spec version: v2 * Contact: devcenter@docusign.com * Generated by: https://github.com/swagger-api/swagger-codegen.git */ using NUnit.Framework; using System; using System.Linq; using System.IO; using System.Collections.Generic; using DocuSign.eSign.Api; using DocuSign.eSign.Model; using DocuSign.eSign.Client; using System.Reflection; namespace DocuSign.eSign.Test { /// <summary> /// Class for testing UserInfoList /// </summary> /// <remarks> /// This file is automatically generated by Swagger Codegen. /// Please update the test case below to test the model. /// </remarks> [TestFixture] public class UserInfoListTests { // TODO uncomment below to declare an instance variable for UserInfoList //private UserInfoList instance; /// <summary> /// Setup before each test /// </summary> [SetUp] public void Init() { // TODO uncomment below to create an instance of UserInfoList //instance = new UserInfoList(); } /// <summary> /// Clean up after each test /// </summary> [TearDown] public void Cleanup() { } /// <summary> /// Test an instance of UserInfoList /// </summary> [Test] public void UserInfoListInstanceTest() { // TODO uncomment below to test "IsInstanceOfType" UserInfoList //Assert.IsInstanceOfType<UserInfoList> (instance, "variable 'instance' is a UserInfoList"); } /// <summary> /// Test the property 'Users' /// </summary> [Test] public void UsersTest() { // TODO unit test for the property 'Users' } } }
24.683544
125
0.597436
[ "MIT" ]
CameronLoewen/docusign-csharp-client
sdk/src/DocuSign.eSign.Test/Model/UserInfoListTests.cs
1,950
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("06.SaveSortedNames")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("06.SaveSortedNames")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("22d071f9-dddc-4cfd-822d-9acb5b603d7a")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
39.054054
85
0.727336
[ "MIT" ]
MarinMarinov/C-Sharp-Part-2
Homework 08- TextFiles/06.SaveSortedNames/Properties/AssemblyInfo.cs
1,448
C#
namespace NaCl.Core.Internal { using System; using System.Linq; using System.Runtime.CompilerServices; public static class CryptoBytes { public static byte[] Combine(params byte[][] arrays) { var rv = new byte[arrays.Sum(a => a.Length)]; var offset = 0; foreach (var array in arrays) { Buffer.BlockCopy(array, 0, rv, offset, array.Length); offset += array.Length; } return rv; } public static bool ConstantTimeEquals(byte[] x, byte[] y) => ConstantTimeEquals((ReadOnlySpan<byte>)x, (ReadOnlySpan<byte>)y); public static bool ConstantTimeEquals(ReadOnlySpan<byte> x, ReadOnlySpan<byte> y) { if (x.Length != y.Length) throw new ArgumentException("x.Length must equal y.Length"); return InternalConstantTimeEquals(x, 0, y, 0, x.Length) != 0; } public static bool ConstantTimeEquals(ArraySegment<byte> x, ArraySegment<byte> y) { if (x.Array is null) throw new ArgumentNullException("x.Array"); if (y.Array is null) throw new ArgumentNullException("y.Array"); if (x.Count != y.Count) throw new ArgumentException("x.Count must equal y.Count"); return InternalConstantTimeEquals(x.Array, x.Offset, y.Array, y.Offset, x.Count) != 0; } public static bool ConstantTimeEquals(byte[] x, int xOffset, byte[] y, int yOffset, int length) { if (x is null) throw new ArgumentNullException(nameof(x)); if (xOffset < 0) throw new ArgumentOutOfRangeException("xOffset", "xOffset < 0"); if (y == null) throw new ArgumentNullException(nameof(y)); if (yOffset < 0) throw new ArgumentOutOfRangeException("yOffset", "yOffset < 0"); if (length < 0) throw new ArgumentOutOfRangeException("length", "length < 0"); if (x.Length - xOffset < length) throw new ArgumentException("xOffset + length > x.Length"); if (y.Length - yOffset < length) throw new ArgumentException("yOffset + length > y.Length"); return InternalConstantTimeEquals(x, xOffset, y, yOffset, length) != 0; } private static uint InternalConstantTimeEquals(ReadOnlySpan<byte> x, int xOffset, ReadOnlySpan<byte> y, int yOffset, int length) { var differentbits = 0; for (var i = 0; i < length; i++) differentbits |= x[xOffset + i] ^ y[yOffset + i]; return (1 & (unchecked((uint)differentbits - 1) >> 8)); } public static void Wipe(byte[] data) { if (data is null) throw new ArgumentNullException(nameof(data)); InternalWipe(data, 0, data.Length); } public static void Wipe(byte[] data, int offset, int count) { if (data is null) throw new ArgumentNullException(nameof(data)); if (offset < 0) throw new ArgumentOutOfRangeException(nameof(offset)); if (count < 0) throw new ArgumentOutOfRangeException(nameof(count), "Requires count >= 0"); if ((uint)offset + (uint)count > (uint)data.Length) throw new ArgumentException("Requires offset + count <= data.Length"); InternalWipe(data, offset, count); } public static void Wipe(ArraySegment<byte> data) { if (data.Array is null) throw new ArgumentNullException("data.Array"); InternalWipe(data.Array, data.Offset, data.Count); } // Secure wiping is hard // * the GC can move around and copy memory // Perhaps this can be avoided by using unmanaged memory or by fixing the position of the array in memory // * Swap files and error dumps can contain secret information // It seems possible to lock memory in RAM, no idea about error dumps // * Compiler could optimize out the wiping if it knows that data won't be read back // I hope this is enough, suppressing inlining // but perhaps `RtlSecureZeroMemory` is needed [MethodImpl(MethodImplOptions.NoInlining)] internal static void InternalWipe(byte[] data, int offset, int count) => Array.Clear(data, offset, count); // shallow wipe of structs //[MethodImpl(MethodImplOptions.NoInlining)] //internal static void InternalWipe<T>(ref T data) where T : struct => data = default; // constant time hex conversion // see http://stackoverflow.com/a/14333437/445517 // // An explanation of the weird bit fiddling: // // 1. `bytes[i] >> 4` extracts the high nibble of a byte // `bytes[i] & 0xF` extracts the low nibble of a byte // 2. `b - 10` // is `< 0` for values `b < 10`, which will become a decimal digit // is `>= 0` for values `b > 10`, which will become a letter from `A` to `F`. // 3. Using `i >> 31` on a signed 32 bit integer extracts the sign, thanks to sign extension. // It will be `-1` for `i < 0` and `0` for `i >= 0`. // 4. Combining 2) and 3), shows that `(b-10)>>31` will be `0` for letters and `-1` for digits. // 5. Looking at the case for letters, the last summand becomes `0`, and `b` is in the range 10 to 15. We want to map it to `A`(65) to `F`(70), which implies adding 55 (`'A'-10`). // 6. Looking at the case for digits, we want to adapt the last summand so it maps `b` from the range 0 to 9 to the range `0`(48) to `9`(57). This means it needs to become -7 (`'0' - 55`). // Now we could just multiply with 7. But since -1 is represented by all bits being 1, we can instead use `& -7` since `(0 & -7) == 0` and `(-1 & -7) == -7`. // // Some further considerations: // // * I didn't use a second loop variable to index into `c`, since measurement shows that calculating it from `i` is cheaper. // * Using exactly `i < bytes.Length` as upper bound of the loop allows the JITter to eliminate bounds checks on `bytes[i]`, so I chose that variant. // * Making `b` an int avoids unnecessary conversions from and to byte. public static string ToHexStringUpper(byte[] data) { if (data is null) return null; var c = new char[data.Length * 2]; int b; for (var i = 0; i < data.Length; i++) { b = data[i] >> 4; c[i * 2] = (char)(55 + b + (((b - 10) >> 31) & -7)); b = data[i] & 0xF; c[i * 2 + 1] = (char)(55 + b + (((b - 10) >> 31) & -7)); } return new string(c); } // Explanation is similar to ToHexStringUpper // constant 55 -> 87 and -7 -> -39 to compensate for the offset 32 between lowercase and uppercase letters public static string ToHexStringLower(byte[] data) { if (data is null) return null; var c = new char[data.Length * 2]; int b; for (var i = 0; i < data.Length; i++) { b = data[i] >> 4; c[i * 2] = (char)(87 + b + (((b - 10) >> 31) & -39)); b = data[i] & 0xF; c[i * 2 + 1] = (char)(87 + b + (((b - 10) >> 31) & -39)); } return new string(c); } public static byte[] FromHexString(string hexString) { if (hexString is null) return null; if (hexString.Length % 2 != 0) throw new FormatException("The hex string is invalid because it has an odd length"); var result = new byte[hexString.Length / 2]; for (var i = 0; i < result.Length; i++) result[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 16); return result; } public static string ToBase64String(byte[] data) { if (data is null) return null; return Convert.ToBase64String(data); } public static byte[] FromBase64String(string s) { if (s is null) return null; return Convert.FromBase64String(s); } } }
39.452055
198
0.543866
[ "MIT" ]
RossMetacraft/GeoVR
source/Libraries/NaCl.Core/Internal/CryptoBytes.cs
8,642
C#
using UnityEngine; using UnityEngine.EventSystems; using UnityEngine.UI; namespace SimpleInputNamespace { public class Joystick : MonoBehaviour, ISimpleInputDraggable { public enum MovementAxes { XandY, X, Y }; public SimpleInput.AxisInput xAxis = new SimpleInput.AxisInput( "Horizontal" ); public SimpleInput.AxisInput yAxis = new SimpleInput.AxisInput( "Vertical" ); private RectTransform joystickTR; private Graphic background; public MovementAxes movementAxes = MovementAxes.XandY; public float valueMultiplier = 1f; #pragma warning disable 0649 [SerializeField] private Image thumb; private RectTransform thumbTR; [SerializeField] private float movementAreaRadius = 75f; [Tooltip( "Radius of the deadzone at the center of the joystick that will yield no input" )] [SerializeField] private float deadzoneRadius; [SerializeField] private bool isDynamicJoystick = false; [SerializeField] private RectTransform dynamicJoystickMovementArea; [SerializeField] private bool canFollowPointer = false; #pragma warning restore 0649 private bool joystickHeld = false; private Vector2 pointerInitialPos; private float _1OverMovementAreaRadius; private float movementAreaRadiusSqr; private float deadzoneRadiusSqr; private Vector2 joystickInitialPos; private float opacity = 1f; private Vector2 m_value = Vector2.zero; public Vector2 Value { get { return m_value; } } private void Awake() { joystickTR = (RectTransform) transform; thumbTR = thumb.rectTransform; background = GetComponent<Graphic>(); if( isDynamicJoystick ) { opacity = 0f; thumb.raycastTarget = false; if( background ) background.raycastTarget = false; OnUpdate(); } else { thumb.raycastTarget = true; if( background ) background.raycastTarget = true; } _1OverMovementAreaRadius = 1f / movementAreaRadius; movementAreaRadiusSqr = movementAreaRadius * movementAreaRadius; deadzoneRadiusSqr = deadzoneRadius * deadzoneRadius; joystickInitialPos = joystickTR.anchoredPosition; thumbTR.localPosition = Vector3.zero; } private void Start() { SimpleInputDragListener eventReceiver; if( !isDynamicJoystick ) { if( background ) eventReceiver = background.gameObject.AddComponent<SimpleInputDragListener>(); else eventReceiver = thumbTR.gameObject.AddComponent<SimpleInputDragListener>(); } else { if( !dynamicJoystickMovementArea ) { dynamicJoystickMovementArea = new GameObject( "Dynamic Joystick Movement Area", typeof( RectTransform ) ).GetComponent<RectTransform>(); dynamicJoystickMovementArea.SetParent( thumb.canvas.transform, false ); dynamicJoystickMovementArea.SetAsFirstSibling(); dynamicJoystickMovementArea.anchorMin = Vector2.zero; dynamicJoystickMovementArea.anchorMax = Vector2.one; dynamicJoystickMovementArea.sizeDelta = Vector2.zero; dynamicJoystickMovementArea.anchoredPosition = Vector2.zero; } eventReceiver = dynamicJoystickMovementArea.gameObject.AddComponent<SimpleInputDragListener>(); } eventReceiver.Listener = this; } private void OnEnable() { xAxis.StartTracking(); yAxis.StartTracking(); SimpleInput.OnUpdate += OnUpdate; } private void OnDisable() { OnPointerUp( null ); xAxis.StopTracking(); yAxis.StopTracking(); SimpleInput.OnUpdate -= OnUpdate; } #if UNITY_EDITOR private void OnValidate() { _1OverMovementAreaRadius = 1f / movementAreaRadius; movementAreaRadiusSqr = movementAreaRadius * movementAreaRadius; deadzoneRadiusSqr = deadzoneRadius * deadzoneRadius; } #endif public void OnPointerDown( PointerEventData eventData ) { joystickHeld = true; if( isDynamicJoystick ) { pointerInitialPos = Vector2.zero; Vector3 joystickPos; RectTransformUtility.ScreenPointToWorldPointInRectangle( dynamicJoystickMovementArea, eventData.position, eventData.pressEventCamera, out joystickPos ); joystickTR.position = joystickPos; } else RectTransformUtility.ScreenPointToLocalPointInRectangle( joystickTR, eventData.position, eventData.pressEventCamera, out pointerInitialPos ); } public void OnDrag( PointerEventData eventData ) { Vector2 pointerPos; RectTransformUtility.ScreenPointToLocalPointInRectangle( joystickTR, eventData.position, eventData.pressEventCamera, out pointerPos ); Vector2 direction = pointerPos - pointerInitialPos; if( movementAxes == MovementAxes.X ) direction.y = 0f; else if( movementAxes == MovementAxes.Y ) direction.x = 0f; if( direction.sqrMagnitude <= deadzoneRadiusSqr ) m_value.Set( 0f, 0f ); else { if( direction.sqrMagnitude > movementAreaRadiusSqr ) { Vector2 directionNormalized = direction.normalized * movementAreaRadius; if( canFollowPointer ) joystickTR.localPosition += (Vector3) ( direction - directionNormalized ); direction = directionNormalized; } m_value = direction * _1OverMovementAreaRadius * valueMultiplier; } thumbTR.localPosition = direction; xAxis.value = m_value.x; yAxis.value = m_value.y; } public void OnPointerUp( PointerEventData eventData ) { joystickHeld = false; m_value = Vector2.zero; thumbTR.localPosition = Vector3.zero; if( !isDynamicJoystick && canFollowPointer ) joystickTR.anchoredPosition = joystickInitialPos; xAxis.value = 0f; yAxis.value = 0f; } private void OnUpdate() { if( !isDynamicJoystick ) return; if( joystickHeld ) opacity = Mathf.Min( 1f, opacity + Time.unscaledDeltaTime * 4f ); else opacity = Mathf.Max( 0f, opacity - Time.unscaledDeltaTime * 4f ); Color c = thumb.color; c.a = opacity; thumb.color = c; if( background ) { c = background.color; c.a = opacity; background.color = c; } } } }
27.141593
157
0.704434
[ "CC0-1.0" ]
MoonyGames/file547
file547/Assets/file547/Packages/SimpleInput/Scripts/AxisInputs/Joystick.cs
6,136
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.X86; namespace JIT.HardwareIntrinsics.X86 { public static partial class Program { private static void CompareGreaterThanInt16() { var test = new SimpleBinaryOpTest__CompareGreaterThanInt16(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); if (Avx.IsSupported) { // Validates passing a static member works, using pinning and Load test.RunClsVarScenario_Load(); } // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); if (Avx.IsSupported) { // Validates passing the field of a local class works, using pinning and Load test.RunClassLclFldScenario_Load(); } // Validates passing an instance member of a class works test.RunClassFldScenario(); if (Avx.IsSupported) { // Validates passing an instance member of a class works, using pinning and Load test.RunClassFldScenario_Load(); } // Validates passing the field of a local struct works test.RunStructLclFldScenario(); if (Avx.IsSupported) { // Validates passing the field of a local struct works, using pinning and Load test.RunStructLclFldScenario_Load(); } // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (Avx.IsSupported) { // Validates passing an instance member of a struct works, using pinning and Load test.RunStructFldScenario_Load(); } } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleBinaryOpTest__CompareGreaterThanInt16 { private struct DataTable { private byte[] inArray1; private byte[] inArray2; private byte[] outArray; private GCHandle inHandle1; private GCHandle inHandle2; private GCHandle outHandle; private ulong alignment; public DataTable(Int16[] inArray1, Int16[] inArray2, Int16[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Int16>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Int16>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Int16>(); if ((alignment != 32 && alignment != 16) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.inArray2 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Int16, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Int16, byte>(ref inArray2[0]), (uint)sizeOfinArray2); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); inHandle2.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector256<Int16> _fld1; public Vector256<Int16> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int16>, byte>(ref testStruct._fld1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Int16>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int16>, byte>(ref testStruct._fld2), ref Unsafe.As<Int16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Int16>>()); return testStruct; } public void RunStructFldScenario(SimpleBinaryOpTest__CompareGreaterThanInt16 testClass) { var result = Avx2.CompareGreaterThan(_fld1, _fld2); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleBinaryOpTest__CompareGreaterThanInt16 testClass) { fixed (Vector256<Int16>* pFld1 = &_fld1) fixed (Vector256<Int16>* pFld2 = &_fld2) { var result = Avx2.CompareGreaterThan( Avx.LoadVector256((Int16*)(pFld1)), Avx.LoadVector256((Int16*)(pFld2)) ); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } } } private static readonly int LargestVectorSize = 32; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector256<Int16>>() / sizeof(Int16); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector256<Int16>>() / sizeof(Int16); private static readonly int RetElementCount = Unsafe.SizeOf<Vector256<Int16>>() / sizeof(Int16); private static Int16[] _data1 = new Int16[Op1ElementCount]; private static Int16[] _data2 = new Int16[Op2ElementCount]; private static Vector256<Int16> _clsVar1; private static Vector256<Int16> _clsVar2; private Vector256<Int16> _fld1; private Vector256<Int16> _fld2; private DataTable _dataTable; static SimpleBinaryOpTest__CompareGreaterThanInt16() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int16>, byte>(ref _clsVar1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Int16>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int16>, byte>(ref _clsVar2), ref Unsafe.As<Int16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Int16>>()); } public SimpleBinaryOpTest__CompareGreaterThanInt16() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int16>, byte>(ref _fld1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Int16>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int16>, byte>(ref _fld2), ref Unsafe.As<Int16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Int16>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); } _dataTable = new DataTable(_data1, _data2, new Int16[RetElementCount], LargestVectorSize); } public bool IsSupported => Avx2.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Avx2.CompareGreaterThan( Unsafe.Read<Vector256<Int16>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<Int16>>(_dataTable.inArray2Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = Avx2.CompareGreaterThan( Avx.LoadVector256((Int16*)(_dataTable.inArray1Ptr)), Avx.LoadVector256((Int16*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned)); var result = Avx2.CompareGreaterThan( Avx.LoadAlignedVector256((Int16*)(_dataTable.inArray1Ptr)), Avx.LoadAlignedVector256((Int16*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(Avx2).GetMethod(nameof(Avx2.CompareGreaterThan), new Type[] { typeof(Vector256<Int16>), typeof(Vector256<Int16>) }) .Invoke(null, new object[] { Unsafe.Read<Vector256<Int16>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<Int16>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int16>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(Avx2).GetMethod(nameof(Avx2.CompareGreaterThan), new Type[] { typeof(Vector256<Int16>), typeof(Vector256<Int16>) }) .Invoke(null, new object[] { Avx.LoadVector256((Int16*)(_dataTable.inArray1Ptr)), Avx.LoadVector256((Int16*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int16>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned)); var result = typeof(Avx2).GetMethod(nameof(Avx2.CompareGreaterThan), new Type[] { typeof(Vector256<Int16>), typeof(Vector256<Int16>) }) .Invoke(null, new object[] { Avx.LoadAlignedVector256((Int16*)(_dataTable.inArray1Ptr)), Avx.LoadAlignedVector256((Int16*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int16>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Avx2.CompareGreaterThan( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector256<Int16>* pClsVar1 = &_clsVar1) fixed (Vector256<Int16>* pClsVar2 = &_clsVar2) { var result = Avx2.CompareGreaterThan( Avx.LoadVector256((Int16*)(pClsVar1)), Avx.LoadVector256((Int16*)(pClsVar2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector256<Int16>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector256<Int16>>(_dataTable.inArray2Ptr); var result = Avx2.CompareGreaterThan(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = Avx.LoadVector256((Int16*)(_dataTable.inArray1Ptr)); var op2 = Avx.LoadVector256((Int16*)(_dataTable.inArray2Ptr)); var result = Avx2.CompareGreaterThan(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned)); var op1 = Avx.LoadAlignedVector256((Int16*)(_dataTable.inArray1Ptr)); var op2 = Avx.LoadAlignedVector256((Int16*)(_dataTable.inArray2Ptr)); var result = Avx2.CompareGreaterThan(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleBinaryOpTest__CompareGreaterThanInt16(); var result = Avx2.CompareGreaterThan(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load)); var test = new SimpleBinaryOpTest__CompareGreaterThanInt16(); fixed (Vector256<Int16>* pFld1 = &test._fld1) fixed (Vector256<Int16>* pFld2 = &test._fld2) { var result = Avx2.CompareGreaterThan( Avx.LoadVector256((Int16*)(pFld1)), Avx.LoadVector256((Int16*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Avx2.CompareGreaterThan(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector256<Int16>* pFld1 = &_fld1) fixed (Vector256<Int16>* pFld2 = &_fld2) { var result = Avx2.CompareGreaterThan( Avx.LoadVector256((Int16*)(pFld1)), Avx.LoadVector256((Int16*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Avx2.CompareGreaterThan(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = Avx2.CompareGreaterThan( Avx.LoadVector256((Int16*)(&test._fld1)), Avx.LoadVector256((Int16*)(&test._fld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunStructFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load)); var test = TestStruct.Create(); test.RunStructFldScenario_Load(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector256<Int16> op1, Vector256<Int16> op2, void* result, [CallerMemberName] string method = "") { Int16[] inArray1 = new Int16[Op1ElementCount]; Int16[] inArray2 = new Int16[Op2ElementCount]; Int16[] outArray = new Int16[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Int16, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<Int16, byte>(ref inArray2[0]), op2); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Int16>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "") { Int16[] inArray1 = new Int16[Op1ElementCount]; Int16[] inArray2 = new Int16[Op2ElementCount]; Int16[] outArray = new Int16[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector256<Int16>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector256<Int16>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Int16>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Int16[] left, Int16[] right, Int16[] result, [CallerMemberName] string method = "") { bool succeeded = true; if (result[0] != ((left[0] > right[0]) ? unchecked((short)(-1)) : 0)) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (result[i] != ((left[i] > right[i]) ? unchecked((short)(-1)) : 0)) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Avx2)}.{nameof(Avx2.CompareGreaterThan)}<Int16>(Vector256<Int16>, Vector256<Int16>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})"); TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
42.327645
187
0.583333
[ "MIT" ]
06needhamt/runtime
src/coreclr/tests/src/JIT/HardwareIntrinsics/X86/Avx2/CompareGreaterThan.Int16.cs
24,804
C#
using System.ComponentModel.DataAnnotations; namespace OrchardCore.Microsoft.Authentication.ViewModels { public class AzureADSettingsViewModel { [Required] public string DisplayName { get; set; } [Required(AllowEmptyStrings = false, ErrorMessage = "Application Id is required")] public string AppId { get; set; } [Required(AllowEmptyStrings = false, ErrorMessage = "Tenant Id is required")] public string TenantId { get; set; } [RegularExpression(@"\/[-A-Za-z0-9+&@#\/%?=~_|!:,.;]+[-A-Za-z0-9+&@#\/%=~_|]", ErrorMessage = "Invalid path")] public string CallbackPath { get; set; } public bool SaveTokens { get; set; } } }
32.272727
118
0.632394
[ "BSD-3-Clause" ]
1051324354/OrchardCore
src/OrchardCore.Modules/OrchardCore.Microsoft.Authentication/ViewModels/AzureADSettingsViewModel.cs
710
C#
using System; using System.Collections.Generic; using Android.Runtime; using Java.Interop; namespace Com.Qmuiteam.Qmui.Widget.Popup { // Metadata.xml XPath class reference: path="/api/package[@name='com.qmuiteam.qmui.widget.popup']/class[@name='QMUIBasePopup']" [global::Android.Runtime.Register ("com/qmuiteam/qmui/widget/popup/QMUIBasePopup", DoNotGenerateAcw=true)] [global::Java.Interop.JavaTypeParameters (new string [] {"T extends com.qmuiteam.qmui.widget.popup.QMUIBasePopup"})] public abstract partial class QMUIBasePopup : global::Java.Lang.Object { // Metadata.xml XPath field reference: path="/api/package[@name='com.qmuiteam.qmui.widget.popup']/class[@name='QMUIBasePopup']/field[@name='DIM_AMOUNT_NOT_EXIST']" [Register ("DIM_AMOUNT_NOT_EXIST")] public const float DimAmountNotExist = (float) -1; // Metadata.xml XPath field reference: path="/api/package[@name='com.qmuiteam.qmui.widget.popup']/class[@name='QMUIBasePopup']/field[@name='NOT_SET']" [Register ("NOT_SET")] public const int NotSet = (int) -1; // Metadata.xml XPath field reference: path="/api/package[@name='com.qmuiteam.qmui.widget.popup']/class[@name='QMUIBasePopup']/field[@name='mAttachedViewRf']" [Register ("mAttachedViewRf")] protected global::Java.Lang.Ref.WeakReference MAttachedViewRf { get { const string __id = "mAttachedViewRf.Ljava/lang/ref/WeakReference;"; var __v = _members.InstanceFields.GetObjectValue (__id, this); return global::Java.Lang.Object.GetObject<global::Java.Lang.Ref.WeakReference> (__v.Handle, JniHandleOwnership.TransferLocalRef); } set { const string __id = "mAttachedViewRf.Ljava/lang/ref/WeakReference;"; IntPtr native_value = global::Android.Runtime.JNIEnv.ToLocalJniHandle (value); try { _members.InstanceFields.SetValue (__id, this, new JniObjectReference (native_value)); } finally { global::Android.Runtime.JNIEnv.DeleteLocalRef (native_value); } } } // Metadata.xml XPath field reference: path="/api/package[@name='com.qmuiteam.qmui.widget.popup']/class[@name='QMUIBasePopup']/field[@name='mContext']" [Register ("mContext")] protected global::Android.Content.Context MContext { get { const string __id = "mContext.Landroid/content/Context;"; var __v = _members.InstanceFields.GetObjectValue (__id, this); return global::Java.Lang.Object.GetObject<global::Android.Content.Context> (__v.Handle, JniHandleOwnership.TransferLocalRef); } set { const string __id = "mContext.Landroid/content/Context;"; IntPtr native_value = global::Android.Runtime.JNIEnv.ToLocalJniHandle (value); try { _members.InstanceFields.SetValue (__id, this, new JniObjectReference (native_value)); } finally { global::Android.Runtime.JNIEnv.DeleteLocalRef (native_value); } } } // Metadata.xml XPath field reference: path="/api/package[@name='com.qmuiteam.qmui.widget.popup']/class[@name='QMUIBasePopup']/field[@name='mWindow']" [Register ("mWindow")] protected global::Android.Widget.PopupWindow MWindow { get { const string __id = "mWindow.Landroid/widget/PopupWindow;"; var __v = _members.InstanceFields.GetObjectValue (__id, this); return global::Java.Lang.Object.GetObject<global::Android.Widget.PopupWindow> (__v.Handle, JniHandleOwnership.TransferLocalRef); } set { const string __id = "mWindow.Landroid/widget/PopupWindow;"; IntPtr native_value = global::Android.Runtime.JNIEnv.ToLocalJniHandle (value); try { _members.InstanceFields.SetValue (__id, this, new JniObjectReference (native_value)); } finally { global::Android.Runtime.JNIEnv.DeleteLocalRef (native_value); } } } // Metadata.xml XPath field reference: path="/api/package[@name='com.qmuiteam.qmui.widget.popup']/class[@name='QMUIBasePopup']/field[@name='mWindowManager']" [Register ("mWindowManager")] protected global::Android.Views.IWindowManager MWindowManager { get { const string __id = "mWindowManager.Landroid/view/WindowManager;"; var __v = _members.InstanceFields.GetObjectValue (__id, this); return global::Java.Lang.Object.GetObject<global::Android.Views.IWindowManager> (__v.Handle, JniHandleOwnership.TransferLocalRef); } set { const string __id = "mWindowManager.Landroid/view/WindowManager;"; IntPtr native_value = global::Android.Runtime.JNIEnv.ToLocalJniHandle (value); try { _members.InstanceFields.SetValue (__id, this, new JniObjectReference (native_value)); } finally { global::Android.Runtime.JNIEnv.DeleteLocalRef (native_value); } } } static readonly JniPeerMembers _members = new XAPeerMembers ("com/qmuiteam/qmui/widget/popup/QMUIBasePopup", typeof (QMUIBasePopup)); internal static IntPtr class_ref { get { return _members.JniPeerType.PeerReference.Handle; } } public override global::Java.Interop.JniPeerMembers JniPeerMembers { get { return _members; } } protected override IntPtr ThresholdClass { get { return _members.JniPeerType.PeerReference.Handle; } } protected override global::System.Type ThresholdType { get { return _members.ManagedPeerType; } } protected QMUIBasePopup (IntPtr javaReference, JniHandleOwnership transfer) : base (javaReference, transfer) {} // Metadata.xml XPath constructor reference: path="/api/package[@name='com.qmuiteam.qmui.widget.popup']/class[@name='QMUIBasePopup']/constructor[@name='QMUIBasePopup' and count(parameter)=1 and parameter[1][@type='android.content.Context']]" [Register (".ctor", "(Landroid/content/Context;)V", "")] public unsafe QMUIBasePopup (global::Android.Content.Context context) : base (IntPtr.Zero, JniHandleOwnership.DoNotTransfer) { const string __id = "(Landroid/content/Context;)V"; if (((global::Java.Lang.Object) this).Handle != IntPtr.Zero) return; try { JniArgumentValue* __args = stackalloc JniArgumentValue [1]; __args [0] = new JniArgumentValue ((context == null) ? IntPtr.Zero : ((global::Java.Lang.Object) context).Handle); var __r = _members.InstanceMethods.StartCreateInstance (__id, ((object) this).GetType (), __args); SetHandle (__r.Handle, JniHandleOwnership.TransferLocalRef); _members.InstanceMethods.FinishCreateInstance (__id, this, __args); } finally { global::System.GC.KeepAlive (context); } } static Delegate cb_getDecorView; #pragma warning disable 0169 static Delegate GetGetDecorViewHandler () { if (cb_getDecorView == null) cb_getDecorView = JNINativeWrapper.CreateDelegate ((_JniMarshal_PP_L) n_GetDecorView); return cb_getDecorView; } static IntPtr n_GetDecorView (IntPtr jnienv, IntPtr native__this) { var __this = global::Java.Lang.Object.GetObject<global::Com.Qmuiteam.Qmui.Widget.Popup.QMUIBasePopup> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); return JNIEnv.ToLocalJniHandle (__this.DecorView); } #pragma warning restore 0169 public virtual unsafe global::Android.Views.View DecorView { // Metadata.xml XPath method reference: path="/api/package[@name='com.qmuiteam.qmui.widget.popup']/class[@name='QMUIBasePopup']/method[@name='getDecorView' and count(parameter)=0]" [Register ("getDecorView", "()Landroid/view/View;", "GetGetDecorViewHandler")] get { const string __id = "getDecorView.()Landroid/view/View;"; try { var __rm = _members.InstanceMethods.InvokeVirtualObjectMethod (__id, this, null); return global::Java.Lang.Object.GetObject<global::Android.Views.View> (__rm.Handle, JniHandleOwnership.TransferLocalRef); } finally { } } } static Delegate cb_getSkinManager; #pragma warning disable 0169 static Delegate GetGetSkinManagerHandler () { if (cb_getSkinManager == null) cb_getSkinManager = JNINativeWrapper.CreateDelegate ((_JniMarshal_PP_L) n_GetSkinManager); return cb_getSkinManager; } static IntPtr n_GetSkinManager (IntPtr jnienv, IntPtr native__this) { var __this = global::Java.Lang.Object.GetObject<global::Com.Qmuiteam.Qmui.Widget.Popup.QMUIBasePopup> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); return JNIEnv.ToLocalJniHandle (__this.SkinManager); } #pragma warning restore 0169 public virtual unsafe global::Com.Qmuiteam.Qmui.Skin.QMUISkinManager SkinManager { // Metadata.xml XPath method reference: path="/api/package[@name='com.qmuiteam.qmui.widget.popup']/class[@name='QMUIBasePopup']/method[@name='getSkinManager' and count(parameter)=0]" [Register ("getSkinManager", "()Lcom/qmuiteam/qmui/skin/QMUISkinManager;", "GetGetSkinManagerHandler")] get { const string __id = "getSkinManager.()Lcom/qmuiteam/qmui/skin/QMUISkinManager;"; try { var __rm = _members.InstanceMethods.InvokeVirtualObjectMethod (__id, this, null); return global::Java.Lang.Object.GetObject<global::Com.Qmuiteam.Qmui.Skin.QMUISkinManager> (__rm.Handle, JniHandleOwnership.TransferLocalRef); } finally { } } } static Delegate cb_dimAmount_F; #pragma warning disable 0169 static Delegate GetDimAmount_FHandler () { if (cb_dimAmount_F == null) cb_dimAmount_F = JNINativeWrapper.CreateDelegate ((_JniMarshal_PPF_L) n_DimAmount_F); return cb_dimAmount_F; } static IntPtr n_DimAmount_F (IntPtr jnienv, IntPtr native__this, float dimAmount) { var __this = global::Java.Lang.Object.GetObject<global::Com.Qmuiteam.Qmui.Widget.Popup.QMUIBasePopup> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); return JNIEnv.ToLocalJniHandle (__this.DimAmount (dimAmount)); } #pragma warning restore 0169 // Metadata.xml XPath method reference: path="/api/package[@name='com.qmuiteam.qmui.widget.popup']/class[@name='QMUIBasePopup']/method[@name='dimAmount' and count(parameter)=1 and parameter[1][@type='float']]" [Register ("dimAmount", "(F)Lcom/qmuiteam/qmui/widget/popup/QMUIBasePopup;", "GetDimAmount_FHandler")] public virtual unsafe global::Java.Lang.Object DimAmount (float dimAmount) { const string __id = "dimAmount.(F)Lcom/qmuiteam/qmui/widget/popup/QMUIBasePopup;"; try { JniArgumentValue* __args = stackalloc JniArgumentValue [1]; __args [0] = new JniArgumentValue (dimAmount); var __rm = _members.InstanceMethods.InvokeVirtualObjectMethod (__id, this, __args); return (Java.Lang.Object) global::Java.Lang.Object.GetObject<global::Java.Lang.Object> (__rm.Handle, JniHandleOwnership.TransferLocalRef); } finally { } } static Delegate cb_dimAmountAttr_I; #pragma warning disable 0169 static Delegate GetDimAmountAttr_IHandler () { if (cb_dimAmountAttr_I == null) cb_dimAmountAttr_I = JNINativeWrapper.CreateDelegate ((_JniMarshal_PPI_L) n_DimAmountAttr_I); return cb_dimAmountAttr_I; } static IntPtr n_DimAmountAttr_I (IntPtr jnienv, IntPtr native__this, int dimAmountAttr) { var __this = global::Java.Lang.Object.GetObject<global::Com.Qmuiteam.Qmui.Widget.Popup.QMUIBasePopup> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); return JNIEnv.ToLocalJniHandle (__this.DimAmountAttr (dimAmountAttr)); } #pragma warning restore 0169 // Metadata.xml XPath method reference: path="/api/package[@name='com.qmuiteam.qmui.widget.popup']/class[@name='QMUIBasePopup']/method[@name='dimAmountAttr' and count(parameter)=1 and parameter[1][@type='int']]" [Register ("dimAmountAttr", "(I)Lcom/qmuiteam/qmui/widget/popup/QMUIBasePopup;", "GetDimAmountAttr_IHandler")] public virtual unsafe global::Java.Lang.Object DimAmountAttr (int dimAmountAttr) { const string __id = "dimAmountAttr.(I)Lcom/qmuiteam/qmui/widget/popup/QMUIBasePopup;"; try { JniArgumentValue* __args = stackalloc JniArgumentValue [1]; __args [0] = new JniArgumentValue (dimAmountAttr); var __rm = _members.InstanceMethods.InvokeVirtualObjectMethod (__id, this, __args); return (Java.Lang.Object) global::Java.Lang.Object.GetObject<global::Java.Lang.Object> (__rm.Handle, JniHandleOwnership.TransferLocalRef); } finally { } } // Metadata.xml XPath method reference: path="/api/package[@name='com.qmuiteam.qmui.widget.popup']/class[@name='QMUIBasePopup']/method[@name='dismiss' and count(parameter)=0]" [Register ("dismiss", "()V", "")] public unsafe void Dismiss () { const string __id = "dismiss.()V"; try { _members.InstanceMethods.InvokeNonvirtualVoidMethod (__id, this, null); } finally { } } static Delegate cb_dismissIfOutsideTouch_Z; #pragma warning disable 0169 static Delegate GetDismissIfOutsideTouch_ZHandler () { if (cb_dismissIfOutsideTouch_Z == null) cb_dismissIfOutsideTouch_Z = JNINativeWrapper.CreateDelegate ((_JniMarshal_PPZ_L) n_DismissIfOutsideTouch_Z); return cb_dismissIfOutsideTouch_Z; } static IntPtr n_DismissIfOutsideTouch_Z (IntPtr jnienv, IntPtr native__this, bool dismissIfOutsideTouch) { var __this = global::Java.Lang.Object.GetObject<global::Com.Qmuiteam.Qmui.Widget.Popup.QMUIBasePopup> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); return JNIEnv.ToLocalJniHandle (__this.DismissIfOutsideTouch (dismissIfOutsideTouch)); } #pragma warning restore 0169 // Metadata.xml XPath method reference: path="/api/package[@name='com.qmuiteam.qmui.widget.popup']/class[@name='QMUIBasePopup']/method[@name='dismissIfOutsideTouch' and count(parameter)=1 and parameter[1][@type='boolean']]" [Register ("dismissIfOutsideTouch", "(Z)Lcom/qmuiteam/qmui/widget/popup/QMUIBasePopup;", "GetDismissIfOutsideTouch_ZHandler")] public virtual unsafe global::Java.Lang.Object DismissIfOutsideTouch (bool dismissIfOutsideTouch) { const string __id = "dismissIfOutsideTouch.(Z)Lcom/qmuiteam/qmui/widget/popup/QMUIBasePopup;"; try { JniArgumentValue* __args = stackalloc JniArgumentValue [1]; __args [0] = new JniArgumentValue (dismissIfOutsideTouch); var __rm = _members.InstanceMethods.InvokeVirtualObjectMethod (__id, this, __args); return (Java.Lang.Object) global::Java.Lang.Object.GetObject<global::Java.Lang.Object> (__rm.Handle, JniHandleOwnership.TransferLocalRef); } finally { } } static Delegate cb_modifyWindowLayoutParams_Landroid_view_WindowManager_LayoutParams_; #pragma warning disable 0169 static Delegate GetModifyWindowLayoutParams_Landroid_view_WindowManager_LayoutParams_Handler () { if (cb_modifyWindowLayoutParams_Landroid_view_WindowManager_LayoutParams_ == null) cb_modifyWindowLayoutParams_Landroid_view_WindowManager_LayoutParams_ = JNINativeWrapper.CreateDelegate ((_JniMarshal_PPL_V) n_ModifyWindowLayoutParams_Landroid_view_WindowManager_LayoutParams_); return cb_modifyWindowLayoutParams_Landroid_view_WindowManager_LayoutParams_; } static void n_ModifyWindowLayoutParams_Landroid_view_WindowManager_LayoutParams_ (IntPtr jnienv, IntPtr native__this, IntPtr native_lp) { var __this = global::Java.Lang.Object.GetObject<global::Com.Qmuiteam.Qmui.Widget.Popup.QMUIBasePopup> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); var lp = global::Java.Lang.Object.GetObject<global::Android.Views.WindowManagerLayoutParams> (native_lp, JniHandleOwnership.DoNotTransfer); __this.ModifyWindowLayoutParams (lp); } #pragma warning restore 0169 // Metadata.xml XPath method reference: path="/api/package[@name='com.qmuiteam.qmui.widget.popup']/class[@name='QMUIBasePopup']/method[@name='modifyWindowLayoutParams' and count(parameter)=1 and parameter[1][@type='android.view.WindowManager.LayoutParams']]" [Register ("modifyWindowLayoutParams", "(Landroid/view/WindowManager$LayoutParams;)V", "GetModifyWindowLayoutParams_Landroid_view_WindowManager_LayoutParams_Handler")] protected virtual unsafe void ModifyWindowLayoutParams (global::Android.Views.WindowManagerLayoutParams lp) { const string __id = "modifyWindowLayoutParams.(Landroid/view/WindowManager$LayoutParams;)V"; try { JniArgumentValue* __args = stackalloc JniArgumentValue [1]; __args [0] = new JniArgumentValue ((lp == null) ? IntPtr.Zero : ((global::Java.Lang.Object) lp).Handle); _members.InstanceMethods.InvokeVirtualVoidMethod (__id, this, __args); } finally { global::System.GC.KeepAlive (lp); } } static Delegate cb_onDismiss; #pragma warning disable 0169 static Delegate GetOnDismissHandler () { if (cb_onDismiss == null) cb_onDismiss = JNINativeWrapper.CreateDelegate ((_JniMarshal_PP_V) n_OnDismiss); return cb_onDismiss; } static void n_OnDismiss (IntPtr jnienv, IntPtr native__this) { var __this = global::Java.Lang.Object.GetObject<global::Com.Qmuiteam.Qmui.Widget.Popup.QMUIBasePopup> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); __this.OnDismiss (); } #pragma warning restore 0169 // Metadata.xml XPath method reference: path="/api/package[@name='com.qmuiteam.qmui.widget.popup']/class[@name='QMUIBasePopup']/method[@name='onDismiss' and count(parameter)=0]" [Register ("onDismiss", "()V", "GetOnDismissHandler")] protected virtual unsafe void OnDismiss () { const string __id = "onDismiss.()V"; try { _members.InstanceMethods.InvokeVirtualVoidMethod (__id, this, null); } finally { } } static Delegate cb_onDismiss_Landroid_widget_PopupWindow_OnDismissListener_; #pragma warning disable 0169 static Delegate GetOnDismiss_Landroid_widget_PopupWindow_OnDismissListener_Handler () { if (cb_onDismiss_Landroid_widget_PopupWindow_OnDismissListener_ == null) cb_onDismiss_Landroid_widget_PopupWindow_OnDismissListener_ = JNINativeWrapper.CreateDelegate ((_JniMarshal_PPL_L) n_OnDismiss_Landroid_widget_PopupWindow_OnDismissListener_); return cb_onDismiss_Landroid_widget_PopupWindow_OnDismissListener_; } static IntPtr n_OnDismiss_Landroid_widget_PopupWindow_OnDismissListener_ (IntPtr jnienv, IntPtr native__this, IntPtr native_listener) { var __this = global::Java.Lang.Object.GetObject<global::Com.Qmuiteam.Qmui.Widget.Popup.QMUIBasePopup> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); var listener = (global::Android.Widget.PopupWindow.IOnDismissListener)global::Java.Lang.Object.GetObject<global::Android.Widget.PopupWindow.IOnDismissListener> (native_listener, JniHandleOwnership.DoNotTransfer); IntPtr __ret = JNIEnv.ToLocalJniHandle (__this.OnDismiss (listener)); return __ret; } #pragma warning restore 0169 // Metadata.xml XPath method reference: path="/api/package[@name='com.qmuiteam.qmui.widget.popup']/class[@name='QMUIBasePopup']/method[@name='onDismiss' and count(parameter)=1 and parameter[1][@type='android.widget.PopupWindow.OnDismissListener']]" [Register ("onDismiss", "(Landroid/widget/PopupWindow$OnDismissListener;)Lcom/qmuiteam/qmui/widget/popup/QMUIBasePopup;", "GetOnDismiss_Landroid_widget_PopupWindow_OnDismissListener_Handler")] public virtual unsafe global::Java.Lang.Object OnDismiss (global::Android.Widget.PopupWindow.IOnDismissListener listener) { const string __id = "onDismiss.(Landroid/widget/PopupWindow$OnDismissListener;)Lcom/qmuiteam/qmui/widget/popup/QMUIBasePopup;"; try { JniArgumentValue* __args = stackalloc JniArgumentValue [1]; __args [0] = new JniArgumentValue ((listener == null) ? IntPtr.Zero : ((global::Java.Lang.Object) listener).Handle); var __rm = _members.InstanceMethods.InvokeVirtualObjectMethod (__id, this, __args); return (Java.Lang.Object) global::Java.Lang.Object.GetObject<global::Java.Lang.Object> (__rm.Handle, JniHandleOwnership.TransferLocalRef); } finally { global::System.GC.KeepAlive (listener); } } static Delegate cb_onSkinChange_II; #pragma warning disable 0169 static Delegate GetOnSkinChange_IIHandler () { if (cb_onSkinChange_II == null) cb_onSkinChange_II = JNINativeWrapper.CreateDelegate ((_JniMarshal_PPII_V) n_OnSkinChange_II); return cb_onSkinChange_II; } static void n_OnSkinChange_II (IntPtr jnienv, IntPtr native__this, int oldSkin, int newSkin) { var __this = global::Java.Lang.Object.GetObject<global::Com.Qmuiteam.Qmui.Widget.Popup.QMUIBasePopup> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); __this.OnSkinChange (oldSkin, newSkin); } #pragma warning restore 0169 // Metadata.xml XPath method reference: path="/api/package[@name='com.qmuiteam.qmui.widget.popup']/class[@name='QMUIBasePopup']/method[@name='onSkinChange' and count(parameter)=2 and parameter[1][@type='int'] and parameter[2][@type='int']]" [Register ("onSkinChange", "(II)V", "GetOnSkinChange_IIHandler")] protected virtual unsafe void OnSkinChange (int oldSkin, int newSkin) { const string __id = "onSkinChange.(II)V"; try { JniArgumentValue* __args = stackalloc JniArgumentValue [2]; __args [0] = new JniArgumentValue (oldSkin); __args [1] = new JniArgumentValue (newSkin); _members.InstanceMethods.InvokeVirtualVoidMethod (__id, this, __args); } finally { } } static Delegate cb_showAtLocation_Landroid_view_View_II; #pragma warning disable 0169 static Delegate GetShowAtLocation_Landroid_view_View_IIHandler () { if (cb_showAtLocation_Landroid_view_View_II == null) cb_showAtLocation_Landroid_view_View_II = JNINativeWrapper.CreateDelegate ((_JniMarshal_PPLII_V) n_ShowAtLocation_Landroid_view_View_II); return cb_showAtLocation_Landroid_view_View_II; } static void n_ShowAtLocation_Landroid_view_View_II (IntPtr jnienv, IntPtr native__this, IntPtr native_parent, int x, int y) { var __this = global::Java.Lang.Object.GetObject<global::Com.Qmuiteam.Qmui.Widget.Popup.QMUIBasePopup> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); var parent = global::Java.Lang.Object.GetObject<global::Android.Views.View> (native_parent, JniHandleOwnership.DoNotTransfer); __this.ShowAtLocation (parent, x, y); } #pragma warning restore 0169 // Metadata.xml XPath method reference: path="/api/package[@name='com.qmuiteam.qmui.widget.popup']/class[@name='QMUIBasePopup']/method[@name='showAtLocation' and count(parameter)=3 and parameter[1][@type='android.view.View'] and parameter[2][@type='int'] and parameter[3][@type='int']]" [Register ("showAtLocation", "(Landroid/view/View;II)V", "GetShowAtLocation_Landroid_view_View_IIHandler")] protected virtual unsafe void ShowAtLocation (global::Android.Views.View parent, int x, int y) { const string __id = "showAtLocation.(Landroid/view/View;II)V"; try { JniArgumentValue* __args = stackalloc JniArgumentValue [3]; __args [0] = new JniArgumentValue ((parent == null) ? IntPtr.Zero : ((global::Java.Lang.Object) parent).Handle); __args [1] = new JniArgumentValue (x); __args [2] = new JniArgumentValue (y); _members.InstanceMethods.InvokeVirtualVoidMethod (__id, this, __args); } finally { global::System.GC.KeepAlive (parent); } } static Delegate cb_skinManager_Lcom_qmuiteam_qmui_skin_QMUISkinManager_; #pragma warning disable 0169 static Delegate GetInvokeSkinManager_Lcom_qmuiteam_qmui_skin_QMUISkinManager_Handler () { if (cb_skinManager_Lcom_qmuiteam_qmui_skin_QMUISkinManager_ == null) cb_skinManager_Lcom_qmuiteam_qmui_skin_QMUISkinManager_ = JNINativeWrapper.CreateDelegate ((_JniMarshal_PPL_L) n_InvokeSkinManager_Lcom_qmuiteam_qmui_skin_QMUISkinManager_); return cb_skinManager_Lcom_qmuiteam_qmui_skin_QMUISkinManager_; } static IntPtr n_InvokeSkinManager_Lcom_qmuiteam_qmui_skin_QMUISkinManager_ (IntPtr jnienv, IntPtr native__this, IntPtr native_skinManager) { var __this = global::Java.Lang.Object.GetObject<global::Com.Qmuiteam.Qmui.Widget.Popup.QMUIBasePopup> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); var skinManager = global::Java.Lang.Object.GetObject<global::Com.Qmuiteam.Qmui.Skin.QMUISkinManager> (native_skinManager, JniHandleOwnership.DoNotTransfer); IntPtr __ret = JNIEnv.ToLocalJniHandle (__this.InvokeSkinManager (skinManager)); return __ret; } #pragma warning restore 0169 // Metadata.xml XPath method reference: path="/api/package[@name='com.qmuiteam.qmui.widget.popup']/class[@name='QMUIBasePopup']/method[@name='skinManager' and count(parameter)=1 and parameter[1][@type='com.qmuiteam.qmui.skin.QMUISkinManager']]" [Register ("skinManager", "(Lcom/qmuiteam/qmui/skin/QMUISkinManager;)Lcom/qmuiteam/qmui/widget/popup/QMUIBasePopup;", "GetInvokeSkinManager_Lcom_qmuiteam_qmui_skin_QMUISkinManager_Handler")] public virtual unsafe global::Java.Lang.Object InvokeSkinManager (global::Com.Qmuiteam.Qmui.Skin.QMUISkinManager skinManager) { const string __id = "skinManager.(Lcom/qmuiteam/qmui/skin/QMUISkinManager;)Lcom/qmuiteam/qmui/widget/popup/QMUIBasePopup;"; try { JniArgumentValue* __args = stackalloc JniArgumentValue [1]; __args [0] = new JniArgumentValue ((skinManager == null) ? IntPtr.Zero : ((global::Java.Lang.Object) skinManager).Handle); var __rm = _members.InstanceMethods.InvokeVirtualObjectMethod (__id, this, __args); return (Java.Lang.Object) global::Java.Lang.Object.GetObject<global::Java.Lang.Object> (__rm.Handle, JniHandleOwnership.TransferLocalRef); } finally { global::System.GC.KeepAlive (skinManager); } } } [global::Android.Runtime.Register ("com/qmuiteam/qmui/widget/popup/QMUIBasePopup", DoNotGenerateAcw=true)] internal partial class QMUIBasePopupInvoker : QMUIBasePopup { public QMUIBasePopupInvoker (IntPtr handle, JniHandleOwnership transfer) : base (handle, transfer) {} static readonly JniPeerMembers _members = new XAPeerMembers ("com/qmuiteam/qmui/widget/popup/QMUIBasePopup", typeof (QMUIBasePopupInvoker)); public override global::Java.Interop.JniPeerMembers JniPeerMembers { get { return _members; } } protected override global::System.Type ThresholdType { get { return _members.ManagedPeerType; } } } }
49.638298
288
0.764291
[ "MIT" ]
daddycoding/XamarinQMUI
XamarinQMUI/QMUI.Droid/Additions/Com.Qmuiteam.Qmui.Widget.Popup.QMUIBasePopup.cs
25,663
C#
using Microsoft.EntityFrameworkCore.Migrations; #nullable disable namespace ShopManagement.Migrations { public partial class AddUserDetails : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.CreateTable( name: "User", columns: table => new { Username = table.Column<string>(type: "nvarchar(450)", nullable: false), UserId = table.Column<int>(type: "int", nullable: false) .Annotation("SqlServer:Identity", "1, 1"), Hash = table.Column<string>(type: "nvarchar(max)", nullable: false), Email = table.Column<string>(type: "nvarchar(max)", nullable: false) }, constraints: table => { table.PrimaryKey("PK_User", x => x.Username); }); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropTable( name: "User"); } } }
33.264706
92
0.526967
[ "MIT" ]
diogolopes18-cyber/PersonalWebsite
ShopManagement/Migrations/20220416204445_AddUserDetails.cs
1,133
C#
using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.IO; using System.Linq; using System.Net; using System.Net.Http; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Mvc; using CodeGen.Web.Models; using CodeGen.Web.Utility; using Newtonsoft.Json; using Microsoft.AspNetCore.Cors; using Microsoft.Extensions.Configuration; // For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860 namespace CodeGen.Web.Controllers { [EnableCors("AllowCors"), Produces("application/json"), Route("api/Codegen")] public class CodegenController : Controller { private readonly IHostingEnvironment _hostingEnvironment; private readonly string _conString = "";//"server=DESKTOP-80DEJMQ; uid=sa; pwd=sa@12345;"; //定義程式的產生(Key,LiquidPath) Dictionary<string, string> _genDefineDic = new Dictionary<string, string> { {"SP","\\template\\StoredProcedure\\SP.liquid" }, {"DbModel","\\template\\Model\\Model.liquid" }, {"Interface","\\template\\Interface\\Interface.liquid" }, {"Service","\\template\\Service\\Service.liquid" }, {"Test","\\template\\Test\\Test.liquid" }, {"Controller","\\template\\Controller\\Controller.liquid" }, {"APIGet","\\template\\WebAPI\\APIController.liquid" }, {"TS","\\template\\TS\\TS.liquid" }, {"View","\\template\\HtmlForm\\HtmlForm.liquid" }, {"Markdown","\\template\\Markdown\\Markdown.liquid" } }; public CodegenController( IHostingEnvironment hostingEnvironment, IConfiguration config) { _hostingEnvironment = hostingEnvironment; _conString = ConfigurationExtensions.GetConnectionString(config, "Default"); } #region ++++++ Database +++++++ // api/Codegen/GetDatabaseList [HttpGet, Route("GetDatabaseList"), Produces("application/json")] public List<vmDatabase> GetDatabaseList() { List<vmDatabase> data = new List<vmDatabase>(); using (SqlConnection con = new SqlConnection(_conString)) { int count = 0; con.Open(); using (SqlCommand cmd = new SqlCommand("SELECT name from sys.databases WHERE name NOT IN ('master', 'tempdb', 'model', 'msdb') ORDER BY create_date", con)) { using (IDataReader dr = cmd.ExecuteReader()) { while (dr.Read()) { count++; data.Add(new vmDatabase() { DatabaseId = count, DatabaseName = dr[0].ToString() }); } } } } return data.ToList(); } // api/Codegen/GetDatabaseTableList [HttpPost, Route("GetDatabaseTableList"), Produces("application/json")] public List<TableInfo> GetDatabaseTableList([FromBody]vmParam model) { var dbName = model.DatabaseName; List<TableInfo> data = getAllTableFromDb(dbName); return data.ToList(); } /// <summary> /// 取得Database下指定Table的欄位資訊 /// </summary> /// <remarks>這是取得Table下的Column清單,並會Keep至Web端</remarks> /// <param name="model"></param> /// <returns></returns> // api/Codegen/GetDatabaseTableColumnList [HttpPost, Route("GetDatabaseTableColumnList"), Produces("application/json")] public List<ColumnInfo> GetDatabaseTableColumnList([FromBody]vmParam model) { var dbName = model.DatabaseName; var tableName = model.TableName; return getColumnsFromTable( dbName, tableName); } [HttpPost, Route("GetMapColumns"), Produces("application/json")] public IActionResult GetMapColumns([FromBody]vmParam model) { var result = ""; string webRootPath = _hostingEnvironment.WebRootPath; //From web var filePath = webRootPath + "\\template\\ColumnMap\\colmap.json"; if (!System.IO.File.Exists(filePath)) { using (StreamWriter sw = System.IO.File.CreateText(filePath)) { sw.Write("[]"); } } var content = System.IO.File.ReadAllText(filePath, Encoding.UTF8); result = content; return Json(result); } [HttpPost, Route("SaveMapColumns"), Produces("application/json")] public void SaveMapColumns([FromBody]object data) { string webRootPath = _hostingEnvironment.WebRootPath; //From web var filePath = webRootPath + "\\template\\ColumnMap\\colmap.json"; System.IO.File.WriteAllText(filePath, string.Empty); var content = JsonConvert.SerializeObject(data); System.IO.File.WriteAllText(filePath, content); } #endregion #region +++++ CodeGeneration +++++ /// <summary> /// (TW)執行產生Code的觸發點 /// </summary> /// <param name="data"></param> /// <returns></returns> // api/Codegen/GenerateCode [HttpPost, Route("GenerateCode"), Produces("application/json")] public IActionResult GenerateCode([FromBody]object data) { Dictionary<string, string> resultCollectionDic = new Dictionary<string, string>(); try { string webRootPath = _hostingEnvironment.WebRootPath; //From wwwroot string contentRootPath = _hostingEnvironment.ContentRootPath; //From Others var postData = JsonConvert.DeserializeObject<dynamic>(data.ToString()); var tableJson = postData.table; var columnsJson = postData.columns; //(TW)取得Table資訊 var tableInfo = JsonConvert.DeserializeObject<TableInfo>(tableJson.ToString()); //(TW)頁面上勾選的Table Columns資訊反序列化 (包括從DB取得的資訊內容) List<ColumnInfo> columnInfos = JsonConvert.DeserializeObject<List<ColumnInfo>>(columnsJson.ToString()); var tableInfoForLiquid = new TableInfoForLiquid(tableInfo); var columnInfosForLiquid = columnInfos.Select(m => new ColumnInfoForLiquid(m)).ToList(); var otherInfoForLiquid = getOtherInfoForLiquid(tableInfoForLiquid, columnInfosForLiquid); foreach (var item in _genDefineDic) { var result = new CustomGenerator(item.Value).Generate(tableInfoForLiquid, columnInfosForLiquid, otherInfoForLiquid, webRootPath); resultCollectionDic.Add(item.Key, result); } } catch (Exception ex) { ex.ToString(); } return Json(resultCollectionDic); } [HttpPost, Route("GenerateAllTable"), Produces("application/json")] public IActionResult GenerateAllTable([FromBody]object data) { Dictionary<string, string> resultCollectionDic = new Dictionary<string, string>(); var builder = new StringBuilder(""); var fileContentMarkdown = ""; var markdownHeader = @" # 資料庫說明文件 # 目錄 [TOC] # 修訂歷程 | Date | Author | Version | Change Reference | | ---------- | ------ | ------- | ------------------------ | | | | | | # 資料表設計 "; builder.AppendLine(markdownHeader); try { string webRootPath = _hostingEnvironment.WebRootPath; //From wwwroot string contentRootPath = _hostingEnvironment.ContentRootPath; //From Others var postData = JsonConvert.DeserializeObject<dynamic>(data.ToString()); var databaseJson = postData.database; bool enableMap = (bool)postData.enableMap; string dbName = databaseJson.DatabaseName; List<TableInfo> tableInfo = getAllTableFromDb(dbName); //Markdown var markdown = _genDefineDic.Where(m => m.Key == "Markdown").FirstOrDefault(); foreach (TableInfo table in tableInfo) { var tableName = table.TableName; List<ColumnInfo> columnInfos = getColumnsFromTable(dbName, tableName); var tableInfoForLiquid = new TableInfoForLiquid(table); var columnInfosForLiquid = columnInfos.Select(m => new ColumnInfoForLiquid(m)).ToList(); var otherInfoForLiquid = getOtherInfoForLiquid(tableInfoForLiquid, columnInfosForLiquid); fileContentMarkdown = new CustomGenerator(markdown.Value).Generate(tableInfoForLiquid, columnInfosForLiquid, otherInfoForLiquid, webRootPath); builder.AppendLine(fileContentMarkdown); } resultCollectionDic.Add(markdown.Key, builder.ToString()); } catch (Exception ex) { ex.ToString(); } return Json(resultCollectionDic); } /// <summary> /// Get All Tables From Database /// </summary> /// <param name="dbName"></param> /// <returns></returns> private List<TableInfo> getAllTableFromDb(string dbName) { List<TableInfo> data = new List<TableInfo>(); string conString_ = _conString + " Database=" + dbName + ";"; using (SqlConnection con = new SqlConnection(conString_)) { int count = 0; con.Open(); var sql = @" select st.TABLE_SCHEMA as TableSchema,st.TABLE_NAME as TableName,ep.value as [Description] from INFORMATION_SCHEMA.TABLES st OUTER APPLY fn_listextendedproperty(default, 'SCHEMA', TABLE_SCHEMA, 'TABLE', TABLE_NAME, null, null) ep where st.TABLE_TYPE='BASE TABLE'"; using (SqlCommand cmd = new SqlCommand(sql, con)) { using (IDataReader reader = cmd.ExecuteReader()) { while (reader.Read()) { ++count; data.Add(new TableInfo { TableId = count, TableSchema = Convert.ToString(reader["TableSchema"]), TableName = Convert.ToString(reader["TableName"]), TableDescription = Convert.ToString(reader["Description"]) }); } } } } return data; } /// <summary> /// (EN)Get Columns From Table /// </summary> /// <param name="dbName"></param> /// <param name="tableName"></param> /// <returns></returns> private List<ColumnInfo> getColumnsFromTable(string dbName, string tableName) { List<ColumnInfo> data = new List<ColumnInfo>(); string conString_ = _conString + " Database=" + dbName + ";"; using (SqlConnection con = new SqlConnection(conString_)) { int count = 0; con.Open(); //20181108-howard fix:改寫取得Column的資訊語法 // --加上column 描述語法 //var sql = @"SELECT COLUMN_NAME, DATA_TYPE, ISNULL(CHARACTER_MAXIMUM_LENGTH,0), IS_NULLABLE, TABLE_SCHEMA FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = @TableName ORDER BY ORDINAL_POSITION"; var sql = @" select st.name [Table], sc.name [Column], sep.value as [Description], info.DATA_TYPE as [ColumnType], ISNULL(info.CHARACTER_MAXIMUM_LENGTH,0) as [Length], info.IS_NULLABLE as [Nullable], --get[YES/NO]word. info.TABLE_SCHEMA as [Schema] from sys.tables st --此資料庫下的Table inner join sys.columns sc on st.object_id = sc.object_id left join sys.extended_properties sep on st.object_id = sep.major_id and sc.column_id = sep.minor_id and sep.name = 'MS_Description' left join INFORMATION_SCHEMA.COLUMNS info on st.name= info.TABLE_NAME and sc.name = info.COLUMN_NAME where st.name = @TableName "; using (SqlCommand cmd = new SqlCommand(sql, con)) { //20181108-howard fix:改寫改用parameter的方式處理 cmd.Parameters.AddWithValue("TableName", tableName); using (IDataReader dr = cmd.ExecuteReader()) { while (dr.Read()) { count++; data.Add(new ColumnInfo() { ColumnId = count, ColumnName = dr["Column"].ToString(), DataType = dr["ColumnType"].ToString(), MaxLength = Convert.ToInt32(dr["Length"].ToString()), IsNullable = (dr["Nullable"].ToString() == "YES") ? true : false, TableName = tableName, TableSchema = dr["Schema"].ToString(), ColumnDescription = (dr["Description"].ToString()??"").Replace("\\n", "").Replace("\\r", "") }); } } } } return data.ToList(); } /// <summary> /// (TW)取得其它資訊內容 /// </summary> /// <param name="tableInfoForLiquid"></param> /// <param name="columnsForLiquid"></param> /// <returns></returns> private OtherInfoForLiquid getOtherInfoForLiquid(TableInfoForLiquid tableInfoForLiquid, List<ColumnInfoForLiquid> columnsForLiquid) { var result = new OtherInfoForLiquid(); var identityColumn = columnsForLiquid.FirstOrDefault();//暫以第一筆表示 if (identityColumn != null) { result.IndentityColumn = identityColumn.MapColumnName; result.IndentityModelType = identityColumn.ModelType; result.IndentityColumnDescription = identityColumn.ColumnDescription; } return result; } #endregion } }
41.549451
212
0.541259
[ "MIT" ]
hougii/MyCodeGen
CodeGen.Web/Controllers/CodegenController.cs
15,380
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Blocker : MonoBehaviour { public Transform Target; private Vector3 Initial; private float Speed = 0.1f; private Rigidbody Rigidbody; public bool canJump = false; public bool canBlock = false; private bool canMove = true; public GameObject GameobjectArms; // Use this for initialization void Start () { Rigidbody = GetComponent<Rigidbody>(); StartCoroutine(DoBlock()); } // Update is called once per frame private void OnCollisionEnter(Collision other) { if (other.gameObject.name == "Court") { canJump = true; } } private void OnCollisionExit(Collision other) { if (other.gameObject.name == "Court") { canJump = false; } } private void OnTriggerEnter(Collider other) { if (other.gameObject.name == "Positioned") { canBlock = true; } } private void OnTriggerExit(Collider other) { if (other.gameObject.name == "Positioned") { canBlock = false; } } IEnumerator DoBlock() { while (true) { yield return new WaitUntil(() => { return canBlock && canJump; }); GameobjectArms.SetActive(true); canMove = false; yield return new WaitUntil(() => { return !(canBlock && canJump); }); GameobjectArms.SetActive(false); canMove = true; } } void FixedUpdate () { // if (!canMove) return; Rigidbody.MovePosition(Vector3.MoveTowards( transform.position, new Vector3( Target.position.x, Initial.y, Target.position.z), Speed )); } }
18.988372
73
0.638089
[ "Apache-2.0" ]
Aaryan-kapur/tf-jam
Assets/Blocker.cs
1,635
C#
#pragma checksum "F:\DotNetSelfPractise_Home\source\MyProjects\LearningNeverEndsEFCoreProject\GameManagementProject\Views\Shared\_ValidationScriptsPartial.cshtml" "{ff1816ec-aa5e-4d10-87f7-6f4963833460}" "4b5e5ef4ebf7354cc35c7dacddd6bc3068f19a47" // <auto-generated/> #pragma warning disable 1591 [assembly: global::Microsoft.AspNetCore.Razor.Hosting.RazorCompiledItemAttribute(typeof(AspNetCore.Views_Shared__ValidationScriptsPartial), @"mvc.1.0.view", @"/Views/Shared/_ValidationScriptsPartial.cshtml")] namespace AspNetCore { #line hidden using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Rendering; using Microsoft.AspNetCore.Mvc.ViewFeatures; #nullable restore #line 1 "F:\DotNetSelfPractise_Home\source\MyProjects\LearningNeverEndsEFCoreProject\GameManagementProject\Views\_ViewImports.cshtml" using GameManagementProject; #line default #line hidden #nullable disable #nullable restore #line 2 "F:\DotNetSelfPractise_Home\source\MyProjects\LearningNeverEndsEFCoreProject\GameManagementProject\Views\_ViewImports.cshtml" using GameManagementProject.Models; #line default #line hidden #nullable disable [global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"4b5e5ef4ebf7354cc35c7dacddd6bc3068f19a47", @"/Views/Shared/_ValidationScriptsPartial.cshtml")] [global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"628337ddbf4a799ecaf4839602f2b1b3a36721ce", @"/Views/_ViewImports.cshtml")] public class Views_Shared__ValidationScriptsPartial : global::Microsoft.AspNetCore.Mvc.Razor.RazorPage<dynamic> { private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_0 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("src", new global::Microsoft.AspNetCore.Html.HtmlString("~/lib/jquery-validation/dist/jquery.validate.min.js"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_1 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("src", new global::Microsoft.AspNetCore.Html.HtmlString("~/lib/jquery-validation-unobtrusive/jquery.validate.unobtrusive.min.js"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); #line hidden #pragma warning disable 0649 private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperExecutionContext __tagHelperExecutionContext; #pragma warning restore 0649 private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperRunner __tagHelperRunner = new global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperRunner(); #pragma warning disable 0169 private string __tagHelperStringValueBuffer; #pragma warning restore 0169 private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperScopeManager __backed__tagHelperScopeManager = null; private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperScopeManager __tagHelperScopeManager { get { if (__backed__tagHelperScopeManager == null) { __backed__tagHelperScopeManager = new global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperScopeManager(StartTagHelperWritingScope, EndTagHelperWritingScope); } return __backed__tagHelperScopeManager; } } private global::Microsoft.AspNetCore.Mvc.Razor.TagHelpers.UrlResolutionTagHelper __Microsoft_AspNetCore_Mvc_Razor_TagHelpers_UrlResolutionTagHelper; #pragma warning disable 1998 public async override global::System.Threading.Tasks.Task ExecuteAsync() { __tagHelperExecutionContext = __tagHelperScopeManager.Begin("script", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "4b5e5ef4ebf7354cc35c7dacddd6bc3068f19a474113", async() => { } ); __Microsoft_AspNetCore_Mvc_Razor_TagHelpers_UrlResolutionTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.Razor.TagHelpers.UrlResolutionTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_Razor_TagHelpers_UrlResolutionTagHelper); __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_0); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); WriteLiteral("\r\n"); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("script", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "4b5e5ef4ebf7354cc35c7dacddd6bc3068f19a475152", async() => { } ); __Microsoft_AspNetCore_Mvc_Razor_TagHelpers_UrlResolutionTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.Razor.TagHelpers.UrlResolutionTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_Razor_TagHelpers_UrlResolutionTagHelper); __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_1); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); WriteLiteral("\r\n"); } #pragma warning restore 1998 [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.ViewFeatures.IModelExpressionProvider ModelExpressionProvider { get; private set; } [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.IUrlHelper Url { get; private set; } [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.IViewComponentHelper Component { get; private set; } [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.Rendering.IJsonHelper Json { get; private set; } [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.Rendering.IHtmlHelper<dynamic> Html { get; private set; } } } #pragma warning restore 1591
68.95098
406
0.766671
[ "MIT" ]
Amphibian007/DotNetSelfPractise_Home
source/MyProjects/LearningNeverEndsEFCoreProject/GameManagementProject/obj/Debug/netcoreapp3.1/Razor/Views/Shared/_ValidationScriptsPartial.cshtml.g.cs
7,033
C#
namespace SimulOP { /// <summary> /// Classe para representar ventiladores [Não implementedo]. /// </summary> class Ventilador : EquipamentoOPI { } }
19.333333
64
0.614943
[ "MIT" ]
rafaelterras/SimulOp
SimulOP/SimulOP/EquipamentosOPI/Ventilador.cs
177
C#
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Framework.Graphics.Shapes; using OpenTK.Graphics; namespace osu.Game.Screens.Edit.Screens.Compose.Layers { public class BorderLayer : Container { protected override Container<Drawable> Content => content; private readonly Container content; public BorderLayer() { InternalChildren = new Drawable[] { new Container { Name = "Border", RelativeSizeAxes = Axes.Both, Masking = true, BorderColour = Color4.White, BorderThickness = 2, Child = new Box { RelativeSizeAxes = Axes.Both, Alpha = 0, AlwaysPresent = true } }, content = new Container { RelativeSizeAxes = Axes.Both } }; } } }
31.717949
93
0.501213
[ "MIT" ]
br-Zhang/osu
osu.Game/Screens/Edit/Screens/Compose/Layers/BorderLayer.cs
1,239
C#
using System; namespace CharlieBackend.Core.DTO.Schedule { public class ScheduledEventFilterRequestDTO { public long? CourseID { get; set; } public long? MentorID { get; set; } public long? GroupID { get; set; } public long? ThemeID { get; set; } public long? StudentAccountID { get; set; } public long? EventOccurrenceID { get; set; } public DateTime? StartDate { get; set; } public DateTime? FinishDate { get; set; } } }
21.166667
52
0.606299
[ "MIT" ]
ViktorMarhitich/WhatBackend
CharlieBackend.Core/DTO/Schedule/ScheduledEventFilterRequestDTO.cs
510
C#
using System.Web; using System.Web.Mvc; namespace Angulari18n { public class FilterConfig { public static void RegisterGlobalFilters(GlobalFilterCollection filters) { filters.Add(new HandleErrorAttribute()); } } }
18.857143
80
0.655303
[ "MIT" ]
johnproctor/SimpleAngulari18n
Angulari18n/App_Start/FilterConfig.cs
266
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // 有关程序集的常规信息通过下列特性集 // 控制。更改这些特性值可修改 // 与程序集关联的信息。 [assembly: AssemblyTitle("ZigBee.Server")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("ZigBee.Server")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // 将 ComVisible 设置为 false 会使此程序集中的类型 // 对 COM 组件不可见。如果需要 // 从 COM 访问此程序集中的某个类型,请针对该类型将 ComVisible 特性设置为 true。 [assembly: ComVisible(false)] // 如果此项目向 COM 公开,则下列 GUID 用于 typelib 的 ID [assembly: Guid("f6f96d5e-618a-443b-872e-ca4a90995ed2")] // 程序集的版本信息由下列四个值组成: // // 主版本 // 次版本 // 内部版本号 // 修订版本 // // 可以指定所有值,也可以使用“修订号”和“内部版本号”的默认值, // 方法是按如下所示使用 "*": [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
26.611111
57
0.693111
[ "Apache-2.0" ]
401175209/ZigBee
ZigBee.Server/Properties/AssemblyInfo.cs
1,319
C#
// // Tweener.cs // // Author: // Jason Smith <jason.smith@xamarin.com> // // Copyright (c) 2012 Xamarin Inc. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System; using System.Collections.Generic; using Xamarin.Forms.Internals; namespace Xamarin.Forms { public static class AnimationExtensions { static readonly Dictionary<AnimatableKey, Info> s_animations; static readonly Dictionary<AnimatableKey, int> s_kinetics; static AnimationExtensions() { s_animations = new Dictionary<AnimatableKey, Info>(); s_kinetics = new Dictionary<AnimatableKey, int>(); } public static bool AbortAnimation(this IAnimatable self, string handle) { var key = new AnimatableKey(self, handle); if (!s_animations.ContainsKey(key) && !s_kinetics.ContainsKey(key)) { return false; } Action abort = () => { AbortAnimation(key); AbortKinetic(key); }; DoAction(self, abort); return true; } public static void Animate(this IAnimatable self, string name, Animation animation, uint rate = 16, uint length = 250, Easing easing = null, Action<double, bool> finished = null, Func<bool> repeat = null) { if (repeat == null) self.Animate(name, animation.GetCallback(), rate, length, easing, finished, null); else { Func<bool> r = () => { var val = repeat(); if (val) animation.ResetChildren(); return val; }; self.Animate(name, animation.GetCallback(), rate, length, easing, finished, r); } } public static void Animate(this IAnimatable self, string name, Action<double> callback, double start, double end, uint rate = 16, uint length = 250, Easing easing = null, Action<double, bool> finished = null, Func<bool> repeat = null) { self.Animate(name, Interpolate(start, end), callback, rate, length, easing, finished, repeat); } public static void Animate(this IAnimatable self, string name, Action<double> callback, uint rate = 16, uint length = 250, Easing easing = null, Action<double, bool> finished = null, Func<bool> repeat = null) { self.Animate(name, x => x, callback, rate, length, easing, finished, repeat); } public static void Animate<T>(this IAnimatable self, string name, Func<double, T> transform, Action<T> callback, uint rate = 16, uint length = 250, Easing easing = null, Action<T, bool> finished = null, Func<bool> repeat = null) { if (transform == null) throw new ArgumentNullException(nameof(transform)); if (callback == null) throw new ArgumentNullException(nameof(callback)); if (self == null) throw new ArgumentNullException(nameof(self)); Action animate = () => AnimateInternal(self, name, transform, callback, rate, length, easing, finished, repeat); DoAction(self, animate); } public static void AnimateKinetic(this IAnimatable self, string name, Func<double, double, bool> callback, double velocity, double drag, Action finished = null) { Action animate = () => AnimateKineticInternal(self, name, callback, velocity, drag, finished); DoAction(self, animate); } public static bool AnimationIsRunning(this IAnimatable self, string handle) { var key = new AnimatableKey(self, handle); return s_animations.ContainsKey(key); } public static Func<double, double> Interpolate(double start, double end = 1.0f, double reverseVal = 0.0f, bool reverse = false) { double target = reverse ? reverseVal : end; return x => start + (target - start) * x; } public static IDisposable Batch(this IAnimatable self) => new BatchObject(self); static void AbortAnimation(AnimatableKey key) { // If multiple animations on the same view with the same name (IOW, the same AnimatableKey) are invoked // asynchronously (e.g., from the `[Animate]To` methods in `ViewExtensions`), it's possible to get into // a situation where after invoking the `Finished` handler below `s_animations` will have a new `Info` // object in it with the same AnimatableKey. We need to continue cancelling animations until that is no // longer the case; thus, the `while` loop. // If we don't cancel all of the animations popping in with this key, `AnimateInternal` will overwrite one // of them with the new `Info` object, and the overwritten animation will never complete; any `await` for // it will never return. while (s_animations.ContainsKey(key)) { Info info = s_animations[key]; s_animations.Remove(key); info.Tweener.ValueUpdated -= HandleTweenerUpdated; info.Tweener.Finished -= HandleTweenerFinished; info.Tweener.Stop(); info.Finished?.Invoke(1.0f, true); } } static void AbortKinetic(AnimatableKey key) { if (!s_kinetics.ContainsKey(key)) { return; } Ticker.Default.Remove(s_kinetics[key]); s_kinetics.Remove(key); } static void AnimateInternal<T>(IAnimatable self, string name, Func<double, T> transform, Action<T> callback, uint rate, uint length, Easing easing, Action<T, bool> finished, Func<bool> repeat) { var key = new AnimatableKey(self, name); AbortAnimation(key); Action<double> step = f => callback(transform(f)); Action<double, bool> final = null; if (finished != null) final = (f, b) => finished(transform(f), b); var info = new Info { Rate = rate, Length = length, Easing = easing ?? Easing.Linear }; var tweener = new Tweener(info.Length); tweener.Handle = key; tweener.ValueUpdated += HandleTweenerUpdated; tweener.Finished += HandleTweenerFinished; info.Tweener = tweener; info.Callback = step; info.Finished = final; info.Repeat = repeat; info.Owner = new WeakReference<IAnimatable>(self); s_animations[key] = info; info.Callback(0.0f); tweener.Start(); } static void AnimateKineticInternal(IAnimatable self, string name, Func<double, double, bool> callback, double velocity, double drag, Action finished = null) { var key = new AnimatableKey(self, name); AbortKinetic(key); double sign = velocity / Math.Abs(velocity); velocity = Math.Abs(velocity); int tick = Ticker.Default.Insert(step => { long ms = step; velocity -= drag * ms; velocity = Math.Max(0, velocity); var result = false; if (velocity > 0) { result = callback(sign * velocity * ms, velocity); } if (!result) { finished?.Invoke(); s_kinetics.Remove(key); } return result; }); s_kinetics[key] = tick; } static void HandleTweenerFinished(object o, EventArgs args) { var tweener = o as Tweener; Info info; if (tweener != null && s_animations.TryGetValue(tweener.Handle, out info)) { IAnimatable owner; if (info.Owner.TryGetTarget(out owner)) owner.BatchBegin(); info.Callback(tweener.Value); var repeat = false; // If the Ticker has been disabled (e.g., by power save mode), then don't repeat the animation var animationsEnabled = Ticker.Default.SystemEnabled; if (info.Repeat != null && animationsEnabled) repeat = info.Repeat(); if (!repeat) { s_animations.Remove(tweener.Handle); tweener.ValueUpdated -= HandleTweenerUpdated; tweener.Finished -= HandleTweenerFinished; } info.Finished?.Invoke(tweener.Value, !animationsEnabled); if (info.Owner.TryGetTarget(out owner)) owner.BatchCommit(); if (repeat) { tweener.Start(); } } } static void HandleTweenerUpdated(object o, EventArgs args) { var tweener = o as Tweener; Info info; IAnimatable owner; if (tweener != null && s_animations.TryGetValue(tweener.Handle, out info) && info.Owner.TryGetTarget(out owner)) { owner.BatchBegin(); info.Callback(info.Easing.Ease(tweener.Value)); owner.BatchCommit(); } } static void DoAction(IAnimatable self, Action action) { if (self is BindableObject element) { if (element.Dispatcher.IsInvokeRequired) { element.Dispatcher.BeginInvokeOnMainThread(action); } else { action(); } return; } if (Device.IsInvokeRequired) { Device.BeginInvokeOnMainThread(action); } else { action(); } } class Info { public Action<double> Callback; public Action<double, bool> Finished; public Func<bool> Repeat; public Tweener Tweener; public Easing Easing { get; set; } public uint Length { get; set; } public WeakReference<IAnimatable> Owner { get; set; } public uint Rate { get; set; } } sealed class BatchObject : IDisposable { IAnimatable _animatable; public BatchObject(IAnimatable animatable) { _animatable = animatable; _animatable?.BatchBegin(); } public void Dispose() { _animatable?.BatchCommit(); _animatable = null; } } } }
29.017699
184
0.684457
[ "MIT" ]
Bobface/Xamarin.Forms
Xamarin.Forms.Core/AnimationExtensions.cs
9,837
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 System; using System.Collections.Generic; using System.Linq; using Moq; using Moq.Protected; using Xunit; namespace Microsoft.VisualStudio.Telemetry { public class VsTelemetryServiceTests { [Fact] public void PostEvent_NullAsEventName_ThrowsArgumentNull() { var service = CreateInstance(); Assert.Throws<ArgumentNullException>("eventName", () => { service.PostEvent(null!); }); } [Fact] public void PostEvent_EmptyAsEventName_ThrowsArgument() { var service = CreateInstance(); Assert.Throws<ArgumentException>("eventName", () => { service.PostEvent(string.Empty); }); } [Fact] public void PostProperty_NullAsEventName_ThrowArgumentNull() { var service = CreateInstance(); Assert.Throws<ArgumentNullException>("eventName", () => { service.PostProperty(null!, "propName", "value"); }); } [Fact] public void PostProperty_EmptyAsEventName_ThrowArgument() { var service = CreateInstance(); Assert.Throws<ArgumentException>("eventName", () => { service.PostProperty(string.Empty, "propName", "value"); }); } [Fact] public void PostProperty_NullAsPropertyName_ThrowArgumentNull() { var service = CreateInstance(); Assert.Throws<ArgumentNullException>("propertyName", () => { service.PostProperty("event1", null!, "value"); }); } [Fact] public void PostProperty_EmptyAsPropertyName_ThrowArgument() { var service = CreateInstance(); Assert.Throws<ArgumentException>("propertyName", () => { service.PostProperty("event1", string.Empty, "value"); }); } [Fact] public void PostProperty_NullAsPropertyValue_ThrowArgumentNull() { var service = CreateInstance(); Assert.Throws<ArgumentNullException>("propertyValue", () => { service.PostProperty("event1", "propName", null!); }); } [Fact] public void PostProperties_NullAsEventName_ThrowArgumentNull() { var service = CreateInstance(); Assert.Throws<ArgumentNullException>("eventName", () => { service.PostProperties(null!, new[] { ("propertyName", (object)"propertyValue") }); }); } [Fact] public void PostProperties_EmptyAsEventName_ThrowArgument() { var service = CreateInstance(); Assert.Throws<ArgumentException>("eventName", () => { service.PostProperties(string.Empty, new[] { ("propertyName", (object)"propertyValue") }); }); } [Fact] public void PostProperties_NullAsPropertyName_ThrowArgumentNull() { var service = CreateInstance(); Assert.Throws<ArgumentNullException>("properties", () => { service.PostProperties("event1", null!); }); } [Fact] public void PostProperties_EmptyProperties_ThrowArgument() { var service = CreateInstance(); Assert.Throws<ArgumentException>("properties", () => { service.PostProperties("event1", Enumerable.Empty<(string propertyName, object propertyValue)>()); }); } [Fact] public void PostEvent_SendsTelemetryEvent() { TelemetryEvent? result = null; var service = CreateInstance((e) => { result = e; }); service.PostEvent(TelemetryEventName.UpToDateCheckSuccess); Assert.NotNull(result); Assert.Equal(TelemetryEventName.UpToDateCheckSuccess, result!.Name); } [Fact] public void PostProperty_SendsTelemetryEventWithProperty() { TelemetryEvent? result = null; var service = CreateInstance((e) => { result = e; }); service.PostProperty(TelemetryEventName.UpToDateCheckFail, TelemetryPropertyName.UpToDateCheckFailReason, "Reason"); Assert.NotNull(result); Assert.Equal(TelemetryEventName.UpToDateCheckFail, result!.Name); Assert.Contains(new KeyValuePair<string, object>(TelemetryPropertyName.UpToDateCheckFailReason, "Reason"), result.Properties); } [Fact] public void PostProperties_SendsTelemetryEventWithProperties() { TelemetryEvent? result = null; var service = CreateInstance((e) => { result = e; }); service.PostProperties(TelemetryEventName.DesignTimeBuildComplete, new[] { (TelemetryPropertyName.DesignTimeBuildCompleteSucceeded, (object)true), (TelemetryPropertyName.DesignTimeBuildCompleteTargets, "Compile") }); Assert.NotNull(result); Assert.Equal(TelemetryEventName.DesignTimeBuildComplete, result!.Name); Assert.Contains(new KeyValuePair<string, object>(TelemetryPropertyName.DesignTimeBuildCompleteSucceeded, true), result.Properties); Assert.Contains(new KeyValuePair<string, object>(TelemetryPropertyName.DesignTimeBuildCompleteTargets, "Compile"), result.Properties); } private static VsTelemetryService CreateInstance(Action<TelemetryEvent>? action = null) { if (action == null) return new VsTelemetryService(); // Override PostEventToSession to avoid actually sending to telemetry var mock = new Mock<VsTelemetryService>(); mock.Protected().Setup("PostEventToSession", ItExpr.IsAny<TelemetryEvent>()) .Callback(action); return mock.Object; } } }
34
201
0.568934
[ "MIT" ]
BillHiebert/roslyn-project-system
tests/Microsoft.VisualStudio.ProjectSystem.Managed.VS.UnitTests/Telemetry/VsTelemetryServiceTests.cs
6,339
C#
using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.InteropServices.ComTypes; using NetOffice; using NetOffice.Attributes; namespace NetOffice.AccessApi.Events { #pragma warning disable #region SinkPoint Interface [SupportByVersion("Access", 14,15,16)] [InternalEntity(InternalEntityKind.ComEventInterface)] [ComImport, Guid("EACB9075-68F8-4E3B-B865-E1CE6BE0447C"), InterfaceType(ComInterfaceType.InterfaceIsIDispatch), TypeLibType((short)0x1010)] public interface DispWebBrowserControlEvents { [SupportByVersion("Access", 14,15,16)] [SinkArgument("code", SinkArgumentType.Int16)] [PreserveSig, MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(2076)] void Updated([In] [Out] ref object code); [SupportByVersion("Access", 14,15,16)] [SinkArgument("code", SinkArgumentType.Int16)] [PreserveSig, MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(2061)] void BeforeUpdate([In] [Out] ref object cancel); [SupportByVersion("Access", 14,15,16)] [PreserveSig, MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(2062)] void AfterUpdate(); [SupportByVersion("Access", 14,15,16)] [PreserveSig, MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(2019)] void Enter(); [SupportByVersion("Access", 14,15,16)] [SinkArgument("code", SinkArgumentType.Int16)] [PreserveSig, MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(2075)] void Exit([In] [Out] ref object cancel); [SupportByVersion("Access", 14,15,16)] [SinkArgument("code", SinkArgumentType.Int16)] [PreserveSig, MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(2205)] void Dirty([In] [Out] ref object cancel); [SupportByVersion("Access", 14,15,16)] [PreserveSig, MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(2077)] void Change(); [SupportByVersion("Access", 14,15,16)] [PreserveSig, MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(2073)] void GotFocus(); [SupportByVersion("Access", 14,15,16)] [PreserveSig, MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(2074)] void LostFocus(); [SupportByVersion("Access", 14,15,16)] [PreserveSig, MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(-600)] void Click(); [SupportByVersion("Access", 14,15,16)] [SinkArgument("code", SinkArgumentType.Int16)] [PreserveSig, MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(-601)] void DblClick([In] [Out] ref object cancel); [SupportByVersion("Access", 14,15,16)] [SinkArgument("button", SinkArgumentType.Int16)] [SinkArgument("shift", SinkArgumentType.Int16)] [SinkArgument("x", SinkArgumentType.Single)] [SinkArgument("y", SinkArgumentType.Single)] [PreserveSig, MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(-605)] void MouseDown([In] [Out] ref object button, [In] [Out] ref object shift, [In] [Out] ref object x, [In] [Out] ref object y); [SupportByVersion("Access", 14,15,16)] [SinkArgument("button", SinkArgumentType.Int16)] [SinkArgument("shift", SinkArgumentType.Int16)] [SinkArgument("x", SinkArgumentType.Single)] [SinkArgument("y", SinkArgumentType.Single)] [PreserveSig, MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(-606)] void MouseMove([In] [Out] ref object button, [In] [Out] ref object shift, [In] [Out] ref object x, [In] [Out] ref object y); [SupportByVersion("Access", 14,15,16)] [SinkArgument("button", SinkArgumentType.Int16)] [SinkArgument("shift", SinkArgumentType.Int16)] [SinkArgument("x", SinkArgumentType.Single)] [SinkArgument("y", SinkArgumentType.Single)] [PreserveSig, MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(-607)] void MouseUp([In] [Out] ref object button, [In] [Out] ref object shift, [In] [Out] ref object x, [In] [Out] ref object y); [SupportByVersion("Access", 14,15,16)] [SinkArgument("keyCode", SinkArgumentType.Int16)] [SinkArgument("shift", SinkArgumentType.Int16)] [PreserveSig, MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(-602)] void KeyDown([In] [Out] ref object keyCode, [In] [Out] ref object shift); [SupportByVersion("Access", 14,15,16)] [SinkArgument("keyAscii", SinkArgumentType.Int16)] [PreserveSig, MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(-603)] void KeyPress([In] [Out] ref object keyAscii); [SupportByVersion("Access", 14,15,16)] [SinkArgument("keyCode", SinkArgumentType.Int16)] [SinkArgument("shift", SinkArgumentType.Int16)] [PreserveSig, MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(-604)] void KeyUp([In] [Out] ref object keyCode, [In] [Out] ref object shift); [SupportByVersion("Access", 14,15,16)] [SinkArgument("pDisp", SinkArgumentType.UnknownProxy)] [SinkArgument("cancel", SinkArgumentType.Bool)] [PreserveSig, MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(2524)] void BeforeNavigate2([In, MarshalAs(UnmanagedType.IDispatch)] object pDisp, [In] [Out] ref object uRL, [In] [Out] ref object flags, [In] [Out] ref object targetFrameName, [In] [Out] ref object postData, [In] [Out] ref object headers, [In] [Out] ref object cancel); [SupportByVersion("Access", 14,15,16)] [SinkArgument("pDisp", SinkArgumentType.UnknownProxy)] [PreserveSig, MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(2528)] void DocumentComplete([In, MarshalAs(UnmanagedType.IDispatch)] object pDisp, [In] [Out] ref object uRL); [SupportByVersion("Access", 14,15,16)] [SinkArgument("progress", SinkArgumentType.Int32)] [SinkArgument("progressMax", SinkArgumentType.Int32)] [PreserveSig, MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(2515)] void ProgressChange([In] object progress, [In] object progressMax); [SupportByVersion("Access", 14,15,16)] [SinkArgument("pDisp", SinkArgumentType.UnknownProxy)] [SinkArgument("cancel", SinkArgumentType.Bool)] [PreserveSig, MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(2510)] void NavigateError([In, MarshalAs(UnmanagedType.IDispatch)] object pDisp, [In] [Out] ref object uRL, [In] [Out] ref object targetFrameName, [In] [Out] ref object statusCode, [In] [Out] ref object cancel); } #endregion #region SinkHelper [InternalEntity(InternalEntityKind.SinkHelper)] [ComVisible(true), ClassInterface(ClassInterfaceType.None), TypeLibType(TypeLibTypeFlags.FHidden)] public class DispWebBrowserControlEvents_SinkHelper : SinkHelper, DispWebBrowserControlEvents { #region Static public static readonly string Id = "EACB9075-68F8-4E3B-B865-E1CE6BE0447C"; #endregion #region Ctor public DispWebBrowserControlEvents_SinkHelper(ICOMObject eventClass, IConnectionPoint connectPoint): base(eventClass) { SetupEventBinding(connectPoint); } #endregion #region DispWebBrowserControlEvents Members public void Updated([In] [Out] ref object code) { if (!Validate("Updated")) { Invoker.ReleaseParamsArray(code); return; } object[] paramsArray = new object[1]; paramsArray.SetValue(code, 0); EventBinding.RaiseCustomEvent("Updated", ref paramsArray); code = ToInt16(paramsArray[0]); } public void BeforeUpdate([In] [Out] ref object cancel) { if (!Validate("BeforeUpdate")) { Invoker.ReleaseParamsArray(cancel); return; } object[] paramsArray = new object[1]; paramsArray.SetValue(cancel, 0); EventBinding.RaiseCustomEvent("BeforeUpdate", ref paramsArray); cancel = (Int16)paramsArray[0]; } public void AfterUpdate() { if (!Validate("AfterUpdate")) { return; } object[] paramsArray = new object[0]; EventBinding.RaiseCustomEvent("AfterUpdate", ref paramsArray); } public void Enter() { if (!Validate("Enter")) { return; } object[] paramsArray = new object[0]; EventBinding.RaiseCustomEvent("Enter", ref paramsArray); } public void Exit([In] [Out] ref object cancel) { if (!Validate("Exit")) { Invoker.ReleaseParamsArray(cancel); return; } object[] paramsArray = new object[1]; paramsArray.SetValue(cancel, 0); EventBinding.RaiseCustomEvent("Exit", ref paramsArray); cancel = ToInt16(paramsArray[0]); } public void Dirty([In] [Out] ref object cancel) { if (!Validate("Dirty")) { Invoker.ReleaseParamsArray(cancel); return; } object[] paramsArray = new object[1]; paramsArray.SetValue(cancel, 0); EventBinding.RaiseCustomEvent("Dirty", ref paramsArray); cancel = ToInt16(paramsArray[0]); } public void Change() { if (!Validate("Change")) { return; } object[] paramsArray = new object[0]; EventBinding.RaiseCustomEvent("Change", ref paramsArray); } public void GotFocus() { if (!Validate("GotFocus")) { return; } object[] paramsArray = new object[0]; EventBinding.RaiseCustomEvent("GotFocus", ref paramsArray); } public void LostFocus() { if (!Validate("LostFocus")) { return; } object[] paramsArray = new object[0]; EventBinding.RaiseCustomEvent("LostFocus", ref paramsArray); } public void Click() { if (!Validate("Click")) { return; } object[] paramsArray = new object[0]; EventBinding.RaiseCustomEvent("Click", ref paramsArray); } public void DblClick([In] [Out] ref object cancel) { if (!Validate("DblClick")) { Invoker.ReleaseParamsArray(cancel); return; } object[] paramsArray = new object[1]; paramsArray.SetValue(cancel, 0); EventBinding.RaiseCustomEvent("DblClick", ref paramsArray); cancel = ToInt16(paramsArray[0]); } public void MouseDown([In] [Out] ref object button, [In] [Out] ref object shift, [In] [Out] ref object x, [In] [Out] ref object y) { if (!Validate("MouseDown")) { Invoker.ReleaseParamsArray(button, shift, x, y); return; } object[] paramsArray = new object[4]; paramsArray.SetValue(button, 0); paramsArray.SetValue(shift, 1); paramsArray.SetValue(x, 2); paramsArray.SetValue(y, 3); EventBinding.RaiseCustomEvent("MouseDown", ref paramsArray); button = ToInt16(paramsArray[0]); shift = ToInt16(paramsArray[1]); x = ToSingle(paramsArray[2]); y = ToSingle(paramsArray[3]); } public void MouseMove([In] [Out] ref object button, [In] [Out] ref object shift, [In] [Out] ref object x, [In] [Out] ref object y) { if (!Validate("MouseMove")) { Invoker.ReleaseParamsArray(button, shift, x, y); return; } object[] paramsArray = new object[4]; paramsArray.SetValue(button, 0); paramsArray.SetValue(shift, 1); paramsArray.SetValue(x, 2); paramsArray.SetValue(y, 3); EventBinding.RaiseCustomEvent("MouseMove", ref paramsArray); button = ToInt16(paramsArray[0]); shift = ToInt16(paramsArray[1]); x = ToSingle(paramsArray[2]); y = ToSingle(paramsArray[3]); } public void MouseUp([In] [Out] ref object button, [In] [Out] ref object shift, [In] [Out] ref object x, [In] [Out] ref object y) { if (!Validate("MouseUp")) { Invoker.ReleaseParamsArray(button, shift, x, y); return; } object[] paramsArray = new object[4]; paramsArray.SetValue(button, 0); paramsArray.SetValue(shift, 1); paramsArray.SetValue(x, 2); paramsArray.SetValue(y, 3); EventBinding.RaiseCustomEvent("MouseUp", ref paramsArray); button = ToInt16(paramsArray[0]); shift = ToInt16(paramsArray[1]); x = ToSingle(paramsArray[2]); y = ToSingle(paramsArray[3]); } public void KeyDown([In] [Out] ref object keyCode, [In] [Out] ref object shift) { if (!Validate("MouseUp")) { Invoker.ReleaseParamsArray(keyCode, shift); return; } object[] paramsArray = new object[2]; paramsArray.SetValue(keyCode, 0); paramsArray.SetValue(shift, 1); EventBinding.RaiseCustomEvent("KeyDown", ref paramsArray); keyCode = ToInt16(paramsArray[0]); shift = ToInt16(paramsArray[1]); } public void KeyPress([In] [Out] ref object keyAscii) { if (!Validate("KeyPress")) { Invoker.ReleaseParamsArray(keyAscii); return; } object[] paramsArray = new object[1]; paramsArray.SetValue(keyAscii, 0); EventBinding.RaiseCustomEvent("KeyPress", ref paramsArray); keyAscii = ToInt16(paramsArray[0]); } public void KeyUp([In] [Out] ref object keyCode, [In] [Out] ref object shift) { if (!Validate("KeyUp")) { Invoker.ReleaseParamsArray(keyCode, shift); return; } object[] paramsArray = new object[2]; paramsArray.SetValue(keyCode, 0); paramsArray.SetValue(shift, 1); EventBinding.RaiseCustomEvent("KeyUp", ref paramsArray); keyCode = ToInt16(paramsArray[0]); shift = ToInt16(paramsArray[1]); } public void BeforeNavigate2([In, MarshalAs(UnmanagedType.IDispatch)] object pDisp, [In] [Out] ref object uRL, [In] [Out] ref object flags, [In] [Out] ref object targetFrameName, [In] [Out] ref object postData, [In] [Out] ref object headers, [In] [Out] ref object cancel) { if (!Validate("BeforeNavigate2")) { Invoker.ReleaseParamsArray(pDisp, uRL, flags, targetFrameName, postData, headers, cancel); return; } object newpDisp = Factory.CreateEventArgumentObjectFromComProxy(EventClass, pDisp) as object; object[] paramsArray = new object[7]; paramsArray[0] = newpDisp; paramsArray.SetValue(uRL, 1); paramsArray.SetValue(flags, 2); paramsArray.SetValue(targetFrameName, 3); paramsArray.SetValue(postData, 4); paramsArray.SetValue(headers, 5); paramsArray.SetValue(cancel, 6); EventBinding.RaiseCustomEvent("BeforeNavigate2", ref paramsArray); uRL = (object)paramsArray[1]; flags = (object)paramsArray[2]; targetFrameName = (object)paramsArray[3]; postData = (object)paramsArray[4]; headers = (object)paramsArray[5]; cancel = ToBoolean(paramsArray[6]); } public void DocumentComplete([In, MarshalAs(UnmanagedType.IDispatch)] object pDisp, [In] [Out] ref object uRL) { if (!Validate("DocumentComplete")) { Invoker.ReleaseParamsArray(pDisp, uRL); return; } object newpDisp = Factory.CreateEventArgumentObjectFromComProxy(EventClass, pDisp) as object; object[] paramsArray = new object[2]; paramsArray[0] = newpDisp; paramsArray.SetValue(uRL, 1); EventBinding.RaiseCustomEvent("DocumentComplete", ref paramsArray); uRL = (object)paramsArray[1]; } public void ProgressChange([In] object progress, [In] object progressMax) { if (!Validate("ProgressChange")) { Invoker.ReleaseParamsArray(progress, progressMax); return; } Int32 newProgress = ToInt32(progress); Int32 newProgressMax = ToInt32(progressMax); object[] paramsArray = new object[2]; paramsArray[0] = newProgress; paramsArray[1] = newProgressMax; EventBinding.RaiseCustomEvent("ProgressChange", ref paramsArray); } public void NavigateError([In, MarshalAs(UnmanagedType.IDispatch)] object pDisp, [In] [Out] ref object uRL, [In] [Out] ref object targetFrameName, [In] [Out] ref object statusCode, [In] [Out] ref object cancel) { if (!Validate("NavigateError")) { Invoker.ReleaseParamsArray(pDisp, uRL, targetFrameName, statusCode, cancel); return; } object newpDisp = Factory.CreateEventArgumentObjectFromComProxy(EventClass, pDisp) as object; object[] paramsArray = new object[5]; paramsArray[0] = newpDisp; paramsArray.SetValue(uRL, 1); paramsArray.SetValue(targetFrameName, 2); paramsArray.SetValue(statusCode, 3); paramsArray.SetValue(cancel, 4); EventBinding.RaiseCustomEvent("NavigateError", ref paramsArray); uRL = (object)paramsArray[1]; targetFrameName = (object)paramsArray[2]; statusCode = (object)paramsArray[3]; cancel = ToBoolean(paramsArray[4]); } #endregion } #endregion #pragma warning restore }
37.451098
278
0.628737
[ "MIT" ]
DominikPalo/NetOffice
Source/Access/Events/DispWebBrowserControlEvents.cs
18,765
C#
using System; using System.Collections.Generic; using System.Reflection; using System.Text; namespace BeatmapDownloader.Abstract.Services.UI { public class DownloadProviderListAttribute : Attribute { public string Name { get; set; } } public static class DownloadProviderListAttributeExtension { public static string GetProviderListDisplayName(this Type type) { foreach (var attribute in type.GetCustomAttributes()) { if (attribute.GetType().FullName == typeof(DownloadProviderListAttribute).FullName) { var prop = attribute.GetType().GetProperty(nameof(DownloadProviderListAttribute.Name)); return prop.GetValue(attribute)?.ToString() ?? type.Name; } } return type.Name; } public static string GetProviderListDisplayName(this object obj) { return GetProviderListDisplayName(obj.GetType()); } } }
31.151515
107
0.626459
[ "MIT" ]
OsuSync/EmberTools
src/plugins/osu/BeatmapDownloader.Abstract/Services/UI/DownloadProviderListAttribute.cs
1,030
C#
using System.Collections.Generic; using System.Linq; namespace kafka4net.Protocols.Requests { class PartitionData { public int Partition; // is calculated at serizlization time //public int MessageSetSize; public IEnumerable<MessageData> Messages; /// <summary>Is not serialized. Is carried through to send error/success notifications /// if herror happen</summary> public Producer Pub; /// <summary> /// Not serialized. /// Copy of origianl, application provided messages. Is needed when error happen /// and driver notifys app that those messages have failed. /// </summary> public Message[] OriginalMessages; /// <summary> /// Non serialazable. Carries compression type until serialization happen, where messages are re-packaged /// into compressed message set. /// </summary> public CompressionType CompressionType; public override string ToString() { return string.Format("Part: {0} Messages: {1}", Partition, Messages == null ? "null" : Messages.Count().ToString()); } } }
33.666667
129
0.614686
[ "Apache-2.0" ]
ntent-ad/kafka4net
src/Protocols/Requests/PartitionData.cs
1,214
C#
using System; namespace ClangNet.Native { /// <summary> /// Completion Context /// </summary> /// <remarks> /// Bits that represent the context under which completion is occurring. /// /// The enumerators in this enumeration may be bitwise-OR'd together if multiple /// contexts are occurring simultaneously. /// </remarks> [Flags] public enum CompletionContext { /// <summary> /// Unexposed /// </summary> /// <remarks> /// The context for completions is unexposed, as only Clang results /// should be included. (This is equivalent to having no context bits set.) /// </remarks> Unexposed = 0, /// <summary> /// Any Type /// </summary> /// <remarks> /// Completions for any possible type should be included in the results. /// </remarks> AnyType = 1 << 0, /// <summary> /// Any Value /// </summary> /// <remarks> /// Completions for any possible value (variables, function calls, etc.) /// should be included in the results. /// </remarks> AnyValue = 1 << 1, /// <summary> /// Objective-C Object Value /// </summary> /// <remarks> /// Completions for values that resolve to an Objective-C object should /// be included in the results. /// </remarks> ObjCObjectValue = 1 << 2, /// <summary> /// Objective-C Selector Value /// </summary> /// <remarks> /// Completions for values that resolve to an Objective-C selector /// should be included in the results. /// </remarks> ObjCSelectorValue = 1 << 3, /// <summary> /// C++ Class Type Value /// </summary> /// <remarks> /// Completions for values that resolve to a C++ class type should be /// included in the results. /// </remarks> CXXClassTypeValue = 1 << 4, /// <summary> /// Dot Member Access /// </summary> /// <remarks> /// Completions for fields of the member being accessed using the dot /// operator should be included in the results. /// </remarks> DotMemberAccess = 1 << 5, /// <summary> /// Arrow Member Access /// </summary> /// <remarks> /// Completions for fields of the member being accessed using the arrow /// operator should be included in the results. /// </remarks> ArrowMemberAccess = 1 << 6, /// <summary> /// Objective-C Property Access /// </summary> /// <remarks> /// Completions for properties of the Objective-C object being accessed /// using the dot operator should be included in the results. /// </remarks> ObjCPropertyAccess = 1 << 7, /// <summary> /// Enum Tag /// </summary> /// <remarks> /// Completions for enum tags should be included in the results. /// </remarks> EnumTag = 1 << 8, /// <summary> /// Union Tag /// </summary> /// <remarks> /// Completions for union tags should be included in the results. /// </remarks> UnionTag = 1 << 9, /// <summary> /// Struct Tag /// </summary> /// <remarks> /// Completions for struct tags should be included in the results. /// </remarks> StructTag = 1 << 10, /// <summary> /// Class Tag /// </summary> /// <remarks> /// Completions for C++ class names should be included in the results. /// </remarks> ClassTag = 1 << 11, /// <summary> /// Namespace /// </summary> /// <remarks> /// Completions for C++ namespaces and namespace aliases should be /// included in the results. /// </remarks> Namespace = 1 << 12, /// <summary> /// Nested Name Specifier /// </summary> /// <remarks> /// Completions for C++ nested name specifiers should be included in /// the results. /// </remarks> NestedNameSpecifier = 1 << 13, /// <summary> /// Objective-C Interface /// </summary> /// <remarks> /// Completions for Objective-C interfaces (classes) should be included /// in the results. /// </remarks> ObjCInterface = 1 << 14, /// <summary> /// Objective-C Protocol /// </summary> /// <remarks> /// Completions for Objective-C protocols should be included in /// the results. /// </remarks> ObjCProtocol = 1 << 15, /// <summary> /// Objective-C Category /// </summary> /// <remarks> /// Completions for Objective-C categories should be included in /// the results. /// </remarks> ObjCCategory = 1 << 16, /// <summary> /// Objective-C Instance Message /// </summary> /// <remarks> /// Completions for Objective-C instance messages should be included /// in the results. /// </remarks> ObjCInstanceMessage = 1 << 17, /// <summary> /// Objective-C Class Message /// </summary> /// <remarks> /// Completions for Objective-C class messages should be included in /// the results. /// </remarks> ObjCClassMessage = 1 << 18, /// <summary> /// Objective-C Selector Name /// </summary> /// <remarks> /// Completions for Objective-C selector names should be included in /// the results. /// </remarks> ObjCSelectorName = 1 << 19, /// <summary> /// Macro Name /// </summary> /// <remarks> /// Completions for preprocessor macro names should be included in /// the results. /// </remarks> MacroName = 1 << 20, /// <summary> /// Natural Language /// </summary> /// <remarks> /// Natural language completions should be included in the results. /// </remarks> NaturalLanguage = 1 << 21, /// <summary> /// Include File /// </summary> /// <remarks> /// #include file completions should be included in the results. /// </remarks> IncludeFile = 1 << 22, /// <summary> /// Unknown /// </summary> /// <remarks> /// The current context is unknown, so set all contexts. /// </remarks> Unknown = ((1 << 23) - 1), } }
29.029787
84
0.501319
[ "MIT" ]
an-embedded-engineer/ClangNet
ClangNet/Managed/Enums/CompletionContext.cs
6,824
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.34209 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace GoogleTranslate.Properties { [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "12.0.0.0")] internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase { private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings()))); public static Settings Default { get { return defaultInstance; } } } }
39.62963
151
0.583178
[ "Unlicense" ]
oggy22/LanguageTools
GoogleTranslate/Properties/Settings.Designer.cs
1,072
C#
using Okta.Xamarin.Demo.ViewModels; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; using Xamarin.Forms.Xaml; namespace Okta.Xamarin.Demo.Views { [XamlCompilation(XamlCompilationOptions.Compile)] public partial class LoginPage : ContentPage { public LoginPage() { InitializeComponent(); this.BindingContext = new LoginViewModel(); } } }
23.380952
55
0.698574
[ "Apache-2.0" ]
kensykora/samples-xamarin
Okta.Xamarin.Demo/Views/LoginPage.xaml.cs
493
C#
namespace Sunny.UI.Demo { partial class FHeaderAsideMain { /// <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.uiLogo1 = new Sunny.UI.UILogo(); this.Header.SuspendLayout(); this.SuspendLayout(); // // Aside // this.Aside.LineColor = System.Drawing.Color.Black; this.Aside.Size = new System.Drawing.Size(250, 575); this.Aside.Style = Sunny.UI.UIStyle.Blue; // // Header // this.Header.Controls.Add(this.uiLogo1); this.Header.Size = new System.Drawing.Size(1024, 110); this.Header.Style = Sunny.UI.UIStyle.Blue; // // uiLogo1 // this.uiLogo1.Font = new System.Drawing.Font("微软雅黑", 12F); this.uiLogo1.Location = new System.Drawing.Point(15, 15); this.uiLogo1.MaximumSize = new System.Drawing.Size(300, 80); this.uiLogo1.MinimumSize = new System.Drawing.Size(300, 80); this.uiLogo1.Name = "uiLogo1"; this.uiLogo1.Size = new System.Drawing.Size(300, 80); this.uiLogo1.Style = Sunny.UI.UIStyle.Custom; this.uiLogo1.TabIndex = 1; this.uiLogo1.Text = "uiLogo1"; // // FHeaderAsideMain // this.AutoScaleDimensions = new System.Drawing.SizeF(10F, 21F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.None; this.ClientSize = new System.Drawing.Size(1024, 720); this.Name = "FHeaderAsideMain"; this.Style = Sunny.UI.UIStyle.Blue; this.Text = "FHeaderAsideMain"; this.Header.ResumeLayout(false); this.ResumeLayout(false); } #endregion private UILogo uiLogo1; } }
35.25
107
0.543486
[ "MIT" ]
BillChan226/Visualization-Project-for-Greyout
VisualTool/Forms/Frames/FHeaderAsideMain.Designer.cs
2,689
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.Threading.Tasks; using Microsoft.EntityFrameworkCore.Internal; using Microsoft.EntityFrameworkCore.Storage; using Xunit; namespace Microsoft.EntityFrameworkCore.InMemory.Tests { public class InMemoryTransactionManagerTest { [Fact] public void Throws_on_BeginTransaction() { var optionsBuilder = new DbContextOptionsBuilder(); optionsBuilder.UseInMemoryDatabase(); var transactionManager = new InMemoryTransactionManager(optionsBuilder.Options); Assert.Equal( InMemoryStrings.TransactionsNotSupported, Assert.Throws<InvalidOperationException>( () => transactionManager.BeginTransaction()).Message); } [Fact] public async Task Throws_on_BeginTransactionAsync() { var optionsBuilder = new DbContextOptionsBuilder(); optionsBuilder.UseInMemoryDatabase(); var transactionManager = new InMemoryTransactionManager(optionsBuilder.Options); Assert.Equal( InMemoryStrings.TransactionsNotSupported, (await Assert.ThrowsAsync<InvalidOperationException>( async () => await transactionManager.BeginTransactionAsync())).Message); } [Fact] public void Throws_on_CommitTransaction() { var optionsBuilder = new DbContextOptionsBuilder(); optionsBuilder.UseInMemoryDatabase(); var transactionManager = new InMemoryTransactionManager(optionsBuilder.Options); Assert.Equal( InMemoryStrings.TransactionsNotSupported, Assert.Throws<InvalidOperationException>( () => transactionManager.CommitTransaction()).Message); } [Fact] public void Throws_on_RollbackTransaction() { var optionsBuilder = new DbContextOptionsBuilder(); optionsBuilder.UseInMemoryDatabase(); var transactionManager = new InMemoryTransactionManager(optionsBuilder.Options); Assert.Equal( InMemoryStrings.TransactionsNotSupported, Assert.Throws<InvalidOperationException>( () => transactionManager.RollbackTransaction()).Message); } [Fact] public void Does_not_throw_on_BeginTransaction_when_transactions_ignored() { var optionsBuilder = new DbContextOptionsBuilder() .UseInMemoryDatabase(b => b.IgnoreTransactions()); var transactionManager = new InMemoryTransactionManager(optionsBuilder.Options); using (var transaction = transactionManager.BeginTransaction()) { transaction.Commit(); transaction.Rollback(); } } [Fact] public async Task Does_not_throw_on_BeginTransactionAsync_when_transactions_ignored() { var optionsBuilder = new DbContextOptionsBuilder() .UseInMemoryDatabase(b => b.IgnoreTransactions()); var transactionManager = new InMemoryTransactionManager(optionsBuilder.Options); using (var transaction = await transactionManager.BeginTransactionAsync()) { transaction.Commit(); transaction.Rollback(); } } [Fact] public void Does_not_throw_on_CommitTransaction_when_transactions_ignored() { var optionsBuilder = new DbContextOptionsBuilder() .UseInMemoryDatabase(b => b.IgnoreTransactions()); var transactionManager = new InMemoryTransactionManager(optionsBuilder.Options); transactionManager.CommitTransaction(); } [Fact] public void Does_not_throw_on_RollbackTransaction_when_transactions_ignored() { var optionsBuilder = new DbContextOptionsBuilder() .UseInMemoryDatabase(b => b.IgnoreTransactions()); var transactionManager = new InMemoryTransactionManager(optionsBuilder.Options); transactionManager.RollbackTransaction(); } } }
35.772358
111
0.643409
[ "Apache-2.0" ]
davidroth/EntityFrameworkCore
test/Microsoft.EntityFrameworkCore.InMemory.Tests/InMemoryTransactionManagerTest.cs
4,400
C#
using Northwind.Api.Models; namespace Northwind.Api.Repository { public interface IProductRepository : IRepository<Product> { } }
15.888889
62
0.734266
[ "MIT" ]
jonalexjm/WebApiPatronRepository
src/api/Northwind.Api.Repository/IProductRepository.cs
143
C#
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Linq.Expressions; namespace NLayer.Common.Extensions { /// <summary> /// Extension methods for <see cref="Collection{T}"/>. /// </summary> public static class CollectionExtensions { /// <summary> /// Adds the elements of the specified collection to the end of the <see cref="T:System.Collections.Generic.List`1" />. /// </summary> /// <typeparam name="T">Any type.</typeparam> /// <param name="target"><see cref="ICollection{T}" /> target collection.</param> /// <param name="collection">The collection whose elements should be added to the end of the <see cref="T:System.Collections.Generic.List`1" />. /// The collection itself cannot be null, but it can contain elements that are null, if type T is a reference type.</param> /// <exception cref="T:System.ArgumentNullException"><paramref name="collection" /> is null.</exception> public static void AddRange<T>(this ICollection<T> target, IEnumerable<T> collection) { if (target == null) { throw new ArgumentNullException(nameof(target)); } if (collection == null) { throw new ArgumentNullException(nameof(collection)); } foreach (var obj in collection) { target.Add(obj); } } /// <summary> /// Removes elements from the specified collection. /// </summary> /// <typeparam name="T">Any type.</typeparam> /// <param name="target"><see cref="ICollection{T}" /> target collection.</param> /// <param name="collection">The collection whose elements should be removed. /// The collection itself cannot be null, but it can contain elements that are null, if type T is a reference type.</param> /// <exception cref="T:System.ArgumentNullException"><paramref name="collection" /> is null.</exception> public static void RemoveRange<T>(this ICollection<T> target, IEnumerable<T> collection) { if (target == null) { throw new ArgumentNullException(nameof(target)); } if (collection == null) { throw new ArgumentNullException(nameof(collection)); } foreach (var obj in collection) { target.Remove(obj); } } /// <summary> /// Orders with direction. /// </summary> /// <typeparam name="TSource">The type of the source.</typeparam> /// <typeparam name="TKey">The type of the key.</typeparam> /// <param name="source">The source.</param> /// <param name="keySelector">The key selector.</param> /// <param name="isDescending">if set to <c>true</c> [is descending].</param> /// <returns></returns> public static IOrderedEnumerable<TSource> OrderByWithDirection<TSource, TKey>( this IEnumerable<TSource> source, Func<TSource, TKey> keySelector, bool isDescending ) { return isDescending ? source.OrderByDescending(keySelector) : source.OrderBy(keySelector); } /// <summary> /// Orders with direction. /// </summary> /// <typeparam name="TSource">The type of the source.</typeparam> /// <typeparam name="TKey">The type of the key.</typeparam> /// <param name="source">The source.</param> /// <param name="keySelector">The key selector.</param> /// <param name="isDescending">if set to <c>true</c> [is descending].</param> /// <returns></returns> public static IOrderedQueryable<TSource> OrderByWithDirection<TSource, TKey>( this IQueryable<TSource> source, Expression<Func<TSource, TKey>> keySelector, bool isDescending ) { return isDescending ? source.OrderByDescending(keySelector) : source.OrderBy(keySelector); } } }
39.850467
152
0.577158
[ "Apache-2.0" ]
ZyshchykMaksim/NLayer.NET
NLayer.NET.Common/Extensions/CollectionExtensions.cs
4,266
C#
// Copyright 2007-2011 Chris Patterson, Dru Sellers, Travis Smith, et. al. // // Licensed under the Apache License, Version 2.0 (the "License"); you may not use // this file except in compliance with the License. You may obtain a copy of the // License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software distributed // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR // CONDITIONS OF ANY KIND, either express or implied. See the License for the // specific language governing permissions and limitations under the License. namespace MassTransit.Tests.Configuration { using Magnum.Extensions; using Magnum.TestFramework; using Messages; using TestFramework; [Scenario] public class When_subscribing_an_object_instance_to_the_bus { IServiceBus _bus; ConsumerOf<PingMessage> _consumer; PingMessage _ping; [When] public void Subscribing_an_object_instance_to_the_bus() { _consumer = new ConsumerOf<PingMessage>(); object instance = _consumer; _bus = ServiceBusFactory.New(x => { x.ReceiveFrom("loopback://localhost/mt_test"); x.Subscribe(s => s.Instance(instance)); }); _ping = new PingMessage(); _bus.Publish(_ping); } [Then] public void Should_have_subscribed() { _bus.ShouldHaveRemoteSubscriptionFor<PingMessage>(); } [Then] public void Should_have_received_the_message() { _consumer.ShouldHaveReceived(_ping, 8.Seconds()); } } }
27.842105
84
0.702583
[ "Apache-2.0" ]
SeanKilleen/MassTransit
src/MassTransit.Tests/Configuration/InstanceSubscription_Specs.cs
1,587
C#
#region Header // Vorspire _,-'/-'/ TimeListEntryOpts.cs // . __,-; ,'( '/ // \. `-.__`-._`:_,-._ _ , . `` // `:-._,------' ` _,`--` -: `_ , ` ,' : // `---..__,,--' (C) 2018 ` -'. -' // # Vita-Nex [http://core.vita-nex.com] # // {o)xxx|===============- # -===============|xxx(o} // # The MIT License (MIT) # #endregion #region References using System; using Server; using Server.Gumps; using VitaNex.SuperGumps.UI; #endregion namespace VitaNex.Schedules { public class ScheduleTimeListEntryGump : MenuGump { public Schedule Schedule { get; set; } public TimeSpan Time { get; set; } public bool UseConfirmDialog { get; set; } public ScheduleTimeListEntryGump( Mobile user, Schedule schedule, Gump parent = null, GumpButton clicked = null, TimeSpan? time = null, bool useConfirm = true) : base(user, parent, clicked: clicked) { Schedule = schedule; Time = time ?? TimeSpan.Zero; UseConfirmDialog = useConfirm; CanMove = false; CanResize = false; } protected override void CompileOptions(MenuGumpOptions list) { base.CompileOptions(list); list.PrependEntry( "Delete", button => { if (UseConfirmDialog) { new ConfirmDialogGump(User, Refresh()) { Title = "Delete Time?", Html = "All data associated with this time will be deleted.\n" + "This action can not be reversed!\nDo you want to continue?", AcceptHandler = OnConfirmDelete }.Send(); } else { OnConfirmDelete(button); } }, HighlightHue); } protected virtual void OnConfirmDelete(GumpButton button) { if (Selected == null) { Close(); return; } Schedule.Info.Times.Remove(Time); Schedule.InvalidateNextTick(); Close(); } } }
22.147727
73
0.544895
[ "MIT" ]
Vita-Nex/Core
Services/Schedules/UI/TimeListEntryOpts.cs
1,949
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Data.Common; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; namespace System.Data.SqlClient { public sealed partial class SqlConnectionStringBuilder : DbConnectionStringBuilder { private enum Keywords { // specific ordering for ConnectionString output construction // NamedConnection, DataSource, FailoverPartner, AttachDBFilename, InitialCatalog, IntegratedSecurity, PersistSecurityInfo, UserID, Password, Enlist, Pooling, MinPoolSize, MaxPoolSize, #if netcoreapp PoolBlockingPeriod, #endif MultipleActiveResultSets, Replication, ConnectTimeout, Encrypt, TrustServerCertificate, LoadBalanceTimeout, PacketSize, TypeSystemVersion, ApplicationName, CurrentLanguage, WorkstationID, UserInstance, TransactionBinding, ApplicationIntent, MultiSubnetFailover, ConnectRetryCount, ConnectRetryInterval, // keep the count value last KeywordsCount } internal const int KeywordsCount = (int)Keywords.KeywordsCount; internal const int DeprecatedKeywordsCount = 4; private static readonly string[] s_validKeywords = CreateValidKeywords(); private static readonly Dictionary<string, Keywords> s_keywords = CreateKeywordsDictionary(); private ApplicationIntent _applicationIntent = DbConnectionStringDefaults.ApplicationIntent; private string _applicationName = DbConnectionStringDefaults.ApplicationName; private string _attachDBFilename = DbConnectionStringDefaults.AttachDBFilename; private string _currentLanguage = DbConnectionStringDefaults.CurrentLanguage; private string _dataSource = DbConnectionStringDefaults.DataSource; private string _failoverPartner = DbConnectionStringDefaults.FailoverPartner; private string _initialCatalog = DbConnectionStringDefaults.InitialCatalog; // private string _namedConnection = DbConnectionStringDefaults.NamedConnection; private string _password = DbConnectionStringDefaults.Password; private string _transactionBinding = DbConnectionStringDefaults.TransactionBinding; private string _typeSystemVersion = DbConnectionStringDefaults.TypeSystemVersion; private string _userID = DbConnectionStringDefaults.UserID; private string _workstationID = DbConnectionStringDefaults.WorkstationID; private int _connectTimeout = DbConnectionStringDefaults.ConnectTimeout; private int _loadBalanceTimeout = DbConnectionStringDefaults.LoadBalanceTimeout; private int _maxPoolSize = DbConnectionStringDefaults.MaxPoolSize; private int _minPoolSize = DbConnectionStringDefaults.MinPoolSize; private int _packetSize = DbConnectionStringDefaults.PacketSize; private int _connectRetryCount = DbConnectionStringDefaults.ConnectRetryCount; private int _connectRetryInterval = DbConnectionStringDefaults.ConnectRetryInterval; private bool _encrypt = DbConnectionStringDefaults.Encrypt; private bool _trustServerCertificate = DbConnectionStringDefaults.TrustServerCertificate; private bool _enlist = DbConnectionStringDefaults.Enlist; private bool _integratedSecurity = DbConnectionStringDefaults.IntegratedSecurity; private bool _multipleActiveResultSets = DbConnectionStringDefaults.MultipleActiveResultSets; private bool _multiSubnetFailover = DbConnectionStringDefaults.MultiSubnetFailover; private bool _persistSecurityInfo = DbConnectionStringDefaults.PersistSecurityInfo; private bool _pooling = DbConnectionStringDefaults.Pooling; private bool _replication = DbConnectionStringDefaults.Replication; private bool _userInstance = DbConnectionStringDefaults.UserInstance; private static string[] CreateValidKeywords() { string[] validKeywords = new string[KeywordsCount]; validKeywords[(int)Keywords.ApplicationIntent] = DbConnectionStringKeywords.ApplicationIntent; validKeywords[(int)Keywords.ApplicationName] = DbConnectionStringKeywords.ApplicationName; validKeywords[(int)Keywords.AttachDBFilename] = DbConnectionStringKeywords.AttachDBFilename; #if netcoreapp validKeywords[(int)Keywords.PoolBlockingPeriod] = DbConnectionStringKeywords.PoolBlockingPeriod; #endif validKeywords[(int)Keywords.ConnectTimeout] = DbConnectionStringKeywords.ConnectTimeout; validKeywords[(int)Keywords.CurrentLanguage] = DbConnectionStringKeywords.CurrentLanguage; validKeywords[(int)Keywords.DataSource] = DbConnectionStringKeywords.DataSource; validKeywords[(int)Keywords.Encrypt] = DbConnectionStringKeywords.Encrypt; validKeywords[(int)Keywords.Enlist] = DbConnectionStringKeywords.Enlist; validKeywords[(int)Keywords.FailoverPartner] = DbConnectionStringKeywords.FailoverPartner; validKeywords[(int)Keywords.InitialCatalog] = DbConnectionStringKeywords.InitialCatalog; validKeywords[(int)Keywords.IntegratedSecurity] = DbConnectionStringKeywords.IntegratedSecurity; validKeywords[(int)Keywords.LoadBalanceTimeout] = DbConnectionStringKeywords.LoadBalanceTimeout; validKeywords[(int)Keywords.MaxPoolSize] = DbConnectionStringKeywords.MaxPoolSize; validKeywords[(int)Keywords.MinPoolSize] = DbConnectionStringKeywords.MinPoolSize; validKeywords[(int)Keywords.MultipleActiveResultSets] = DbConnectionStringKeywords.MultipleActiveResultSets; validKeywords[(int)Keywords.MultiSubnetFailover] = DbConnectionStringKeywords.MultiSubnetFailover; // validKeywords[(int)Keywords.NamedConnection] = DbConnectionStringKeywords.NamedConnection; validKeywords[(int)Keywords.PacketSize] = DbConnectionStringKeywords.PacketSize; validKeywords[(int)Keywords.Password] = DbConnectionStringKeywords.Password; validKeywords[(int)Keywords.PersistSecurityInfo] = DbConnectionStringKeywords.PersistSecurityInfo; validKeywords[(int)Keywords.Pooling] = DbConnectionStringKeywords.Pooling; validKeywords[(int)Keywords.Replication] = DbConnectionStringKeywords.Replication; validKeywords[(int)Keywords.TransactionBinding] = DbConnectionStringKeywords.TransactionBinding; validKeywords[(int)Keywords.TrustServerCertificate] = DbConnectionStringKeywords.TrustServerCertificate; validKeywords[(int)Keywords.TypeSystemVersion] = DbConnectionStringKeywords.TypeSystemVersion; validKeywords[(int)Keywords.UserID] = DbConnectionStringKeywords.UserID; validKeywords[(int)Keywords.UserInstance] = DbConnectionStringKeywords.UserInstance; validKeywords[(int)Keywords.WorkstationID] = DbConnectionStringKeywords.WorkstationID; validKeywords[(int)Keywords.ConnectRetryCount] = DbConnectionStringKeywords.ConnectRetryCount; validKeywords[(int)Keywords.ConnectRetryInterval] = DbConnectionStringKeywords.ConnectRetryInterval; return validKeywords; } private static Dictionary<string, Keywords> CreateKeywordsDictionary() { Dictionary<string, Keywords> hash = new Dictionary<string, Keywords>(KeywordsCount + SqlConnectionString.SynonymCount, StringComparer.OrdinalIgnoreCase); hash.Add(DbConnectionStringKeywords.ApplicationIntent, Keywords.ApplicationIntent); hash.Add(DbConnectionStringKeywords.ApplicationName, Keywords.ApplicationName); hash.Add(DbConnectionStringKeywords.AttachDBFilename, Keywords.AttachDBFilename); #if netcoreapp hash.Add(DbConnectionStringKeywords.PoolBlockingPeriod, Keywords.PoolBlockingPeriod); #endif hash.Add(DbConnectionStringKeywords.ConnectTimeout, Keywords.ConnectTimeout); hash.Add(DbConnectionStringKeywords.CurrentLanguage, Keywords.CurrentLanguage); hash.Add(DbConnectionStringKeywords.DataSource, Keywords.DataSource); hash.Add(DbConnectionStringKeywords.Encrypt, Keywords.Encrypt); hash.Add(DbConnectionStringKeywords.Enlist, Keywords.Enlist); hash.Add(DbConnectionStringKeywords.FailoverPartner, Keywords.FailoverPartner); hash.Add(DbConnectionStringKeywords.InitialCatalog, Keywords.InitialCatalog); hash.Add(DbConnectionStringKeywords.IntegratedSecurity, Keywords.IntegratedSecurity); hash.Add(DbConnectionStringKeywords.LoadBalanceTimeout, Keywords.LoadBalanceTimeout); hash.Add(DbConnectionStringKeywords.MultipleActiveResultSets, Keywords.MultipleActiveResultSets); hash.Add(DbConnectionStringKeywords.MaxPoolSize, Keywords.MaxPoolSize); hash.Add(DbConnectionStringKeywords.MinPoolSize, Keywords.MinPoolSize); hash.Add(DbConnectionStringKeywords.MultiSubnetFailover, Keywords.MultiSubnetFailover); // hash.Add(DbConnectionStringKeywords.NamedConnection, Keywords.NamedConnection); hash.Add(DbConnectionStringKeywords.PacketSize, Keywords.PacketSize); hash.Add(DbConnectionStringKeywords.Password, Keywords.Password); hash.Add(DbConnectionStringKeywords.PersistSecurityInfo, Keywords.PersistSecurityInfo); hash.Add(DbConnectionStringKeywords.Pooling, Keywords.Pooling); hash.Add(DbConnectionStringKeywords.Replication, Keywords.Replication); hash.Add(DbConnectionStringKeywords.TransactionBinding, Keywords.TransactionBinding); hash.Add(DbConnectionStringKeywords.TrustServerCertificate, Keywords.TrustServerCertificate); hash.Add(DbConnectionStringKeywords.TypeSystemVersion, Keywords.TypeSystemVersion); hash.Add(DbConnectionStringKeywords.UserID, Keywords.UserID); hash.Add(DbConnectionStringKeywords.UserInstance, Keywords.UserInstance); hash.Add(DbConnectionStringKeywords.WorkstationID, Keywords.WorkstationID); hash.Add(DbConnectionStringKeywords.ConnectRetryCount, Keywords.ConnectRetryCount); hash.Add(DbConnectionStringKeywords.ConnectRetryInterval, Keywords.ConnectRetryInterval); hash.Add(DbConnectionStringSynonyms.APP, Keywords.ApplicationName); hash.Add(DbConnectionStringSynonyms.EXTENDEDPROPERTIES, Keywords.AttachDBFilename); hash.Add(DbConnectionStringSynonyms.INITIALFILENAME, Keywords.AttachDBFilename); hash.Add(DbConnectionStringSynonyms.CONNECTIONTIMEOUT, Keywords.ConnectTimeout); hash.Add(DbConnectionStringSynonyms.TIMEOUT, Keywords.ConnectTimeout); hash.Add(DbConnectionStringSynonyms.LANGUAGE, Keywords.CurrentLanguage); hash.Add(DbConnectionStringSynonyms.ADDR, Keywords.DataSource); hash.Add(DbConnectionStringSynonyms.ADDRESS, Keywords.DataSource); hash.Add(DbConnectionStringSynonyms.NETWORKADDRESS, Keywords.DataSource); hash.Add(DbConnectionStringSynonyms.SERVER, Keywords.DataSource); hash.Add(DbConnectionStringSynonyms.DATABASE, Keywords.InitialCatalog); hash.Add(DbConnectionStringSynonyms.TRUSTEDCONNECTION, Keywords.IntegratedSecurity); hash.Add(DbConnectionStringSynonyms.ConnectionLifetime, Keywords.LoadBalanceTimeout); hash.Add(DbConnectionStringSynonyms.Pwd, Keywords.Password); hash.Add(DbConnectionStringSynonyms.PERSISTSECURITYINFO, Keywords.PersistSecurityInfo); hash.Add(DbConnectionStringSynonyms.UID, Keywords.UserID); hash.Add(DbConnectionStringSynonyms.User, Keywords.UserID); hash.Add(DbConnectionStringSynonyms.WSID, Keywords.WorkstationID); Debug.Assert((KeywordsCount + SqlConnectionString.SynonymCount) == hash.Count, "initial expected size is incorrect"); return hash; } public SqlConnectionStringBuilder() : this((string)null) { } public SqlConnectionStringBuilder(string connectionString) : base() { if (!string.IsNullOrEmpty(connectionString)) { ConnectionString = connectionString; } } public override object this[string keyword] { get { Keywords index = GetIndex(keyword); return GetAt(index); } set { if (null != value) { Keywords index = GetIndex(keyword); switch (index) { case Keywords.ApplicationIntent: this.ApplicationIntent = ConvertToApplicationIntent(keyword, value); break; case Keywords.ApplicationName: ApplicationName = ConvertToString(value); break; case Keywords.AttachDBFilename: AttachDBFilename = ConvertToString(value); break; case Keywords.CurrentLanguage: CurrentLanguage = ConvertToString(value); break; case Keywords.DataSource: DataSource = ConvertToString(value); break; case Keywords.FailoverPartner: FailoverPartner = ConvertToString(value); break; case Keywords.InitialCatalog: InitialCatalog = ConvertToString(value); break; // case Keywords.NamedConnection: NamedConnection = ConvertToString(value); break; case Keywords.Password: Password = ConvertToString(value); break; case Keywords.UserID: UserID = ConvertToString(value); break; case Keywords.TransactionBinding: TransactionBinding = ConvertToString(value); break; case Keywords.TypeSystemVersion: TypeSystemVersion = ConvertToString(value); break; case Keywords.WorkstationID: WorkstationID = ConvertToString(value); break; case Keywords.ConnectTimeout: ConnectTimeout = ConvertToInt32(value); break; case Keywords.LoadBalanceTimeout: LoadBalanceTimeout = ConvertToInt32(value); break; case Keywords.MaxPoolSize: MaxPoolSize = ConvertToInt32(value); break; case Keywords.MinPoolSize: MinPoolSize = ConvertToInt32(value); break; case Keywords.PacketSize: PacketSize = ConvertToInt32(value); break; case Keywords.IntegratedSecurity: IntegratedSecurity = ConvertToIntegratedSecurity(value); break; #if netcoreapp case Keywords.PoolBlockingPeriod: PoolBlockingPeriod = ConvertToPoolBlockingPeriod(keyword, value); break; #endif case Keywords.Encrypt: Encrypt = ConvertToBoolean(value); break; case Keywords.TrustServerCertificate: TrustServerCertificate = ConvertToBoolean(value); break; case Keywords.Enlist: Enlist = ConvertToBoolean(value); break; case Keywords.MultipleActiveResultSets: MultipleActiveResultSets = ConvertToBoolean(value); break; case Keywords.MultiSubnetFailover: MultiSubnetFailover = ConvertToBoolean(value); break; case Keywords.PersistSecurityInfo: PersistSecurityInfo = ConvertToBoolean(value); break; case Keywords.Pooling: Pooling = ConvertToBoolean(value); break; case Keywords.Replication: Replication = ConvertToBoolean(value); break; case Keywords.UserInstance: UserInstance = ConvertToBoolean(value); break; case Keywords.ConnectRetryCount: ConnectRetryCount = ConvertToInt32(value); break; case Keywords.ConnectRetryInterval: ConnectRetryInterval = ConvertToInt32(value); break; default: Debug.Fail("unexpected keyword"); throw UnsupportedKeyword(keyword); } } else { Remove(keyword); } } } public ApplicationIntent ApplicationIntent { get { return _applicationIntent; } set { if (!DbConnectionStringBuilderUtil.IsValidApplicationIntentValue(value)) { throw ADP.InvalidEnumerationValue(typeof(ApplicationIntent), (int)value); } SetApplicationIntentValue(value); _applicationIntent = value; } } public string ApplicationName { get { return _applicationName; } set { SetValue(DbConnectionStringKeywords.ApplicationName, value); _applicationName = value; } } public string AttachDBFilename { get { return _attachDBFilename; } set { SetValue(DbConnectionStringKeywords.AttachDBFilename, value); _attachDBFilename = value; } } public int ConnectTimeout { get { return _connectTimeout; } set { if (value < 0) { throw ADP.InvalidConnectionOptionValue(DbConnectionStringKeywords.ConnectTimeout); } SetValue(DbConnectionStringKeywords.ConnectTimeout, value); _connectTimeout = value; } } public string CurrentLanguage { get { return _currentLanguage; } set { SetValue(DbConnectionStringKeywords.CurrentLanguage, value); _currentLanguage = value; } } public string DataSource { get { return _dataSource; } set { SetValue(DbConnectionStringKeywords.DataSource, value); _dataSource = value; } } public bool Encrypt { get { return _encrypt; } set { SetValue(DbConnectionStringKeywords.Encrypt, value); _encrypt = value; } } public bool TrustServerCertificate { get { return _trustServerCertificate; } set { SetValue(DbConnectionStringKeywords.TrustServerCertificate, value); _trustServerCertificate = value; } } public bool Enlist { get { return _enlist; } set { SetValue(DbConnectionStringKeywords.Enlist, value); _enlist = value; } } public string FailoverPartner { get { return _failoverPartner; } set { SetValue(DbConnectionStringKeywords.FailoverPartner, value); _failoverPartner = value; } } [TypeConverter(typeof(SqlInitialCatalogConverter))] public string InitialCatalog { get { return _initialCatalog; } set { SetValue(DbConnectionStringKeywords.InitialCatalog, value); _initialCatalog = value; } } public bool IntegratedSecurity { get { return _integratedSecurity; } set { SetValue(DbConnectionStringKeywords.IntegratedSecurity, value); _integratedSecurity = value; } } public int LoadBalanceTimeout { get { return _loadBalanceTimeout; } set { if (value < 0) { throw ADP.InvalidConnectionOptionValue(DbConnectionStringKeywords.LoadBalanceTimeout); } SetValue(DbConnectionStringKeywords.LoadBalanceTimeout, value); _loadBalanceTimeout = value; } } public int MaxPoolSize { get { return _maxPoolSize; } set { if (value < 1) { throw ADP.InvalidConnectionOptionValue(DbConnectionStringKeywords.MaxPoolSize); } SetValue(DbConnectionStringKeywords.MaxPoolSize, value); _maxPoolSize = value; } } public int ConnectRetryCount { get { return _connectRetryCount; } set { if ((value < 0) || (value > 255)) { throw ADP.InvalidConnectionOptionValue(DbConnectionStringKeywords.ConnectRetryCount); } SetValue(DbConnectionStringKeywords.ConnectRetryCount, value); _connectRetryCount = value; } } public int ConnectRetryInterval { get { return _connectRetryInterval; } set { if ((value < 1) || (value > 60)) { throw ADP.InvalidConnectionOptionValue(DbConnectionStringKeywords.ConnectRetryInterval); } SetValue(DbConnectionStringKeywords.ConnectRetryInterval, value); _connectRetryInterval = value; } } public int MinPoolSize { get { return _minPoolSize; } set { if (value < 0) { throw ADP.InvalidConnectionOptionValue(DbConnectionStringKeywords.MinPoolSize); } SetValue(DbConnectionStringKeywords.MinPoolSize, value); _minPoolSize = value; } } public bool MultipleActiveResultSets { get { return _multipleActiveResultSets; } set { SetValue(DbConnectionStringKeywords.MultipleActiveResultSets, value); _multipleActiveResultSets = value; } } [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Reviewed and Approved by UE")] public bool MultiSubnetFailover { get { return _multiSubnetFailover; } set { SetValue(DbConnectionStringKeywords.MultiSubnetFailover, value); _multiSubnetFailover = value; } } /* [DisplayName(DbConnectionStringKeywords.NamedConnection)] [ResCategoryAttribute(Res.DataCategory_NamedConnectionString)] [ResDescriptionAttribute(Res.DbConnectionString_NamedConnection)] [RefreshPropertiesAttribute(RefreshProperties.All)] [TypeConverter(typeof(NamedConnectionStringConverter))] public string NamedConnection { get { return _namedConnection; } set { SetValue(DbConnectionStringKeywords.NamedConnection, value); _namedConnection = value; } } */ public int PacketSize { get { return _packetSize; } set { if ((value < TdsEnums.MIN_PACKET_SIZE) || (TdsEnums.MAX_PACKET_SIZE < value)) { throw SQL.InvalidPacketSizeValue(); } SetValue(DbConnectionStringKeywords.PacketSize, value); _packetSize = value; } } public string Password { get { return _password; } set { SetValue(DbConnectionStringKeywords.Password, value); _password = value; } } public bool PersistSecurityInfo { get { return _persistSecurityInfo; } set { SetValue(DbConnectionStringKeywords.PersistSecurityInfo, value); _persistSecurityInfo = value; } } public bool Pooling { get { return _pooling; } set { SetValue(DbConnectionStringKeywords.Pooling, value); _pooling = value; } } public bool Replication { get { return _replication; } set { SetValue(DbConnectionStringKeywords.Replication, value); _replication = value; } } public string TransactionBinding { get { return _transactionBinding; } set { SetValue(DbConnectionStringKeywords.TransactionBinding, value); _transactionBinding = value; } } public string TypeSystemVersion { get { return _typeSystemVersion; } set { SetValue(DbConnectionStringKeywords.TypeSystemVersion, value); _typeSystemVersion = value; } } public string UserID { get { return _userID; } set { SetValue(DbConnectionStringKeywords.UserID, value); _userID = value; } } public bool UserInstance { get { return _userInstance; } set { SetValue(DbConnectionStringKeywords.UserInstance, value); _userInstance = value; } } public string WorkstationID { get { return _workstationID; } set { SetValue(DbConnectionStringKeywords.WorkstationID, value); _workstationID = value; } } public override ICollection Keys { get { return new System.Collections.ObjectModel.ReadOnlyCollection<string>(s_validKeywords); } } public override ICollection Values { get { // written this way so if the ordering of Keywords & _validKeywords changes // this is one less place to maintain object[] values = new object[s_validKeywords.Length]; for (int i = 0; i < values.Length; ++i) { values[i] = GetAt((Keywords)i); } return new System.Collections.ObjectModel.ReadOnlyCollection<object>(values); } } public override void Clear() { base.Clear(); for (int i = 0; i < s_validKeywords.Length; ++i) { Reset((Keywords)i); } } public override bool ContainsKey(string keyword) { ADP.CheckArgumentNull(keyword, nameof(keyword)); return s_keywords.ContainsKey(keyword); } private static bool ConvertToBoolean(object value) { return DbConnectionStringBuilderUtil.ConvertToBoolean(value); } private static int ConvertToInt32(object value) { return DbConnectionStringBuilderUtil.ConvertToInt32(value); } private static bool ConvertToIntegratedSecurity(object value) { return DbConnectionStringBuilderUtil.ConvertToIntegratedSecurity(value); } private static string ConvertToString(object value) { return DbConnectionStringBuilderUtil.ConvertToString(value); } private static ApplicationIntent ConvertToApplicationIntent(string keyword, object value) { return DbConnectionStringBuilderUtil.ConvertToApplicationIntent(keyword, value); } private object GetAt(Keywords index) { switch (index) { case Keywords.ApplicationIntent: return this.ApplicationIntent; case Keywords.ApplicationName: return ApplicationName; case Keywords.AttachDBFilename: return AttachDBFilename; #if netcoreapp case Keywords.PoolBlockingPeriod: return PoolBlockingPeriod; #endif case Keywords.ConnectTimeout: return ConnectTimeout; case Keywords.CurrentLanguage: return CurrentLanguage; case Keywords.DataSource: return DataSource; case Keywords.Encrypt: return Encrypt; case Keywords.Enlist: return Enlist; case Keywords.FailoverPartner: return FailoverPartner; case Keywords.InitialCatalog: return InitialCatalog; case Keywords.IntegratedSecurity: return IntegratedSecurity; case Keywords.LoadBalanceTimeout: return LoadBalanceTimeout; case Keywords.MultipleActiveResultSets: return MultipleActiveResultSets; case Keywords.MaxPoolSize: return MaxPoolSize; case Keywords.MinPoolSize: return MinPoolSize; case Keywords.MultiSubnetFailover: return MultiSubnetFailover; // case Keywords.NamedConnection: return NamedConnection; case Keywords.PacketSize: return PacketSize; case Keywords.Password: return Password; case Keywords.PersistSecurityInfo: return PersistSecurityInfo; case Keywords.Pooling: return Pooling; case Keywords.Replication: return Replication; case Keywords.TransactionBinding: return TransactionBinding; case Keywords.TrustServerCertificate: return TrustServerCertificate; case Keywords.TypeSystemVersion: return TypeSystemVersion; case Keywords.UserID: return UserID; case Keywords.UserInstance: return UserInstance; case Keywords.WorkstationID: return WorkstationID; case Keywords.ConnectRetryCount: return ConnectRetryCount; case Keywords.ConnectRetryInterval: return ConnectRetryInterval; default: Debug.Fail("unexpected keyword"); throw UnsupportedKeyword(s_validKeywords[(int)index]); } } private Keywords GetIndex(string keyword) { ADP.CheckArgumentNull(keyword, nameof(keyword)); Keywords index; if (s_keywords.TryGetValue(keyword, out index)) { return index; } throw UnsupportedKeyword(keyword); } public override bool Remove(string keyword) { ADP.CheckArgumentNull(keyword, nameof(keyword)); Keywords index; if (s_keywords.TryGetValue(keyword, out index)) { if (base.Remove(s_validKeywords[(int)index])) { Reset(index); return true; } } return false; } private void Reset(Keywords index) { switch (index) { case Keywords.ApplicationIntent: _applicationIntent = DbConnectionStringDefaults.ApplicationIntent; break; case Keywords.ApplicationName: _applicationName = DbConnectionStringDefaults.ApplicationName; break; case Keywords.AttachDBFilename: _attachDBFilename = DbConnectionStringDefaults.AttachDBFilename; break; #if netcoreapp case Keywords.PoolBlockingPeriod: _poolBlockingPeriod = DbConnectionStringDefaults.PoolBlockingPeriod; break; #endif case Keywords.ConnectTimeout: _connectTimeout = DbConnectionStringDefaults.ConnectTimeout; break; case Keywords.CurrentLanguage: _currentLanguage = DbConnectionStringDefaults.CurrentLanguage; break; case Keywords.DataSource: _dataSource = DbConnectionStringDefaults.DataSource; break; case Keywords.Encrypt: _encrypt = DbConnectionStringDefaults.Encrypt; break; case Keywords.Enlist: _enlist = DbConnectionStringDefaults.Enlist; break; case Keywords.FailoverPartner: _failoverPartner = DbConnectionStringDefaults.FailoverPartner; break; case Keywords.InitialCatalog: _initialCatalog = DbConnectionStringDefaults.InitialCatalog; break; case Keywords.IntegratedSecurity: _integratedSecurity = DbConnectionStringDefaults.IntegratedSecurity; break; case Keywords.LoadBalanceTimeout: _loadBalanceTimeout = DbConnectionStringDefaults.LoadBalanceTimeout; break; case Keywords.MultipleActiveResultSets: _multipleActiveResultSets = DbConnectionStringDefaults.MultipleActiveResultSets; break; case Keywords.MaxPoolSize: _maxPoolSize = DbConnectionStringDefaults.MaxPoolSize; break; case Keywords.MinPoolSize: _minPoolSize = DbConnectionStringDefaults.MinPoolSize; break; case Keywords.MultiSubnetFailover: _multiSubnetFailover = DbConnectionStringDefaults.MultiSubnetFailover; break; // case Keywords.NamedConnection: // _namedConnection = DbConnectionStringDefaults.NamedConnection; // break; case Keywords.PacketSize: _packetSize = DbConnectionStringDefaults.PacketSize; break; case Keywords.Password: _password = DbConnectionStringDefaults.Password; break; case Keywords.PersistSecurityInfo: _persistSecurityInfo = DbConnectionStringDefaults.PersistSecurityInfo; break; case Keywords.Pooling: _pooling = DbConnectionStringDefaults.Pooling; break; case Keywords.ConnectRetryCount: _connectRetryCount = DbConnectionStringDefaults.ConnectRetryCount; break; case Keywords.ConnectRetryInterval: _connectRetryInterval = DbConnectionStringDefaults.ConnectRetryInterval; break; case Keywords.Replication: _replication = DbConnectionStringDefaults.Replication; break; case Keywords.TransactionBinding: _transactionBinding = DbConnectionStringDefaults.TransactionBinding; break; case Keywords.TrustServerCertificate: _trustServerCertificate = DbConnectionStringDefaults.TrustServerCertificate; break; case Keywords.TypeSystemVersion: _typeSystemVersion = DbConnectionStringDefaults.TypeSystemVersion; break; case Keywords.UserID: _userID = DbConnectionStringDefaults.UserID; break; case Keywords.UserInstance: _userInstance = DbConnectionStringDefaults.UserInstance; break; case Keywords.WorkstationID: _workstationID = DbConnectionStringDefaults.WorkstationID; break; default: Debug.Fail("unexpected keyword"); throw UnsupportedKeyword(s_validKeywords[(int)index]); } } private void SetValue(string keyword, bool value) { base[keyword] = value.ToString(); } private void SetValue(string keyword, int value) { base[keyword] = value.ToString((System.IFormatProvider)null); } private void SetValue(string keyword, string value) { ADP.CheckArgumentNull(value, keyword); base[keyword] = value; } private void SetApplicationIntentValue(ApplicationIntent value) { Debug.Assert(DbConnectionStringBuilderUtil.IsValidApplicationIntentValue(value), "invalid value"); base[DbConnectionStringKeywords.ApplicationIntent] = DbConnectionStringBuilderUtil.ApplicationIntentToString(value); } public override bool ShouldSerialize(string keyword) { ADP.CheckArgumentNull(keyword, nameof(keyword)); Keywords index; return s_keywords.TryGetValue(keyword, out index) && base.ShouldSerialize(s_validKeywords[(int)index]); } public override bool TryGetValue(string keyword, out object value) { Keywords index; if (s_keywords.TryGetValue(keyword, out index)) { value = GetAt(index); return true; } value = null; return false; } private static readonly string[] s_notSupportedKeywords = new string[] { DbConnectionStringKeywords.AsynchronousProcessing, DbConnectionStringKeywords.ConnectionReset, DbConnectionStringKeywords.ContextConnection, DbConnectionStringKeywords.TransactionBinding, DbConnectionStringSynonyms.Async }; private static readonly string[] s_notSupportedNetworkLibraryKeywords = new string[] { DbConnectionStringKeywords.NetworkLibrary, DbConnectionStringSynonyms.NET, DbConnectionStringSynonyms.NETWORK }; private Exception UnsupportedKeyword(string keyword) { if (s_notSupportedKeywords.Contains(keyword, StringComparer.OrdinalIgnoreCase)) { return SQL.UnsupportedKeyword(keyword); } else if (s_notSupportedNetworkLibraryKeywords.Contains(keyword, StringComparer.OrdinalIgnoreCase)) { return SQL.NetworkLibraryKeywordNotSupported(); } else { return ADP.KeywordNotSupported(keyword); } } private sealed class SqlInitialCatalogConverter : StringConverter { // converter classes should have public ctor public SqlInitialCatalogConverter() { } public override bool GetStandardValuesSupported(ITypeDescriptorContext context) { return GetStandardValuesSupportedInternal(context); } private bool GetStandardValuesSupportedInternal(ITypeDescriptorContext context) { // Only say standard values are supported if the connection string has enough // information set to instantiate a connection and retrieve a list of databases bool flag = false; if (null != context) { SqlConnectionStringBuilder constr = (context.Instance as SqlConnectionStringBuilder); if (null != constr) { if ((0 < constr.DataSource.Length) && (constr.IntegratedSecurity || (0 < constr.UserID.Length))) { flag = true; } } } return flag; } public override bool GetStandardValuesExclusive(ITypeDescriptorContext context) { // Although theoretically this could be true, some people may want to just type in a name return false; } public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context) { // There can only be standard values if the connection string is in a state that might // be able to instantiate a connection if (GetStandardValuesSupportedInternal(context)) { // Create an array list to store the database names List<string> values = new List<string>(); try { SqlConnectionStringBuilder constr = (SqlConnectionStringBuilder)context.Instance; // Create a connection using (SqlConnection connection = new SqlConnection()) { // Create a basic connection string from current property values connection.ConnectionString = constr.ConnectionString; // Try to open the connection connection.Open(); DataTable databaseTable = connection.GetSchema("DATABASES"); foreach (DataRow row in databaseTable.Rows) { string dbName = (string)row["database_name"]; values.Add(dbName); } } } catch (SqlException e) { ADP.TraceExceptionWithoutRethrow(e); // silently fail } // Return values as a StandardValuesCollection return new StandardValuesCollection(values); } return null; } } } }
42.880079
165
0.60031
[ "MIT" ]
ARhj/corefx
src/System.Data.SqlClient/src/System/Data/SqlClient/SqlConnectionStringBuilder.cs
43,266
C#
namespace _03._Composite { using System; /// <summary> /// The 'Leaf' class /// </summary> public class PrimitiveElement : DrawingElement { public PrimitiveElement(string name) : base(name) { } public override void Add(DrawingElement d) { Console.WriteLine( "Cannot add to a PrimitiveElement"); } public override void Remove(DrawingElement d) { Console.WriteLine( "Cannot remove from a PrimitiveElement"); } public override void Display(int indent) { Console.WriteLine( new string('-', indent) + " " + this._name); } } }
21.970588
60
0.511379
[ "MIT" ]
pirocorp/Databases-Advanced---Entity-Framework
15. DESIGN PATTERNS/02. Structural Patterns/03. Composite/PrimitiveElement.cs
749
C#
// Copyright © 2010-2014 The CefSharp Authors. All rights reserved. // // Use of this source code is governed by a BSD-style license that can be found in the LICENSE file. using System; using System.Windows.Forms; using CefSharp.Example; namespace CefSharp.WinForms.Example { class Program { [STAThread] static void Main() { CefExample.Init(); var browser = new BrowserForm(); Application.Run(browser); } } }
21.434783
100
0.626775
[ "BSD-3-Clause" ]
ivan-sam/CefSharp
CefSharp.WinForms.Example/Program.cs
496
C#
using System.Collections.Generic; using System.Linq; using GW2EIEvtcParser.EncounterLogic; using GW2EIEvtcParser.ParsedData; using GW2EIEvtcParser.Extensions; namespace GW2EIEvtcParser.EIData { internal static class ProfHelper { private static readonly List<InstantCastFinder> _genericInstantCastFinders = new List<InstantCastFinder>() { new DamageCastFinder(9433, 9433, 500), // Earth Sigil new DamageCastFinder(9292, 9292, 500), // Air Sigil new DamageCastFinder(9428, 9428, 500), // Hydro Sigil new EXTHealingCastFinder(12836, 12836, EIData.InstantCastFinder.DefaultICD), // Water Blast Combo }; internal static void AttachMasterToGadgetByCastData(CombatData combatData, HashSet<AgentItem> gadgets, List<long> castIDS, long castEndThreshold) { var possibleCandidates = new HashSet<AgentItem>(); var gadgetSpawnCastData = new List<AnimatedCastEvent>(); foreach (long id in castIDS) { gadgetSpawnCastData.AddRange(combatData.GetAnimatedCastData(id)); } gadgetSpawnCastData.Sort((x, y) => x.Time.CompareTo(y.Time)); foreach (AbstractCastEvent castEvent in gadgetSpawnCastData) { long start = castEvent.Time; long end = castEvent.EndTime; possibleCandidates.Add(castEvent.Caster); foreach (AgentItem gadget in gadgets) { if (gadget.FirstAware >= start && gadget.FirstAware <= end + castEndThreshold) { // more than one candidate, put to unknown and drop the search if (gadget.Master != null && gadget.GetFinalMaster() != castEvent.Caster.GetFinalMaster()) { gadget.SetMaster(ParserHelper._unknownAgent); break; } gadget.SetMaster(castEvent.Caster.GetFinalMaster()); } } } if (possibleCandidates.Count == 1) { foreach (AgentItem gadget in gadgets) { if (gadget.Master == null) { gadget.SetMaster(possibleCandidates.First().GetFinalMaster()); } } } } internal static HashSet<AgentItem> GetOffensiveGadgetAgents(CombatData combatData, long damageSkillID, HashSet<AgentItem> playerAgents) { var res = new HashSet<AgentItem>(); foreach (AbstractHealthDamageEvent evt in combatData.GetDamageData(damageSkillID)) { // dst must no be a gadget nor a friendly player // src must be a masterless gadget if (!playerAgents.Contains(evt.To.GetFinalMaster()) && evt.To.Type != AgentItem.AgentType.Gadget && evt.From.Type == AgentItem.AgentType.Gadget && evt.From.Master == null) { res.Add(evt.From); } } return res; } internal static void SetGadgetMaster(HashSet<AgentItem> gadgets, AgentItem master) { foreach (AgentItem gadget in gadgets) { gadget.SetMaster(master); } } internal static void AttachMasterToRacialGadgets(List<Player> players, CombatData combatData) { var playerAgents = new HashSet<AgentItem>(players.Select(x => x.AgentItem)); // Sylvari stuff HashSet<AgentItem> seedTurrets = GetOffensiveGadgetAgents(combatData, 12455, playerAgents); HashSet<AgentItem> graspingWines = GetOffensiveGadgetAgents(combatData, 1290, playerAgents); AttachMasterToGadgetByCastData(combatData, seedTurrets, new List<long> { 12456, 12457 }, 1000); AttachMasterToGadgetByCastData(combatData, graspingWines, new List<long> { 12453 }, 1000); // melandru avatar works fine already } // public static List<InstantCastEvent> ComputeInstantCastEvents(List<Player> players, CombatData combatData, SkillData skillData, AgentData agentData, FightLogic logic) { var instantCastFinders = new HashSet<InstantCastFinder>(_genericInstantCastFinders); logic.GetInstantCastFinders().ForEach(x => instantCastFinders.Add(x)); var res = new List<InstantCastEvent>(); foreach (Player p in players) { switch (p.Prof) { // case "Elementalist": ElementalistHelper.InstantCastFinder.ForEach(x => instantCastFinders.Add(x)); break; case "Tempest": ElementalistHelper.InstantCastFinder.ForEach(x => instantCastFinders.Add(x)); TempestHelper.InstantCastFinder.ForEach(x => instantCastFinders.Add(x)); break; case "Weaver": ElementalistHelper.InstantCastFinder.ForEach(x => instantCastFinders.Add(x)); WeaverHelper.InstantCastFinder.ForEach(x => instantCastFinders.Add(x)); break; // case "Necromancer": NecromancerHelper.InstantCastFinder.ForEach(x => instantCastFinders.Add(x)); break; case "Reaper": NecromancerHelper.InstantCastFinder.ForEach(x => instantCastFinders.Add(x)); ReaperHelper.InstantCastFinder.ForEach(x => instantCastFinders.Add(x)); break; case "Scourge": NecromancerHelper.InstantCastFinder.ForEach(x => instantCastFinders.Add(x)); ScourgeHelper.InstantCastFinder.ForEach(x => instantCastFinders.Add(x)); break; // case "Mesmer": MesmerHelper.InstantCastFinder.ForEach(x => instantCastFinders.Add(x)); break; case "Chronomancer": MesmerHelper.InstantCastFinder.ForEach(x => instantCastFinders.Add(x)); ChronomancerHelper.InstantCastFinder.ForEach(x => instantCastFinders.Add(x)); break; case "Mirage": MesmerHelper.InstantCastFinder.ForEach(x => instantCastFinders.Add(x)); MirageHelper.InstantCastFinder.ForEach(x => instantCastFinders.Add(x)); break; // case "Thief": ThiefHelper.InstantCastFinder.ForEach(x => instantCastFinders.Add(x)); break; case "Daredevil": ThiefHelper.InstantCastFinder.ForEach(x => instantCastFinders.Add(x)); DaredevilHelper.InstantCastFinder.ForEach(x => instantCastFinders.Add(x)); break; case "Deadeye": ThiefHelper.InstantCastFinder.ForEach(x => instantCastFinders.Add(x)); DeadeyeHelper.InstantCastFinder.ForEach(x => instantCastFinders.Add(x)); break; // case "Engineer": EngineerHelper.InstantCastFinder.ForEach(x => instantCastFinders.Add(x)); break; case "Scrapper": EngineerHelper.InstantCastFinder.ForEach(x => instantCastFinders.Add(x)); ScrapperHelper.InstantCastFinder.ForEach(x => instantCastFinders.Add(x)); break; case "Holosmith": EngineerHelper.InstantCastFinder.ForEach(x => instantCastFinders.Add(x)); HolosmithHelper.InstantCastFinder.ForEach(x => instantCastFinders.Add(x)); break; // case "Ranger": RangerHelper.InstantCastFinder.ForEach(x => instantCastFinders.Add(x)); break; case "Druid": RangerHelper.InstantCastFinder.ForEach(x => instantCastFinders.Add(x)); DruidHelper.InstantCastFinder.ForEach(x => instantCastFinders.Add(x)); break; case "Soulbeast": RangerHelper.InstantCastFinder.ForEach(x => instantCastFinders.Add(x)); SoulbeastHelper.InstantCastFinder.ForEach(x => instantCastFinders.Add(x)); break; // case "Revenant": RevenantHelper.InstantCastFinder.ForEach(x => instantCastFinders.Add(x)); break; case "Herald": RevenantHelper.InstantCastFinder.ForEach(x => instantCastFinders.Add(x)); HeraldHelper.InstantCastFinder.ForEach(x => instantCastFinders.Add(x)); break; case "Renegade": RevenantHelper.InstantCastFinder.ForEach(x => instantCastFinders.Add(x)); RenegadeHelper.InstantCastFinder.ForEach(x => instantCastFinders.Add(x)); break; // case "Guardian": GuardianHelper.InstantCastFinder.ForEach(x => instantCastFinders.Add(x)); break; case "Dragonhunter": GuardianHelper.InstantCastFinder.ForEach(x => instantCastFinders.Add(x)); DragonhunterHelper.InstantCastFinder.ForEach(x => instantCastFinders.Add(x)); break; case "Firebrand": GuardianHelper.InstantCastFinder.ForEach(x => instantCastFinders.Add(x)); FirebrandHelper.InstantCastFinder.ForEach(x => instantCastFinders.Add(x)); break; // case "Warrior": WarriorHelper.InstantCastFinder.ForEach(x => instantCastFinders.Add(x)); break; case "Berserker": WarriorHelper.InstantCastFinder.ForEach(x => instantCastFinders.Add(x)); BerserkerHelper.InstantCastFinder.ForEach(x => instantCastFinders.Add(x)); break; case "Spellbreaker": WarriorHelper.InstantCastFinder.ForEach(x => instantCastFinders.Add(x)); SpellbreakerHelper.InstantCastFinder.ForEach(x => instantCastFinders.Add(x)); break; } } res.AddRange(ComputeInstantCastEvents(combatData, skillData, agentData, instantCastFinders.ToList())); return res; } private static List<InstantCastEvent> ComputeInstantCastEvents(CombatData combatData, SkillData skillData, AgentData agentData, List<InstantCastFinder> instantCastFinders) { var res = new List<InstantCastEvent>(); ulong build = combatData.GetBuildEvent().Build; foreach (InstantCastFinder icf in instantCastFinders) { if (icf.Available(build)) { if (icf.NotAccurate) { skillData.NotAccurate.Add(icf.SkillID); } res.AddRange(icf.ComputeInstantCast(combatData, skillData, agentData)); } } return res; } } }
51.016878
187
0.534199
[ "MIT" ]
enlich/GW2-Elite-Insights-Parser
GW2EIEvtcParser/EIData/ProfHelpers/ProfHelper.cs
12,093
C#
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Metadata.Builders; using opieandanthonylive.Data.Domain; namespace opieandanthonylive.Data.Maps { public class GuestAppearanceTypeMap : IEntityTypeConfiguration<GuestAppearanceType> { public void Configure( EntityTypeBuilder<GuestAppearanceType> builder) { builder.ToTable("GuestAppearanceTypes"); builder.HasKey(t => t.GuestAppearanceTypeID); builder.Property(t => t.GuestAppearanceTypeID) .IsRequired() .ValueGeneratedOnAdd(); builder.Property(t => t.AppearanceTypeName) .IsRequired() .HasMaxLength(150); builder.HasIndex(t => t.AppearanceTypeName) .HasName("IX_GuestAppearanceType_AppearanceTypeName") .IsUnique(); } } }
26.933333
61
0.712871
[ "MIT" ]
vreniose95/opieandanthonylive
src/Data/old/opieandanthonylive.Data/Data/Maps/GuestAppearanceTypeMap.cs
810
C#
/* * Kubernetes * * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) * * OpenAPI spec version: v1.5.1-660c2a2 * * Generated by: https://github.com/swagger-api/swagger-codegen.git */ using System; using System.Linq; using System.IO; using System.Text; using System.Text.RegularExpressions; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using System.ComponentModel.DataAnnotations; namespace io.kubernetes.csharp.Model { /// <summary> /// NodeStatus is information about the current status of a node. /// </summary> [DataContract] public partial class V1NodeStatus : IEquatable<V1NodeStatus>, IValidatableObject { /// <summary> /// Initializes a new instance of the <see cref="V1NodeStatus" /> class. /// </summary> /// <param name="Addresses">List of addresses reachable to the node. Queried from cloud provider, if available. More info: http://releases.k8s.io/HEAD/docs/admin/node.md#node-addresses.</param> /// <param name="Allocatable">Allocatable represents the resources of a node that are available for scheduling. Defaults to Capacity..</param> /// <param name="Capacity">Capacity represents the total resources of a node. More info: http://kubernetes.io/docs/user-guide/persistent-volumes#capacity for more details..</param> /// <param name="Conditions">Conditions is an array of current observed node conditions. More info: http://releases.k8s.io/HEAD/docs/admin/node.md#node-condition.</param> /// <param name="DaemonEndpoints">Endpoints of daemons running on the Node..</param> /// <param name="Images">List of container images on this node.</param> /// <param name="NodeInfo">Set of ids/uuids to uniquely identify the node. More info: http://releases.k8s.io/HEAD/docs/admin/node.md#node-info.</param> /// <param name="Phase">NodePhase is the recently observed lifecycle phase of the node. More info: http://releases.k8s.io/HEAD/docs/admin/node.md#node-phase The field is never populated, and now is deprecated..</param> /// <param name="VolumesAttached">List of volumes that are attached to the node..</param> /// <param name="VolumesInUse">List of attachable volumes in use (mounted) by the node..</param> public V1NodeStatus(List<V1NodeAddress> Addresses = default(List<V1NodeAddress>), Dictionary<string, ResourceQuantity> Allocatable = default(Dictionary<string, ResourceQuantity>), Dictionary<string, ResourceQuantity> Capacity = default(Dictionary<string, ResourceQuantity>), List<V1NodeCondition> Conditions = default(List<V1NodeCondition>), V1NodeDaemonEndpoints DaemonEndpoints = default(V1NodeDaemonEndpoints), List<V1ContainerImage> Images = default(List<V1ContainerImage>), V1NodeSystemInfo NodeInfo = default(V1NodeSystemInfo), string Phase = default(string), List<V1AttachedVolume> VolumesAttached = default(List<V1AttachedVolume>), List<string> VolumesInUse = default(List<string>)) { this.Addresses = Addresses; this.Allocatable = Allocatable; this.Capacity = Capacity; this.Conditions = Conditions; this.DaemonEndpoints = DaemonEndpoints; this.Images = Images; this.NodeInfo = NodeInfo; this.Phase = Phase; this.VolumesAttached = VolumesAttached; this.VolumesInUse = VolumesInUse; } /// <summary> /// List of addresses reachable to the node. Queried from cloud provider, if available. More info: http://releases.k8s.io/HEAD/docs/admin/node.md#node-addresses /// </summary> /// <value>List of addresses reachable to the node. Queried from cloud provider, if available. More info: http://releases.k8s.io/HEAD/docs/admin/node.md#node-addresses</value> [DataMember(Name="addresses", EmitDefaultValue=false)] public List<V1NodeAddress> Addresses { get; set; } /// <summary> /// Allocatable represents the resources of a node that are available for scheduling. Defaults to Capacity. /// </summary> /// <value>Allocatable represents the resources of a node that are available for scheduling. Defaults to Capacity.</value> [DataMember(Name="allocatable", EmitDefaultValue=false)] public Dictionary<string, ResourceQuantity> Allocatable { get; set; } /// <summary> /// Capacity represents the total resources of a node. More info: http://kubernetes.io/docs/user-guide/persistent-volumes#capacity for more details. /// </summary> /// <value>Capacity represents the total resources of a node. More info: http://kubernetes.io/docs/user-guide/persistent-volumes#capacity for more details.</value> [DataMember(Name="capacity", EmitDefaultValue=false)] public Dictionary<string, ResourceQuantity> Capacity { get; set; } /// <summary> /// Conditions is an array of current observed node conditions. More info: http://releases.k8s.io/HEAD/docs/admin/node.md#node-condition /// </summary> /// <value>Conditions is an array of current observed node conditions. More info: http://releases.k8s.io/HEAD/docs/admin/node.md#node-condition</value> [DataMember(Name="conditions", EmitDefaultValue=false)] public List<V1NodeCondition> Conditions { get; set; } /// <summary> /// Endpoints of daemons running on the Node. /// </summary> /// <value>Endpoints of daemons running on the Node.</value> [DataMember(Name="daemonEndpoints", EmitDefaultValue=false)] public V1NodeDaemonEndpoints DaemonEndpoints { get; set; } /// <summary> /// List of container images on this node /// </summary> /// <value>List of container images on this node</value> [DataMember(Name="images", EmitDefaultValue=false)] public List<V1ContainerImage> Images { get; set; } /// <summary> /// Set of ids/uuids to uniquely identify the node. More info: http://releases.k8s.io/HEAD/docs/admin/node.md#node-info /// </summary> /// <value>Set of ids/uuids to uniquely identify the node. More info: http://releases.k8s.io/HEAD/docs/admin/node.md#node-info</value> [DataMember(Name="nodeInfo", EmitDefaultValue=false)] public V1NodeSystemInfo NodeInfo { get; set; } /// <summary> /// NodePhase is the recently observed lifecycle phase of the node. More info: http://releases.k8s.io/HEAD/docs/admin/node.md#node-phase The field is never populated, and now is deprecated. /// </summary> /// <value>NodePhase is the recently observed lifecycle phase of the node. More info: http://releases.k8s.io/HEAD/docs/admin/node.md#node-phase The field is never populated, and now is deprecated.</value> [DataMember(Name="phase", EmitDefaultValue=false)] public string Phase { get; set; } /// <summary> /// List of volumes that are attached to the node. /// </summary> /// <value>List of volumes that are attached to the node.</value> [DataMember(Name="volumesAttached", EmitDefaultValue=false)] public List<V1AttachedVolume> VolumesAttached { get; set; } /// <summary> /// List of attachable volumes in use (mounted) by the node. /// </summary> /// <value>List of attachable volumes in use (mounted) by the node.</value> [DataMember(Name="volumesInUse", EmitDefaultValue=false)] public List<string> VolumesInUse { get; set; } /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { var sb = new StringBuilder(); sb.Append("class V1NodeStatus {\n"); sb.Append(" Addresses: ").Append(Addresses).Append("\n"); sb.Append(" Allocatable: ").Append(Allocatable).Append("\n"); sb.Append(" Capacity: ").Append(Capacity).Append("\n"); sb.Append(" Conditions: ").Append(Conditions).Append("\n"); sb.Append(" DaemonEndpoints: ").Append(DaemonEndpoints).Append("\n"); sb.Append(" Images: ").Append(Images).Append("\n"); sb.Append(" NodeInfo: ").Append(NodeInfo).Append("\n"); sb.Append(" Phase: ").Append(Phase).Append("\n"); sb.Append(" VolumesAttached: ").Append(VolumesAttached).Append("\n"); sb.Append(" VolumesInUse: ").Append(VolumesInUse).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public string ToJson() { return JsonConvert.SerializeObject(this, Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="obj">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object obj) { // credit: http://stackoverflow.com/a/10454552/677735 return this.Equals(obj as V1NodeStatus); } /// <summary> /// Returns true if V1NodeStatus instances are equal /// </summary> /// <param name="other">Instance of V1NodeStatus to be compared</param> /// <returns>Boolean</returns> public bool Equals(V1NodeStatus other) { // credit: http://stackoverflow.com/a/10454552/677735 if (other == null) return false; return ( this.Addresses == other.Addresses || this.Addresses != null && this.Addresses.SequenceEqual(other.Addresses) ) && ( this.Allocatable == other.Allocatable || this.Allocatable != null && this.Allocatable.SequenceEqual(other.Allocatable) ) && ( this.Capacity == other.Capacity || this.Capacity != null && this.Capacity.SequenceEqual(other.Capacity) ) && ( this.Conditions == other.Conditions || this.Conditions != null && this.Conditions.SequenceEqual(other.Conditions) ) && ( this.DaemonEndpoints == other.DaemonEndpoints || this.DaemonEndpoints != null && this.DaemonEndpoints.Equals(other.DaemonEndpoints) ) && ( this.Images == other.Images || this.Images != null && this.Images.SequenceEqual(other.Images) ) && ( this.NodeInfo == other.NodeInfo || this.NodeInfo != null && this.NodeInfo.Equals(other.NodeInfo) ) && ( this.Phase == other.Phase || this.Phase != null && this.Phase.Equals(other.Phase) ) && ( this.VolumesAttached == other.VolumesAttached || this.VolumesAttached != null && this.VolumesAttached.SequenceEqual(other.VolumesAttached) ) && ( this.VolumesInUse == other.VolumesInUse || this.VolumesInUse != null && this.VolumesInUse.SequenceEqual(other.VolumesInUse) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { // credit: http://stackoverflow.com/a/263416/677735 unchecked // Overflow is fine, just wrap { int hash = 41; // Suitable nullity checks etc, of course :) if (this.Addresses != null) hash = hash * 59 + this.Addresses.GetHashCode(); if (this.Allocatable != null) hash = hash * 59 + this.Allocatable.GetHashCode(); if (this.Capacity != null) hash = hash * 59 + this.Capacity.GetHashCode(); if (this.Conditions != null) hash = hash * 59 + this.Conditions.GetHashCode(); if (this.DaemonEndpoints != null) hash = hash * 59 + this.DaemonEndpoints.GetHashCode(); if (this.Images != null) hash = hash * 59 + this.Images.GetHashCode(); if (this.NodeInfo != null) hash = hash * 59 + this.NodeInfo.GetHashCode(); if (this.Phase != null) hash = hash * 59 + this.Phase.GetHashCode(); if (this.VolumesAttached != null) hash = hash * 59 + this.VolumesAttached.GetHashCode(); if (this.VolumesInUse != null) hash = hash * 59 + this.VolumesInUse.GetHashCode(); return hash; } } public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) { yield break; } } }
51.846442
698
0.595102
[ "Apache-2.0" ]
mbohlool/client-csharp
kubernetes/src/io.kubernetes.csharp/Model/V1NodeStatus.cs
13,843
C#
/* **************************************************************************** * * Copyright (c) Microsoft Corporation. * * This source code is subject to terms and conditions of the Apache License, Version 2.0. A * copy of the license can be found in the License.html file at the root of this distribution. If * you cannot locate the Apache License, Version 2.0, please send an email to * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound * by the terms of the Apache License, Version 2.0. * * You must not remove this notice, or any other, from this software. * * * ***************************************************************************/ #if FEATURE_COM #if FEATURE_CORE_DLR using System.Linq.Expressions; #else using Microsoft.Scripting.Ast; #endif using System; using System.Dynamic; using System.Collections.ObjectModel; using System.Diagnostics; using System.Runtime.CompilerServices; namespace Microsoft.Scripting.ComInterop { /// <summary> /// Invokes the object. If it falls back, just produce an error. /// </summary> internal sealed class ComInvokeAction : InvokeBinder { internal ComInvokeAction(CallInfo callInfo) : base(callInfo) { } public override int GetHashCode() { return base.GetHashCode(); } public override bool Equals(object obj) { return base.Equals(obj as ComInvokeAction); } public override DynamicMetaObject FallbackInvoke(DynamicMetaObject target, DynamicMetaObject[] args, DynamicMetaObject errorSuggestion) { DynamicMetaObject res; if (ComBinder.TryBindInvoke(this, target, args, out res)) { return res; } return errorSuggestion ?? new DynamicMetaObject( Expression.Throw( Expression.New( typeof(NotSupportedException).GetConstructor(new[] { typeof(string) }), Expression.Constant(Strings.CannotCall) ) ), target.Restrictions.Merge(BindingRestrictions.Combine(args)) ); } } /// <summary> /// Splats the arguments to another nested dynamic site, which does the /// real invocation of the IDynamicMetaObjectProvider. /// </summary> internal sealed class SplatInvokeBinder : CallSiteBinder { internal readonly static SplatInvokeBinder Instance = new SplatInvokeBinder(); // Just splat the args and dispatch through a nested site public override Expression Bind(object[] args, ReadOnlyCollection<ParameterExpression> parameters, LabelTarget returnLabel) { Debug.Assert(args.Length == 2); int count = ((object[])args[1]).Length; ParameterExpression array = parameters[1]; var nestedArgs = new ReadOnlyCollectionBuilder<Expression>(count + 1); var delegateArgs = new Type[count + 3]; // args + target + returnType + CallSite nestedArgs.Add(parameters[0]); delegateArgs[0] = typeof(CallSite); delegateArgs[1] = typeof(object); for (int i = 0; i < count; i++) { nestedArgs.Add(Expression.ArrayAccess(array, Expression.Constant(i))); delegateArgs[i + 2] = typeof(object).MakeByRefType(); } delegateArgs[delegateArgs.Length - 1] = typeof(object); return Expression.IfThen( Expression.Equal(Expression.ArrayLength(array), Expression.Constant(count)), Expression.Return( returnLabel, Expression.MakeDynamic( Expression.GetDelegateType(delegateArgs), new ComInvokeAction(new CallInfo(count)), nestedArgs ) ) ); } } } #endif
37.528302
145
0.592006
[ "MIT" ]
TrevorDArcyEvans/EllieWare
code/IronLanguages/Runtime/Microsoft.Dynamic/ComInterop/ComInvokeAction.cs
3,980
C#
// suppress "Missing XML comment for publicly visible type or member" #pragma warning disable 1591 #region ReSharper warnings // ReSharper disable PartialTypeWithSinglePart // ReSharper disable RedundantNameQualifier // ReSharper disable InconsistentNaming // ReSharper disable CheckNamespace // ReSharper disable UnusedParameter.Local // ReSharper disable RedundantUsingDirective #endregion namespace tests { using System.Collections.Generic; [System.CodeDom.Compiler.GeneratedCode("gbc", "0.11.0.0")] public enum EnumType1 { EnumValue1 = unchecked((int)5), EnumValue2 = unchecked((int)10), EnumValue3 = unchecked((int)-10), EnumValue4 = unchecked((int)42), Low = unchecked((int)1), EnumValue5 = unchecked((int)-10), EnumValue6 = unchecked((int)4294967286), Int32Min = unchecked((int)-2147483648), Int32Max = unchecked((int)2147483647), UInt32Min = unchecked((int)0), UInt32Max = unchecked((int)4294967295), HexNeg = unchecked((int)-255), OctNeg = unchecked((int)-83), } [global::Bond.Schema] [System.CodeDom.Compiler.GeneratedCode("gbc", "0.11.0.0")] public partial class Foo { [global::Bond.Id(0)] public bool m_bool_1 { get; set; } [global::Bond.Id(1)] public bool m_bool_2 { get; set; } [global::Bond.Id(2)] public bool? m_bool_3 { get; set; } [global::Bond.Id(3)] public string m_str_1 { get; set; } [global::Bond.Id(4)] public string m_str_2 { get; set; } [global::Bond.Id(5)] public sbyte m_int8_4 { get; set; } [global::Bond.Id(6)] public sbyte? m_int8_5 { get; set; } [global::Bond.Id(7)] public short m_int16_4 { get; set; } [global::Bond.Id(8)] public short? m_int16_5 { get; set; } [global::Bond.Id(9)] public int? m_int32_4 { get; set; } [global::Bond.Id(10)] public int m_int32_max { get; set; } [global::Bond.Id(11)] public long? m_int64_4 { get; set; } [global::Bond.Id(12)] public long m_int64_max { get; set; } [global::Bond.Id(13)] public byte m_uint8_2 { get; set; } [global::Bond.Id(14)] public byte? m_uint8_3 { get; set; } [global::Bond.Id(15)] public ushort m_uint16_2 { get; set; } [global::Bond.Id(16)] public ushort? m_uint16_3 { get; set; } [global::Bond.Id(17)] public uint? m_uint32_3 { get; set; } [global::Bond.Id(18)] public uint m_uint32_max { get; set; } [global::Bond.Id(19)] public ulong? m_uint64_3 { get; set; } [global::Bond.Id(20)] public ulong m_uint64_max { get; set; } [global::Bond.Id(21)] public double? m_double_3 { get; set; } [global::Bond.Id(22)] public double m_double_4 { get; set; } [global::Bond.Id(23)] public double m_double_5 { get; set; } [global::Bond.Id(24)] public float? m_float_3 { get; set; } [global::Bond.Id(25)] public float m_float_4 { get; set; } [global::Bond.Id(26)] public float m_float_7 { get; set; } [global::Bond.Id(27)] public EnumType1 m_enum1 { get; set; } [global::Bond.Id(28)] public EnumType1 m_enum2 { get; set; } [global::Bond.Id(29)] public EnumType1? m_enum3 { get; set; } [global::Bond.Id(30)] public EnumType1 m_enum_int32min { get; set; } [global::Bond.Id(31)] public EnumType1 m_enum_int32max { get; set; } [global::Bond.Id(32)] public EnumType1 m_enum_uint32_min { get; set; } [global::Bond.Id(33)] public EnumType1 m_enum_uint32_max { get; set; } [global::Bond.Id(34), global::Bond.Type(typeof(global::Bond.Tag.wstring))] public string m_wstr_1 { get; set; } [global::Bond.Id(35), global::Bond.Type(typeof(global::Bond.Tag.wstring))] public string m_wstr_2 { get; set; } [global::Bond.Id(36)] public long m_int64_neg_hex { get; set; } [global::Bond.Id(37)] public long m_int64_neg_oct { get; set; } public Foo() : this("tests.Foo", "Foo") {} protected Foo(string fullName, string name) { m_bool_1 = true; m_bool_2 = false; m_str_1 = "default string value"; m_int8_4 = -127; m_int16_4 = -32767; m_int32_max = 2147483647; m_int64_max = 9223372036854775807; m_uint8_2 = 255; m_uint16_2 = 65535; m_uint32_max = 4294967295; m_uint64_max = 18446744073709551615; m_double_4 = -123.456789; m_double_5 = -0.0; m_float_4 = 2.71828183F; m_float_7 = 0.0F; m_enum1 = EnumType1.EnumValue1; m_enum2 = EnumType1.EnumValue3; m_enum_int32min = EnumType1.Int32Min; m_enum_int32max = EnumType1.Int32Max; m_enum_uint32_min = EnumType1.UInt32Min; m_enum_uint32_max = EnumType1.UInt32Max; m_wstr_1 = "default wstring value"; m_int64_neg_hex = -4095; m_int64_neg_oct = -83; } } } // tests
28.550265
82
0.568569
[ "MIT" ]
grisharav/bond
compiler/tests/generated/collection-interfaces/defaults_types.cs
5,396
C#
using System; using System.Linq; using OfficeRibbonXEditor.Helpers; using OfficeRibbonXEditor.ViewModels.Dialogs; using OfficeRibbonXEditor.Views.Controls; namespace OfficeRibbonXEditor.Views.Dialogs { /// <summary> /// Interaction logic for SettingsDialog /// </summary> [ExportView(typeof(SettingsDialogViewModel))] public partial class SettingsDialog : DialogControl { public SettingsDialog() { InitializeComponent(); WrapModeBox.ItemsSource = Enum.GetValues(typeof(ScintillaNET.WrapMode)).Cast<ScintillaNET.WrapMode>(); } } }
26.478261
114
0.706076
[ "MIT" ]
JDiaz11/office-ribbonx-editor
src/OfficeRibbonXEditor/Views/Dialogs/SettingsDialog.xaml.cs
611
C#
// Licensed to Elasticsearch B.V under one or more agreements. // Elasticsearch B.V licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information using System; using System.Collections.Generic; using Elastic.Elasticsearch.Ephemeral; using Elastic.Elasticsearch.Xunit.XunitPlumbing; using Elastic.Transport; using FluentAssertions; using Nest; using Tests.Framework.EndpointTests; using Tests.Framework.EndpointTests.TestState; namespace Tests.XPack.Security.User.PutUser { [SkipVersion("<2.3.0", "")] public class PutUserApiTests : ApiIntegrationTestBase<Security, PutUserResponse, IPutUserRequest, PutUserDescriptor, PutUserRequest> { public PutUserApiTests(Security cluster, EndpointUsage usage) : base(cluster, usage) { } protected override bool ExpectIsValid => true; protected override object ExpectJson => new { roles = new[] { "user" }, password = Password, email = Email, full_name = CallIsolatedValue, metadata = new { x = CallIsolatedValue } }; protected override int ExpectStatusCode => 200; protected override Func<PutUserDescriptor, IPutUserRequest> Fluent => d => d .Roles("user") .Password(Password) .Email(Email) .FullName(CallIsolatedValue) .Metadata(m => m .Add("x", CallIsolatedValue) ); protected override HttpMethod HttpMethod => HttpMethod.PUT; protected override PutUserRequest Initializer => new PutUserRequest(CallIsolatedValue) { Roles = new[] { "user" }, Password = Password, Email = Email, FullName = CallIsolatedValue, Metadata = new Dictionary<string, object> { { "x", CallIsolatedValue } } }; protected override bool SupportsDeserialization => false; protected override string UrlPath => $"/_security/user/{CallIsolatedValue}"; private string Email => $"{CallIsolatedValue}@example.example"; private string Password => CallIsolatedValue; protected override LazyResponses ClientUsage() => Calls( (client, f) => client.Security.PutUser(CallIsolatedValue, f), (client, f) => client.Security.PutUserAsync(CallIsolatedValue, f), (client, r) => client.Security.PutUser(r), (client, r) => client.Security.PutUserAsync(r) ); protected override PutUserDescriptor NewDescriptor() => new PutUserDescriptor(CallIsolatedValue); protected override void ExpectResponse(PutUserResponse response) => response.Created.Should().BeTrue("{0}", response.DebugInformation); } public class PutUserRunAsApiTests : PutUserApiTests { public PutUserRunAsApiTests(Security cluster, EndpointUsage usage) : base(cluster, usage) { // ReSharper disable VirtualMemberCallInConstructor var x = Client.Security.GetUser(new GetUserRequest(ClusterAuthentication.User.Username)); var y = Client.Security.GetRole(new GetRoleRequest(ClusterAuthentication.User.Role)); // ReSharper restore VirtualMemberCallInConstructor } protected override bool ExpectIsValid => false; protected override int ExpectStatusCode => 403; protected override Func<PutUserDescriptor, IPutUserRequest> Fluent => f => base.Fluent(f .RequestConfiguration(c => c .RunAs(ClusterAuthentication.User.Username) )); protected override PutUserRequest Initializer { get { var request = base.Initializer; request.RequestConfiguration = new RequestConfiguration { RunAs = ClusterAuthentication.User.Username }; return request; } } protected override void ExpectResponse(PutUserResponse response) { } } }
30.577586
133
0.741472
[ "Apache-2.0" ]
Jiasyuan/elasticsearch-net
tests/Tests/XPack/Security/User/PutUser/PutUserApiTests.cs
3,547
C#
using System.IO; using System.Runtime.Serialization; using GameEstate.Red.Formats.Red.CR2W.Reflection; using FastMember; using static GameEstate.Red.Formats.Red.Records.Enums; namespace GameEstate.Red.Formats.Red.Types { [DataContract(Namespace = "")] [REDMeta] public class CDummyComponent : CComponent { public CDummyComponent(CR2WFile cr2w, CVariable parent, string name) : base(cr2w, parent, name){ } public static new CVariable Create(CR2WFile cr2w, CVariable parent, string name) => new CDummyComponent(cr2w, parent, name); public override void Read(BinaryReader file, uint size) => base.Read(file, size); public override void Write(BinaryWriter file) => base.Write(file); } }
31.434783
127
0.742739
[ "MIT" ]
bclnet/GameEstate
src/Estates/Red/GameEstate.Red.Format/Red/W3/RTTIConvert/CDummyComponent.cs
723
C#
using Scripts.Map; using Scripts.Map.Room.ModulableRoom; using Scripts.ScriptableObjects; using UnityEngine; namespace Scripts.Exploration { public class Submarine : MonoBehaviour { private AirlockRoom _base; private Rigidbody2D _rb; private SpriteRenderer _sr; private void Start() { _rb = GetComponent<Rigidbody2D>(); _sr = GetComponent<SpriteRenderer>(); SubmarineManager.S.RegisterSubmarine(this); } public void GetNewAirlock(AirlockRoom airlock) { if (_base == null) { for (int i = 0; i < airlock.Emplacements.Length; i++) { if (airlock.Emplacements[i] == null) { airlock.Emplacements[i] = this; _base = airlock; break; } } } } private void FixedUpdate() { Vector2? objective = null; if (SubmarineManager.S.Objective.HasValue) { objective = SubmarineManager.S.Objective.Value; } if (objective == null) { objective = _base?.Position; } if (objective != null) { if (Vector2.Distance(transform.position, objective.Value) < 1f) _rb.velocity = Vector2.zero; else { _rb.velocity = (objective.Value - (Vector2)transform.position).normalized * ConfigManager.S.Config.SubmarineSpeed; var r = ConfigManager.S.Config.SubmarineRadius; for (int x = -r; x <= r; x++) { for (int y = -r; y <= r; y++) { MapManager.S.DiscoverTile(Mathf.RoundToInt(transform.position.x) + x, Mathf.RoundToInt(-transform.position.y) + y); } } } } } } }
30.685714
143
0.453445
[ "MIT" ]
BionomeeX/LudumDare48
Assets/Scripts/Exploration/Submarine.cs
2,150
C#
namespace Microsoft.FeatureFlighting.Common.Config { /// <summary> /// Configuration when feature flags are evaluated /// </summary> public class FlagEvaluationConfiguration { /// <summary> /// Flag to indicate if exceptions should be ignored when evaluating feature flags /// </summary> public bool IgnoreException { get; set; } /// <summary> /// Flag to indicate if additional messages should be added when feature flag is enabled /// </summary> public bool AddEnabledContext { get; set; } /// <summary> /// Flag to indicate if additional messages should be added when feature flag is disabled /// </summary> public bool AddDisabledContext { get; set; } /// <summary> /// Gets a default <see cref="FlagEvaluationConfiguration"/> /// </summary> /// <returns></returns> public static FlagEvaluationConfiguration GetDefault() { return new FlagEvaluationConfiguration() { IgnoreException = false, AddDisabledContext = false, AddEnabledContext = false }; } } }
33.131579
98
0.566322
[ "MIT" ]
t739/FeatureFlightingManagement
src/service/Common/Config/FlagEvaluationConfiguration.cs
1,261
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ // Generation date: 9/11/2020 3:24:26 PM namespace Microsoft.Dynamics.DataEntities { /// <summary> /// There are no comments for RTax25DebtType in the schema. /// </summary> public enum RTax25DebtType { Debit = 0, Credit = 1 } }
29
81
0.478261
[ "MIT" ]
NathanClouseAX/AAXDataEntityPerfTest
Projects/AAXDataEntityPerfTest/ConsoleApp1/Connected Services/D365/RTax25DebtType.cs
669
C#
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; namespace WhiteBoard.Objects { public class Pool<T> where T : new() { private Stack<T> _stack; public Pool() { _stack = new Stack<T>(); } // Creates a Pool of objects for later use. public Pool(int size) { _stack = new Stack<T>(size); for (int i = 0; i < size; i++) { _stack.Push(new T()); } } // Fetchs an object for use. public T Fetch() { if (_stack.Count > 0) { return _stack.Pop(); } return new T(); } // Returns an object to the Pool. public void Return(T item) { _stack.Push(item); } } }
19.061224
51
0.465739
[ "MIT" ]
RobLach/Overly-Professional
src/WhiteBoard/Objects/ResourceManager.cs
936
C#
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.Collections.Generic; using System.IO; using System.Linq; using osu.Framework.IO.File; namespace osu.Framework.Platform { public class NativeStorage : Storage { private readonly GameHost host; public NativeStorage(string baseName, GameHost host = null) : base(baseName) { this.host = host; } protected override string LocateBasePath() => @"./"; //use current directory by default public override bool Exists(string path) => File.Exists(GetFullPath(path)); public override bool ExistsDirectory(string path) => Directory.Exists(GetFullPath(path)); public override void DeleteDirectory(string path) { path = GetFullPath(path); // handles the case where the directory doesn't exist, which will throw a DirectoryNotFoundException. if (Directory.Exists(path)) Directory.Delete(path, true); } public override void Delete(string path) => FileSafety.FileDelete(GetFullPath(path)); public override IEnumerable<string> GetDirectories(string path) => getRelativePaths(Directory.GetDirectories(GetFullPath(path))); public override IEnumerable<string> GetFiles(string path, string pattern = "*") => getRelativePaths(Directory.GetFiles(GetFullPath(path), pattern)); private IEnumerable<string> getRelativePaths(IEnumerable<string> paths) { string basePath = Path.GetFullPath(GetFullPath(string.Empty)); return paths.Select(Path.GetFullPath).Select(path => { if (!path.StartsWith(basePath)) throw new ArgumentException($"\"{path}\" does not start with \"{basePath}\" and is probably malformed"); return path.Substring(basePath.Length).TrimStart(Path.DirectorySeparatorChar); }); } public override string GetFullPath(string path, bool createIfNotExisting = false) { path = path.Replace(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar); var basePath = Path.GetFullPath(Path.Combine(BasePath, BaseName, SubDirectory)).TrimEnd(Path.DirectorySeparatorChar); var resolvedPath = Path.GetFullPath(Path.Combine(basePath, path)); if (!resolvedPath.StartsWith(basePath)) throw new ArgumentException($"\"{resolvedPath}\" traverses outside of \"{basePath}\" and is probably malformed"); if (createIfNotExisting) Directory.CreateDirectory(Path.GetDirectoryName(resolvedPath)); return resolvedPath; } public override void OpenInNativeExplorer() => host?.OpenFileExternally(GetFullPath(string.Empty)); public override Stream GetStream(string path, FileAccess access = FileAccess.Read, FileMode mode = FileMode.OpenOrCreate) { path = GetFullPath(path, access != FileAccess.Read); if (string.IsNullOrEmpty(path)) throw new ArgumentNullException(nameof(path)); switch (access) { case FileAccess.Read: if (!File.Exists(path)) return null; return File.Open(path, FileMode.Open, access, FileShare.Read); default: return File.Open(path, mode, access); } } public override string GetDatabaseConnectionString(string name) => string.Concat("Data Source=", GetFullPath($@"{name}.db", true)); public override void DeleteDatabase(string name) => Delete($@"{name}.db"); } }
41.301075
166
0.637074
[ "MIT" ]
AyakuraYuki/osu-framework
osu.Framework/Platform/NativeStorage.cs
3,751
C#
//----------------------------------------------------------------------------- // Copyright (c) 2012 GarageGames, LLC // // 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. //----------------------------------------------------------------------------- //------------------------------------------------------------------------------ // Loading info is text displayed on the client side while the mission // is being loaded. This information is extracted from the mission file // and sent to each the client as it joins. //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // clearLoadInfo // // Clears the mission info stored //------------------------------------------------------------------------------ function clearLoadInfo() { if (isObject(theLevelInfo)) theLevelInfo.delete(); } //------------------------------------------------------------------------------ // buildLoadInfo // // Extract the map description from the .mis file //------------------------------------------------------------------------------ function buildLoadInfo( %mission ) { clearLoadInfo(); %infoObject = ""; %file = new FileObject(); if ( %file.openForRead( %mission ) ) { %inInfoBlock = false; while ( !%file.isEOF() ) { %line = %file.readLine(); %line = trim( %line ); if( %line $= "new ScriptObject(MissionInfo) {" ) %inInfoBlock = true; else if( %line $= "new LevelInfo(theLevelInfo) {" ) %inInfoBlock = true; else if( %inInfoBlock && %line $= "};" ) { %inInfoBlock = false; %infoObject = %infoObject @ %line; break; } if( %inInfoBlock ) %infoObject = %infoObject @ %line @ " "; } %file.close(); } else error("Level file " @ %mission @ " not found."); // Will create the object "MissionInfo" eval( %infoObject ); %file.delete(); } //------------------------------------------------------------------------------ // dumpLoadInfo // // Echo the mission information to the console //------------------------------------------------------------------------------ function dumpLoadInfo() { echo( "Level Name: " @ theLevelInfo.name ); echo( "Level Description:" ); for( %i = 0; theLevelInfo.desc[%i] !$= ""; %i++ ) echo (" " @ theLevelInfo.desc[%i]); } //------------------------------------------------------------------------------ // sendLoadInfoToClient // // Sends mission description to the client //------------------------------------------------------------------------------ function sendLoadInfoToClient( %client ) { messageClient( %client, 'MsgLoadInfo', "", theLevelInfo.levelName ); // Send Mission Description a line at a time for( %i = 0; theLevelInfo.desc[%i] !$= ""; %i++ ) messageClient( %client, 'MsgLoadDescripition', "", theLevelInfo.desc[%i] ); messageClient( %client, 'MsgLoadInfoDone' ); }
37.127273
81
0.499755
[ "MIT" ]
7erj1/RPG_Starter
Templates/RPGDemo/game/core/scripts/server/levelInfo.cs
3,975
C#
namespace ReciboKravMaga { partial class Form1 { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(Form1)); this.label1 = new System.Windows.Forms.Label(); this.studentName = new System.Windows.Forms.TextBox(); this.amountPaid = new System.Windows.Forms.TextBox(); this.label2 = new System.Windows.Forms.Label(); this.paymentType = new System.Windows.Forms.GroupBox(); this.otherPaymentType = new System.Windows.Forms.TextBox(); this.otherType = new System.Windows.Forms.RadioButton(); this.threeMonths = new System.Windows.Forms.RadioButton(); this.oneMonth = new System.Windows.Forms.RadioButton(); this.label3 = new System.Windows.Forms.Label(); this.button1 = new System.Windows.Forms.Button(); this.paymentDate = new System.Windows.Forms.DateTimePicker(); this.paymentType.SuspendLayout(); this.SuspendLayout(); // // label1 // this.label1.AutoSize = true; this.label1.Location = new System.Drawing.Point(88, 12); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(41, 15); this.label1.TabIndex = 0; this.label1.Text = "Aluno:"; // // studentName // this.studentName.CharacterCasing = System.Windows.Forms.CharacterCasing.Upper; this.studentName.Location = new System.Drawing.Point(135, 12); this.studentName.MaxLength = 200; this.studentName.Name = "studentName"; this.studentName.Size = new System.Drawing.Size(264, 21); this.studentName.TabIndex = 0; // // amountPaid // this.amountPaid.Location = new System.Drawing.Point(135, 39); this.amountPaid.Name = "amountPaid"; this.amountPaid.Size = new System.Drawing.Size(102, 21); this.amountPaid.TabIndex = 1; // // label2 // this.label2.AutoSize = true; this.label2.Cursor = System.Windows.Forms.Cursors.VSplit; this.label2.Location = new System.Drawing.Point(64, 42); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(65, 15); this.label2.TabIndex = 3; this.label2.Text = "Valor (R$):"; // // paymentType // this.paymentType.Controls.Add(this.otherPaymentType); this.paymentType.Controls.Add(this.otherType); this.paymentType.Controls.Add(this.threeMonths); this.paymentType.Controls.Add(this.oneMonth); this.paymentType.Location = new System.Drawing.Point(75, 98); this.paymentType.Name = "paymentType"; this.paymentType.Size = new System.Drawing.Size(246, 96); this.paymentType.TabIndex = 3; this.paymentType.TabStop = false; this.paymentType.Text = "Tipo do Pagamento"; // // otherPaymentType // this.otherPaymentType.CharacterCasing = System.Windows.Forms.CharacterCasing.Upper; this.otherPaymentType.Enabled = false; this.otherPaymentType.Location = new System.Drawing.Point(75, 59); this.otherPaymentType.Name = "otherPaymentType"; this.otherPaymentType.Size = new System.Drawing.Size(165, 21); this.otherPaymentType.TabIndex = 5; // // otherType // this.otherType.AutoSize = true; this.otherType.Location = new System.Drawing.Point(11, 60); this.otherType.Name = "otherType"; this.otherType.Size = new System.Drawing.Size(58, 19); this.otherType.TabIndex = 2; this.otherType.TabStop = true; this.otherType.Text = "Outro:"; this.otherType.UseVisualStyleBackColor = true; this.otherType.CheckedChanged += new System.EventHandler(this.oneMonth_CheckedChanged); // // threeMonths // this.threeMonths.AutoSize = true; this.threeMonths.Location = new System.Drawing.Point(123, 34); this.threeMonths.Name = "threeMonths"; this.threeMonths.Size = new System.Drawing.Size(111, 19); this.threeMonths.TabIndex = 1; this.threeMonths.TabStop = true; this.threeMonths.Text = "Trimestralidade"; this.threeMonths.UseVisualStyleBackColor = true; this.threeMonths.CheckedChanged += new System.EventHandler(this.oneMonth_CheckedChanged); // // oneMonth // this.oneMonth.AutoSize = true; this.oneMonth.Location = new System.Drawing.Point(11, 34); this.oneMonth.Name = "oneMonth"; this.oneMonth.Size = new System.Drawing.Size(97, 19); this.oneMonth.TabIndex = 0; this.oneMonth.TabStop = true; this.oneMonth.Text = "Mensalidade"; this.oneMonth.UseVisualStyleBackColor = true; this.oneMonth.CheckedChanged += new System.EventHandler(this.oneMonth_CheckedChanged); // // label3 // this.label3.AutoSize = true; this.label3.Cursor = System.Windows.Forms.Cursors.VSplit; this.label3.Location = new System.Drawing.Point(9, 72); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(120, 15); this.label3.TabIndex = 5; this.label3.Text = "Data do Pagamento:"; // // button1 // this.button1.Location = new System.Drawing.Point(98, 205); this.button1.Name = "button1"; this.button1.Size = new System.Drawing.Size(206, 44); this.button1.TabIndex = 99; this.button1.Text = "Gerar Recibo"; this.button1.UseVisualStyleBackColor = true; this.button1.Click += new System.EventHandler(this.button1_Click); // // paymentDate // this.paymentDate.CustomFormat = ""; this.paymentDate.Format = System.Windows.Forms.DateTimePickerFormat.Short; this.paymentDate.Location = new System.Drawing.Point(135, 67); this.paymentDate.Name = "paymentDate"; this.paymentDate.Size = new System.Drawing.Size(102, 21); this.paymentDate.TabIndex = 2; // // Form1 // this.AcceptButton = this.button1; this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch; this.ClientSize = new System.Drawing.Size(414, 261); this.Controls.Add(this.paymentDate); this.Controls.Add(this.button1); this.Controls.Add(this.label3); this.Controls.Add(this.paymentType); this.Controls.Add(this.label2); this.Controls.Add(this.amountPaid); this.Controls.Add(this.studentName); this.Controls.Add(this.label1); this.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle; this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); this.MaximizeBox = false; this.MinimizeBox = false; this.Name = "Form1"; this.SizeGripStyle = System.Windows.Forms.SizeGripStyle.Hide; this.Text = "Gerador Recibo de Pagamento - Centro de Krav Maga Moema"; this.paymentType.ResumeLayout(false); this.paymentType.PerformLayout(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.Label label1; private System.Windows.Forms.TextBox studentName; private System.Windows.Forms.TextBox amountPaid; private System.Windows.Forms.Label label2; private System.Windows.Forms.GroupBox paymentType; private System.Windows.Forms.TextBox otherPaymentType; private System.Windows.Forms.RadioButton otherType; private System.Windows.Forms.RadioButton threeMonths; private System.Windows.Forms.RadioButton oneMonth; private System.Windows.Forms.Label label3; private System.Windows.Forms.Button button1; private System.Windows.Forms.DateTimePicker paymentDate; } }
45.375
137
0.589226
[ "MIT" ]
Khalarii/KravMagaReceiptGenerator
ReciboKravMaga/ReciboKravMaga/Form1.Designer.cs
9,803
C#
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System.Reflection; using System.Windows; using System.Windows.Controls; using System.Windows.Input; using ThinkGeo.MapSuite.Layers; namespace ThinkGeo.MapSuite.GisEditor.Plugins { /// <summary> /// Interaction logic for ConnectToDatabaseUserControl.xaml /// </summary> public partial class DatabaseLayerInfoUserControl : UserControl { public DatabaseLayerInfoUserControl() { InitializeComponent(); autoCompleteServerName.IsTextCompletionEnabled = true; autoCompleteServerName.FilterMode = AutoCompleteFilterMode.Contains; } [Obfuscation] private void TreeViewItem_MouseDoubleClick(object sender, MouseButtonEventArgs e) { MsSqlTableDataRepositoryItem currentItem = sender.GetDataContext<MsSqlTableDataRepositoryItem>(); if (currentItem != null && currentItem.IsLeaf) { DataRepositoryItem databaseItem = currentItem.Parent.Parent.Parent.Parent as DataRepositoryItem; DatabaseLayerInfoViewModel<MsSqlFeatureLayer> viewModel = DataContext as DatabaseLayerInfoViewModel<MsSqlFeatureLayer>; viewModel.Model.DatabaseName = databaseItem.Name; viewModel.CurrentItem = currentItem; DropdownButton.IsChecked = false; } } [Obfuscation] private void TextBox_KeyDown(object sender, KeyEventArgs e) { if (e.Key == Key.Enter) { DatabaseLayerInfoViewModel<MsSqlFeatureLayer> viewModel = DataContext as DatabaseLayerInfoViewModel<MsSqlFeatureLayer>; if (viewModel != null) { viewModel.ConnectToDatabaseCommand.Execute(null); } } } [Obfuscation] private void Button_Click(object sender, RoutedEventArgs e) { DatabaseLayerInfoViewModel<MsSqlFeatureLayer> viewModel = DataContext as DatabaseLayerInfoViewModel<MsSqlFeatureLayer>; MsSql2008FeatureLayerInfo info = new MsSql2008FeatureLayerInfo(); info.Password = viewModel.Password; info.ServerName = viewModel.ServerName; info.UserName = viewModel.UserName; info.UseTrustAuthority = viewModel.UseTrustAuthentication; viewModel.IsServerConnected = true; DataRepositoryTree.DataContext = new DatabaseTreeViewModel(info); } [Obfuscation] private void dropdownTB_MouseLeftButtonUp(object sender, MouseButtonEventArgs e) { DropdownButton.IsChecked = true; } } }
39.701149
135
0.682687
[ "Apache-2.0" ]
ThinkGeo/GIS-Editor
MapSuiteGisEditor/GisEditorPluginCore/Shares/Wizards/SqlLayerWizard/View/DatabaseLayerInfoUserControl.xaml.cs
3,454
C#
using System; namespace Soltys.Database { internal class AstValue:IAstNode { public ReadOnlySpan<AstExpression> Expressions => this.expressions; private readonly AstExpression[] expressions; public AstValue(AstExpression[] expressions) { this.expressions = expressions; } public void Accept(IAstVisitor visitor) => visitor.VisitValue(this); } }
22.157895
76
0.660333
[ "MIT" ]
soltys/Melange
src/Database/Soltys.Database/Cmd/AST/AstValue.cs
421
C#
using System.Linq; using System.Threading.Tasks; using NUnit.Framework; using SJP.Schematic.Tests.Utilities; namespace SJP.Schematic.PostgreSql.Tests.Integration.Versions.V10 { internal sealed partial class PostgreSqlRelationalDatabaseTableProviderTests : PostgreSql10Test { [Test] public async Task Columns_WhenGivenTableWithOneColumn_ReturnsColumnCollectionWithOneValue() { var table = await GetTableAsync("v10_table_test_table_1").ConfigureAwait(false); Assert.That(table.Columns, Has.Exactly(1).Items); } [Test] public async Task Columns_WhenGivenTableWithOneColumn_ReturnsColumnWithCorrectName() { var table = await GetTableAsync("v10_table_test_table_1").ConfigureAwait(false); var column = table.Columns.Single(); const string columnName = "test_column"; Assert.That(column.Name.LocalName, Is.EqualTo(columnName)); } [Test] public async Task Columns_WhenGivenTableWithMultipleColumns_ReturnsColumnsInCorrectOrder() { var expectedColumnNames = new[] { "first_name", "middle_name", "last_name" }; var table = await GetTableAsync("v10_table_test_table_4").ConfigureAwait(false); var columns = table.Columns; var columnNames = columns.Select(c => c.Name.LocalName); Assert.That(columnNames, Is.EqualTo(expectedColumnNames)); } [Test] public async Task Columns_WhenGivenTableWithNullableColumn_ColumnReturnsIsNullableTrue() { const string tableName = "v10_table_test_table_1"; var table = await GetTableAsync(tableName).ConfigureAwait(false); var column = table.Columns.Single(); Assert.That(column.IsNullable, Is.True); } [Test] public async Task Columns_WhenGivenTableWithNotNullableColumn_ColumnReturnsIsNullableFalse() { const string tableName = "v10_table_test_table_2"; var table = await GetTableAsync(tableName).ConfigureAwait(false); var column = table.Columns.Single(); Assert.That(column.IsNullable, Is.False); } [Test] public async Task Columns_WhenGivenTableWithColumnWithNoDefaultValue_ColumnReturnsNoneDefaultValue() { const string tableName = "v10_table_test_table_1"; var table = await GetTableAsync(tableName).ConfigureAwait(false); var column = table.Columns.Single(); Assert.That(column.DefaultValue, OptionIs.None); } [Test] public async Task Columns_WhenGivenTableWithNonComputedColumn_ReturnsIsComputedFalse() { const string tableName = "v10_table_test_table_1"; var table = await GetTableAsync(tableName).ConfigureAwait(false); var column = table.Columns.Single(); Assert.That(column.IsComputed, Is.False); } [Test] public async Task Columns_WhenGivenTableColumnWithoutIdentity_ReturnsNoneAutoincrement() { const string tableName = "v10_table_test_table_1"; var table = await GetTableAsync(tableName).ConfigureAwait(false); var column = table.Columns.Single(); Assert.That(column.AutoIncrement, OptionIs.None); } [Test] public async Task Columns_WhenGivenTableColumnWithSerialIdentity_ReturnsSomeAutoincrement() { const string tableName = "v10_table_test_table_35"; var table = await GetTableAsync(tableName).ConfigureAwait(false); var column = table.Columns[table.Columns.Count - 1]; Assert.That(column.AutoIncrement, OptionIs.Some); } [Test] public async Task Columns_WhenGivenTableColumnWithSerialIdentity_ReturnsCorrectInitialValue() { const string tableName = "v10_table_test_table_35"; var table = await GetTableAsync(tableName).ConfigureAwait(false); var column = table.Columns[table.Columns.Count - 1]; Assert.That(column.AutoIncrement.UnwrapSome().InitialValue, Is.EqualTo(1)); } [Test] public async Task Columns_WhenGivenTableColumnWithSerialIdentity_ReturnsCorrectIncrement() { const string tableName = "v10_table_test_table_35"; var table = await GetTableAsync(tableName).ConfigureAwait(false); var column = table.Columns[table.Columns.Count - 1]; Assert.That(column.AutoIncrement.UnwrapSome().Increment, Is.EqualTo(1)); } [Test] public async Task Columns_WhenGivenTableColumnWithIdentity_ReturnsSomeAutoincrement() { const string tableName = "v10_table_test_table_36"; var table = await GetTableAsync(tableName).ConfigureAwait(false); var column = table.Columns[table.Columns.Count - 1]; Assert.That(column.AutoIncrement, OptionIs.Some); } [Test] public async Task Columns_WhenGivenTableColumnWithIdentity_ReturnsDefaultInitialValue() { const string tableName = "v10_table_test_table_36"; var table = await GetTableAsync(tableName).ConfigureAwait(false); var column = table.Columns[table.Columns.Count - 1]; Assert.That(column.AutoIncrement.UnwrapSome().InitialValue, Is.EqualTo(123m)); } [Test] public async Task Columns_WhenGivenTableColumnWithIdentity_ReturnsDefaultIncrement() { const string tableName = "v10_table_test_table_36"; var table = await GetTableAsync(tableName).ConfigureAwait(false); var column = table.Columns[table.Columns.Count - 1]; Assert.That(column.AutoIncrement.UnwrapSome().Increment, Is.EqualTo(456m)); } } }
40.738255
109
0.645964
[ "MIT" ]
sjp/Schematic
src/SJP.Schematic.PostgreSql.Tests/Integration/Versions/V10/PostgreSqlRelationalDatabaseTableProviderTests.Columns.cs
6,072
C#
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! namespace Google.Cloud.ContactCenterInsights.V1.Snippets { using Google.Api.Gax.ResourceNames; using Google.Cloud.ContactCenterInsights.V1; public sealed partial class GeneratedContactCenterInsightsClientStandaloneSnippets { /// <summary>Snippet for CreateConversation</summary> /// <remarks> /// This snippet has been automatically generated for illustrative purposes only. /// It may require modifications to work in your environment. /// </remarks> public void CreateConversationResourceNames() { // Create client ContactCenterInsightsClient contactCenterInsightsClient = ContactCenterInsightsClient.Create(); // Initialize request argument(s) LocationName parent = LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"); Conversation conversation = new Conversation(); string conversationId = ""; // Make the request Conversation response = contactCenterInsightsClient.CreateConversation(parent, conversation, conversationId); } } }
41.547619
121
0.704871
[ "Apache-2.0" ]
googleapis/googleapis-gen
google/cloud/contactcenterinsights/v1/google-cloud-contactcenterinsights-v1-csharp/Google.Cloud.ContactCenterInsights.V1.StandaloneSnippets/ContactCenterInsightsClient.CreateConversationResourceNamesSnippet.g.cs
1,745
C#
using Volo.Abp; namespace BookStore.EntityFrameworkCore { public abstract class BookStoreEntityFrameworkCoreTestBase : BookStoreTestBase<BookStoreEntityFrameworkCoreTestModule> { } }
19.9
123
0.798995
[ "MIT" ]
271943794/abp-samples
BlazorPageUniTest/test/BookStore.EntityFrameworkCore.Tests/EntityFrameworkCore/BookStoreEntityFrameworkCoreTestBase.cs
201
C#
// <auto-generated /> using System; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Migrations; using Microsoft.EntityFrameworkCore.Storage.ValueConversion; using MoviesRecommendationSystem.Data; namespace MoviesRecommendationSystem.Data.Migrations { [DbContext(typeof(MoviesRecommendationDbContext))] [Migration("20210728171906_FixEditorToUserRelationship")] partial class FixEditorToUserRelationship { protected override void BuildTargetModel(ModelBuilder modelBuilder) { #pragma warning disable 612, 618 modelBuilder .HasAnnotation("Relational:MaxIdentifierLength", 128) .HasAnnotation("ProductVersion", "5.0.8") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole", b => { b.Property<string>("Id") .HasColumnType("nvarchar(450)"); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken() .HasColumnType("nvarchar(max)"); b.Property<string>("Name") .HasMaxLength(256) .HasColumnType("nvarchar(256)"); b.Property<string>("NormalizedName") .HasMaxLength(256) .HasColumnType("nvarchar(256)"); b.HasKey("Id"); b.HasIndex("NormalizedName") .IsUnique() .HasDatabaseName("RoleNameIndex") .HasFilter("[NormalizedName] IS NOT NULL"); b.ToTable("AspNetRoles"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<string>", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("ClaimType") .HasColumnType("nvarchar(max)"); b.Property<string>("ClaimValue") .HasColumnType("nvarchar(max)"); b.Property<string>("RoleId") .IsRequired() .HasColumnType("nvarchar(450)"); b.HasKey("Id"); b.HasIndex("RoleId"); b.ToTable("AspNetRoleClaims"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<string>", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("ClaimType") .HasColumnType("nvarchar(max)"); b.Property<string>("ClaimValue") .HasColumnType("nvarchar(max)"); b.Property<string>("UserId") .IsRequired() .HasColumnType("nvarchar(450)"); b.HasKey("Id"); b.HasIndex("UserId"); b.ToTable("AspNetUserClaims"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<string>", b => { b.Property<string>("LoginProvider") .HasMaxLength(128) .HasColumnType("nvarchar(128)"); b.Property<string>("ProviderKey") .HasMaxLength(128) .HasColumnType("nvarchar(128)"); b.Property<string>("ProviderDisplayName") .HasColumnType("nvarchar(max)"); b.Property<string>("UserId") .IsRequired() .HasColumnType("nvarchar(450)"); b.HasKey("LoginProvider", "ProviderKey"); b.HasIndex("UserId"); b.ToTable("AspNetUserLogins"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<string>", b => { b.Property<string>("UserId") .HasColumnType("nvarchar(450)"); b.Property<string>("RoleId") .HasColumnType("nvarchar(450)"); b.HasKey("UserId", "RoleId"); b.HasIndex("RoleId"); b.ToTable("AspNetUserRoles"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<string>", b => { b.Property<string>("UserId") .HasColumnType("nvarchar(450)"); b.Property<string>("LoginProvider") .HasMaxLength(128) .HasColumnType("nvarchar(128)"); b.Property<string>("Name") .HasMaxLength(128) .HasColumnType("nvarchar(128)"); b.Property<string>("Value") .HasColumnType("nvarchar(max)"); b.HasKey("UserId", "LoginProvider", "Name"); b.ToTable("AspNetUserTokens"); }); modelBuilder.Entity("MoviesRecommendationSystem.Data.Models.Actor", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("Name") .IsRequired() .HasMaxLength(50) .HasColumnType("nvarchar(50)"); b.HasKey("Id"); b.ToTable("Actors"); }); modelBuilder.Entity("MoviesRecommendationSystem.Data.Models.Director", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("Name") .IsRequired() .HasMaxLength(50) .HasColumnType("nvarchar(50)"); b.HasKey("Id"); b.ToTable("Directors"); }); modelBuilder.Entity("MoviesRecommendationSystem.Data.Models.Editor", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<DateTime>("BirthDate") .HasColumnType("datetime2"); b.Property<string>("FirstName") .IsRequired() .HasMaxLength(50) .HasColumnType("nvarchar(50)"); b.Property<string>("LastName") .IsRequired() .HasMaxLength(50) .HasColumnType("nvarchar(50)"); b.Property<string>("UserId") .IsRequired() .HasColumnType("nvarchar(450)"); b.HasKey("Id"); b.HasIndex("UserId") .IsUnique(); b.ToTable("Editors"); }); modelBuilder.Entity("MoviesRecommendationSystem.Data.Models.Genre", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("Name") .IsRequired() .HasMaxLength(30) .HasColumnType("nvarchar(30)"); b.HasKey("Id"); b.ToTable("Genres"); }); modelBuilder.Entity("MoviesRecommendationSystem.Data.Models.Movie", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<int>("DirectorId") .HasColumnType("int"); b.Property<int?>("EditorId") .HasColumnType("int"); b.Property<string>("ImageUrl") .IsRequired() .HasColumnType("nvarchar(max)"); b.Property<string>("Language") .IsRequired() .HasMaxLength(30) .HasColumnType("nvarchar(30)"); b.Property<string>("Plot") .IsRequired() .HasMaxLength(200) .HasColumnType("nvarchar(200)"); b.Property<int>("ReleaseYear") .HasColumnType("int"); b.Property<int>("Runtime") .HasColumnType("int"); b.Property<string>("Studio") .IsRequired() .HasMaxLength(40) .HasColumnType("nvarchar(40)"); b.Property<string>("Title") .IsRequired() .HasMaxLength(150) .HasColumnType("nvarchar(150)"); b.HasKey("Id"); b.HasIndex("DirectorId"); b.HasIndex("EditorId"); b.ToTable("Movies"); }); modelBuilder.Entity("MoviesRecommendationSystem.Data.Models.MovieActor", b => { b.Property<int>("MovieId") .HasColumnType("int"); b.Property<int>("ActorId") .HasColumnType("int"); b.HasKey("MovieId", "ActorId"); b.HasIndex("ActorId"); b.ToTable("MovieActors"); }); modelBuilder.Entity("MoviesRecommendationSystem.Data.Models.MovieGenre", b => { b.Property<int>("MovieId") .HasColumnType("int"); b.Property<int>("GenreId") .HasColumnType("int"); b.HasKey("MovieId", "GenreId"); b.HasIndex("GenreId"); b.ToTable("MovieGenres"); }); modelBuilder.Entity("MoviesRecommendationSystem.Data.Models.Series", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<int>("AverageRuntime") .HasColumnType("int"); b.Property<int>("EndYear") .HasColumnType("int"); b.Property<string>("ImageUrl") .IsRequired() .HasColumnType("nvarchar(max)"); b.Property<string>("Language") .IsRequired() .HasMaxLength(30) .HasColumnType("nvarchar(30)"); b.Property<string>("Plot") .IsRequired() .HasMaxLength(200) .HasColumnType("nvarchar(200)"); b.Property<int>("ReleaseYear") .HasColumnType("int"); b.Property<int>("SeasonCount") .HasColumnType("int"); b.Property<string>("Studio") .HasColumnType("nvarchar(max)"); b.Property<int>("StudioId") .HasColumnType("int"); b.Property<string>("Title") .IsRequired() .HasMaxLength(150) .HasColumnType("nvarchar(150)"); b.HasKey("Id"); b.ToTable("Series"); }); modelBuilder.Entity("MoviesRecommendationSystem.Data.Models.SeriesActor", b => { b.Property<int>("SeriesId") .HasColumnType("int"); b.Property<int>("ActorId") .HasColumnType("int"); b.HasKey("SeriesId", "ActorId"); b.HasIndex("ActorId"); b.ToTable("SeriesActors"); }); modelBuilder.Entity("MoviesRecommendationSystem.Data.Models.SeriesGenre", b => { b.Property<int>("SeriesId") .HasColumnType("int"); b.Property<int>("GenreId") .HasColumnType("int"); b.HasKey("SeriesId", "GenreId"); b.HasIndex("GenreId"); b.ToTable("SeriesGenres"); }); modelBuilder.Entity("MoviesRecommendationSystem.Data.Models.User", b => { b.Property<string>("Id") .HasColumnType("nvarchar(450)"); b.Property<int>("AccessFailedCount") .HasColumnType("int"); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken() .HasColumnType("nvarchar(max)"); b.Property<string>("Email") .HasMaxLength(256) .HasColumnType("nvarchar(256)"); b.Property<bool>("EmailConfirmed") .HasColumnType("bit"); b.Property<bool>("LockoutEnabled") .HasColumnType("bit"); b.Property<DateTimeOffset?>("LockoutEnd") .HasColumnType("datetimeoffset"); b.Property<string>("Name") .HasMaxLength(50) .HasColumnType("nvarchar(50)"); b.Property<string>("NormalizedEmail") .HasMaxLength(256) .HasColumnType("nvarchar(256)"); b.Property<string>("NormalizedUserName") .HasMaxLength(256) .HasColumnType("nvarchar(256)"); b.Property<string>("PasswordHash") .HasColumnType("nvarchar(max)"); b.Property<string>("PhoneNumber") .HasColumnType("nvarchar(max)"); b.Property<bool>("PhoneNumberConfirmed") .HasColumnType("bit"); b.Property<string>("SecurityStamp") .HasColumnType("nvarchar(max)"); b.Property<bool>("TwoFactorEnabled") .HasColumnType("bit"); b.Property<string>("UserName") .HasMaxLength(256) .HasColumnType("nvarchar(256)"); b.HasKey("Id"); b.HasIndex("NormalizedEmail") .HasDatabaseName("EmailIndex"); b.HasIndex("NormalizedUserName") .IsUnique() .HasDatabaseName("UserNameIndex") .HasFilter("[NormalizedUserName] IS NOT NULL"); b.ToTable("AspNetUsers"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<string>", b => { b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) .WithMany() .HasForeignKey("RoleId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<string>", b => { b.HasOne("MoviesRecommendationSystem.Data.Models.User", null) .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<string>", b => { b.HasOne("MoviesRecommendationSystem.Data.Models.User", null) .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<string>", b => { b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) .WithMany() .HasForeignKey("RoleId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.HasOne("MoviesRecommendationSystem.Data.Models.User", null) .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<string>", b => { b.HasOne("MoviesRecommendationSystem.Data.Models.User", null) .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("MoviesRecommendationSystem.Data.Models.Editor", b => { b.HasOne("MoviesRecommendationSystem.Data.Models.User", null) .WithOne() .HasForeignKey("MoviesRecommendationSystem.Data.Models.Editor", "UserId") .OnDelete(DeleteBehavior.Restrict) .IsRequired(); }); modelBuilder.Entity("MoviesRecommendationSystem.Data.Models.Movie", b => { b.HasOne("MoviesRecommendationSystem.Data.Models.Director", "Director") .WithMany("Movies") .HasForeignKey("DirectorId") .OnDelete(DeleteBehavior.Restrict) .IsRequired(); b.HasOne("MoviesRecommendationSystem.Data.Models.Editor", "Editor") .WithMany("Movies") .HasForeignKey("EditorId") .OnDelete(DeleteBehavior.Restrict); b.Navigation("Director"); b.Navigation("Editor"); }); modelBuilder.Entity("MoviesRecommendationSystem.Data.Models.MovieActor", b => { b.HasOne("MoviesRecommendationSystem.Data.Models.Actor", "Actor") .WithMany("MovieActors") .HasForeignKey("ActorId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.HasOne("MoviesRecommendationSystem.Data.Models.Movie", "Movie") .WithMany("MovieActors") .HasForeignKey("MovieId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.Navigation("Actor"); b.Navigation("Movie"); }); modelBuilder.Entity("MoviesRecommendationSystem.Data.Models.MovieGenre", b => { b.HasOne("MoviesRecommendationSystem.Data.Models.Genre", "Genre") .WithMany("MovieGenres") .HasForeignKey("GenreId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.HasOne("MoviesRecommendationSystem.Data.Models.Movie", "Movie") .WithMany("MovieGenres") .HasForeignKey("MovieId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.Navigation("Genre"); b.Navigation("Movie"); }); modelBuilder.Entity("MoviesRecommendationSystem.Data.Models.SeriesActor", b => { b.HasOne("MoviesRecommendationSystem.Data.Models.Actor", "Actor") .WithMany() .HasForeignKey("ActorId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.HasOne("MoviesRecommendationSystem.Data.Models.Series", "Series") .WithMany("SeriesActors") .HasForeignKey("SeriesId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.Navigation("Actor"); b.Navigation("Series"); }); modelBuilder.Entity("MoviesRecommendationSystem.Data.Models.SeriesGenre", b => { b.HasOne("MoviesRecommendationSystem.Data.Models.Genre", "Genre") .WithMany() .HasForeignKey("GenreId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.HasOne("MoviesRecommendationSystem.Data.Models.Series", "Series") .WithMany("SeriesGenres") .HasForeignKey("SeriesId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.Navigation("Genre"); b.Navigation("Series"); }); modelBuilder.Entity("MoviesRecommendationSystem.Data.Models.Actor", b => { b.Navigation("MovieActors"); }); modelBuilder.Entity("MoviesRecommendationSystem.Data.Models.Director", b => { b.Navigation("Movies"); }); modelBuilder.Entity("MoviesRecommendationSystem.Data.Models.Editor", b => { b.Navigation("Movies"); }); modelBuilder.Entity("MoviesRecommendationSystem.Data.Models.Genre", b => { b.Navigation("MovieGenres"); }); modelBuilder.Entity("MoviesRecommendationSystem.Data.Models.Movie", b => { b.Navigation("MovieActors"); b.Navigation("MovieGenres"); }); modelBuilder.Entity("MoviesRecommendationSystem.Data.Models.Series", b => { b.Navigation("SeriesActors"); b.Navigation("SeriesGenres"); }); #pragma warning restore 612, 618 } } }
37.297134
125
0.453049
[ "MIT" ]
histefanov/ASP-NET-Project-Movies-Recommendation-System
MoviesRecommendationSystem/Data/Migrations/20210728171906_FixEditorToUserRelationship.Designer.cs
24,730
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Head : Characteristic { public Head(Sprite[] sprites) { string[] listOfSpriteNames = CustomizableOptions.featureSprites.Head; listOfSprites = new Sprite[sprites.Length]; listOfSprites = sprites; for (int i = 0; i < spritesOnDisplay.Length; i++) { if (i >= listOfSprites.Length) break; //Debug.Log(listOfSpriteNames[i]); //listOfSprites[i] = Resources.Load<Sprite>("Hair / " + listOfSpriteNames[i]); spritesOnDisplay[i] = listOfSprites[i]; } firstSpriteIndex = 0; lastSpriteIndex = Mathf.Min(listOfSprites.Length - 1, 4); } }
28.692308
90
0.624665
[ "Unlicense" ]
jjerion/PrototypeHotGirlSummer
Hot Girl Summer Prototype 1/Assets/Scripts/Character Creator/Head.cs
748
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.Collections.ObjectModel; using System.Runtime.Serialization; using System.Xml; using System.Xml.Serialization; using System.Diagnostics; namespace System.ServiceModel.Syndication { // sealed because the ctor results in a call to the virtual InsertItem method public sealed class SyndicationElementExtensionCollection : Collection<SyndicationElementExtension> { private XmlBuffer _buffer; private readonly bool _initialized; internal SyndicationElementExtensionCollection() : this((XmlBuffer)null) { } internal SyndicationElementExtensionCollection(XmlBuffer buffer) : base() { _buffer = buffer; if (_buffer != null) { PopulateElements(); } _initialized = true; } internal SyndicationElementExtensionCollection(SyndicationElementExtensionCollection source) : base() { _buffer = source._buffer; for (int i = 0; i < source.Items.Count; ++i) { base.Add(source.Items[i]); } _initialized = true; } public void Add(object extension) { if (extension is SyndicationElementExtension) { base.Add((SyndicationElementExtension)extension); } else { Add(extension, (DataContractSerializer)null); } } public void Add(string outerName, string outerNamespace, object dataContractExtension) { Add(outerName, outerNamespace, dataContractExtension, null); } public void Add(object dataContractExtension, DataContractSerializer serializer) { Add(null, null, dataContractExtension, serializer); } public void Add(string outerName, string outerNamespace, object dataContractExtension, XmlObjectSerializer dataContractSerializer) { if (dataContractExtension == null) { throw new ArgumentNullException(nameof(dataContractExtension)); } if (dataContractSerializer == null) { dataContractSerializer = new DataContractSerializer(dataContractExtension.GetType()); } base.Add(new SyndicationElementExtension(outerName, outerNamespace, dataContractExtension, dataContractSerializer)); } public void Add(object xmlSerializerExtension, XmlSerializer serializer) { if (xmlSerializerExtension == null) { throw new ArgumentNullException(nameof(xmlSerializerExtension)); } if (serializer == null) { serializer = new XmlSerializer(xmlSerializerExtension.GetType()); } base.Add(new SyndicationElementExtension(xmlSerializerExtension, serializer)); } public void Add(XmlReader xmlReader) { if (xmlReader == null) { throw new ArgumentNullException(nameof(xmlReader)); } base.Add(new SyndicationElementExtension(xmlReader)); } public XmlReader GetReaderAtElementExtensions() { XmlBuffer extensionsBuffer = GetOrCreateBufferOverExtensions(); XmlReader reader = extensionsBuffer.GetReader(0); reader.ReadStartElement(); return reader; } public Collection<TExtension> ReadElementExtensions<TExtension>(string extensionName, string extensionNamespace) { return ReadElementExtensions<TExtension>(extensionName, extensionNamespace, new DataContractSerializer(typeof(TExtension))); } public Collection<TExtension> ReadElementExtensions<TExtension>(string extensionName, string extensionNamespace, XmlObjectSerializer serializer) { if (serializer == null) { throw new ArgumentNullException(nameof(serializer)); } return ReadExtensions<TExtension>(extensionName, extensionNamespace, serializer, null); } public Collection<TExtension> ReadElementExtensions<TExtension>(string extensionName, string extensionNamespace, XmlSerializer serializer) { if (serializer == null) { throw new ArgumentNullException(nameof(serializer)); } return ReadExtensions<TExtension>(extensionName, extensionNamespace, null, serializer); } internal void WriteTo(XmlWriter writer, Func<string, string, bool> shouldSkipElement) { if (_buffer != null) { using (XmlDictionaryReader reader = _buffer.GetReader(0)) { reader.ReadStartElement(); while (reader.IsStartElement()) { if (shouldSkipElement != null && shouldSkipElement(reader.LocalName, reader.NamespaceURI)) { reader.Skip(); continue; } writer.WriteNode(reader, false); } } } else { for (int i = 0; i < Items.Count; ++i) { Items[i].WriteTo(writer); } } } protected override void ClearItems() { base.ClearItems(); Debug.Assert(_initialized, "The constructor should never clear the collection."); _buffer = null; } protected override void InsertItem(int index, SyndicationElementExtension item) { if (item == null) { throw new ArgumentNullException(nameof(item)); } base.InsertItem(index, item); // clear the cached buffer if the operation is happening outside the constructor if (_initialized) { _buffer = null; } } protected override void RemoveItem(int index) { base.RemoveItem(index); Debug.Assert(_initialized, "The constructor should never remove items from the collection."); _buffer = null; } protected override void SetItem(int index, SyndicationElementExtension item) { if (item == null) { throw new ArgumentNullException(nameof(item)); } base.SetItem(index, item); Debug.Assert(_initialized, "The constructor should never set items in the collection."); _buffer = null; } private XmlBuffer GetOrCreateBufferOverExtensions() { if (_buffer != null) { return _buffer; } XmlBuffer newBuffer = new XmlBuffer(int.MaxValue); using (XmlWriter writer = newBuffer.OpenSection(XmlDictionaryReaderQuotas.Max)) { writer.WriteStartElement(Rss20Constants.ExtensionWrapperTag); for (int i = 0; i < Count; ++i) { this[i].WriteTo(writer); } writer.WriteEndElement(); } newBuffer.CloseSection(); newBuffer.Close(); _buffer = newBuffer; return newBuffer; } private void PopulateElements() { using (XmlDictionaryReader reader = _buffer.GetReader(0)) { reader.ReadStartElement(); int index = 0; while (reader.IsStartElement()) { base.Add(new SyndicationElementExtension(_buffer, index, reader.LocalName, reader.NamespaceURI)); reader.Skip(); ++index; } } } private Collection<TExtension> ReadExtensions<TExtension>(string extensionName, string extensionNamespace, XmlObjectSerializer dcSerializer, XmlSerializer xmlSerializer) { if (string.IsNullOrEmpty(extensionName)) { throw new ArgumentException(SR.ExtensionNameNotSpecified); } Debug.Assert((dcSerializer == null) != (xmlSerializer == null), "exactly one serializer should be supplied"); // normalize the null and empty namespace if (extensionNamespace == null) { extensionNamespace = string.Empty; } Collection<TExtension> results = new Collection<TExtension>(); for (int i = 0; i < Count; ++i) { if (extensionName != this[i].OuterName || extensionNamespace != this[i].OuterNamespace) { continue; } if (dcSerializer != null) { results.Add(this[i].GetObject<TExtension>(dcSerializer)); } else { results.Add(this[i].GetObject<TExtension>(xmlSerializer)); } } return results; } } }
34.33213
177
0.554679
[ "MIT" ]
2m0nd/runtime
src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/SyndicationElementExtensionCollection.cs
9,510
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.DocumentDB.V20151106.Outputs { /// <summary> /// The conflict resolution policy for the container. /// </summary> [OutputType] public sealed class ConflictResolutionPolicyResponse { /// <summary> /// The conflict resolution path in the case of LastWriterWins mode. /// </summary> public readonly string? ConflictResolutionPath; /// <summary> /// The procedure to resolve conflicts in the case of custom mode. /// </summary> public readonly string? ConflictResolutionProcedure; /// <summary> /// Indicates the conflict resolution mode. /// </summary> public readonly string? Mode; [OutputConstructor] private ConflictResolutionPolicyResponse( string? conflictResolutionPath, string? conflictResolutionProcedure, string? mode) { ConflictResolutionPath = conflictResolutionPath; ConflictResolutionProcedure = conflictResolutionProcedure; Mode = mode; } } }
30.73913
81
0.649929
[ "Apache-2.0" ]
polivbr/pulumi-azure-native
sdk/dotnet/DocumentDB/V20151106/Outputs/ConflictResolutionPolicyResponse.cs
1,414
C#
using Microsoft.VisualStudio.TestTools.UnitTesting; using PKISharp.WACS.Configuration; using PKISharp.WACS.Plugins.InstallationPlugins; using PKISharp.WACS.Services; using PKISharp.WACS.UnitTests.Mock.Services; using System; namespace PKISharp.WACS.UnitTests.Tests.InstallationPluginTests { [TestClass] public class ArgumentParserTests { private readonly Mock.Services.LogService log; private readonly VersionService version; public ArgumentParserTests() { log = new Mock.Services.LogService(true); version = new VersionService(log); } private string? TestScript(string parameters) { var argParser = new ArgumentsParser(log, new MockPluginService(log, version), $"--scriptparameters {parameters} --verbose".Split(' ')); var argService = new ArgumentsService(log, argParser); var args = argService.GetArguments<ScriptArguments>(); return args?.ScriptParameters; } [TestMethod] [ExpectedException(typeof(Exception))] public void Illegal() => TestScript("hello nonsense"); [TestMethod] public void SingleParam() => Assert.AreEqual("hello", TestScript("hello")); [TestMethod] public void SingleParamExtra() => Assert.AreEqual("hello", TestScript("hello --verbose")); [TestMethod] public void MultipleParams() => Assert.AreEqual("hello world", TestScript("\"hello world\"")); [TestMethod] public void MultipleParamsExtra() => Assert.AreEqual("hello world", TestScript("\"hello world\" --test --verbose")); [TestMethod] public void MultipleParamsDoubleQuotes() => Assert.AreEqual("\"hello world\"", TestScript("\"\"hello world\"\"")); [TestMethod] public void MultipleParamsDoubleQuotesExtra() => Assert.AreEqual("\"hello world\"", TestScript("\"\"hello world\"\" --test --verbose")); [TestMethod] public void MultipleParamsSingleQuotes() => Assert.AreEqual("'hello world'", TestScript("\"'hello world'\"")); [TestMethod] public void EmbeddedKeySingle() => Assert.AreEqual("'hello --world'", TestScript("\"'hello --world'\"")); [TestMethod] public void EmbeddedKeyDouble() => Assert.AreEqual("\"hello --world\"", TestScript("\"\"hello --world\"\"")); [TestMethod] public void Real() => Assert.AreEqual("'{CertThumbprint}' 'IIS,SMTP,IMAP' '1' '{CacheFile}' '{CachePassword}' '{CertFriendlyName}'", TestScript("\"'{CertThumbprint}' 'IIS,SMTP,IMAP' '1' '{CacheFile}' '{CachePassword}' '{CertFriendlyName}'\"")); } }
39.573529
252
0.640654
[ "Apache-2.0" ]
Skulblaka/win-acme
src/main.test/Tests/InstallationPluginTests/ArgumentParserTests.cs
2,693
C#
using System; using System.Collections.Generic; using System.Diagnostics; using System.Text; namespace Paillave.Etl.Core { public interface ITraceContent { string Type { get; } TraceLevel Level { get; } string Message { get; } } }
17.933333
34
0.654275
[ "MIT" ]
fundprocess/Etl.Net
src/Paillave.Etl/Core/ITraceContent.cs
271
C#
using eCommerce.Commons.Objects.Responses.Products; using eCommerce.Commons.Objects.Responses.ShoppingCart; using eCommerce.ShoppingCart.Core.Objects.Dtos; namespace eCommerce.ShoppingCart.Core.Helpers.Mappers { public class MapperHelper : IMapperHelper { public ShoppingCartResponse MappToShoppingCartResponse(ShoppingCartDto dto) { var product = dto.Product != null ? new ProductResponse() { Code = dto.Product.Id, Name = dto.Product.Name, Image = dto.Product.Image, } : new ProductResponse(); return new ShoppingCartResponse() { CustomerId = dto.CustomerId, Id = dto.Id, InitialPrice = dto.InitialPrice, Price = dto.Price, Product = product, SigDiff = GetSigDiff(dto.InitialPrice, dto.Price), PercentDiff = CalculatePercentDiff(dto.InitialPrice, dto.Price), Quantity = dto.Quantity, Available = dto.Product != null ? dto.Product.Available : false }; } private static string GetSigDiff(decimal initialPrice, decimal price) { return initialPrice > price ? "-" : initialPrice == price ? "=" : "+"; } private static decimal CalculatePercentDiff(decimal initialPrice, decimal price) { decimal value = 0; if (initialPrice == price) return value; decimal minValue; decimal maxValue; if (initialPrice > price) { minValue = price; maxValue = initialPrice; } else { minValue = initialPrice; maxValue = price; } decimal result = (minValue / maxValue) * 100; var strResult = result.ToString("#.#"); return Convert.ToDecimal(strResult); } } }
33.163934
88
0.542758
[ "Apache-2.0" ]
wepea93/PICA.eCommerce
src/Services/eCommerce.ShoppingCart/eCommerce.ShoppingCart.Core/Helpers/Mappers/MapperHelper.cs
2,025
C#
using System; using System.Collections.Generic; using System.Text; namespace Laugris.Sage { /// <summary> /// Description of the Visual element size /// </summary> public enum DimensionType { /// <summary> /// The specified dimension is an absolute number of pixels. /// </summary> Absolute, /// <summary> /// The specified dimension holds a float and should be multiplied by the /// height or width of the object being animated. /// </summary> RelativeToSelf, /// <summary> /// The specified dimension holds a float and should be multiplied by the /// height or width of the parent of the object being animated. /// </summary> RelativeToParent } }
29.107143
82
0.580368
[ "Artistic-2.0" ]
perevoznyk/krento
src/Laugris.Sage/Presentation/DimensionType.cs
817
C#
using Abp.EntityHistory; using Afonsoft.Ranking.Authorization.Users; namespace Afonsoft.Ranking.Auditing { /// <summary> /// A helper class to store an <see cref="EntityChange"/> and a <see cref="User"/> object. /// </summary> public class EntityChangeAndUser { public EntityChange EntityChange { get; set; } public User User { get; set; } } }
25.733333
94
0.65285
[ "MIT" ]
afonsoft/Ranking
src/Afonsoft.Ranking.Application/Auditing/EntityChangeAndUser.cs
388
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Hatfield.EnviroData.DataProfile.WQ.Models { public class Site : WQProfileEntity { public int Id { get; set; } public string Name { get; set; } public string Description { get; set; } public double? Latitude { get; set; } public double? Longitude { get; set; } } }
23.421053
51
0.65618
[ "MPL-2.0", "MPL-2.0-no-copyleft-exception" ]
HatfieldConsultants/Hatfield.EnviroData.Core
Source/Hatfield.EnviroData.DataProfile.WQ.Models/Site.cs
447
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Keypress : MonoBehaviour { // Start is called before the first frame update void Start() { } // Update is called once per frame void Update() { } }
15.421053
52
0.62116
[ "MIT" ]
davtamay/DecisionIntervention
DecisionIntervention/Assets/Keypress.cs
295
C#
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AzureNextGen.RecoveryServices.Latest.Outputs { [OutputType] public sealed class ProcessServerDetailsResponse { /// <summary> /// The available memory. /// </summary> public readonly int AvailableMemoryInBytes; /// <summary> /// The available disk space. /// </summary> public readonly int AvailableSpaceInBytes; /// <summary> /// The free disk space percentage. /// </summary> public readonly double FreeSpacePercentage; /// <summary> /// The health of the process server. /// </summary> public readonly string Health; /// <summary> /// The health errors. /// </summary> public readonly ImmutableArray<Outputs.HealthErrorResponse> HealthErrors; /// <summary> /// The historic health of the process server based on the health in last 24 hours. /// </summary> public readonly string HistoricHealth; /// <summary> /// The process server Id. /// </summary> public readonly string Id; /// <summary> /// The last heartbeat received from the process server. /// </summary> public readonly string LastHeartbeatUtc; /// <summary> /// The memory usage percentage. /// </summary> public readonly double MemoryUsagePercentage; /// <summary> /// The process server name. /// </summary> public readonly string Name; /// <summary> /// The processor usage percentage. /// </summary> public readonly double ProcessorUsagePercentage; /// <summary> /// The throughput in bytes. /// </summary> public readonly int ThroughputInBytes; /// <summary> /// The uploading pending data in bytes. /// </summary> public readonly int ThroughputUploadPendingDataInBytes; /// <summary> /// The total memory. /// </summary> public readonly int TotalMemoryInBytes; /// <summary> /// The total disk space. /// </summary> public readonly int TotalSpaceInBytes; /// <summary> /// The used memory. /// </summary> public readonly int UsedMemoryInBytes; /// <summary> /// The used disk space. /// </summary> public readonly int UsedSpaceInBytes; /// <summary> /// The process server version. /// </summary> public readonly string Version; [OutputConstructor] private ProcessServerDetailsResponse( int availableMemoryInBytes, int availableSpaceInBytes, double freeSpacePercentage, string health, ImmutableArray<Outputs.HealthErrorResponse> healthErrors, string historicHealth, string id, string lastHeartbeatUtc, double memoryUsagePercentage, string name, double processorUsagePercentage, int throughputInBytes, int throughputUploadPendingDataInBytes, int totalMemoryInBytes, int totalSpaceInBytes, int usedMemoryInBytes, int usedSpaceInBytes, string version) { AvailableMemoryInBytes = availableMemoryInBytes; AvailableSpaceInBytes = availableSpaceInBytes; FreeSpacePercentage = freeSpacePercentage; Health = health; HealthErrors = healthErrors; HistoricHealth = historicHealth; Id = id; LastHeartbeatUtc = lastHeartbeatUtc; MemoryUsagePercentage = memoryUsagePercentage; Name = name; ProcessorUsagePercentage = processorUsagePercentage; ThroughputInBytes = throughputInBytes; ThroughputUploadPendingDataInBytes = throughputUploadPendingDataInBytes; TotalMemoryInBytes = totalMemoryInBytes; TotalSpaceInBytes = totalSpaceInBytes; UsedMemoryInBytes = usedMemoryInBytes; UsedSpaceInBytes = usedSpaceInBytes; Version = version; } } }
30.952703
91
0.592229
[ "Apache-2.0" ]
test-wiz-sec/pulumi-azure-nextgen
sdk/dotnet/RecoveryServices/Latest/Outputs/ProcessServerDetailsResponse.cs
4,581
C#
using System; using System.Collections.Generic; using System.ComponentModel; using System.Text; namespace Cynosura.Studio.Core.Requests.EntityChanges.Models { public class EntityChangeModel { public int Id { get; set; } [DisplayName("Entity Id")] public int EntityId { get; set; } [DisplayName("Action")] public Core.Enums.ChangeAction Action { get; set; } [DisplayName("From")] public string From { get; set; } [DisplayName("To")] public string To { get; set; } [DisplayName("Creation Date")] public DateTime CreationDate { get; set; } [DisplayName("Creation User")] public int? CreationUserId { get; set; } public Users.Models.UserShortModel CreationUser { get; set; } public IList<EntityPropertyChange> Changes { get; set; } } }
25.676471
69
0.626575
[ "MIT" ]
CynosuraPlatform/Cynosura.Studio
Cynosura.Studio.Core/Requests/EntityChanges/Models/EntityChangeModel.cs
875
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.ComponentModel; using System.Net.Http; using System.Threading.Tasks; using Xunit; namespace NuGetGallery.FunctionalTests.Statistics { public class PackageStatisticsTests { /// <summary> /// Double-checks whether expected fields exist in the packages feed. /// </summary> [Fact] [Description("Verify the webresponse for stats/downloads/last6weeks/ returns all 6 fields")] [Priority(1)] [Category("P1Tests")] public async Task PackageFeedStatsConfidenceTest() { var requestUrl = UrlHelper.V2FeedRootUrl + @"stats/downloads/last6weeks/"; string responseText; using (var httpClient = new HttpClient()) { responseText = await httpClient.GetStringAsync(requestUrl); } string firstPackage = responseText.Substring(responseText.IndexOf("{"), responseText.IndexOf("}") - responseText.IndexOf("{")); Assert.True(firstPackage.Contains(@"""PackageId"": """), "Expected PackageId field is missing."); Assert.True(firstPackage.Contains(@"""PackageVersion"": """), "Expected PackageVersion field is missing."); Assert.True(firstPackage.Contains(@"""Gallery"": """), "Expected Gallery field is missing."); Assert.True(firstPackage.Contains(@"""PackageTitle"": """), "Expected PackageTitle field is missing."); Assert.True(firstPackage.Contains(@"""PackageIconUrl"": """), "Expected PackageIconUrl field is missing."); Assert.True(firstPackage.Contains(@"""Downloads"": "), "Expected PackageIconUrl field is missing."); } /// <summary> /// Verify copunt querystring parameter in the Packages feed. /// </summary> [Fact] [Description("Verify the webresponse for stats/downloads/last6weeks/ contains the right amount of packages")] [Priority(1)] [Category("P1Tests")] public async Task PackageFeedCountParameterTest() { using (var httpClient = new HttpClient()) { var requestUrl = UrlHelper.V2FeedRootUrl + @"stats/downloads/last6weeks/"; var responseText = await httpClient.GetStringAsync(requestUrl); string[] separators = { "}," }; int packageCount = responseText.Split(separators, StringSplitOptions.RemoveEmptyEntries).Length; // Only verify the stats feed contains 500 packages for production if (UrlHelper.BaseUrl.ToLowerInvariant() == Constants.NuGetOrgUrl) { Assert.True(packageCount == 500, "Expected feed to contain 500 packages. Actual count: " + packageCount); } requestUrl = UrlHelper.V2FeedRootUrl + @"stats/downloads/last6weeks?count=5"; // Get the response. responseText = await httpClient.GetStringAsync(requestUrl); packageCount = responseText.Split(separators, StringSplitOptions.RemoveEmptyEntries).Length; Assert.True(packageCount == 5, "Expected feed to contain 5 packages. Actual count: " + packageCount); } } } }
46.216216
139
0.630409
[ "Apache-2.0" ]
JarLob/NuGetGallery
tests/NuGetGallery.FunctionalTests/Statistics/PackageStatisticsTests.cs
3,422
C#
using System; using System.Collections.Generic; using System.Text; // // Visual Basic .NET Parser // // Copyright (C) 2005, Microsoft Corporation. All rights reserved. // // THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER // EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF // MERCHANTIBILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE. // using VBConverter.CodeParser.Trees.Comments; using VBConverter.CodeParser.Trees.Expressions; namespace VBConverter.CodeParser.Trees.Statements { /// <summary> /// A parse tree for an AddHandler statement. /// </summary> public sealed class AddHandlerStatement : HandlerStatement { /// <summary> /// Constructs a new parse tree for an AddHandler statement. /// </summary> /// <param name="name">The name of the event.</param> /// <param name="commaLocation">The location of the ','.</param> /// <param name="delegateExpression">The delegate expression.</param> /// <param name="span">The location of the parse tree.</param> /// <param name="comments">The comments for the parse tree.</param> public AddHandlerStatement(Expression name, Location commaLocation, Expression delegateExpression, Span span, IList<Comment> comments) : base(TreeType.AddHandlerStatement, name, commaLocation, delegateExpression, span, comments) { } } }
37.72973
231
0.721347
[ "MIT" ]
wwdenis/vbconverter
Parser/Trees/Statements/AddHandlerStatement.cs
1,396
C#
using System.ComponentModel.Composition; using System.Diagnostics.CodeAnalysis; using STR.MvvmCommon; namespace Str.Wallpaper.Wpf.ViewModels { [Export] [ViewModel(nameof(NotifyIconViewModel))] [SuppressMessage("ReSharper", "MemberCanBeInternal")] [SuppressMessage("ReSharper", "MemberCanBePrivate.Global")] public sealed class NotifyIconViewModel : ObservableObject { #region Private Fields private string tooltipText; private RelayCommand doubleClick; private RelayCommand exit; #endregion Private Fields #region Properties public string TooltipText { get { return tooltipText; } set { SetField(ref tooltipText, value, () => TooltipText); } } public RelayCommand DoubleClick { get { return doubleClick; } set { SetField(ref doubleClick, value, () => DoubleClick); } } public RelayCommand Exit { get { return exit; } set { SetField(ref exit, value, () => Exit); } } #endregion Properties } }
21.913043
66
0.688492
[ "MIT" ]
stricq/STR.Wallpaper
Str.Wallpaper.Wpf/ViewModels/NotifyIconViewModel.cs
1,010
C#
using GLib; using System; using Uno.UI.Runtime.Skia; namespace Authentication.OidcDemo.Skia.Gtk { class Program { static void Main(string[] args) { ExceptionManager.UnhandledException += delegate (UnhandledExceptionArgs expArgs) { Console.WriteLine("GLIB UNHANDLED EXCEPTION" + expArgs.ExceptionObject.ToString()); expArgs.ExitApplication = true; }; var host = new GtkHost(() => new App(), args); host.Run(); } } }
19.608696
87
0.696231
[ "Apache-2.0" ]
Mohsens22/Uno.Samples
UI/Authentication.OidcDemo/Authentication.OidcDemo/Authentication.OidcDemo.Skia.Gtk/Program.cs
453
C#
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using WebMvc1.Models; namespace WebMvc1.Controllers { public class HomeController : Controller { public IActionResult Index() { return View(); } public IActionResult About() { ViewData["Message"] = "Your application description page."; return View(); } public IActionResult Contact() { ViewData["Message"] = "Your contact page."; return View(); } public IActionResult Error() { return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier }); } } }
21.763158
112
0.593712
[ "MIT" ]
AtwindYu/Asp.NetCore2
sources/WebMvc1/Controllers/HomeController.cs
829
C#
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Globalization; using Xunit; namespace System.Globalization.CalendarsTests { //System.Globalization.KoreanCalendar.IsLeapYear(System.Int32,System.Int32) public class KoreanCalendarIsLeapYear { private readonly RandomDataGenerator _generator = new RandomDataGenerator(); #region Positive Test Logic // PosTest1:Invoke the method with min date time [Fact] public void PosTest1() { System.Globalization.Calendar kC = new KoreanCalendar(); System.Globalization.Calendar gC = new GregorianCalendar(); DateTime dateTime = gC.ToDateTime(1, 1, 1, 0, 0, 0, 0); int year = dateTime.Year; int era = gC.GetEra(dateTime); bool expectedValue = gC.IsLeapYear(year, era); bool actualValue; actualValue = kC.IsLeapYear(year + 2333, kC.GetEra(dateTime)); Assert.Equal(expectedValue, actualValue); } // PosTest2:Invoke the method with max date time [Fact] public void PosTest2() { System.Globalization.Calendar kC = new KoreanCalendar(); System.Globalization.Calendar gC = new GregorianCalendar(); DateTime dateTime = gC.ToDateTime(9999, 12, 31, 0, 0, 0, 0); int year = dateTime.Year; int era = gC.GetEra(dateTime); bool expectedValue = gC.IsLeapYear(year, era); bool actualValue; actualValue = kC.IsLeapYear(year + 2333, kC.GetEra(dateTime)); Assert.Equal(expectedValue, actualValue); } // PosTest3:Invoke the method with normal date time [Fact] public void PosTest3() { System.Globalization.Calendar kC = new KoreanCalendar(); System.Globalization.Calendar gC = new GregorianCalendar(); DateTime dateTime = gC.ToDateTime(1900, 2, 28, 0, 0, 0, 0); int year = dateTime.Year; int era = gC.GetEra(dateTime); bool expectedValue = gC.IsLeapYear(year, era); bool actualValue; actualValue = kC.IsLeapYear(year + 2333, kC.GetEra(dateTime)); Assert.Equal(expectedValue, actualValue); } // PosTest4:Invoke the method with leap day date time [Fact] public void PosTest4() { System.Globalization.Calendar kC = new KoreanCalendar(); System.Globalization.Calendar gC = new GregorianCalendar(); DateTime dateTime = gC.ToDateTime(1200, 2, 29, 0, 0, 0, 0); int year = dateTime.Year; int era = gC.GetEra(dateTime); bool expectedValue = gC.IsLeapYear(year, era); bool actualValue; actualValue = kC.IsLeapYear(year + 2333, kC.GetEra(dateTime)); Assert.Equal(expectedValue, actualValue); } #endregion #region Negative Test Logic // NegTest1:Invoke the method with the year outside the lower supported range [Fact] public void NegTest1() { System.Globalization.Calendar kC = new KoreanCalendar(); int year = 2333; int era = 1; bool actualValue; Assert.Throws<ArgumentOutOfRangeException>(() => { actualValue = kC.IsLeapYear(year, era); }); } // NegTest2:Invoke the method with the year outside the lower supported range [Fact] public void NegTest2() { System.Globalization.Calendar kC = new KoreanCalendar(); int year = 0; int era = 1; bool actualValue; Assert.Throws<ArgumentOutOfRangeException>(() => { actualValue = kC.IsLeapYear(year, era); }); } // NegTest3:Invoke the method with the year outside the upper supported range [Fact] public void NegTest3() { System.Globalization.Calendar kC = new KoreanCalendar(); int year = 123333; int era = 1; bool actualValue; Assert.Throws<ArgumentOutOfRangeException>(() => { actualValue = kC.IsLeapYear(year, era); }); } // NegTest4:Invoke the method with the era outside the lower supported range [Fact] public void NegTest4() { System.Globalization.Calendar kC = new KoreanCalendar(); int year = _generator.GetInt16(-55) % 9999 + 2334; int month = _generator.GetInt16(-55) % 12 + 1; // The KoreanEra is 1, however using an Era value of 0 defaults to "current era" for the calendar being used. In order to force // the ArgumentOutOfRangeException the era must not be 0 or 1 int era = -1; bool actualValue; Assert.Throws<ArgumentOutOfRangeException>(() => { actualValue = kC.IsLeapYear(year, era); }); } // NegTest5:Invoke the method with the era outside the upper supported range [Fact] public void NegTest5() { System.Globalization.Calendar kC = new KoreanCalendar(); int year = _generator.GetInt16(-55) % 9999 + 2334; int month = _generator.GetInt16(-55) % 12 + 1; int era = 2; bool actualValue; Assert.Throws<ArgumentOutOfRangeException>(() => { actualValue = kC.IsLeapYear(year, era); }); } #endregion } }
37.895425
139
0.573991
[ "MIT" ]
690486439/corefx
src/System.Globalization.Calendars/tests/KoreanCalendar/KoreanCalendarIsLeapYear.cs
5,798
C#
using RapidCMS.Core.Abstractions.Data; using RapidCMS.Core.Repositories; using RapidCMSTests.EFCore; using RapidCMSTests.Entities; using RapidCMSTests.Models.Cms; using System; using System.Collections.Generic; using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; using System.Linq; using RapidCMS.Core.Abstractions.Forms; namespace RapidCMSTests.Repositories { public class CountryRepository : MappedBaseRepository<CountryCmsModel, Country> { private readonly TestDbContext _dbContext; public CountryRepository(TestDbContext dbContext) { _dbContext = dbContext; } public override async Task DeleteAsync(string id, IParent? parent) { int.TryParse(id, out var entityId); var country = await _dbContext.Countries.FirstOrDefaultAsync(x => x.Id == entityId); _dbContext.Countries.Remove(country); await _dbContext.SaveChangesAsync(); } public override async Task<IEnumerable<CountryCmsModel>> GetAllAsync(IParent? parent, IQuery<Country> query) { var queryable = _dbContext.Countries.AsQueryable(); if (query.SearchTerm != null) { queryable = queryable.Where(x => x.Name.Contains(query.SearchTerm)); } queryable = query.ApplyDataView(queryable); queryable = query.ApplyOrder(queryable).Skip(query.Skip).Take(query.Take + 1); var results = await queryable.ToListAsync(); query.HasMoreData(results.Count > query.Take); return results.Take(query.Take).Select(x => (CountryCmsModel)x); } public override async Task<CountryCmsModel?> GetByIdAsync(string id, IParent? parent) { int.TryParse(id, out var entityId); return await _dbContext.Countries.FirstOrDefaultAsync(x => x.Id == entityId); } public override Task<CountryCmsModel> NewAsync(IParent? parent, Type? variantType = null) { return Task.FromResult(new CountryCmsModel()); } public override async Task<CountryCmsModel?> InsertAsync(IEditContext<CountryCmsModel> editContext) { var country = (Country)editContext.Entity; var entry = _dbContext.Countries.Add(country); await _dbContext.SaveChangesAsync(); return entry.Entity; } public override async Task UpdateAsync(IEditContext<CountryCmsModel> editContext) { var country = (Country)editContext.Entity; var entity = await _dbContext.Countries.FirstOrDefaultAsync(x => x.Id == country.Id); entity.Name = country.Name; _dbContext.Countries.Update(entity); await _dbContext.SaveChangesAsync(); } public override async Task<IEnumerable<CountryCmsModel>?> GetAllRelatedAsync(IRelated related, IQuery<Country> query) { if (related.Entity is PersonCmsModel person) { return await GetRelatedToGivenPersonAsync(query, person, true); } throw new InvalidOperationException(); } public override async Task<IEnumerable<CountryCmsModel>?> GetAllNonRelatedAsync(IRelated related, IQuery<Country> query) { if (related.Entity is PersonCmsModel person) { return await GetRelatedToGivenPersonAsync(query, person, false); } throw new InvalidOperationException(); } private async Task<IEnumerable<CountryCmsModel>> GetRelatedToGivenPersonAsync(IQuery<Country> query, PersonCmsModel person, bool related) { var personId = int.TryParse(person.Id, out var id) ? id : default(int?); var queryable = _dbContext.Countries.Where(x => x.People.Any(x => x.PersonId == personId) == related); if (query.SearchTerm != null) { queryable = queryable.Where(x => x.Name.Contains(query.SearchTerm)); } queryable = query.ApplyDataView(queryable); queryable = query.ApplyOrder(queryable).Skip(query.Skip).Take(query.Take + 1); var results = await queryable.ToListAsync(); query.HasMoreData(results.Count > query.Take); return results.Take(query.Take).Select(x => (CountryCmsModel)x); } public override async Task AddAsync(IRelated related, string id) { if (related.Entity is PersonCmsModel person && int.TryParse(person.Id, out var personId) && int.TryParse(id, out var countryId)) { _dbContext.PersonCountry.Add(new PersonCountry { CountryId = countryId, PersonId = personId }); await _dbContext.SaveChangesAsync(); } else { throw new InvalidOperationException(); } } public override async Task RemoveAsync(IRelated related, string id) { if (related.Entity is PersonCmsModel person && int.TryParse(person.Id, out var personId) && int.TryParse(id, out var countryId)) { _dbContext.PersonCountry.Remove(new PersonCountry { CountryId = countryId, PersonId = personId }); await _dbContext.SaveChangesAsync(); } else { throw new InvalidOperationException(); } } } }
34.493902
145
0.607389
[ "MIT" ]
ThomasBleijendaal/RapidCMS-Tests
RapidCMSTests/RapidCMSTests/Repositories/CountryRepository.cs
5,659
C#
using System.Collections.Generic; using System.Security.AccessControl; namespace System.IO.Abstractions { /// <inheritdoc cref="IDirectoryInfo"/> [Serializable] public abstract class DirectoryInfoBase : FileSystemInfoBase, IDirectoryInfo { /// <inheritdoc /> protected DirectoryInfoBase(IFileSystem fileSystem) : base(fileSystem) { } [Obsolete("This constructor only exists to support mocking libraries.", error: true)] internal DirectoryInfoBase() { } /// <inheritdoc cref="IDirectoryInfo.Create()"/> public abstract void Create(); /// <inheritdoc cref="IDirectoryInfo.Create(DirectorySecurity)"/> public abstract void Create(DirectorySecurity directorySecurity); /// <inheritdoc cref="IDirectoryInfo.CreateSubdirectory(string)"/> public abstract IDirectoryInfo CreateSubdirectory(string path); /// <inheritdoc cref="IDirectoryInfo.Delete(bool)"/> public abstract void Delete(bool recursive); /// <inheritdoc cref="IDirectoryInfo.EnumerateDirectories()"/> public abstract IEnumerable<IDirectoryInfo> EnumerateDirectories(); /// <inheritdoc cref="IDirectoryInfo.EnumerateDirectories(string)"/> public abstract IEnumerable<IDirectoryInfo> EnumerateDirectories(string searchPattern); /// <inheritdoc cref="IDirectoryInfo.EnumerateDirectories(string,SearchOption)"/> public abstract IEnumerable<IDirectoryInfo> EnumerateDirectories(string searchPattern, SearchOption searchOption); #if FEATURE_ENUMERATION_OPTIONS /// <inheritdoc cref="IDirectoryInfo.EnumerateDirectories(string,EnumerationOptions)"/> public abstract IEnumerable<IDirectoryInfo> EnumerateDirectories(string searchPattern, EnumerationOptions enumerationOptions); #endif /// <inheritdoc cref="IDirectoryInfo.EnumerateFiles()"/> public abstract IEnumerable<IFileInfo> EnumerateFiles(); /// <inheritdoc cref="IDirectoryInfo.EnumerateFiles(string)"/> public abstract IEnumerable<IFileInfo> EnumerateFiles(string searchPattern); /// <inheritdoc cref="IDirectoryInfo.EnumerateFiles(string,SearchOption)"/> public abstract IEnumerable<IFileInfo> EnumerateFiles(string searchPattern, SearchOption searchOption); #if FEATURE_ENUMERATION_OPTIONS /// <inheritdoc cref="IDirectoryInfo.EnumerateFiles(string,EnumerationOptions)"/> public abstract IEnumerable<IFileInfo> EnumerateFiles(string searchPattern, EnumerationOptions enumerationOptions); #endif /// <inheritdoc cref="IDirectoryInfo.EnumerateFileSystemInfos()"/> public abstract IEnumerable<IFileSystemInfo> EnumerateFileSystemInfos(); /// <inheritdoc cref="IDirectoryInfo.EnumerateFileSystemInfos(string)"/> public abstract IEnumerable<IFileSystemInfo> EnumerateFileSystemInfos(string searchPattern); /// <inheritdoc cref="IDirectoryInfo.EnumerateFileSystemInfos(string,SearchOption)"/> public abstract IEnumerable<IFileSystemInfo> EnumerateFileSystemInfos(string searchPattern, SearchOption searchOption); #if FEATURE_ENUMERATION_OPTIONS /// <inheritdoc cref="IDirectoryInfo.EnumerateFileSystemInfos(string,EnumerationOptions)"/> public abstract IEnumerable<IFileSystemInfo> EnumerateFileSystemInfos(string searchPattern, EnumerationOptions enumerationOptions); #endif /// <inheritdoc cref="IDirectoryInfo.GetAccessControl()"/> public abstract DirectorySecurity GetAccessControl(); /// <inheritdoc cref="IDirectoryInfo.GetAccessControl(AccessControlSections)"/> public abstract DirectorySecurity GetAccessControl(AccessControlSections includeSections); /// <inheritdoc cref="IDirectoryInfo.GetDirectories()"/> public abstract IDirectoryInfo[] GetDirectories(); /// <inheritdoc cref="IDirectoryInfo.GetDirectories(string)"/> public abstract IDirectoryInfo[] GetDirectories(string searchPattern); /// <inheritdoc cref="IDirectoryInfo.GetDirectories(string,SearchOption)"/> public abstract IDirectoryInfo[] GetDirectories(string searchPattern, SearchOption searchOption); #if FEATURE_ENUMERATION_OPTIONS /// <inheritdoc cref="IDirectoryInfo.GetDirectories(string,EnumerationOptions)"/> public abstract IDirectoryInfo[] GetDirectories(string searchPattern, EnumerationOptions enumerationOptions); #endif /// <inheritdoc cref="IDirectoryInfo.GetFiles(string)"/> public abstract IFileInfo[] GetFiles(); /// <inheritdoc cref="IDirectoryInfo.GetFiles(string)"/> public abstract IFileInfo[] GetFiles(string searchPattern); /// <inheritdoc cref="IDirectoryInfo.GetFiles(string,SearchOption)"/> public abstract IFileInfo[] GetFiles(string searchPattern, SearchOption searchOption); #if FEATURE_ENUMERATION_OPTIONS /// <inheritdoc cref="IDirectoryInfo.GetFiles(string,EnumerationOptions)"/> public abstract IFileInfo[] GetFiles(string searchPattern, EnumerationOptions enumerationOptions); #endif /// <inheritdoc cref="IDirectoryInfo.GetFileSystemInfos()"/> public abstract IFileSystemInfo[] GetFileSystemInfos(); /// <inheritdoc cref="IDirectoryInfo.GetFileSystemInfos(string)"/> public abstract IFileSystemInfo[] GetFileSystemInfos(string searchPattern); /// <inheritdoc cref="IDirectoryInfo.GetFileSystemInfos(string,SearchOption)"/> public abstract IFileSystemInfo[] GetFileSystemInfos(string searchPattern, SearchOption searchOption); #if FEATURE_ENUMERATION_OPTIONS /// <inheritdoc cref="IDirectoryInfo.GetFileSystemInfos(string,EnumerationOptions)"/> public abstract IFileSystemInfo[] GetFileSystemInfos(string searchPattern, EnumerationOptions enumerationOptions); #endif /// <inheritdoc cref="IDirectoryInfo.MoveTo"/> public abstract void MoveTo(string destDirName); /// <inheritdoc cref="IDirectoryInfo.SetAccessControl"/> public abstract void SetAccessControl(DirectorySecurity directorySecurity); /// <inheritdoc cref="IDirectoryInfo.Parent"/> public abstract IDirectoryInfo Parent { get; } /// <inheritdoc cref="IDirectoryInfo.Root"/> public abstract IDirectoryInfo Root { get; } /// <inheritdoc /> public static implicit operator DirectoryInfoBase(DirectoryInfo directoryInfo) { if (directoryInfo == null) { return null; } return new DirectoryInfoWrapper(new FileSystem(), directoryInfo); } } }
46.524476
139
0.7317
[ "MIT" ]
BrianMcBrayer/System.IO.Abstractions
src/System.IO.Abstractions/DirectoryInfoBase.cs
6,655
C#
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using Windows.Devices.Input; using Windows.Foundation; using Windows.UI.Input; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Controls.Primitives; using Windows.UI.Xaml.Documents; using Windows.UI.Xaml.Input; using Uno.UI.Samples.Controls; using V = System.Collections.Generic.Dictionary<string, object>; namespace UITests.Shared.Windows_UI_Input.PointersTests { [SampleControlInfo("Pointers", "Sequence")] public sealed partial class EventsSequences : Page { private readonly List<(object evt, RoutedEventArgs args)> _tapResult = new List<(object, RoutedEventArgs)>(); private readonly List<(object evt, RoutedEventArgs args)> _clickResult = new List<(object, RoutedEventArgs)>(); private readonly List<(object evt, RoutedEventArgs args)> _translatedTapResult = new List<(object, RoutedEventArgs)>(); private readonly List<(object evt, RoutedEventArgs args)> _translatedClickResult = new List<(object, RoutedEventArgs)>(); private readonly List<(object evt, RoutedEventArgs args)> _hyperlinkResult = new List<(object, RoutedEventArgs)>(); private readonly List<(object evt, RoutedEventArgs args)> _listViewResult = new List<(object, RoutedEventArgs)>(); private static readonly object ClickEvent = new object(); [Flags] private enum EventsKind { Pointers = 1, Manipulation = 2, Gestures = 4, Click = 8 } public EventsSequences() { this.InitializeComponent(); SetupEvents(TestTapTarget, _tapResult, EventsKind.Pointers | EventsKind.Manipulation | EventsKind.Gestures); SetupEvents(TestClickTarget, _clickResult, EventsKind.Pointers | EventsKind.Manipulation | EventsKind.Gestures | EventsKind.Click); SetupEvents(TestTranslatedTapTarget, _translatedTapResult, EventsKind.Pointers | EventsKind.Manipulation | EventsKind.Gestures); SetupEvents(TestTranslatedClickTarget, _translatedClickResult, EventsKind.Pointers | EventsKind.Manipulation | EventsKind.Gestures | EventsKind.Click); SetupEvents(TestHyperlinkTarget, _hyperlinkResult, EventsKind.Pointers | EventsKind.Gestures); SetupEvents(TestHyperlinkInner, _hyperlinkResult, EventsKind.Click); SetupEvents(TestListViewTarget, _listViewResult, EventsKind.Pointers | EventsKind.Gestures | EventsKind.Click); _pointerType.ItemsSource = Enum.GetNames(typeof(PointerDeviceType)); // Values for automated tests #if __ANDROID__ || __IOS__ _pointerType.SelectedValue = PointerDeviceType.Touch.ToString(); #else _pointerType.SelectedValue = PointerDeviceType.Mouse.ToString(); #endif } #if __IOS__ // On iOS pen is handled exactly as if it was a finger ... private bool PenSupportsHover = false; #else private bool PenSupportsHover = true; #endif private PointerDeviceType PointerType => (PointerDeviceType)Enum.Parse(typeof(PointerDeviceType), _pointerType.SelectedValue.ToString()); private void ResetTapTest(object sender, RoutedEventArgs e) => Clear(_tapResult, TestTapResult); private void ValidateTapTest(object sender, RoutedEventArgs e) { var args = new EventSequenceValidator(_tapResult); var result = false; switch (PointerType) { case PointerDeviceType.Mouse: case PointerDeviceType.Pen when PenSupportsHover: result = args.One(PointerEnteredEvent) && args.Some(PointerMovedEvent) // Could be "Maybe" but WASM UI test generates it and we want to validate it && args.One(PointerPressedEvent) && args.MaybeSome(PointerMovedEvent) && args.One(PointerReleasedEvent) && args.One(TappedEvent) && args.MaybeSome(PointerMovedEvent) && args.One(PointerExitedEvent) && args.End(); break; case PointerDeviceType.Pen: case PointerDeviceType.Touch: result = args.One(PointerEnteredEvent) && args.One(PointerPressedEvent) && args.MaybeSome(PointerMovedEvent) && args.One(PointerReleasedEvent) && args.One(TappedEvent) && args.One(PointerExitedEvent) && args.End(); break; } TestTapResult.Text = result ? "SUCCESS" : "FAILED"; } private void ResetClickTest(object sender, RoutedEventArgs e) => Clear(_clickResult, TestClickResult); private void ValidateClickTest(object sender, RoutedEventArgs e) { // Pointer pressed and released are handled by the ButtonBase var args = new EventSequenceValidator(_clickResult); var result = false; switch (PointerType) { case PointerDeviceType.Mouse: case PointerDeviceType.Pen when PenSupportsHover: result = args.One(PointerEnteredEvent) && args.Some(PointerMovedEvent) // Could be "Maybe" but WASM UI test generates it and we want to validate it && args.Click() && args.One(PointerCaptureLostEvent) && args.One(TappedEvent) && args.MaybeSome(PointerMovedEvent) && args.One(PointerExitedEvent) && args.End(); break; case PointerDeviceType.Pen: case PointerDeviceType.Touch: result = args.One(PointerEnteredEvent) && args.MaybeSome(PointerMovedEvent) && args.Click() && args.One(PointerCaptureLostEvent) && args.One(TappedEvent) && args.One(PointerExitedEvent) && args.End(); break; } TestClickResult.Text = result ? "SUCCESS" : "FAILED"; } private void ResetTranslatedTapTest(object sender, RoutedEventArgs e) => Clear(_translatedTapResult, TestTranslatedTapResult); private void ValidateTranslatedTapTest(object sender, RoutedEventArgs e) { var args = new EventSequenceValidator(_translatedTapResult); var result = false; switch (PointerType) { case PointerDeviceType.Mouse: case PointerDeviceType.Pen when PenSupportsHover: result = args.One(PointerEnteredEvent) && args.MaybeSome(PointerMovedEvent) && args.One(PointerPressedEvent) && args.One(ManipulationStartingEvent) && args.Some(PointerMovedEvent) && args.One(ManipulationStartedEvent) && args.Some(PointerMovedEvent, ManipulationDeltaEvent) // && args.One(TappedEvent) // No tap as we moved too far && args.One(PointerReleasedEvent) && args.Some(ManipulationCompletedEvent) && args.MaybeSome(PointerMovedEvent) && args.One(PointerExitedEvent) && args.End(); break; case PointerDeviceType.Pen: case PointerDeviceType.Touch: result = args.One(PointerEnteredEvent) && args.One(PointerPressedEvent) && args.One(ManipulationStartingEvent) && args.Some(PointerMovedEvent) && args.One(ManipulationStartedEvent) && args.Some(PointerMovedEvent, ManipulationDeltaEvent) // && args.One(TappedEvent) // No tap as we moved too far && args.One(PointerReleasedEvent) && args.Some(ManipulationCompletedEvent) && args.One(PointerExitedEvent) && args.End(); break; } TestTranslatedTapResult.Text = result ? "SUCCESS" : "FAILED"; } private void ResetTranslatedClickTest(object sender, RoutedEventArgs e) => Clear(_translatedClickResult, TestTranslatedClickResult); private void ValidateTranslatedClickTest(object sender, RoutedEventArgs e) { // Pointer pressed and released are handled by the ButtonBase var args = new EventSequenceValidator(_translatedClickResult); var result = false; switch (PointerType) { case PointerDeviceType.Mouse: case PointerDeviceType.Pen when PenSupportsHover: result = args.One(PointerEnteredEvent) && args.MaybeSome(PointerMovedEvent) && args.One(ManipulationStartingEvent) && args.Some(PointerMovedEvent) && args.One(ManipulationStartedEvent) && args.Some(PointerMovedEvent, ManipulationDeltaEvent) && args.Click() && args.One(PointerCaptureLostEvent) // && args.One(TappedEvent) // No tap as we moved too far && args.Some(ManipulationCompletedEvent) && args.MaybeSome(PointerMovedEvent) && args.One(PointerExitedEvent) && args.End(); break; case PointerDeviceType.Pen: case PointerDeviceType.Touch: result = args.One(PointerEnteredEvent) && args.One(ManipulationStartingEvent) && args.Some(PointerMovedEvent) && args.One(ManipulationStartedEvent) && args.Some(PointerMovedEvent, ManipulationDeltaEvent) && args.Click() && args.One(PointerCaptureLostEvent) // && args.One(TappedEvent) // No tap as we moved too far && args.Some(ManipulationCompletedEvent) && args.One(PointerExitedEvent) && args.End(); break; } TestTranslatedClickResult.Text = result ? "SUCCESS" : "FAILED"; } private void ResetHyperlinkTest(object sender, RoutedEventArgs e) => Clear(_hyperlinkResult, TestHyperlinkResult); private void ValidateHyperlinkTest(object sender, RoutedEventArgs e) { // We subscribed at booth, the TextBlock (Pointers and Gestures) and the Hyperlink (Click) // Pointer pressed is handled by the TextBlock, but NOT the released // We MUST not receive a Tapped (when clicking on an hyperlink) neither a CaptureLost var args = new EventSequenceValidator(_hyperlinkResult); var result = false; switch (PointerType) { case PointerDeviceType.Mouse: case PointerDeviceType.Pen when PenSupportsHover: result = args.One(PointerEnteredEvent) && args.Some(PointerMovedEvent) // Could be "Maybe" but WASM UI test generates it and we want to validate it #if NETFX_CORE && args.One(PointerReleasedEvent) && args.Click() #else && args.Click() && args.One(PointerReleasedEvent) #endif && args.MaybeSome(PointerMovedEvent) && args.One(PointerExitedEvent) && args.End(); break; case PointerDeviceType.Pen: case PointerDeviceType.Touch: #if __IOS__ // KNOWN ISSUE: // On iOS as the Entered/Exited are generated on Pressed/Released, which are Handled by the Hyperlink, // we do not receive the expected Entered/Exited on parent control. // As a side effect we will also not receive the Tap as it is an interpretation of those missing Pointer events. result = args.Click() && args.End(); #else result = args.One(PointerEnteredEvent) && args.MaybeSome(PointerMovedEvent) #if NETFX_CORE && args.One(PointerReleasedEvent) && args.Click() #elif __WASM__ // KNOWN ISSUE: We don't get a released if not previously pressed, but pressed are muted by the Hyperlink which is a UIElement on wasm && args.Click() #else && args.Click() && args.One(PointerReleasedEvent) #endif && args.One(PointerExitedEvent) && args.End(); #endif break; } TestHyperlinkResult.Text = result ? "SUCCESS" : "FAILED"; } private void ResetListViewTest(object sender, RoutedEventArgs e) => Clear(_listViewResult, TestListViewResult); private void ValidateListViewTest(object sender, RoutedEventArgs e) { // We subscribed at booth, the TextBlock (Pointers and Gestures) and the Hyperlink (Click) // Pointer pressed and released are handled by the TextBlock var args = new EventSequenceValidator(_listViewResult); var result = false; switch (PointerType) { case PointerDeviceType.Mouse: case PointerDeviceType.Pen when PenSupportsHover: result = args.One(PointerEnteredEvent) && args.Some(PointerMovedEvent) // Could be "Maybe" but WASM UI test generate it and we want to validate it && args.Click() && args.One(TappedEvent) && args.MaybeSome(PointerMovedEvent) && args.MaybeOne(PointerExitedEvent) // This should be "One" (Not maybe) ... but the ListView is a complex control && args.End(); break; case PointerDeviceType.Pen: case PointerDeviceType.Touch: result = args.MaybeOne(PointerEnteredEvent) // This should be "One" (Not maybe) ... but the ListView is a complex control && args.MaybeSome(PointerMovedEvent) && args.Click() && args.MaybeOne(TappedEvent) // This should be "One" (Not maybe) ... but the ListView is a complex control && args.MaybeOne(PointerExitedEvent) // This should be "One" (Not maybe) ... but the ListView is a complex control && args.End(); break; } TestListViewResult.Text = result ? "SUCCESS" : "FAILED"; } #region Common helpers private void Clear(IList events, TextBlock result) { events.Clear(); result.Text = "** no result **"; Output.Text = ""; } private void SetupEvents(DependencyObject target, IList<(object, RoutedEventArgs)> events, EventsKind kind, string name = null, bool captureOnPress = false) { name = name ?? (target as FrameworkElement)?.Name ?? $"{target.GetType().Name}:{target.GetHashCode():X6}"; if (kind.HasFlag(EventsKind.Pointers) && target is UIElement pointerTarget) { pointerTarget.PointerEntered += (snd, e) => OnPointerEvent(PointerEnteredEvent, "Entered", e); pointerTarget.PointerPressed += (snd, e) => { OnPointerEvent(PointerPressedEvent, "Pressed", e); if (captureOnPress) { var captured = pointerTarget.CapturePointer(e.Pointer); Log($"[{name}] Captured: {captured}"); } }; pointerTarget.PointerMoved += (snd, e) => OnPointerEvent(PointerMovedEvent, "Moved", e); pointerTarget.PointerReleased += (snd, e) => OnPointerEvent(PointerReleasedEvent, "Released", e); pointerTarget.PointerCanceled += (snd, e) => OnPointerEvent(PointerCanceledEvent, "Canceled", e); pointerTarget.PointerExited += (snd, e) => OnPointerEvent(PointerExitedEvent, "Exited", e); pointerTarget.PointerCaptureLost += (snd, e) => OnPointerEvent(PointerCaptureLostEvent, "CaptureLost", e); } if (kind.HasFlag(EventsKind.Manipulation) && target is UIElement manipulationTarget) { manipulationTarget.ManipulationStarting += (snd, e) => OnEvt(ManipulationStartingEvent, "ManipStarting", e, () => e.Mode); manipulationTarget.ManipulationStarted += (snd, e) => OnEvt(ManipulationStartedEvent, "ManipStarted", e, () => e.Position, () => e.PointerDeviceType, () => e.Cumulative); manipulationTarget.ManipulationDelta += (snd, e) => OnEvt(ManipulationDeltaEvent, "ManipDelta", e, () => e.Position, () => e.PointerDeviceType, () => e.Delta, () => e.Cumulative); manipulationTarget.ManipulationInertiaStarting += (snd, e) => OnEvt(ManipulationInertiaStartingEvent, "ManipInertia", e, () => e.PointerDeviceType, () => e.Delta, () => e.Cumulative, () => e.Velocities); manipulationTarget.ManipulationCompleted += (snd, e) => OnEvt(ManipulationCompletedEvent, "ManipCompleted", e, () => e.Position, () => e.PointerDeviceType, () => e.Cumulative); } if (kind.HasFlag(EventsKind.Gestures) && target is UIElement gestureTarget) { // Those events are built using the GestureRecognizer gestureTarget.Tapped += (snd, e) => OnEvent(TappedEvent, "Tapped", e); gestureTarget.DoubleTapped += (snd, e) => OnEvent(DoubleTappedEvent, "DoubleTapped", e); } if (kind.HasFlag(EventsKind.Click)) { if (target is ButtonBase button) button.Click += (snd, e) => OnEvent(ClickEvent, "Click", e); if (target is Hyperlink hyperlink) hyperlink.Click += (snd, e) => OnEvent(ClickEvent, "Click", e); if (target is ListViewBase listView) listView.ItemClick += (snd, e) => OnEvent(ClickEvent, "Click", e); } void OnEvent(object evt, string evtName, RoutedEventArgs e, string extra = null) { events.Add((evt, e)); Log($"[{name}] {evtName} {extra}"); } void OnPointerEvent(RoutedEvent evt, string evtName, PointerRoutedEventArgs e) { events.Add((evt, e)); var point = e.GetCurrentPoint(this); Log($"[{name}] {evtName}: id={e.Pointer.PointerId} " + $"| frame={point.FrameId}" + $"| type={e.Pointer.PointerDeviceType} " + $"| position={point.Position} " + $"| rawPosition={point.RawPosition} " + $"| inContact={point.IsInContact} " + $"| inRange={point.Properties.IsInRange} " + $"| primary={point.Properties.IsPrimary}" + $"| intermediates={e.GetIntermediatePoints(this)?.Count.ToString() ?? "null"} "); } void OnEvt(object evt, string evtName, RoutedEventArgs e, params Expression<Func<object>>[] values) { events.Add((evt, e)); Log($"[{name}] {evtName}: {string.Join("| ", values.Select(v => $"{((v.Body as UnaryExpression)?.Operand as MemberExpression)?.Member.Name ?? "??"}: {v.Compile()()}"))}"); } } private void Log(string message) { System.Diagnostics.Debug.WriteLine(message); Output.Text += message + "\r\n"; } private class EventSequenceValidator { private readonly IList<(object evt, RoutedEventArgs args)> _args; private int _index = 0; public EventSequenceValidator(IList<(object evt, RoutedEventArgs args)> args) { _args = args; } /// <summary> /// [1..1] /// </summary> public bool Click() => _index < _args.Count && _args[_index++].evt == ClickEvent; /// <summary> /// [1..1] /// </summary> public bool One(params RoutedEvent[] evt) => _index < _args.Count && evt.Contains(_args[_index++].evt); /// <summary> /// [1..*] /// </summary> public bool Some(params RoutedEvent[] evt) => One(evt) && MaybeSome(evt); /// <summary> /// [0..1] /// </summary> public bool MaybeOne(RoutedEvent evt) { if (_index < _args.Count && _args[_index].evt == evt) { ++_index; } return true; } /// <summary> /// [0..*] /// </summary> public bool MaybeSome(params RoutedEvent[] evt) { while (_index < _args.Count && evt.Contains(_args[_index].evt)) { ++_index; } return true; } public bool End() => _index >= _args.Count; } #endregion } }
37.187891
207
0.691574
[ "Apache-2.0" ]
06needhamt/uno
src/SamplesApp/UITests.Shared/Windows_UI_Input/PointersTests/EventsSequences.xaml.cs
17,815
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace owdl.Properties { [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0")] internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase { private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings()))); public static Settings Default { get { return defaultInstance; } } } }
34.16129
151
0.578848
[ "MIT" ]
hexadezi/owdl
owdl/Properties/Settings.Designer.cs
1,061
C#
using Lyn.Types.Fundamental; namespace Lyn.Protocol.Bolt3.Types { public class Keyset { public Keyset(PublicKey revocationKey, PublicKey localHtlcKey, PublicKey remoteHtlcKey, PublicKey localDelayedPaymentKey, PublicKey remotePaymentKey) { RevocationKey = revocationKey; LocalHtlcKey = localHtlcKey; RemoteHtlcKey = remoteHtlcKey; LocalDelayedPaymentKey = localDelayedPaymentKey; RemotePaymentKey = remotePaymentKey; } public PublicKey RevocationKey { get; set; } public PublicKey LocalHtlcKey { get; set; } public PublicKey RemoteHtlcKey { get; set; } public PublicKey LocalDelayedPaymentKey { get; set; } public PublicKey RemotePaymentKey { get; set; } }; }
36.272727
157
0.672932
[ "MIT" ]
block-core/lyn
src/Lyn.Protocol/Bolt3/Types/Keyset.cs
800
C#
namespace Camunda.Api.Client.History { public class CleanableProcessInstanceReport: CleanableProcessInstanceReportCount { /// <summary> /// Sort the results by a given criterion. A valid value is activityId. Must be used in conjunction with the sortOrder parameter. /// </summary> public CleanableProcessInstanceReportSorting SortBy; /// <summary> /// Sort the results in a given order. Values may be asc for ascending order or desc for descending order. Must be used in conjunction with the sortBy parameter. /// </summary> public SortOrder SortOrder; /// <summary> /// Pagination of results. Specifies the index of the first result to return. /// </summary> public int? FirstResult; /// <summary> /// Pagination of results. Specifies the maximum number of results to return. Will return less results if there are no more results left. /// </summary> public int? MaxResults; } public enum CleanableProcessInstanceReportSorting { Finished } }
35.741935
169
0.657942
[ "MIT" ]
Maicelicious/Camunda.Api.Client
Camunda.Api.Client/History/CleanableProcessInstanceReport.cs
1,110
C#
// (c) Eric Vander Wal, 2017 All rights reserved. // Custom Action by DumbGameDev // www.dumbgamedev.com using UnityEngine; using TMPro; namespace HutongGames.PlayMaker.Actions { [ActionCategory("TextMesh Pro UGUI Basic")] [Tooltip("Set Text Mesh Pro input field component.")] public class setTextmeshProInputText : FsmStateAction { [RequiredField] [CheckForComponent(typeof(TMP_InputField))] [Tooltip("Textmesh Pro Input component is required.")] public FsmOwnerDefault gameObject; [TitleAttribute("Textmesh Pro Text")] [Tooltip("The text for Textmesh Pro.")] public FsmString textString; [Tooltip("Check this box to preform this action every frame.")] public FsmBool everyFrame; private TMP_InputField _inputField; public override void Reset() { gameObject = null; textString = null; everyFrame = false; } public override void OnEnter() { var go = Fsm.GetOwnerDefaultTarget(gameObject); _inputField = go.GetComponent<TMP_InputField>(); SetMeshPro(); if (!everyFrame.Value) { Finish(); } } public override void OnUpdate() { if (everyFrame.Value) { SetMeshPro(); } } private void SetMeshPro() { var go = Fsm.GetOwnerDefaultTarget(gameObject); if (go == null) { return; } _inputField.text = textString.Value; } } }
24.985075
71
0.554361
[ "MIT" ]
H1NIVyrus/BRKDWNSANDBRKUPS
Assets/PlayMaker Custom Actions/Basic/setTextmeshProInputText.cs
1,676
C#
using System; using System.Linq; using System.Web; using System.Web.UI; using Microsoft.AspNet.Identity; using Microsoft.AspNet.Identity.Owin; using Owin; using ASP.NETWebForms.Models; namespace ASP.NETWebForms.Account { public partial class Register : Page { protected void CreateUser_Click(object sender, EventArgs e) { var manager = Context.GetOwinContext().GetUserManager<ApplicationUserManager>(); var signInManager = Context.GetOwinContext().Get<ApplicationSignInManager>(); var user = new ApplicationUser() { UserName = Email.Text, Email = Email.Text }; IdentityResult result = manager.Create(user, Password.Text); if (result.Succeeded) { // For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771 //string code = manager.GenerateEmailConfirmationToken(user.Id); //string callbackUrl = IdentityHelper.GetUserConfirmationRedirectUrl(code, user.Id, Request); //manager.SendEmail(user.Id, "Confirm your account", "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>."); signInManager.SignIn( user, isPersistent: false, rememberBrowser: false); IdentityHelper.RedirectToReturnUrl(Request.QueryString["ReturnUrl"], Response); } else { ErrorMessage.Text = result.Errors.FirstOrDefault(); } } } }
43.833333
155
0.650824
[ "MIT" ]
todor-enikov/TelerikAcademy
ASP .NET Web Forms/1.Introduction to ASP.NET/1.Few Web applications/ASP.NETWebForms/Account/Register.aspx.cs
1,580
C#
using Microsoft.EntityFrameworkCore; namespace fy21_simplemtapp.Model { public class Subscription { public bool IsActive { get; set; } = false; public string Id { get; set; } = "1CD21362-9CED-42EB-8958-F965F67C328F"; public string PartitionKey { get; set; } = "CEE"; } public class DatabaseContext : DbContext { public DbSet<Subscription> Subscriptions{ get; set; } public DatabaseContext(DbContextOptions<DatabaseContext> context) : base(context) { } protected override void OnModelCreating(ModelBuilder modelBuilder) { base.OnModelCreating(modelBuilder); modelBuilder.HasDefaultContainer("aad"); modelBuilder.Entity<Subscription>().ToContainer("aad").HasPartitionKey(o=>o.PartitionKey).HasKey(o=>o.Id); } } }
33.56
118
0.661502
[ "MIT" ]
ceeidpnotes/ceeidpnotes
Demos-Src/CS/NOT_FINISHED/TKFY22-step2-mtapp-cosmos/TKFY22-step2-mtapp-cosmos/Model/Subscription.cs
841
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.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.Logging; namespace Microsoft.AspNetCore.Http.Connections.Client.Internal { internal class LoggingHttpMessageHandler : DelegatingHandler { private readonly ILogger<LoggingHttpMessageHandler> _logger; public LoggingHttpMessageHandler(HttpMessageHandler inner, ILoggerFactory loggerFactory) : base(inner) { if (loggerFactory == null) { throw new ArgumentNullException(nameof(loggerFactory)); } _logger = loggerFactory.CreateLogger<LoggingHttpMessageHandler>(); } protected override async Task<HttpResponseMessage> SendAsync( HttpRequestMessage request, CancellationToken cancellationToken ) { Log.SendingHttpRequest(_logger, request.Method, request.RequestUri!); var response = await base.SendAsync(request, cancellationToken); if (!response.IsSuccessStatusCode) { Log.UnsuccessfulHttpResponse( _logger, response.StatusCode, request.Method, request.RequestUri! ); } return response; } private static class Log { private static readonly Action< ILogger, HttpMethod, Uri, Exception? > _sendingHttpRequest = LoggerMessage.Define<HttpMethod, Uri>( LogLevel.Trace, new EventId(1, "SendingHttpRequest"), "Sending HTTP request {RequestMethod} '{RequestUrl}'." ); private static readonly Action< ILogger, int, HttpMethod, Uri, Exception? > _unsuccessfulHttpResponse = LoggerMessage.Define<int, HttpMethod, Uri>( LogLevel.Warning, new EventId(2, "UnsuccessfulHttpResponse"), "Unsuccessful HTTP response {StatusCode} return from {RequestMethod} '{RequestUrl}'." ); public static void SendingHttpRequest( ILogger logger, HttpMethod requestMethod, Uri requestUrl ) { _sendingHttpRequest(logger, requestMethod, requestUrl, null); } public static void UnsuccessfulHttpResponse( ILogger logger, HttpStatusCode statusCode, HttpMethod requestMethod, Uri requestUrl ) { _unsuccessfulHttpResponse(logger, (int)statusCode, requestMethod, requestUrl, null); } } } }
32.21875
111
0.563207
[ "Apache-2.0" ]
belav/aspnetcore
src/SignalR/clients/csharp/Http.Connections.Client/src/Internal/LoggingHttpMessageHandler.cs
3,093
C#
/* * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the datapipeline-2012-10-29.normal.json service model. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Text; using System.Xml.Serialization; using Amazon.DataPipeline.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; using ThirdParty.Json.LitJson; namespace Amazon.DataPipeline.Model.Internal.MarshallTransformations { /// <summary> /// ActivatePipeline Request Marshaller /// </summary> public class ActivatePipelineRequestMarshaller : IMarshaller<IRequest, ActivatePipelineRequest> , IMarshaller<IRequest,AmazonWebServiceRequest> { /// <summary> /// Marshaller the request object to the HTTP request. /// </summary> /// <param name="input"></param> /// <returns></returns> public IRequest Marshall(AmazonWebServiceRequest input) { return this.Marshall((ActivatePipelineRequest)input); } /// <summary> /// Marshaller the request object to the HTTP request. /// </summary> /// <param name="publicRequest"></param> /// <returns></returns> public IRequest Marshall(ActivatePipelineRequest publicRequest) { IRequest request = new DefaultRequest(publicRequest, "Amazon.DataPipeline"); string target = "DataPipeline.ActivatePipeline"; request.Headers["X-Amz-Target"] = target; request.Headers["Content-Type"] = "application/x-amz-json-1.1"; request.Headers[Amazon.Util.HeaderKeys.XAmzApiVersion] = "2012-10-29"; request.HttpMethod = "POST"; request.ResourcePath = "/"; request.MarshallerVersion = 2; using (StringWriter stringWriter = new StringWriter(CultureInfo.InvariantCulture)) { JsonWriter writer = new JsonWriter(stringWriter); writer.WriteObjectStart(); var context = new JsonMarshallerContext(request, writer); if(publicRequest.IsSetParameterValues()) { context.Writer.WritePropertyName("parameterValues"); context.Writer.WriteArrayStart(); foreach(var publicRequestParameterValuesListValue in publicRequest.ParameterValues) { context.Writer.WriteObjectStart(); var marshaller = ParameterValueMarshaller.Instance; marshaller.Marshall(publicRequestParameterValuesListValue, context); context.Writer.WriteObjectEnd(); } context.Writer.WriteArrayEnd(); } if(publicRequest.IsSetPipelineId()) { context.Writer.WritePropertyName("pipelineId"); context.Writer.Write(publicRequest.PipelineId); } if(publicRequest.IsSetStartTimestamp()) { context.Writer.WritePropertyName("startTimestamp"); context.Writer.Write(publicRequest.StartTimestamp); } writer.WriteObjectEnd(); string snippet = stringWriter.ToString(); request.Content = System.Text.Encoding.UTF8.GetBytes(snippet); } return request; } private static ActivatePipelineRequestMarshaller _instance = new ActivatePipelineRequestMarshaller(); internal static ActivatePipelineRequestMarshaller GetInstance() { return _instance; } /// <summary> /// Gets the singleton. /// </summary> public static ActivatePipelineRequestMarshaller Instance { get { return _instance; } } } }
36.708661
147
0.610682
[ "Apache-2.0" ]
DetlefGolze/aws-sdk-net
sdk/src/Services/DataPipeline/Generated/Model/Internal/MarshallTransformations/ActivatePipelineRequestMarshaller.cs
4,662
C#
namespace Stateless.Web { using System; public class StateMachineContent { public string Id { get; set; } = Guid.NewGuid().ToString("N"); public string Key { get; set; } public string ContentType { get; set; } public long Size { get; set; } public DateTime Created { get; set; } public DateTime Updated { get; set; } } }
19.6
70
0.576531
[ "Apache-2.0" ]
geffzhang/stateless-web
src/Stateless.Web/StateMachineContent.cs
394
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace FrameworkQ.Rules.Lang { public class Operand : Expression { public Operand() { PrepareOperations(); } private void PrepareOperations() { _operations = new Dictionary<string, ResolveDelegate>(); _operations["+"] = this.ValidateAndOperate; _operations["-"] = this.ValidateAndOperate; _operations["="] = this.ValidateAndOperate; _operations[">"]= this.ValidateAndOperate; _operations[">="] = this.ValidateAndOperate; _operations["<"] = this.ValidateAndOperate; _operations["<="] = this.ValidateAndOperate; _operations["*"]= this.ValidateAndOperate; _operations["/"]= this.ValidateAndOperate; } public override string Name => "op"; public override bool HasChildren => false; public override void ReadFromSerializer(ILangSerializer serializer) { throw new NotImplementedException(); } public override void WriteToSerializer(ILangSerializer serializer) { throw new NotImplementedException(); } public IExpression LeftExpression { get; set; } public IExpression RightExpression { get; set; } public delegate Variable ResolveDelegate (IExpression left, IExpression right, string op); private Dictionary<string, ResolveDelegate> _operations = null; public string Operator { get; set; } public override Variable Resolve() { if (_operations.ContainsKey(this.Operator)) { return _operations[this.Operator].Invoke(this.LeftExpression, this.RightExpression, this.Operator); } else { throw new InvalidOperationException("Invalid op code in expression"); } throw new InvalidOperationException("Invalid op code in expression"); } #region Operations Variable ValidateAndOperate(IExpression left, IExpression right, string op) { Variable leftResult = left.Resolve(); Variable rightResult = right.Resolve(); if (leftResult.IsNumeric() && rightResult.IsNumeric()) { return NumericOperation((decimal)leftResult.ReadValue(), (decimal)rightResult.ReadValue(), op); } else if (leftResult.ReadValue().GetType().Equals(rightResult.ReadValue().GetType())) { if (leftResult.ReadValue().GetType() == typeof(StringVariable)) { return StringOperation(leftResult.ReadValue().ToString(), rightResult.ReadValue().ToString(), op); } } else { throw new InvalidOperationException("Trying to add different variable types will not work."); } throw new InvalidOperationException("Trying to add different variable types will not work."); } Variable NumericOperation(Decimal left, Decimal right, string op) { NumberVariable ret = new NumberVariable(); if (op == "+") { ret.WriteValue(left + right); } else if (op == "-") { ret.WriteValue(left - right); } else if (op == "*") { ret.WriteValue(left * right); } else if (op == "/") { ret.WriteValue(left / right); } else if (op == ">") { BoolVariable varRet = new BoolVariable(); varRet.WriteValue(left>right); varRet.LockValue(); return varRet; } else if (op == ">=") { BoolVariable varRet = new BoolVariable(); varRet.WriteValue(left>=right); varRet.LockValue(); return varRet; } else if (op == "<") { BoolVariable varRet = new BoolVariable(); varRet.WriteValue(left<right); varRet.LockValue(); return varRet; } else if (op == "<=") { BoolVariable varRet = new BoolVariable(); varRet.WriteValue(left<=right); varRet.LockValue(); return varRet; } else if (op == "=") { BoolVariable varRet = new BoolVariable(); varRet.WriteValue(left.Equals(right) ); varRet.LockValue(); return varRet; } else { throw new InvalidOperationException(op + " cannot be used between two numeric variables"); } ret.LockValue(); return ret; } Variable StringOperation(String left, String right, string op) { StringVariable ret = new StringVariable(); if (op == "+") { ret.WriteValue(left + right); } else if (op == "=") { BoolVariable varRet = new BoolVariable(); varRet.WriteValue(left.Equals(right) ); varRet.LockValue(); return varRet; } ret.LockValue(); return ret; } #endregion } }
33.258427
119
0.492568
[ "MIT" ]
raasiel/FrameworkQ.Rules
FrameworkQ.Rules/Lang/Operand.cs
5,922
C#
// <auto-generated> // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. // </auto-generated> namespace Microsoft.Azure.Management.RecoveryServices.SiteRecovery { using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; using System.Threading; using System.Threading.Tasks; /// <summary> /// Extension methods for ReplicationProtectionContainersOperations. /// </summary> public static partial class ReplicationProtectionContainersOperationsExtensions { /// <summary> /// Gets the list of protection container for a fabric. /// </summary> /// <remarks> /// Lists the protection containers in the specified fabric. /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='fabricName'> /// Fabric name. /// </param> public static IPage<ProtectionContainer> ListByReplicationFabrics(this IReplicationProtectionContainersOperations operations, string fabricName) { return operations.ListByReplicationFabricsAsync(fabricName).GetAwaiter().GetResult(); } /// <summary> /// Gets the list of protection container for a fabric. /// </summary> /// <remarks> /// Lists the protection containers in the specified fabric. /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='fabricName'> /// Fabric name. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<ProtectionContainer>> ListByReplicationFabricsAsync(this IReplicationProtectionContainersOperations operations, string fabricName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListByReplicationFabricsWithHttpMessagesAsync(fabricName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets the protection container details. /// </summary> /// <remarks> /// Gets the details of a protection container. /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='fabricName'> /// Fabric name. /// </param> /// <param name='protectionContainerName'> /// Protection container name. /// </param> public static ProtectionContainer Get(this IReplicationProtectionContainersOperations operations, string fabricName, string protectionContainerName) { return operations.GetAsync(fabricName, protectionContainerName).GetAwaiter().GetResult(); } /// <summary> /// Gets the protection container details. /// </summary> /// <remarks> /// Gets the details of a protection container. /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='fabricName'> /// Fabric name. /// </param> /// <param name='protectionContainerName'> /// Protection container name. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<ProtectionContainer> GetAsync(this IReplicationProtectionContainersOperations operations, string fabricName, string protectionContainerName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetWithHttpMessagesAsync(fabricName, protectionContainerName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Create a protection container. /// </summary> /// <remarks> /// Operation to create a protection container. /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='fabricName'> /// Unique fabric ARM name. /// </param> /// <param name='protectionContainerName'> /// Unique protection container ARM name. /// </param> /// <param name='creationInput'> /// Creation input. /// </param> public static ProtectionContainer Create(this IReplicationProtectionContainersOperations operations, string fabricName, string protectionContainerName, CreateProtectionContainerInput creationInput) { return operations.CreateAsync(fabricName, protectionContainerName, creationInput).GetAwaiter().GetResult(); } /// <summary> /// Create a protection container. /// </summary> /// <remarks> /// Operation to create a protection container. /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='fabricName'> /// Unique fabric ARM name. /// </param> /// <param name='protectionContainerName'> /// Unique protection container ARM name. /// </param> /// <param name='creationInput'> /// Creation input. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<ProtectionContainer> CreateAsync(this IReplicationProtectionContainersOperations operations, string fabricName, string protectionContainerName, CreateProtectionContainerInput creationInput, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.CreateWithHttpMessagesAsync(fabricName, protectionContainerName, creationInput, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Adds a protectable item to the replication protection container. /// </summary> /// <remarks> /// The operation to a add a protectable item to a protection container(Add /// physical server). /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='fabricName'> /// The name of the fabric. /// </param> /// <param name='protectionContainerName'> /// The name of the protection container. /// </param> /// <param name='discoverProtectableItemRequest'> /// The request object to add a protectable item. /// </param> public static ProtectionContainer DiscoverProtectableItem(this IReplicationProtectionContainersOperations operations, string fabricName, string protectionContainerName, DiscoverProtectableItemRequest discoverProtectableItemRequest) { return operations.DiscoverProtectableItemAsync(fabricName, protectionContainerName, discoverProtectableItemRequest).GetAwaiter().GetResult(); } /// <summary> /// Adds a protectable item to the replication protection container. /// </summary> /// <remarks> /// The operation to a add a protectable item to a protection container(Add /// physical server). /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='fabricName'> /// The name of the fabric. /// </param> /// <param name='protectionContainerName'> /// The name of the protection container. /// </param> /// <param name='discoverProtectableItemRequest'> /// The request object to add a protectable item. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<ProtectionContainer> DiscoverProtectableItemAsync(this IReplicationProtectionContainersOperations operations, string fabricName, string protectionContainerName, DiscoverProtectableItemRequest discoverProtectableItemRequest, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.DiscoverProtectableItemWithHttpMessagesAsync(fabricName, protectionContainerName, discoverProtectableItemRequest, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Removes a protection container. /// </summary> /// <remarks> /// Operation to remove a protection container. /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='fabricName'> /// Unique fabric ARM name. /// </param> /// <param name='protectionContainerName'> /// Unique protection container ARM name. /// </param> public static void Delete(this IReplicationProtectionContainersOperations operations, string fabricName, string protectionContainerName) { operations.DeleteAsync(fabricName, protectionContainerName).GetAwaiter().GetResult(); } /// <summary> /// Removes a protection container. /// </summary> /// <remarks> /// Operation to remove a protection container. /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='fabricName'> /// Unique fabric ARM name. /// </param> /// <param name='protectionContainerName'> /// Unique protection container ARM name. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task DeleteAsync(this IReplicationProtectionContainersOperations operations, string fabricName, string protectionContainerName, CancellationToken cancellationToken = default(CancellationToken)) { (await operations.DeleteWithHttpMessagesAsync(fabricName, protectionContainerName, null, cancellationToken).ConfigureAwait(false)).Dispose(); } /// <summary> /// Switches protection from one container to another or one replication /// provider to another. /// </summary> /// <remarks> /// Operation to switch protection from one container to another or one /// replication provider to another. /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='fabricName'> /// Unique fabric name. /// </param> /// <param name='protectionContainerName'> /// Protection container name. /// </param> /// <param name='switchInput'> /// Switch protection input. /// </param> public static ProtectionContainer SwitchProtection(this IReplicationProtectionContainersOperations operations, string fabricName, string protectionContainerName, SwitchProtectionInput switchInput) { return operations.SwitchProtectionAsync(fabricName, protectionContainerName, switchInput).GetAwaiter().GetResult(); } /// <summary> /// Switches protection from one container to another or one replication /// provider to another. /// </summary> /// <remarks> /// Operation to switch protection from one container to another or one /// replication provider to another. /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='fabricName'> /// Unique fabric name. /// </param> /// <param name='protectionContainerName'> /// Protection container name. /// </param> /// <param name='switchInput'> /// Switch protection input. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<ProtectionContainer> SwitchProtectionAsync(this IReplicationProtectionContainersOperations operations, string fabricName, string protectionContainerName, SwitchProtectionInput switchInput, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.SwitchProtectionWithHttpMessagesAsync(fabricName, protectionContainerName, switchInput, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets the list of all protection containers in a vault. /// </summary> /// <remarks> /// Lists the protection containers in a vault. /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static IPage<ProtectionContainer> List(this IReplicationProtectionContainersOperations operations) { return operations.ListAsync().GetAwaiter().GetResult(); } /// <summary> /// Gets the list of all protection containers in a vault. /// </summary> /// <remarks> /// Lists the protection containers in a vault. /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<ProtectionContainer>> ListAsync(this IReplicationProtectionContainersOperations operations, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Create a protection container. /// </summary> /// <remarks> /// Operation to create a protection container. /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='fabricName'> /// Unique fabric ARM name. /// </param> /// <param name='protectionContainerName'> /// Unique protection container ARM name. /// </param> /// <param name='creationInput'> /// Creation input. /// </param> public static ProtectionContainer BeginCreate(this IReplicationProtectionContainersOperations operations, string fabricName, string protectionContainerName, CreateProtectionContainerInput creationInput) { return operations.BeginCreateAsync(fabricName, protectionContainerName, creationInput).GetAwaiter().GetResult(); } /// <summary> /// Create a protection container. /// </summary> /// <remarks> /// Operation to create a protection container. /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='fabricName'> /// Unique fabric ARM name. /// </param> /// <param name='protectionContainerName'> /// Unique protection container ARM name. /// </param> /// <param name='creationInput'> /// Creation input. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<ProtectionContainer> BeginCreateAsync(this IReplicationProtectionContainersOperations operations, string fabricName, string protectionContainerName, CreateProtectionContainerInput creationInput, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.BeginCreateWithHttpMessagesAsync(fabricName, protectionContainerName, creationInput, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Adds a protectable item to the replication protection container. /// </summary> /// <remarks> /// The operation to a add a protectable item to a protection container(Add /// physical server). /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='fabricName'> /// The name of the fabric. /// </param> /// <param name='protectionContainerName'> /// The name of the protection container. /// </param> /// <param name='discoverProtectableItemRequest'> /// The request object to add a protectable item. /// </param> public static ProtectionContainer BeginDiscoverProtectableItem(this IReplicationProtectionContainersOperations operations, string fabricName, string protectionContainerName, DiscoverProtectableItemRequest discoverProtectableItemRequest) { return operations.BeginDiscoverProtectableItemAsync(fabricName, protectionContainerName, discoverProtectableItemRequest).GetAwaiter().GetResult(); } /// <summary> /// Adds a protectable item to the replication protection container. /// </summary> /// <remarks> /// The operation to a add a protectable item to a protection container(Add /// physical server). /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='fabricName'> /// The name of the fabric. /// </param> /// <param name='protectionContainerName'> /// The name of the protection container. /// </param> /// <param name='discoverProtectableItemRequest'> /// The request object to add a protectable item. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<ProtectionContainer> BeginDiscoverProtectableItemAsync(this IReplicationProtectionContainersOperations operations, string fabricName, string protectionContainerName, DiscoverProtectableItemRequest discoverProtectableItemRequest, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.BeginDiscoverProtectableItemWithHttpMessagesAsync(fabricName, protectionContainerName, discoverProtectableItemRequest, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Removes a protection container. /// </summary> /// <remarks> /// Operation to remove a protection container. /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='fabricName'> /// Unique fabric ARM name. /// </param> /// <param name='protectionContainerName'> /// Unique protection container ARM name. /// </param> public static void BeginDelete(this IReplicationProtectionContainersOperations operations, string fabricName, string protectionContainerName) { operations.BeginDeleteAsync(fabricName, protectionContainerName).GetAwaiter().GetResult(); } /// <summary> /// Removes a protection container. /// </summary> /// <remarks> /// Operation to remove a protection container. /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='fabricName'> /// Unique fabric ARM name. /// </param> /// <param name='protectionContainerName'> /// Unique protection container ARM name. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task BeginDeleteAsync(this IReplicationProtectionContainersOperations operations, string fabricName, string protectionContainerName, CancellationToken cancellationToken = default(CancellationToken)) { (await operations.BeginDeleteWithHttpMessagesAsync(fabricName, protectionContainerName, null, cancellationToken).ConfigureAwait(false)).Dispose(); } /// <summary> /// Switches protection from one container to another or one replication /// provider to another. /// </summary> /// <remarks> /// Operation to switch protection from one container to another or one /// replication provider to another. /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='fabricName'> /// Unique fabric name. /// </param> /// <param name='protectionContainerName'> /// Protection container name. /// </param> /// <param name='switchInput'> /// Switch protection input. /// </param> public static ProtectionContainer BeginSwitchProtection(this IReplicationProtectionContainersOperations operations, string fabricName, string protectionContainerName, SwitchProtectionInput switchInput) { return operations.BeginSwitchProtectionAsync(fabricName, protectionContainerName, switchInput).GetAwaiter().GetResult(); } /// <summary> /// Switches protection from one container to another or one replication /// provider to another. /// </summary> /// <remarks> /// Operation to switch protection from one container to another or one /// replication provider to another. /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='fabricName'> /// Unique fabric name. /// </param> /// <param name='protectionContainerName'> /// Protection container name. /// </param> /// <param name='switchInput'> /// Switch protection input. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<ProtectionContainer> BeginSwitchProtectionAsync(this IReplicationProtectionContainersOperations operations, string fabricName, string protectionContainerName, SwitchProtectionInput switchInput, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.BeginSwitchProtectionWithHttpMessagesAsync(fabricName, protectionContainerName, switchInput, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets the list of protection container for a fabric. /// </summary> /// <remarks> /// Lists the protection containers in the specified fabric. /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> public static IPage<ProtectionContainer> ListByReplicationFabricsNext(this IReplicationProtectionContainersOperations operations, string nextPageLink) { return operations.ListByReplicationFabricsNextAsync(nextPageLink).GetAwaiter().GetResult(); } /// <summary> /// Gets the list of protection container for a fabric. /// </summary> /// <remarks> /// Lists the protection containers in the specified fabric. /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<ProtectionContainer>> ListByReplicationFabricsNextAsync(this IReplicationProtectionContainersOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListByReplicationFabricsNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets the list of all protection containers in a vault. /// </summary> /// <remarks> /// Lists the protection containers in a vault. /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> public static IPage<ProtectionContainer> ListNext(this IReplicationProtectionContainersOperations operations, string nextPageLink) { return operations.ListNextAsync(nextPageLink).GetAwaiter().GetResult(); } /// <summary> /// Gets the list of all protection containers in a vault. /// </summary> /// <remarks> /// Lists the protection containers in a vault. /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<ProtectionContainer>> ListNextAsync(this IReplicationProtectionContainersOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } } }
47.38522
331
0.571059
[ "MIT" ]
93mishra/azure-sdk-for-net
sdk/recoveryservices-siterecovery/Microsoft.Azure.Management.RecoveryServices.SiteRecovery/src/Generated/ReplicationProtectionContainersOperationsExtensions.cs
30,137
C#
using BattleTech; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace BTRandomMechComponentUpgrader { class Modifier_Additions : IMechDefSpawnModifier { public void ModifyMech(MechDef mDef, SimGameState s, UpgradeList ulist, ref float canFreeTonns, List<string[]> changedAmmoTypes, MechDef fromData) { BTRandomMechComponentUpgrader_Init.Log.Log("checking addition sublists"); List<MechComponentRef> inv = mDef.Inventory.ToList(); foreach (UpgradeList.UpgradeEntry[] l in ulist.Additions) { if (s.NetworkRandom.Float(0f, 1f) < ulist.UpgradePerComponentChance) { string log = ""; UpgradeList.UpgradeEntry ue = ulist.RollEntryFromSubList(l, s.NetworkRandom, -1, s.CurrentDate, ref log, ulist.UpgradePerComponentChance); if (ue != null && !ue.ID.Equals("")) { MechComponentDef d = s.GetComponentDefFromID(ue.ID); ChassisLocations loc = mDef.SearchLocationToAddComponent(d, canFreeTonns, inv, null, ChassisLocations.None); if (loc == ChassisLocations.None) { BTRandomMechComponentUpgrader_Init.Log.Log("cannot add " + log); continue; } BTRandomMechComponentUpgrader_Init.Log.Log($"adding {log} into {loc}"); MechComponentRef r = new MechComponentRef(ue.ID, null, d.ComponentType, loc, -1, ComponentDamageLevel.Functional, false); r.SetComponentDef(d); inv.Add(r); canFreeTonns -= d.Tonnage; } else BTRandomMechComponentUpgrader_Init.Log.Log("cannot add, nothing rolled " + log); } } mDef.SetInventory(inv.ToArray()); } } }
46.444444
158
0.561244
[ "MIT" ]
mcb5637/BTRandomMechComponentUpgrader
BTRandomMechComponentUpgrader/Modifier_Additions.cs
2,092
C#
using CleanArchitecture.Core.Entities; using CleanArchitecture.Core.Extensions; using MediatR; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Identity; using Microsoft.Extensions.Logging; using System.Diagnostics; using System.Threading; using System.Threading.Tasks; namespace CleanArchitecture.Application.Behaviours { public class PerformanceBehaviour<TRequest, TResponse> : IPipelineBehavior<TRequest, TResponse> { private readonly Stopwatch _timer; private readonly ILogger<TRequest> _logger; private readonly IHttpContextAccessor _httpContextAccessor; private readonly UserManager<ApplicationUser> _userManager; public PerformanceBehaviour(ILogger<TRequest> logger, IHttpContextAccessor httpContextAccessor, UserManager<ApplicationUser> userManager) { _timer = new Stopwatch(); _logger = logger; _httpContextAccessor = httpContextAccessor; _userManager = userManager; } public async Task<TResponse> Handle(TRequest request, CancellationToken cancellationToken, RequestHandlerDelegate<TResponse> next) { _timer.Start(); var response = await next(); _timer.Stop(); var elapsedMilliseconds = _timer.ElapsedMilliseconds; if (elapsedMilliseconds > 500) { var requestName = typeof(TRequest).Name; var userId = _httpContextAccessor.HttpContext.User.GetUserId(); var userName = userId.HasValue ? _userManager.GetUserName(_httpContextAccessor.HttpContext.User) : string.Empty; _logger.LogWarning("CleanArchitecture Long Running Request: {Name} ({ElapsedMilliseconds} milliseconds) {@UserId} {@UserName} {@Request}", requestName, elapsedMilliseconds, userId, userName, request); } return response; } } }
39.204082
216
0.696512
[ "MIT" ]
ayzdru/CleanArchitecture
source/CleanArchitecture.Application/Behaviours/PerformanceBehaviour.cs
1,923
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Concurrent; using Microsoft.CodeAnalysis.Storage; using Microsoft.CodeAnalysis.SQLite.v2.Interop; namespace Microsoft.CodeAnalysis.SQLite.v2 { internal partial class SQLitePersistentStorage { /// <summary> /// Mapping from the workspace's ID for a document, to the ID we use in the DB for the document. /// Kept locally so we don't have to hit the DB for the common case of trying to determine the /// DB id for a document. /// </summary> private readonly ConcurrentDictionary<DocumentId, int> _documentIdToIdMap = new(); /// <summary> /// Given a document, and the name of a stream to read/write, gets the integral DB ID to /// use to find the data inside the DocumentData table. /// </summary> private bool TryGetDocumentDataId( SqlConnection connection, DocumentKey documentKey, string name, bool allowWrite, out long dataId) { dataId = 0; var documentId = TryGetDocumentId(connection, documentKey, allowWrite); var nameId = TryGetStringId(connection, name, allowWrite); if (documentId == null || nameId == null) return false; // Our data ID is just a 64bit int combining the two 32bit values of our documentId and nameId. dataId = CombineInt32ValuesToInt64(documentId.Value, nameId.Value); return true; } private int? TryGetDocumentId(SqlConnection connection, DocumentKey document, bool allowWrite) { // First see if we've cached the ID for this value locally. If so, just return // what we already have. if (_documentIdToIdMap.TryGetValue(document.Id, out var existingId)) return existingId; var id = TryGetDocumentIdFromDatabase(connection, document, allowWrite); if (id != null) { // Cache the value locally so we don't need to go back to the DB in the future. _documentIdToIdMap.TryAdd(document.Id, id.Value); } return id; } private int? TryGetDocumentIdFromDatabase(SqlConnection connection, DocumentKey document, bool allowWrite) { var projectId = TryGetProjectId(connection, document.Project, allowWrite); if (projectId == null) return null; // Key the document off its project id, and its path and name. That way we work properly // in host and test scenarios. var documentPathId = TryGetStringId(connection, document.FilePath, allowWrite); var documentNameId = TryGetStringId(connection, document.Name, allowWrite); if (documentPathId == null || documentNameId == null) return null; // Unique identify the document through the key: projectId-documentPathId-documentNameId return TryGetStringId( connection, GetDocumentIdString(projectId.Value, documentPathId.Value, documentNameId.Value), allowWrite); } } }
44
122
0.642943
[ "MIT" ]
AlFasGD/roslyn
src/Workspaces/Core/Portable/Storage/SQLite/v2/SQLitePersistentStorage_DocumentIds.cs
3,346
C#
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Collections.Generic; using Microsoft.CodeAnalysis.Editor.CSharp.SignatureHelp; using Microsoft.CodeAnalysis.Editor.UnitTests.SignatureHelp; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Roslyn.Test.Utilities; using Xunit; using Microsoft.CodeAnalysis.CSharp; using System.Threading.Tasks; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.SignatureHelp { public class GenericNameSignatureHelpProviderTests : AbstractCSharpSignatureHelpProviderTests { public GenericNameSignatureHelpProviderTests(CSharpTestWorkspaceFixture workspaceFixture) : base(workspaceFixture) { } internal override ISignatureHelpProvider CreateSignatureHelpProvider() { return new GenericNameSignatureHelpProvider(); } #region "Declaring generic type objects" [WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task NestedGenericTerminated() { var markup = @" class G<T> { }; class C { void Foo() { G<G<int>$$> } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("G<T>", string.Empty, string.Empty, currentParameterIndex: 0)); await TestAsync(markup, expectedOrderedItems); } [WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task DeclaringGenericTypeWith1ParameterTerminated() { var markup = @" class G<T> { }; class C { void Foo() { [|G<$$|]> } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("G<T>", string.Empty, string.Empty, currentParameterIndex: 0)); await TestAsync(markup, expectedOrderedItems); } [WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task DeclaringGenericTypeWith2ParametersOn1() { var markup = @" class G<S, T> { }; class C { void Foo() { [|G<$$|]> } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("G<S, T>", string.Empty, string.Empty, currentParameterIndex: 0)); await TestAsync(markup, expectedOrderedItems); } [WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task DeclaringGenericTypeWith2ParametersOn2() { var markup = @" class G<S, T> { }; class C { void Foo() { [|G<int, $$|]> } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("G<S, T>", string.Empty, string.Empty, currentParameterIndex: 1)); await TestAsync(markup, expectedOrderedItems); } [WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task DeclaringGenericTypeWith2ParametersOn1XmlDoc() { var markup = @" /// <summary> /// Summary for G /// </summary> /// <typeparam name=""S"">TypeParamS. Also see <see cref=""T""/></typeparam> /// <typeparam name=""T"">TypeParamT</typeparam> class G<S, T> { }; class C { void Foo() { [|G<$$|]> } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("G<S, T>", "Summary for G", "TypeParamS. Also see T", currentParameterIndex: 0)); await TestAsync(markup, expectedOrderedItems); } [WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task DeclaringGenericTypeWith2ParametersOn2XmlDoc() { var markup = @" /// <summary> /// Summary for G /// </summary> /// <typeparam name=""S"">TypeParamS</typeparam> /// <typeparam name=""T"">TypeParamT. Also see <see cref=""S""/></typeparam> class G<S, T> { }; class C { void Foo() { [|G<int, $$|]> } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("G<S, T>", "Summary for G", "TypeParamT. Also see S", currentParameterIndex: 1)); await TestAsync(markup, expectedOrderedItems); } #endregion #region "Constraints on generic types" [WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task DeclaringGenericTypeWithConstraintsStruct() { var markup = @" class G<S> where S : struct { }; class C { void Foo() { [|G<$$|]> } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("G<S> where S : struct", string.Empty, string.Empty, currentParameterIndex: 0)); await TestAsync(markup, expectedOrderedItems); } [WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task DeclaringGenericTypeWithConstraintsClass() { var markup = @" class G<S> where S : class { }; class C { void Foo() { [|G<$$|]> } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("G<S> where S : class", string.Empty, string.Empty, currentParameterIndex: 0)); await TestAsync(markup, expectedOrderedItems); } [WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task DeclaringGenericTypeWithConstraintsNew() { var markup = @" class G<S> where S : new() { }; class C { void Foo() { [|G<$$|]> } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("G<S> where S : new()", string.Empty, string.Empty, currentParameterIndex: 0)); await TestAsync(markup, expectedOrderedItems); } [WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task DeclaringGenericTypeWithConstraintsBase() { var markup = @" class Base { } class G<S> where S : Base { }; class C { void Foo() { [|G<$$|]> } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("G<S> where S : Base", string.Empty, string.Empty, currentParameterIndex: 0)); await TestAsync(markup, expectedOrderedItems); } [WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task DeclaringGenericTypeWithConstraintsBaseGenericWithGeneric() { var markup = @" class Base<T> { } class G<S> where S : Base<S> { }; class C { void Foo() { [|G<$$|]> } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("G<S> where S : Base<S>", string.Empty, string.Empty, currentParameterIndex: 0)); await TestAsync(markup, expectedOrderedItems); } [WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task DeclaringGenericTypeWithConstraintsBaseGenericWithNonGeneric() { var markup = @" class Base<T> { } class G<S> where S : Base<int> { }; class C { void Foo() { [|G<$$|]> } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("G<S> where S : Base<int>", string.Empty, string.Empty, currentParameterIndex: 0)); await TestAsync(markup, expectedOrderedItems); } [WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task DeclaringGenericTypeWithConstraintsBaseGenericNested() { var markup = @" class Base<T> { } class G<S> where S : Base<Base<int>> { }; class C { void Foo() { [|G<$$|]> } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("G<S> where S : Base<Base<int>>", string.Empty, string.Empty, currentParameterIndex: 0)); await TestAsync(markup, expectedOrderedItems); } [WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task DeclaringGenericTypeWithConstraintsDeriveFromAnotherGenericParameter() { var markup = @" class G<S, T> where S : T { }; class C { void Foo() { [|G<$$|]> } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("G<S, T> where S : T", string.Empty, string.Empty, currentParameterIndex: 0)); await TestAsync(markup, expectedOrderedItems); } [WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task DeclaringGenericTypeWithConstraintsMixed1() { var markup = @" /// <summary> /// Summary1 /// </summary> /// <typeparam name=""S"">SummaryS</typeparam> /// <typeparam name=""T"">SummaryT</typeparam> class G<S, T> where S : Base, new() where T : class, S, IFoo, new() { }; internal interface IFoo { } internal class Base { } class C { void Foo() { [|G<$$|]> } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("G<S, T> where S : Base, new()", "Summary1", "SummaryS", currentParameterIndex: 0)); await TestAsync(markup, expectedOrderedItems); } [WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task DeclaringGenericTypeWithConstraintsMixed2() { var markup = @" /// <summary> /// Summary1 /// </summary> /// <typeparam name=""S"">SummaryS</typeparam> /// <typeparam name=""T"">SummaryT</typeparam> class G<S, T> where S : Base, new() where T : class, S, IFoo, new() { }; internal interface IFoo { } internal class Base { } class C { void Foo() { [|G<bar, $$|]> } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("G<S, T> where T : class, S, IFoo, new()", "Summary1", "SummaryT", currentParameterIndex: 1)); await TestAsync(markup, expectedOrderedItems); } #endregion #region "Generic member invocation" [WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task InvokingGenericMethodWith1ParameterTerminated() { var markup = @" class C { void Foo<T>() { } void Bar() { [|Foo<$$|]> } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("void C.Foo<T>()", string.Empty, string.Empty, currentParameterIndex: 0)); await TestAsync(markup, expectedOrderedItems); } [WorkItem(544091)] [WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task InvokingGenericMethodWith2ParametersOn1() { var markup = @" class C { /// <summary> /// Method summary /// </summary> /// <typeparam name=""S"" > type param S. see <see cref=""T""/> </typeparam> /// <typeparam name=""T"">type param T. </typeparam> /// <param name=""s"">parameter s</param> /// <param name=""t"">parameter t</param> void Foo<S, T>(S s, T t) { } void Bar() { [|Foo<$$|]> } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("void C.Foo<S, T>(S s, T t)", "Method summary", "type param S. see T", currentParameterIndex: 0)); await TestAsync(markup, expectedOrderedItems); } [WorkItem(544091)] [WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task InvokingGenericMethodWith2ParametersOn2() { var markup = @" class C { void Foo<S, T>(S s, T t) { } void Bar() { [|Foo<int, $$|]> } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("void C.Foo<S, T>(S s, T t)", string.Empty, string.Empty, currentParameterIndex: 1)); await TestAsync(markup, expectedOrderedItems); } [WorkItem(544091)] [WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task InvokingGenericMethodWith2ParametersOn1XmlDoc() { var markup = @" class C { /// <summary> /// SummaryForFoo /// </summary> /// <typeparam name=""S"">SummaryForS</typeparam> /// <typeparam name=""T"">SummaryForT</typeparam> void Foo<S, T>(S s, T t) { } void Bar() { [|Foo<$$|]> } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("void C.Foo<S, T>(S s, T t)", "SummaryForFoo", "SummaryForS", currentParameterIndex: 0)); await TestAsync(markup, expectedOrderedItems); } [WorkItem(544091)] [WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task InvokingGenericMethodWith2ParametersOn2XmlDoc() { var markup = @" class C { /// <summary> /// SummaryForFoo /// </summary> /// <typeparam name=""S"">SummaryForS</typeparam> /// <typeparam name=""T"">SummaryForT</typeparam> void Foo<S, T>(S s, T t) { } void Bar() { [|Foo<int, $$|]> } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("void C.Foo<S, T>(S s, T t)", "SummaryForFoo", "SummaryForT", currentParameterIndex: 1)); await TestAsync(markup, expectedOrderedItems); } [WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task CallingGenericExtensionMethod() { var markup = @" class G { }; class C { void Bar() { G g = null; g.[|Foo<$$|]> } } static class FooClass { public static void Foo<T>(this G g) { } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem($"({CSharpFeaturesResources.Extension}) void G.Foo<T>()", string.Empty, string.Empty, currentParameterIndex: 0)); // TODO: Enable the script case when we have support for extension methods in scripts await TestAsync(markup, expectedOrderedItems, usePreviousCharAsTrigger: false, sourceCodeKind: Microsoft.CodeAnalysis.SourceCodeKind.Regular); } #endregion #region "Constraints on generic methods" [WorkItem(544091)] [WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task InvokingGenericMethodWithConstraintsMixed1() { var markup = @" class Base { } interface IFoo { } class C { /// <summary> /// FooSummary /// </summary> /// <typeparam name=""S"">ParamS</typeparam> /// <typeparam name=""T"">ParamT</typeparam> S Foo<S, T>(S s, T t) where S : Base, new() where T : class, S, IFoo, new() { return null; } void Bar() { [|Foo<$$|]> } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("S C.Foo<S, T>(S s, T t) where S : Base, new()", "FooSummary", "ParamS", currentParameterIndex: 0)); await TestAsync(markup, expectedOrderedItems); } [WorkItem(544091)] [WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task InvokingGenericMethodWithConstraintsMixed2() { var markup = @" class Base { } interface IFoo { } class C { /// <summary> /// FooSummary /// </summary> /// <typeparam name=""S"">ParamS</typeparam> /// <typeparam name=""T"">ParamT</typeparam> S Foo<S, T>(S s, T t) where S : Base, new() where T : class, S, IFoo, new() { return null; } void Bar() { [|Foo<Base, $$|]> } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("S C.Foo<S, T>(S s, T t) where T : class, S, IFoo, new()", "FooSummary", "ParamT", currentParameterIndex: 1)); await TestAsync(markup, expectedOrderedItems); } #endregion #region "Trigger tests" [WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public void TestTriggerCharacters() { char[] expectedCharacters = { ',', '<' }; char[] unexpectedCharacters = { ' ', '[', '(' }; VerifyTriggerCharacters(expectedCharacters, unexpectedCharacters); } [WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task FieldUnavailableInOneLinkedFile() { var markup = @"<Workspace> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""FOO""> <Document FilePath=""SourceDocument""><![CDATA[ class C { #if FOO class D<T> { } #endif void foo() { var x = new D<$$ } } ]]> </Document> </Project> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2""> <Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""SourceDocument""/> </Project> </Workspace>"; var expectedDescription = new SignatureHelpTestItem($"D<T>\r\n\r\n{string.Format(FeaturesResources.ProjectAvailability, "Proj1", FeaturesResources.Available)}\r\n{string.Format(FeaturesResources.ProjectAvailability, "Proj2", FeaturesResources.NotAvailable)}\r\n\r\n{FeaturesResources.UseTheNavigationBarToSwitchContext}", currentParameterIndex: 0); await VerifyItemWithReferenceWorkerAsync(markup, new[] { expectedDescription }, false); } [WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task ExcludeFilesWithInactiveRegions() { var markup = @"<Workspace> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""FOO,BAR""> <Document FilePath=""SourceDocument""><![CDATA[ class C { #if FOO class D<T> { } #endif #if BAR void foo() { var x = new D<$$ } #endif } ]]> </Document> </Project> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2""> <Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""SourceDocument"" /> </Project> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj3"" PreprocessorSymbols=""BAR""> <Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""SourceDocument""/> </Project> </Workspace>"; var expectedDescription = new SignatureHelpTestItem($"D<T>\r\n\r\n{string.Format(FeaturesResources.ProjectAvailability, "Proj1", FeaturesResources.Available)}\r\n{string.Format(FeaturesResources.ProjectAvailability, "Proj3", FeaturesResources.NotAvailable)}\r\n\r\n{FeaturesResources.UseTheNavigationBarToSwitchContext}", currentParameterIndex: 0); await VerifyItemWithReferenceWorkerAsync(markup, new[] { expectedDescription }, false); } #endregion #region "EditorBrowsable tests" [WorkItem(7336, "DevDiv_Projects/Roslyn")] [WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task EditorBrowsable_GenericType_BrowsableAlways() { var markup = @" class Program { void M() { var c = new C<$$ } }"; var referencedCode = @" [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Always)] public class C<T> { }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("C<T>", string.Empty, string.Empty, currentParameterIndex: 0)); await TestSignatureHelpInEditorBrowsableContextsAsync(markup: markup, referencedCode: referencedCode, expectedOrderedItemsMetadataReference: expectedOrderedItems, expectedOrderedItemsSameSolution: expectedOrderedItems, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task EditorBrowsable_GenericType_BrowsableNever() { var markup = @" class Program { void M() { var c = new C<$$ } }"; var referencedCode = @" [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public class C<T> { }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("C<T>", string.Empty, string.Empty, currentParameterIndex: 0)); await TestSignatureHelpInEditorBrowsableContextsAsync(markup: markup, referencedCode: referencedCode, expectedOrderedItemsMetadataReference: new List<SignatureHelpTestItem>(), expectedOrderedItemsSameSolution: expectedOrderedItems, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task EditorBrowsable_GenericType_BrowsableAdvanced() { var markup = @" class Program { void M() { var c = new C<$$ } }"; var referencedCode = @" [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Advanced)] public class C<T> { }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("C<T>", string.Empty, string.Empty, currentParameterIndex: 0)); await TestSignatureHelpInEditorBrowsableContextsAsync(markup: markup, referencedCode: referencedCode, expectedOrderedItemsMetadataReference: new List<SignatureHelpTestItem>(), expectedOrderedItemsSameSolution: expectedOrderedItems, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp, hideAdvancedMembers: true); await TestSignatureHelpInEditorBrowsableContextsAsync(markup: markup, referencedCode: referencedCode, expectedOrderedItemsMetadataReference: expectedOrderedItems, expectedOrderedItemsSameSolution: expectedOrderedItems, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp, hideAdvancedMembers: false); } #endregion [WorkItem(1083601)] [WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task DeclaringGenericTypeWithBadTypeArgumentList() { var markup = @" class G<T> { }; class C { void Foo() { G{$$> } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); await TestAsync(markup, expectedOrderedItems); } } }
30.699275
360
0.601676
[ "Apache-2.0" ]
0x53A/roslyn
src/EditorFeatures/CSharpTest/SignatureHelp/GenericNameSignatureHelpProviderTests.cs
25,419
C#
using System; using XFScrollviewAnimations.Plugin.Abstractions; namespace XFScrollviewAnimations.Plugin { /// <summary> /// /// </summary> public static class CrossScrollViewAnimations { static Lazy<IXFScrollviewAnimations> Implementation = new Lazy<IXFScrollviewAnimations>(() => CreateAnimation(), System.Threading.LazyThreadSafetyMode.PublicationOnly); /// <summary> /// Current settings to use /// </summary> public static IXFScrollviewAnimations Current { get { var ret = Implementation.Value; if (ret == null) { throw NotImplementedInReferenceAssembly(); } return ret; } } static IXFScrollviewAnimations CreateAnimation() { #if PORTABLE return null; #else return new ScrollViewAnimations(); #endif } internal static Exception NotImplementedInReferenceAssembly() { return new NotImplementedException("This functionality is not implemented in the portable version of this assembly. You should reference the HexisSoftware.Plugins.XFScrollviewAnimations NuGet package from your main application project in order to reference the platform-specific implementation."); } } }
31.454545
310
0.624277
[ "MIT" ]
HexisSoftware/XFScrollviewAnimations
src/XFScrollviewAnimations.Plugin/CrossScrollViewAnimations.cs
1,384
C#
using System; using System.Collections.Generic; using System.Text; using Dapper; using Xunit; using Gyomu.Test.Common; namespace Gyomu.Test { public class StatusCodeTest { private const short testApplicationId = 32650; [Theory] [InlineData(Gyomu.Common.SettingItem.DBType.MSSQL)] [InlineData(Gyomu.Common.SettingItem.DBType.POSTGRESQL)] public void RegisterStatusCodeTest(Gyomu.Common.SettingItem.DBType db) { DBConnectionFactoryTest.LockProcess(db, new Action[] { GyomuDataAccessTest.deleteApplicationInfo, GyomuDataAccessTest.insertApplicationInfo, GyomuDataAccessTest.deleteStatusHandler,GyomuDataAccessTest.insertStatusHandler, registerStatusCode, GyomuDataAccessTest.deleteStatusInfo, GyomuDataAccessTest.deleteStatusHandler, GyomuDataAccessTest.deleteApplicationInfo } ); } private static void registerStatusCode() { Gyomu.Common.Configurator config = Gyomu.Common.BaseConfigurator.GetInstance(); config.ApplicationID = Common.GyomuDataAccessTest.testApplicationId; StatusCode retVal = Gyomu.StatusCode.Debug("Debug Test", config); Console.WriteLine(retVal.StatusID); } } }
38.857143
102
0.671324
[ "MIT" ]
Yoshihisa-Matsumoto/Gyomu
Gyomu.Test/StatusCodeTest.cs
1,362
C#
using Alex.Worlds; using MiNET.Entities; namespace Alex.Entities.Passive { public class SkeletonHorse : AbstractHorse { public SkeletonHorse(World level) : base(level) { Height = 1.6; Width = 1.396484; } } }
14.933333
49
0.696429
[ "MPL-2.0", "MPL-2.0-no-copyleft-exception" ]
codingwatching/Alex
src/Alex/Entities/Passive/SkeletonHorse.cs
224
C#