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 UnityEngine; using System.Collections; using UnityEngine.UI; using System.IO; public class SettingsController : MonoBehaviour { public Toggle fullscreenToggle; public Dropdown resolutionDrop; public Dropdown textQualityDrop; public Dropdown antialiasingDrop; public Dropdown vSyncDrop; public Slider volume; public Button saveButton; public Resolution[] resolutions; public Settings gameSettings; void OnEnable() { gameSettings = new Settings(); fullscreenToggle.onValueChanged.AddListener(delegate { FullscreenToggle(); }); resolutionDrop.onValueChanged.AddListener(delegate { ResolutionChange(); }); textQualityDrop.onValueChanged.AddListener(delegate { TextQChange(); }); antialiasingDrop.onValueChanged.AddListener(delegate { AntialiasingChange(); }); vSyncDrop.onValueChanged.AddListener(delegate { VsyncChange(); }); volume.onValueChanged.AddListener(delegate { VolumeChange(); }); saveButton.onClick.AddListener(delegate { saveSettings(); }); resolutions = Screen.resolutions; foreach(Resolution resolution in resolutions) { resolutionDrop.options.Add(new Dropdown.OptionData(resolution.ToString())); } loadSettings(); } public void FullscreenToggle() { gameSettings.fullscreen = Screen.fullScreen = fullscreenToggle.isOn; } public void ResolutionChange() { Screen.SetResolution(resolutions[resolutionDrop.value].width, resolutions[resolutionDrop.value].height, Screen.fullScreen, resolutions[resolutionDrop.value].refreshRate); gameSettings.resolutionIndex = resolutionDrop.value; } public void AntialiasingChange() { QualitySettings.antiAliasing = gameSettings.antialiasing = (int)Mathf.Pow(2, antialiasingDrop.value); } public void VsyncChange() { QualitySettings.vSyncCount = gameSettings.vSync = vSyncDrop.value; } public void TextQChange() { gameSettings.textureQuality = QualitySettings.masterTextureLimit = textQualityDrop.value; } public void VolumeChange() { gameSettings.volume = AudioListener.volume = volume.value; } public void saveSettings() { string jsonData = JsonUtility.ToJson(gameSettings,true); File.WriteAllText(Application.persistentDataPath + "/gamesettings.json", jsonData); MenuController.instance.closeOptions(); } public void loadSettings() { gameSettings = JsonUtility.FromJson<Settings>(File.ReadAllText( Application.persistentDataPath + "/gamesettings.json")); fullscreenToggle.isOn = gameSettings.fullscreen; resolutionDrop.value = gameSettings.resolutionIndex; antialiasingDrop.value = gameSettings.antialiasing; vSyncDrop.value = gameSettings.vSync; textQualityDrop.value = gameSettings.textureQuality; volume.value = gameSettings.volume; resolutionDrop.RefreshShownValue(); } }
34.579545
178
0.706868
[ "Unlicense" ]
BritanyEnriquez/Calabozo-Embrujado
Assets/Main menu with parallax FREE/Scripts/SettingsController.cs
3,045
C#
using EventStore.Client; using FluentAssertions; using IntroductionToEventSourcing.OptimisticConcurrency.Tools; using Xunit; namespace IntroductionToEventSourcing.OptimisticConcurrency.Mixed; // EVENTS public record ShoppingCartOpened( Guid ShoppingCartId, Guid ClientId ); public record ProductItemAddedToShoppingCart( Guid ShoppingCartId, PricedProductItem ProductItem ); public record ProductItemRemovedFromShoppingCart( Guid ShoppingCartId, PricedProductItem ProductItem ); public record ShoppingCartConfirmed( Guid ShoppingCartId, DateTime ConfirmedAt ); public record ShoppingCartCanceled( Guid ShoppingCartId, DateTime CanceledAt ); // VALUE OBJECTS public record ProductItem( Guid ProductId, int Quantity ); public record PricedProductItem( Guid ProductId, int Quantity, decimal UnitPrice ); public static class ShoppingCartExtensions { public static ShoppingCart GetShoppingCart(this IEnumerable<object> events) { var shoppingCart = (ShoppingCart)Activator.CreateInstance(typeof(ShoppingCart), true)!; foreach (var @event in events) { shoppingCart.When(@event); } return shoppingCart; } } public class OptimisticConcurrencyTests: EventStoreDBTest { [Fact] public async Task GettingState_ForSequenceOfEvents_ShouldSucceed() { var shoppingCartId = Guid.NewGuid(); var clientId = Guid.NewGuid(); var shoesId = Guid.NewGuid(); var tShirtId = Guid.NewGuid(); var twoPairsOfShoes = new ProductItem(shoesId, 2); var tShirt = new ProductItem(tShirtId, 1); var shoesPrice = 100; var tShirtPrice = 50; // Open await EventStore.Add<ShoppingCart, OpenShoppingCart>( command => ShoppingCart.StreamName(command.ShoppingCartId), command => ShoppingCart.Open(command.ShoppingCartId, command.ClientId).Event, OpenShoppingCart.From(shoppingCartId, clientId), CancellationToken.None ); // Try to open again // Should fail as stream was already created var exception = await Record.ExceptionAsync(async () => { await EventStore.Add<ShoppingCart, OpenShoppingCart>( command => ShoppingCart.StreamName(command.ShoppingCartId), command => ShoppingCart.Open(command.ShoppingCartId, command.ClientId).Event, OpenShoppingCart.From(shoppingCartId, clientId), CancellationToken.None ); } ); exception.Should().BeOfType<WrongExpectedVersionException>(); // Add two pairs of shoes await EventStore.GetAndUpdate<ShoppingCart, AddProductItemToShoppingCart>( command => ShoppingCart.StreamName(command.ShoppingCartId), (command, shoppingCart) => shoppingCart.AddProduct(FakeProductPriceCalculator.Returning(shoesPrice), command.ProductItem), AddProductItemToShoppingCart.From(shoppingCartId, twoPairsOfShoes), 0, CancellationToken.None ); // Add T-Shirt // Should fail because of sending the same expected version as previous call exception = await Record.ExceptionAsync(async () => { await EventStore.GetAndUpdate<ShoppingCart, AddProductItemToShoppingCart>( command => ShoppingCart.StreamName(command.ShoppingCartId), (command, shoppingCart) => shoppingCart.AddProduct(FakeProductPriceCalculator.Returning(tShirtPrice), command.ProductItem), AddProductItemToShoppingCart.From(shoppingCartId, tShirt), 0, CancellationToken.None ); } ); exception.Should().BeOfType<WrongExpectedVersionException>(); var shoppingCart = await EventStore.Get<ShoppingCart>(ShoppingCart.StreamName(shoppingCartId), CancellationToken.None); shoppingCart.Id.Should().Be(shoppingCartId); shoppingCart.ClientId.Should().Be(clientId); shoppingCart.ProductItems.Should().HaveCount(1); shoppingCart.Status.Should().Be(ShoppingCartStatus.Pending); shoppingCart.ProductItems[0].ProductId.Should().Be(shoesId); shoppingCart.ProductItems[0].Quantity.Should().Be(twoPairsOfShoes.Quantity); shoppingCart.ProductItems[0].UnitPrice.Should().Be(shoesPrice); } }
33.079137
127
0.661375
[ "MIT" ]
MaciejWolf/EventSourcing.NetCore
Workshops/IntroductionToEventSourcing/Solved/11-OptimisticConcurrency.EventStoreDB/Mixed/OptimisticConcurrencyTests.cs
4,598
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 cloudfront-2018-06-18.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.CloudFront.Model { /// <summary> /// A complex type that lists the active CloudFront key pairs, if any, that are associated /// with <code>AwsAccountNumber</code>. /// /// /// <para> /// For more information, see <a>ActiveTrustedSigners</a>. /// </para> /// </summary> public partial class KeyPairIds { private List<string> _items = new List<string>(); private int? _quantity; /// <summary> /// Gets and sets the property Items. /// <para> /// A complex type that lists the active CloudFront key pairs, if any, that are associated /// with <code>AwsAccountNumber</code>. /// </para> /// /// <para> /// For more information, see <a>ActiveTrustedSigners</a>. /// </para> /// </summary> public List<string> Items { get { return this._items; } set { this._items = value; } } // Check to see if Items property is set internal bool IsSetItems() { return this._items != null && this._items.Count > 0; } /// <summary> /// Gets and sets the property Quantity. /// <para> /// The number of active CloudFront key pairs for <code>AwsAccountNumber</code>. /// </para> /// /// <para> /// For more information, see <a>ActiveTrustedSigners</a>. /// </para> /// </summary> public int Quantity { get { return this._quantity.GetValueOrDefault(); } set { this._quantity = value; } } // Check to see if Quantity property is set internal bool IsSetQuantity() { return this._quantity.HasValue; } } }
30.022222
108
0.592154
[ "Apache-2.0" ]
GitGaby/aws-sdk-net
sdk/src/Services/CloudFront/Generated/Model/KeyPairIds.cs
2,702
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Reflection.Emit; using DataDynamics.PageFX.Common.TypeSystem; namespace DataDynamics.PageFX.Core.IL { public static class CIL { #region StackBehaviour internal static int GetPopCount(IMethod method, Instruction instruction) { var c = instruction.Code; if (c == InstructionCode.Ret) { if (method.IsVoid()) return 0; return 1; } //if (c == InstructionCode.Stfld) // return 2; //if (c == InstructionCode.Stsfld) // return 1; switch (instruction.OpCode.StackBehaviourPop) { case StackBehaviour.Pop0: return 0; case StackBehaviour.Pop1: case StackBehaviour.Popi: case StackBehaviour.Popref: return 1; case StackBehaviour.Pop1_pop1: case StackBehaviour.Popi_pop1: case StackBehaviour.Popi_popi: case StackBehaviour.Popi_popi8: case StackBehaviour.Popi_popr4: case StackBehaviour.Popi_popr8: case StackBehaviour.Popref_pop1: case StackBehaviour.Popref_popi: return 2; case StackBehaviour.Popi_popi_popi: case StackBehaviour.Popref_popi_popi: case StackBehaviour.Popref_popi_popi8: case StackBehaviour.Popref_popi_popr4: case StackBehaviour.Popref_popi_popr8: case StackBehaviour.Popref_popi_popref: case StackBehaviour.Popref_popi_pop1: return 3; case StackBehaviour.Varpop: { //TODO: return -1; } default: throw new ArgumentOutOfRangeException(); } } internal static int GetPushCount(Instruction instruction) { //InstructionCode c = instruction.Code; switch (instruction.OpCode.StackBehaviourPush) { case StackBehaviour.Push0: return 0; case StackBehaviour.Push1: case StackBehaviour.Pushi: case StackBehaviour.Pushi8: case StackBehaviour.Pushr4: case StackBehaviour.Pushr8: case StackBehaviour.Pushref: return 1; case StackBehaviour.Push1_push1: return 2; case StackBehaviour.Varpush: { //TODO: return -1; } default: throw new ArgumentOutOfRangeException(); } } #endregion #region OpCodes public const ushort MultiBytePrefix = 0xFE; public static OpCode? GetShortOpCode(byte code) { LoadAllOpCodes(); var i = _short[code]; if (i != null) return i.OpCode; return null; } public static OpCode? GetLongOpCode(byte code) { LoadAllOpCodes(); var i = _long[code]; if (i != null) return i.OpCode; return null; } public static OpCode[] GetOpCodes() { LoadAllOpCodes(); return _all.ToArray(); } public static int InstructionCount { get { LoadAllOpCodes(); return _all.Count; } } private sealed class I { public readonly OpCode OpCode; public bool IsUsed; public I(OpCode c) { OpCode = c; } public override string ToString() { return string.Format("{0,15} [{1}, 0x{1:X2}]", OpCode, (ushort)OpCode.Value); } } static I[] _short; static I[] _long; static List<OpCode> _all; static void LoadAllOpCodes() { if (_all != null) return; _all = new List<OpCode>(226); _short = new I[256]; _long = new I[256]; const BindingFlags bf = BindingFlags.Public | BindingFlags.Static | BindingFlags.GetField; var fields = typeof(OpCodes).GetFields(bf); foreach (var fi in fields) { var c = (OpCode)fi.GetValue(null); if (c.Size == 1) { _short[c.Value] = new I(c); } else { int i = (ushort)c.Value & 0xFF; _long[i] = new I(c); } _all.Add(c); } } #endregion #region GetEquivalent public static InstructionCode? GetEquivalent(InstructionCode code) { switch (code) { case InstructionCode.Beq: return InstructionCode.Beq_S; case InstructionCode.Beq_S: return InstructionCode.Beq; case InstructionCode.Bge: return InstructionCode.Bge_S; case InstructionCode.Bge_S: return InstructionCode.Bge; case InstructionCode.Bge_Un: return InstructionCode.Bge_Un_S; case InstructionCode.Bge_Un_S: return InstructionCode.Bge_Un; case InstructionCode.Bgt: return InstructionCode.Bgt_S; case InstructionCode.Bgt_S: return InstructionCode.Bgt; case InstructionCode.Bgt_Un: return InstructionCode.Bgt_Un_S; case InstructionCode.Bgt_Un_S: return InstructionCode.Bgt_Un; case InstructionCode.Ble: return InstructionCode.Ble_S; case InstructionCode.Ble_S: return InstructionCode.Ble; case InstructionCode.Ble_Un: return InstructionCode.Ble_Un_S; case InstructionCode.Ble_Un_S: return InstructionCode.Ble_Un; case InstructionCode.Blt: return InstructionCode.Blt_S; case InstructionCode.Blt_S: return InstructionCode.Blt; case InstructionCode.Blt_Un: return InstructionCode.Blt_Un_S; case InstructionCode.Blt_Un_S: return InstructionCode.Blt_Un; case InstructionCode.Bne_Un: return InstructionCode.Bne_Un_S; case InstructionCode.Bne_Un_S: return InstructionCode.Bne_Un; case InstructionCode.Br: return InstructionCode.Br_S; case InstructionCode.Br_S: return InstructionCode.Br; case InstructionCode.Brfalse: return InstructionCode.Brfalse_S; case InstructionCode.Brfalse_S: return InstructionCode.Brfalse; case InstructionCode.Brtrue: return InstructionCode.Brtrue_S; case InstructionCode.Brtrue_S: return InstructionCode.Brtrue; case InstructionCode.Leave: return InstructionCode.Leave_S; case InstructionCode.Leave_S: return InstructionCode.Leave; case InstructionCode.Ldarg: return InstructionCode.Ldarga_S; case InstructionCode.Ldarg_S: return InstructionCode.Ldarg; case InstructionCode.Ldarga: return InstructionCode.Ldarga_S; case InstructionCode.Ldarga_S: return InstructionCode.Ldarga; case InstructionCode.Ldloc: return InstructionCode.Ldloc_S; case InstructionCode.Ldloc_S: return InstructionCode.Ldloc; case InstructionCode.Ldloca: return InstructionCode.Ldloca_S; case InstructionCode.Ldloca_S: return InstructionCode.Ldloca; case InstructionCode.Starg: return InstructionCode.Starg_S; case InstructionCode.Starg_S: return InstructionCode.Starg; case InstructionCode.Stloc: return InstructionCode.Stloc_S; case InstructionCode.Stloc_S: return InstructionCode.Stloc; } return null; } #endregion #region Coverage public static float Coverage { get { return _coveredCount / (float)InstructionCount; } } static int _coveredCount; public static void ResetCoverage() { LoadAllOpCodes(); foreach (var i in _short) if (i != null) i.IsUsed = false; foreach (var i in _long) if (i != null) i.IsUsed = false; _coveredCount = 0; } static void UpdateCoverageCore(ushort code) { int i = code & 0xFF; if (code >> 8 == MultiBytePrefix) { if (!_long[i].IsUsed) { _long[i].IsUsed = true; ++_coveredCount; } } else { if (!_short[i].IsUsed) { _short[i].IsUsed = true; ++_coveredCount; } } } internal static void UpdateCoverage(InstructionCode code) { LoadAllOpCodes(); UpdateCoverageCore((ushort)code); var eq = GetEquivalent(code); if (eq != null) { UpdateCoverageCore((ushort)eq.Value); } } internal static void UpdateCoverage(IEnumerable<Instruction> list) { foreach (var instruction in list) { UpdateCoverage(instruction.Code); } } static IEnumerable<I> GetAllInstructions() { return _short.Concat(_long); } public static void DumpCoverage(TextWriter writer) { writer.WriteLine("CIL Instruction Set Coverage: {0}% ({1} from {2})", Coverage * 100, _coveredCount, InstructionCount); writer.WriteLine("--------------------------------------------------"); writer.WriteLine("Not covered instructions:"); writer.WriteLine("--------------------------------------------------"); foreach (var i in GetAllInstructions()) if (i != null && !i.IsUsed) writer.WriteLine(i); writer.WriteLine(); writer.WriteLine("--------------------------------------------------"); writer.WriteLine("Covered instructions:"); writer.WriteLine("--------------------------------------------------"); foreach (var i in GetAllInstructions()) if (i != null && i.IsUsed) writer.WriteLine(i); } public static void DumpCoverage(string path) { Directory.CreateDirectory(Path.GetDirectoryName(path)); using (var writer = new StreamWriter(path)) DumpCoverage(writer); } #endregion } }
34.825485
103
0.467308
[ "MIT" ]
GrapeCity/pagefx
source/libs/Core/IL/CIL.cs
12,572
C#
// ============================================================================================================== // Microsoft patterns & practices // CQRS Journey project // ============================================================================================================== // ©2012 Microsoft. All rights reserved. Certain content used with permission from contributors // http://go.microsoft.com/fwlink/p/?LinkID=258575 // 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 Payments.ReadModel { using System; public interface IPaymentDao { ThirdPartyProcessorPaymentDetails GetThirdPartyProcessorPaymentDetails(Guid paymentId); } }
55.565217
114
0.56338
[ "Apache-2.0" ]
wayne-o/delete-me
source/Conference/Payments/ReadModel/IPaymentDao.cs
1,281
C#
namespace ComponentFramework { using System; using System.Collections.Generic; using System.Diagnostics; using System.Reflection; using System.Runtime.CompilerServices; public class ComponentObject { #region Constructors public ComponentObject() { this.components = new List<Component>(); } #endregion #region Properties private List<Component> components { get; set; } #endregion #region Methods public T AddComponent<T>() where T : Component { T component = Activator.CreateInstance<T>(); this.AddComponent(component); return component; } public T AddComponent<T>(T component) where T : Component { if (component.Parent != null) { throw new InvalidOperationException("Components cannot be assigned to multiple component objects."); } component.Parent = this; this.components.Add(component); return component; } public List<T> GetComponents<T>() where T : Component { List<T> results = new List<T>(); List<Component> components = this.components; int componentCount = components.Count; for (int i = 0; i < componentCount; i++) { Component component = components[i]; if (component is T typedComponent) { results.Add(typedComponent); } } return results; } public void InvokeComponents(object parameter1 = null, object parameter2 = null, object parameter3 = null, object parameter4 = null, object parameter5 = null, object parameter6 = null, object parameter7 = null, object parameter8 = null, [CallerMemberName] string methodName = "Default", int depth = 1, object source = null) { // Enumerator Components for (int i = 0; i < this.components.Count; i++) { // Component Component component = this.components[i]; // Lock Component lock (component) { // Is Enabled? if (!component.IsEnabled) { continue; } // Populate Type Cache if (component.TypeCache == null) { Type type = component.GetType(); component.TypeCache = type.GetTypeInfo(); } // Populate Connection if (!component.Connections.ContainsKey(methodName)) { // Stack StackTrace stackTrace = new StackTrace(); StackFrame parentStackFrame = stackTrace.GetFrame(depth); // Method MethodBase parentMethodBase = parentStackFrame.GetMethod(); // Parameters ParameterInfo[] parentParameterInfos = parentMethodBase.GetParameters(); Type[] types = new Type[parentParameterInfos.Length + 1]; string[] names = new string[parentParameterInfos.Length + 1]; types[0] = this.GetType(); names[0] = "source"; for (int j = 0; j < parentParameterInfos.Length; j++) { ParameterInfo parentParameterInfo = parentParameterInfos[j]; Type parameterType = parentParameterInfo.ParameterType; if (parameterType.IsValueType) { Type boxedType = typeof(Boxed<>); parameterType = boxedType.MakeGenericType(parameterType); } types[j + 1] = parameterType; names[j + 1] = parentParameterInfo.Name; } // Return Type MethodInfo parentMethodInfo = parentMethodBase as MethodInfo; if (parentMethodInfo != null && parentMethodInfo.ReturnType != typeof(void)) { Type boxedType = typeof(Boxed<>); Type returnType = boxedType.MakeGenericType(parentMethodInfo.ReturnType); Type[] typesPlusReturn = new Type[types.Length + 1]; Array.Copy(types, typesPlusReturn, types.Length); typesPlusReturn[types.Length] = returnType; types = typesPlusReturn; } // Connection ComponentConnection connection = new ComponentConnection(); connection.ParameterTypes = types; connection.ParameterNames = names; connection.ParameterBuffer = new object[types.Length]; // Component Method MethodInfo methodInfo = component.TypeCache.GetMethod(methodName, types); if (methodInfo != null) { Type actionType = typeof(Action<>); if (types.Length == 1) { actionType = typeof(Action<>); } else if (types.Length == 2) { actionType = typeof(Action<,>); } else if (types.Length == 3) { actionType = typeof(Action<,,>); } else if (types.Length == 4) { actionType = typeof(Action<,,,>); } else if (types.Length == 5) { actionType = typeof(Action<,,,,>); } else if (types.Length == 6) { actionType = typeof(Action<,,,,,>); } else if (types.Length == 7) { actionType = typeof(Action<,,,,,,>); } else if (types.Length == 8) { actionType = typeof(Action<,,,,,,,>); } else if (types.Length == 8) { actionType = typeof(Action<,,,,,,,,>); } Type specificActionType = actionType.MakeGenericType(types); connection.MethodDelegate = methodInfo.CreateDelegate(specificActionType, component); } // Add component.Connections.Add(methodName, connection); } // Get Connection ComponentConnection connectionToExecute = component.Connections[methodName]; // Parameter Buffer connectionToExecute.ParameterBuffer[0] = source ?? this; if (connectionToExecute.ParameterBuffer.Length > 1) { connectionToExecute.ParameterBuffer[1] = parameter1; } if (connectionToExecute.ParameterBuffer.Length > 2) { connectionToExecute.ParameterBuffer[2] = parameter2; } if (connectionToExecute.ParameterBuffer.Length > 3) { connectionToExecute.ParameterBuffer[3] = parameter3; } if (connectionToExecute.ParameterBuffer.Length > 4) { connectionToExecute.ParameterBuffer[4] = parameter4; } if (connectionToExecute.ParameterBuffer.Length > 5) { connectionToExecute.ParameterBuffer[5] = parameter5; } if (connectionToExecute.ParameterBuffer.Length > 6) { connectionToExecute.ParameterBuffer[6] = parameter6; } if (connectionToExecute.ParameterBuffer.Length > 7) { connectionToExecute.ParameterBuffer[7] = parameter7; } if (connectionToExecute.ParameterBuffer.Length > 8) { connectionToExecute.ParameterBuffer[8] = parameter8; } if (connectionToExecute.ParameterBuffer.Length > 8) { connectionToExecute.ParameterBuffer[9] = parameter8; } // Execute if (connectionToExecute.MethodDelegate != null) { connectionToExecute.MethodDelegate.DynamicInvoke(connectionToExecute.ParameterBuffer); component.DynamicInvoke(methodName, connectionToExecute.ParameterTypes, connectionToExecute.ParameterNames, connectionToExecute.ParameterBuffer, true); component.InvokeComponents(parameter1, parameter2, parameter3, parameter4, parameter5, parameter6, parameter7, parameter8, methodName, depth + 1, this); } else { component.DynamicInvoke(methodName, connectionToExecute.ParameterTypes, connectionToExecute.ParameterNames, connectionToExecute.ParameterBuffer, false); } } } // Reset Boxer Boxer.Reset(); } #endregion } }
43.163934
331
0.448253
[ "MIT" ]
bhickenbottom/Claw
ComponentFramework/ComponentObject.cs
10,534
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Ncqrs.Commanding.CommandExecution.Mapping.Attributes; using Ncqrs.Commanding; namespace Ncqrs.Eventing.Storage.WindowsAzure.Tests.Env { [MapsToAggregateRootMethod(typeof(Note), "ChangeNoteText")] public class ChangeNoteCommand : CommandBase { [AggregateRootId] public Guid NoteId { get; set; } public string NewNoteText { get; set; } } }
26.222222
63
0.733051
[ "Apache-2.0" ]
adamcogx/ncqrs
Extensions/src/Ncqrs.Eventing.Storage.WindowsAzure.Tests/Env/ChangeNoteCommand.cs
474
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Reflection.Context.Projection; namespace System.Reflection.Context.Custom { internal sealed class CustomFieldInfo : ProjectingFieldInfo { public CustomFieldInfo(FieldInfo template, CustomReflectionContext context) : base(template, context.Projector) { ReflectionContext = context; } public CustomReflectionContext ReflectionContext { get; } // Currently only the results of GetCustomAttributes can be customizaed. // We don't need to override GetCustomAttributesData. public override object[] GetCustomAttributes(bool inherit) { return GetCustomAttributes(typeof(object), inherit); } public override object[] GetCustomAttributes(Type attributeType, bool inherit) { return AttributeUtils.GetCustomAttributes( ReflectionContext, this, attributeType, inherit ); } public override bool IsDefined(Type attributeType, bool inherit) { return AttributeUtils.IsDefined(this, attributeType, inherit); } } }
32.219512
86
0.647237
[ "MIT" ]
belav/runtime
src/libraries/System.Reflection.Context/src/System/Reflection/Context/Custom/CustomFieldInfo.cs
1,321
C#
using System; using System.Xml.Serialization; namespace Alipay.AopSdk.Domain { /// <summary> /// AlipayOpenPublicThirdCustomerServiceModel Data Structure. /// </summary> [Serializable] public class AlipayOpenPublicThirdCustomerServiceModel : AopObject { /// <summary> /// 服务窗商户在渠道商处对应的用户id /// </summary> [XmlElement("channel_uid")] public string ChannelUid { get; set; } } }
23.421053
70
0.642697
[ "MIT" ]
ArcherTrister/LeXun.Alipay.AopSdk
src/Alipay.AopSdk/Domain/AlipayOpenPublicThirdCustomerServiceModel.cs
475
C#
using System.Collections.Generic; using System.IO.Abstractions.TestingHelpers; using System.Runtime.InteropServices; using Microsoft.Extensions.Logging; public class IngestionOrchestratorTests { private readonly DriveWatcher driveWatcherService; private readonly TestDriveAttachedNotifier testDriveAttachedNotifier; private readonly Mock<IDriveTypeIdentifier> mockDriveTypeIdentifier; private readonly MockFileSystem mockFileSystem; private readonly Mock<IngestionService> mockIngestionService; public IngestionOrchestratorTests() { var logger = new Mock<ILogger<DriveWatcher>>(); testDriveAttachedNotifier = new TestDriveAttachedNotifier(); mockDriveTypeIdentifier = new Mock<IDriveTypeIdentifier>(); mockFileSystem = new MockFileSystem(); mockIngestionService = new Mock<IngestionService>( new Mock<ILogger<IngestionService>>().Object, new Mock<IEnvironment>().Object, new List<IIngestionStrategy>(), new Mock<ICopyProvider>().Object, mockFileSystem ); mockIngestionService.Setup(x => x.Ingest(It.IsAny<IDriveInfo>(), It.IsAny<CancellationToken>())); driveWatcherService = new DriveWatcher( logger.Object, testDriveAttachedNotifier, mockDriveTypeIdentifier.Object, mockFileSystem, mockIngestionService.Object ); } [MacOsSpecificFact] public async Task ShouldIngestDrivesOnStartup_MacOS() { mockDriveTypeIdentifier.Setup(x => x.IsRemovableDrive(It.IsAny<IDriveInfo>())).Returns(Task.FromResult(true)); await driveWatcherService.StartAsync(new CancellationToken()); mockIngestionService.Verify(x => x.Ingest(It.Is<IDriveInfo>(driveInfo => driveInfo.RootDirectory.FullName == "/:"), It.IsAny<CancellationToken>()), Times.Once); } [MacOsSpecificFact] public async Task ShouldIngestOnDriveAttached_MacOS() { var rootDirectory = "/Volumes/TestDrive"; await driveWatcherService.StartAsync(new CancellationToken()); mockFileSystem.AddDirectory(rootDirectory); var driveInfo = mockFileSystem.DriveInfo.FromDriveName("/Volumes/TestDrive"); testDriveAttachedNotifier.AttachDrive(driveInfo); mockIngestionService.Verify(x => x.Ingest(It.Is<IDriveInfo>(driveInfo => driveInfo.RootDirectory.FullName == rootDirectory), It.IsAny<CancellationToken>()), Times.Once); } [WindowsSpecificFact] public async Task ShouldIngestDrivesOnStartup_Windows() { mockDriveTypeIdentifier.Setup(x => x.IsRemovableDrive(It.IsAny<IDriveInfo>())).Returns(Task.FromResult(true)); await driveWatcherService.StartAsync(new CancellationToken()); mockIngestionService.Verify(x => x.Ingest(It.Is<IDriveInfo>(driveInfo => driveInfo.RootDirectory.FullName == @"C:\"), It.IsAny<CancellationToken>()), Times.Once); } }
46.0625
177
0.717436
[ "MIT" ]
biltongza/CardIngestor
Ingestor.Daemon.Tests/DriveWatcherTests.cs
2,948
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace Microsoft.Store.PartnerCenter.PowerShell.Commands { using System.Collections.Generic; using System.Linq; using System.Management.Automation; using PartnerCenter.Models; using PartnerCenter.Models.Incidents; /// <summary> /// Gets a list of service incidents from Partner Center. /// </summary> [Cmdlet(VerbsCommon.Get, "PartnerServiceIncident"), OutputType(typeof(ServiceIncidentDetail))] public class GetPartnerServiceIncident : PartnerCmdlet { /// <summary> /// Gets or sets the optional status type. /// </summary> [Parameter(Mandatory = false, HelpMessage = "Specifies which status types to return.")] [ValidateSet(nameof(ServiceIncidentStatus.Critical), nameof(ServiceIncidentStatus.Information), nameof(ServiceIncidentStatus.Normal), nameof(ServiceIncidentStatus.Warning))] public ServiceIncidentStatus? Status { get; set; } /// <summary> /// Gets or sets the optional Resolved switch. /// </summary> [Parameter(Mandatory = false, HelpMessage = "If specified resolved incidents are also returned.")] public SwitchParameter Resolved { get; set; } /// <summary> /// Executes the operations associated with the cmdlet. /// </summary> public override void ExecuteCmdlet() { ResourceCollection<ServiceIncidents> incidents; IEnumerable<ServiceIncidentDetail> results; incidents = Partner.ServiceIncidents.GetAsync().ConfigureAwait(false).GetAwaiter().GetResult(); if (incidents.TotalCount > 0) { results = incidents.Items.SelectMany(i => i.Incidents); if (Status.HasValue) { results = results.Where(i => i.Status == Status); } if (!Resolved) { results = results.Where(i => !i.Resolved); } WriteObject(results, true); } } } }
37.813559
181
0.621246
[ "MIT" ]
arjjsolutions/Partner-Center-PowerShell
src/PowerShell/Commands/GetPartnerServiceIncident.cs
2,233
C#
using System; using System.Runtime.InteropServices; using OptixCore.Library.Native; namespace OptixCore.Library { /// <summary> /// Defines the Matrix layout used by Optix: Row major or Column major /// </summary> public enum MatrixLayout { ColumnMajor = 0, RowMajor = 1 }; /// <summary> /// Type of Bounding Volume Hierarchy algorithm that will be used for <see cref="OptixCore.Library.Acceleration">Acceleration</see> construction. /// </summary> public enum AccelBuilder { /// <summary> /// Specifies that no acceleration structure is explicitly built. Traversal linearly loops /// through the list of primitives to intersect. This can be useful e.g. for higher level groups with only /// few children, where managing a more complex structure introduces unnecessary overhead. /// </summary> NoAccel, /// <summary> /// A standard bounding volume hierarchy, useful for most types of graph levels and geometry. /// Medium build speed, good ray tracing performance. /// </summary> Bvh, /// <summary> /// A high quality BVH variant for maximum ray tracing performance. Slower build speed and /// slightly higher memory footprint than <see cref="AccelBuilder.Bvh">Bvh</see> /// </summary> Sbvh, /// <summary> /// High quality similar to <see cref="AccelBuilder.Sbvh">Sbvh</see> but with fast build performance. The Trbvh builder uses about /// 2.5 times the size of the final BVH for scratch space. A CPU-based Trbvh builder that does not /// have the memory constraints is available. OptiX includes an optional automatic fallback to the /// CPU version when out of GPU memory /// </summary> Trbvh, /// <summary> /// Very fast GPU based accelertion good for animated scenes.<br/> /// Traversers: <see cref="OptixCore.Library.AccelTraverser">Bvh</see> or <see cref="OptixCore.Library.AccelTraverser">BvhCompact</see>. /// </summary> [Obsolete("version 4.0")] Lbvh, /// <summary> /// Uses a fast construction scheme to produce a medium quality bounding volume hierarchy.<br/> /// Traversers: <see cref="OptixCore.Library.AccelTraverser.Bvh">Bvh</see> or <see cref="OptixCore.Library.AccelTraverser.Bvh">BvhCompact</see>. /// </summary> [Obsolete("version 4.0")] MedianBvh, /// <summary> /// Constructs a high quality kd-tree and is comparable to Sbvh in traversal perfromance.<br/> /// Has the highest memory footprint and construction time.<br/> /// Requires certain properties to be set, such as: <see cref="OptixCore.Library.Acceleration.VertexBufferName">VertexBufferName</see> /// and <see cref="OptixCore.Library.Acceleration.IndexBufferName">IndexBufferName</see>.<br/> /// Traversers: <see cref="OptixCore.Library.AccelTraverser">Bvh</see> or <see cref="OptixCore.Library.AccelTraverser">BvhCompact</see>. /// </summary> [Obsolete("version 4.0")] TriangleKdTree }; /// <summary> /// Type of Bounding Volume Hierarchy algorithm that will be used for <see cref="OptixCore.Library.Acceleration">Acceleration</see> traversal. /// </summary> [Obsolete("Obsolete after verseion 4.0")] public enum AccelTraverser { /// <summary> /// No Acceleration structure. Linearly traverses primitives in the scene.<br/> /// Builders: <see cref="AccelBuilder">NoAccel</see>. /// </summary> NoAccel, /// <summary> /// Uses a classic Bounding Volume Hierarchy traversal.<br/> /// Builders: <see cref="OptixCore.Library.AccelBuilder">Lbvh</see>, <see cref="OptixCore.Library.AccelBuilder">Bvh</see> /// <see cref="OptixCore.Library.AccelBuilder">MedianBvh</see>, or <see cref="OptixCore.Library.AccelBuilder">Sbvh</see>.<br/> /// </summary> Bvh, /// <summary> /// Compresses bvh data by a factor of 4 before uploading to the GPU. Acceleration data is decompressed on the fly during traversal.<br/> /// Useful for large static scenes that require more than a gigabyte of memory, and to minimize page misses for virtual memory.<br/> /// Builders: <see cref="OptixCore.Library.AccelBuilder">Lbvh</see>, <see cref="OptixCore.Library.AccelBuilder">Bvh</see> /// <see cref="OptixCore.Library.AccelBuilder">MedianBvh</see>, or <see cref="OptixCore.Library.AccelBuilder">Sbvh</see>.<br/> /// </summary> BvhCompact, /// <summary> /// Uses a kd-tree traverser.<br/> /// Builders: <see cref="OptixCore.Library.AccelBuilder">TriangleKdTree</see>. /// </summary> KdTree }; public class Acceleration : OptixNode { AccelBuilder mBuilder; public Acceleration(Context context, AccelBuilder mBuilder) : base(context) { CheckError(Api.rtAccelerationCreate(context.InternalPtr, ref InternalPtr)); gch = GCHandle.Alloc(InternalPtr, GCHandleType.Pinned); Builder = mBuilder; MarkAsDirty(); } internal Acceleration(Context ctx, IntPtr acc) : base(ctx) { InternalPtr = acc; IntPtr str = IntPtr.Zero; CheckError(Api.rtAccelerationGetBuilder(InternalPtr, ref str)); String temp = Marshal.PtrToStringAnsi(str); if (temp == "RtcBvh") { mBuilder = AccelBuilder.Trbvh; } else { mBuilder = AccelBuilder.NoAccel; } //mBuilder = (AccelBuilder)Enum.Parse(mBuilder.GetType(), Marshal.PtrToStringAnsi(str)); } public override void Validate() { CheckError(Api.rtAccelerationValidate(InternalPtr)); } public override void Destroy() { if (InternalPtr != IntPtr.Zero) CheckError(Api.rtAccelerationDestroy(InternalPtr)); InternalPtr = IntPtr.Zero; gch.Free(); } public void MarkAsDirty() { CheckError(Api.rtAccelerationMarkDirty(InternalPtr)); } public bool IsDirty() { CheckError(Api.rtAccelerationIsDirty(InternalPtr, out var dirty)); return dirty == 1; } public BufferStream Data { get { uint size = 0u; CheckError(Api.rtAccelerationGetDataSize(InternalPtr, ref size)); var data = IntPtr.Zero; CheckError(Api.rtAccelerationGetData(InternalPtr, data)); return new BufferStream(data, size, true, false, true); } set => CheckError(Api.rtAccelerationSetData(InternalPtr, value.DataPointer, (uint)value.Length)); } /// <summary> /// Sets the 'refit' property on the acceleration structure. Refit tells Optix that only small geometry changes have been made, /// and to NOT perform a full rebuild of the hierarchy. Only a valid property on Bvh built acceleration structures. /// </summary> /// <remarks> /// Available in: Trbvh, Bvh If set to "1", the builder will only readjust the node bounds of the /// bounding volume hierarchy instead of constructing it from scratch.Refit is only effective if there is /// an initial BVH already in place, and the underlying geometry has undergone relatively modest /// deformation.In this case, the builder delivers a very fast BVH update without sacrificing too much /// ray tracing performance.The default is "0". /// </remarks> public bool Refit { get { switch (mBuilder) { case AccelBuilder.Trbvh: case AccelBuilder.Bvh: IntPtr str = IntPtr.Zero; CheckError(Api.rtAccelerationGetProperty(InternalPtr, "refit", ref str)); return int.Parse(Marshal.PtrToStringAnsi(str)) == 1; default: return false; } } set { switch (mBuilder) { case AccelBuilder.Trbvh: case AccelBuilder.Bvh: CheckError(Api.rtAccelerationSetProperty(InternalPtr, "refit", value ? "1" : "0")); break; default: break; } } } /// <summary> /// Sets 'vertex_buffer_name' property of the acceleration structure. This notifies Sbvh and TriangkeKdTree builders to look at the /// vertex buffer assigned to 'vertex_buffer_name' in order to build the hierarchy. /// This must match the name of the variable the buffer is attached to. /// Property only valid for Sbvh or TriangleKdTree built acceleration structures. /// </summary> /// <remarks> /// Available in: Trbvh, Sbvh The name of the buffer variable holding triangle /// vertex data.Each vertex consists of 3 floats.The default is "vertex_buffer" /// </remarks> public string VertexBufferName { get { switch (mBuilder) { case AccelBuilder.Trbvh: case AccelBuilder.Sbvh: IntPtr str = IntPtr.Zero; CheckError(Api.rtAccelerationGetProperty(InternalPtr, "vertex_buffer_name", ref str)); return Marshal.PtrToStringAnsi(str); default: return "vertex_buffer"; } } set { switch (mBuilder) { case AccelBuilder.Trbvh: case AccelBuilder.Sbvh: CheckError(Api.rtAccelerationSetProperty(InternalPtr, "vertex_buffer_name", value)); break; default: break; } } } /// <summary> /// Sets 'vertex_buffer_stride' property in bytes of the acceleration structure. This defines the offset between two vertices. Default is assumed to be 0. /// Property only valid for Sbvh or TriangleKdTree built acceleration structures. /// </summary> /// <remarks> /// Available in: Trbvh, Sbvh The offset between two vertices in the vertex /// buffer, given in bytes.The default value is "0", which assumes the vertices are tightly packed /// </remarks> public int VertexBufferStride { get { switch (mBuilder) { case AccelBuilder.Trbvh: case AccelBuilder.Sbvh: IntPtr str = IntPtr.Zero; CheckError(Api.rtAccelerationGetProperty(InternalPtr, "vertex_buffer_stride", ref str)); return int.Parse(Marshal.PtrToStringAnsi(str)); default: return 0; } } set { switch (mBuilder) { case AccelBuilder.Trbvh: case AccelBuilder.Sbvh: CheckError(Api.rtAccelerationSetProperty(InternalPtr, "vertex_buffer_stride", value.ToString())); break; default: break; } } } /// <summary> /// Sets 'index_buffer_name' property of the acceleration structure. This notifies Sbvh and TriangkeKdTree builders to look at the /// index buffer assigned to 'index_buffer_name' in order to build the hierarchy. /// This must match the name of the variable the buffer is attached to. /// Property only valid for Sbvh or TriangleKdTree built acceleration structures. /// </summary> /// <remarks> /// Available in: Trbvh, Sbvh The name of the buffer variable holding vertex /// index data.The entries in this buffer are indices of type int, where each index refers to one entry /// in the vertex buffer.A sequence of three indices represents one triangle. If no index buffer is /// given, the vertices in the vertex buffer are assumed to be a list of triangles, i.e.every 3 vertices in /// a row form a triangle.The default is "index_buffer". /// </remarks> public string IndexBufferName { get { switch (mBuilder) { case AccelBuilder.Trbvh: case AccelBuilder.Sbvh: IntPtr str = IntPtr.Zero; CheckError(Api.rtAccelerationGetProperty(InternalPtr, "index_buffer_name", ref str)); return Marshal.PtrToStringAnsi(str); default: return "index_buffer"; } } set { switch (mBuilder) { case AccelBuilder.Trbvh: case AccelBuilder.Sbvh: CheckError(Api.rtAccelerationSetProperty(InternalPtr, "index_buffer_name", value)); break; default: break; } } } /// <summary> /// Sets 'index_buffer_stride' property in bytes of the acceleration structure. This defines the offset between two indices. Default is assumed to be 0. /// Property only valid for Sbvh or TriangleKdTree built acceleration structures. /// </summary> /// <remarks> /// Available in: Trbvh, Sbvh The offset between two indices in the index buffer, /// given in bytes.The default value is "0", which assumes the indices are tightly packed. /// </remarks> public int IndexBufferStride { get { switch (mBuilder) { case AccelBuilder.Trbvh: case AccelBuilder.Sbvh: IntPtr str = IntPtr.Zero; CheckError(Api.rtAccelerationGetProperty(InternalPtr, "index_buffer_stride", ref str)); return int.Parse(Marshal.PtrToStringAnsi(str)); default: return 0; } } set { switch (mBuilder) { case AccelBuilder.Trbvh: case AccelBuilder.Sbvh: CheckError(Api.rtAccelerationSetProperty(InternalPtr, "index_buffer_stride", value.ToString())); break; default: break; } } } /// <summary> /// Sets 'chunk_size' property of the acceleration structure. /// </summary> /// <remarks> /// Available in: Trbvh Number of bytes to be used for a partitioned acceleration /// structure build. If no chunk size is set, or set to "0", the chunk size is chosen automatically. If set /// to "-1", the chunk size is unlimited. The minimum chunk size is 64MB. Please note that specifying /// a small chunk size reduces the peak-memory footprint of the Trbvh but can result in slower /// rendering performance. /// </remarks> public int ChunkSize { get { if (mBuilder == AccelBuilder.Trbvh) { var str = IntPtr.Zero; CheckError(Api.rtAccelerationGetProperty(InternalPtr, "chunk_size", ref str)); return int.Parse(Marshal.PtrToStringAnsi(str)); } return 0; } set { if (mBuilder == AccelBuilder.Trbvh) { CheckError(Api.rtAccelerationSetProperty(InternalPtr, "chunk_size", value.ToString())); } } } /// <summary> /// Sets 'motion_steps' property of the acceleration structure. /// </summary> /// <remarks> /// Available in: Trbvh Number of motion steps to build into an acceleration structure /// that contains motion geometry or motion transforms. Ignored for acceleration structures built over /// static nodes. Gives a tradeoff between device memory and time: if the input geometry or /// transforms have many motion steps, then increasing the motion steps in the acceleration /// structure may result in faster traversal, at the cost of linear increase in memory usage. Default 2, /// and clamped >=1. /// </remarks> public int MotionSteps { get { if (mBuilder == AccelBuilder.Trbvh) { var str = IntPtr.Zero; CheckError(Api.rtAccelerationGetProperty(InternalPtr, "motion_steps", ref str)); return int.Parse(Marshal.PtrToStringAnsi(str)); } return 2; } set { if (mBuilder == AccelBuilder.Trbvh) { CheckError(Api.rtAccelerationSetProperty(InternalPtr, "motion_steps", value.ToString())); } } } public AccelBuilder Builder { get => mBuilder; set { CheckError(Api.rtAccelerationSetBuilder(InternalPtr, value.ToString())); mBuilder = value; } } } }
40.59867
162
0.551557
[ "MIT" ]
jonnybasic/tesNet
OptixCore.Library/Acceleration.cs
18,312
C#
/*Write a recursive program for generating and printing all ordered k-element subsets from n-element set (variations Vkn). Example: n=3, k=2, set = {hi, a, b} → (hi hi), (hi a), (hi b), (a hi), (a a), (a b), (b hi), (b a), (b b)*/ namespace Subsets { using System; public class Startup { public const int K = 2; public static readonly string[] elements = { "hi", "a", "b" }; public static int N = elements.Length; public static int[] variations = new int[N]; public static void Main() { Variations(0); } private static void Variations(int depth) { if (depth >= K) { Print(); return; } for (int i = 0; i < N; i++) { variations[depth] = i; Variations(depth + 1); } } private static void Print() { for (int i = 0; i < K; i++) { Console.Write(elements[variations[i]] + " "); } Console.WriteLine(); } } }
25.311111
123
0.447761
[ "MIT" ]
danisio/DataStructuresAndAlgorithms-Homeworks
07.Recursion/05.Subsets/Startup.cs
1,143
C#
using System.ComponentModel.DataAnnotations; using System.Threading.Tasks; using GW.Site.Data; using GW.Site.Extensions; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; using Microsoft.Extensions.Logging; namespace GW.Site.Pages.Account { public class LoginWith2faModel : PageModel { private readonly SignInManager<ApplicationUser> _signInManager; private readonly ILogger<LoginWith2faModel> _logger; public LoginWith2faModel(SignInManager<ApplicationUser> signInManager, ILogger<LoginWith2faModel> logger) { _signInManager = signInManager; _logger = logger; } [BindProperty] public InputModel Input { get; set; } public bool RememberMe { get; set; } public string ReturnUrl { get; set; } public class InputModel { [Required] [StringLength(7, ErrorMessage = "The {0} must be at least {2} and at max {1} characters long.", MinimumLength = 6)] [DataType(DataType.Text)] [Display(Name = "Authenticator code")] public string TwoFactorCode { get; set; } [Display(Name = "Remember this machine")] public bool RememberMachine { get; set; } } public async Task<IActionResult> OnGetAsync(bool rememberMe, string returnUrl = null) { // Ensure the user has gone through the username & password screen first var user = await _signInManager.GetTwoFactorAuthenticationUserAsync(); if (user == null) { return NotFound(); } ReturnUrl = returnUrl; RememberMe = rememberMe; return Page(); } public async Task<IActionResult> OnPostAsync(bool rememberMe, string returnUrl = null) { if (!ModelState.IsValid) { return Page(); } var user = await _signInManager.GetTwoFactorAuthenticationUserAsync(); if (user == null) { return NotFound(); } var authenticatorCode = Input.TwoFactorCode.Replace(" ", string.Empty).Replace("-", string.Empty); var result = await _signInManager.TwoFactorAuthenticatorSignInAsync(authenticatorCode, rememberMe, Input.RememberMachine); if (result.Succeeded) { _logger.LogInformation("User with ID '{UserId}' logged in with 2fa.", user.Id); return LocalRedirect(Url.GetLocalUrl(returnUrl)); } else if (result.IsLockedOut) { _logger.LogWarning("User with ID '{UserId}' account locked out.", user.Id); return RedirectToPage("./Lockout"); } else { _logger.LogWarning("Invalid authenticator code entered for user with ID '{UserId}'.", user.Id); ModelState.AddModelError(string.Empty, "Invalid authenticator code."); return Page(); } } } }
34.56383
135
0.574331
[ "MIT" ]
goatwranglers/podcastsite
BlogTemplate/Pages/Account/LoginWith2fa.cshtml.cs
3,249
C#
using System; using Advertise.ServiceLayer.Contracts.Products; using Advertise.ViewModel.Models.Products; using System.Threading.Tasks; using Advertise.DomainClasses.Entities.Products; using Advertise.DataLayer.Context; using AutoMapper; using System.Data.Entity; using System.Linq; using AutoMapper.QueryableExtensions; using EntityFramework.Extensions; using System.Collections.Generic; namespace Advertise.ServiceLayer.EFServices.Products { public class ProductImageService : IProductImageService { #region Fields private readonly IMapper _mapper; private readonly IUnitOfWork _unitOfWork; private readonly IDbSet<ProductImage> _productImage; #endregion #region Ctor public ProductImageService(IMapper mapper, IUnitOfWork unitOfWork) { _mapper = mapper; _unitOfWork = unitOfWork; _productImage = unitOfWork.Set<ProductImage>(); } #endregion #region Edit public void EditImageProductForComany() { throw new NotImplementedException(); } public int EditImageForComany() { throw new NotImplementedException(); } public async Task EditAsync(ProductImageEditViewModel viewModel) { var productImage = await _productImage.FirstAsync(model => model.Id == viewModel.Id); _mapper.Map(viewModel, productImage); await _unitOfWork.SaveAllChangesAsync(auditUserId: new Guid("9D2B0228-4D0D-4C23-8B49-01A698857709")); } public async Task<ProductImageEditViewModel> GetForEditAsync(Guid id) { return await _productImage .AsNoTracking() .ProjectTo<ProductImageEditViewModel>(parameters: null, configuration: _mapper.ConfigurationProvider) .FirstOrDefaultAsync(model => model.Id == id); } #endregion #region Create public async Task CreateAsync(ProductImageCreateViewModel viewModel) { var productImage = _mapper.Map<ProductImage>(viewModel); _productImage.Add(productImage); await _unitOfWork.SaveAllChangesAsync(auditUserId: new Guid("9D2B0228-4D0D-4C23-8B49-01A698857709")); } public async Task<ProductImageCreateViewModel> GetForCreateAsync() { return await Task.Run(() => new ProductImageCreateViewModel()); } #endregion #region Delete public Task DeleteAsync(ProductImageDeleteViewModel viewModel) { return _productImage.Where(model => model.Id == viewModel.Id).DeleteAsync(); } public async Task<ProductImageDeleteViewModel> GetForDeleteAsync(Guid id) { return await _productImage .AsNoTracking() .ProjectTo<ProductImageDeleteViewModel>(parameters: null, configuration: _mapper.ConfigurationProvider) .FirstOrDefaultAsync(model => model.Id == id); } #endregion #region Read public IList<ProductImageListViewModel> GetChildList(Guid? parentId) { throw new NotImplementedException(); } public IList<ProductImageListViewModel> GetParentList() { throw new NotImplementedException(); } public async Task<IEnumerable<ProductImageListViewModel>> GetListAsync() { return await _productImage .AsNoTracking() .ProjectTo<ProductImageListViewModel>(parameters: null, configuration: _mapper.ConfigurationProvider) .ToListAsync(); } public async Task<ProductImageDetailViewModel> GetDetailsAsync(Guid id) { return await _productImage .AsNoTracking() .ProjectTo<ProductImageDetailViewModel>(parameters: null, configuration: _mapper.ConfigurationProvider) .FirstOrDefaultAsync(model => model.Id == id); } public Task<ProductImageListViewModel> FindById(Guid id) { throw new NotImplementedException(); } public Task FillCreateViewModel(ProductImageCreateViewModel viewModel) { throw new NotImplementedException(); } public int EditOrderImageProductForComany() { throw new NotImplementedException(); } public int GetCountAllImage() { throw new NotImplementedException(); } public int GetAllImage() { throw new NotImplementedException(); } public int GetCountImageProductCompany() { throw new NotImplementedException(); } public int GetImageProductCompany() { throw new NotImplementedException(); } public int GetCountAllImageCompany() { throw new NotImplementedException(); } public int GetCountImageInPlan() { throw new NotImplementedException(); } #endregion } }
30.502959
119
0.628904
[ "Apache-2.0" ]
imangit/Advertise
Advertise/Advertise.ServiceLayer/EFServices/Products/ProductImageService.cs
5,157
C#
using System; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace Calendar4e.Models { public class Task { [Key] public Int64 TaskID { get; set; } public String subject { get; set; } public String description { get; set; } [DataType(DataType.Date)] public String start { get; set; } [DataType(DataType.Date)] public String end { get; set; } public bool allDay { get; set; } = false; public String color { get; set; } = "rgba(128, 128, 128, 0.9)"; public virtual Student Student { get; set; } } }
23.275862
71
0.591111
[ "MIT" ]
pepsm/JS-Practice
calendar4e/Calendar4e/Models/Task.cs
677
C#
/* _BEGIN_TEMPLATE_ { "id": "TRLA_174", "name": [ "铁角鼓手", "Ironhorn Drummer" ], "text": [ "在你的回合时,你的随从的生命值无法被降到1点以下。", "Your minions can't be reduced below 1 Health on your turn." ], "cardClass": "WARRIOR", "type": "MINION", "cost": 5, "rarity": null, "set": "TROLL", "collectible": null, "dbfId": 52927 } _END_TEMPLATE_ */ namespace HREngine.Bots { class Sim_TRLA_174 : SimTemplate //* 铁角鼓手 Ironhorn Drummer { //Your minions can't be reduced below 1 Health on your turn. //在你的回合时,你的随从的生命值无法被降到1点以下。 } }
19.724138
68
0.606643
[ "MIT" ]
chi-rei-den/Silverfish
cards/TROLL/TRLA/Sim_TRLA_174.cs
684
C#
namespace OnlineHelpdeskAppUI.Forms { partial class UserForm { /// <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.btn_logout = new System.Windows.Forms.Button(); this.lbl_greetings = new System.Windows.Forms.Label(); this.link_addticket = new System.Windows.Forms.LinkLabel(); this.link_tickets = new System.Windows.Forms.LinkLabel(); this.SuspendLayout(); // // btn_logout // this.btn_logout.Location = new System.Drawing.Point(695, 12); this.btn_logout.Name = "btn_logout"; this.btn_logout.Size = new System.Drawing.Size(93, 34); this.btn_logout.TabIndex = 1; this.btn_logout.Text = "Log Out"; this.btn_logout.UseVisualStyleBackColor = true; this.btn_logout.Click += new System.EventHandler(this.btn_logout_Click); // // lbl_greetings // this.lbl_greetings.AutoSize = true; this.lbl_greetings.Location = new System.Drawing.Point(25, 29); this.lbl_greetings.Name = "lbl_greetings"; this.lbl_greetings.Size = new System.Drawing.Size(74, 17); this.lbl_greetings.TabIndex = 7; this.lbl_greetings.Text = "Welcome, "; // // link_addticket // this.link_addticket.AutoSize = true; this.link_addticket.Location = new System.Drawing.Point(28, 81); this.link_addticket.Name = "link_addticket"; this.link_addticket.Size = new System.Drawing.Size(75, 17); this.link_addticket.TabIndex = 8; this.link_addticket.TabStop = true; this.link_addticket.Text = "Add Ticket"; this.link_addticket.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.link_addticket_LinkClicked); // // link_tickets // this.link_tickets.AutoSize = true; this.link_tickets.Location = new System.Drawing.Point(31, 123); this.link_tickets.Name = "link_tickets"; this.link_tickets.Size = new System.Drawing.Size(53, 17); this.link_tickets.TabIndex = 9; this.link_tickets.TabStop = true; this.link_tickets.Text = "Tickets"; this.link_tickets.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.link_tickets_LinkClicked); // // UserForm // this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 16F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(800, 450); this.Controls.Add(this.link_tickets); this.Controls.Add(this.link_addticket); this.Controls.Add(this.lbl_greetings); this.Controls.Add(this.btn_logout); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedToolWindow; this.Name = "UserForm"; this.Text = "UserForm"; this.Load += new System.EventHandler(this.UserForm_Load); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.Button btn_logout; private System.Windows.Forms.Label lbl_greetings; private System.Windows.Forms.LinkLabel link_addticket; private System.Windows.Forms.LinkLabel link_tickets; } }
42.378641
138
0.594731
[ "MIT" ]
matin360/OnlineHelpDeskApp
OnlineHelpdeskAppUI/OnlineHelpdeskAppUI/Forms/UserForm.Designer.cs
4,367
C#
using Newtonsoft.Json; using System.Collections.Generic; namespace CM.Payments.Client.Model { /// <summary> /// Details of the charge request. /// </summary> public class ChargeRequest { /// <summary> /// Total amount to be paid for the charge. /// </summary> [JsonProperty("amount")] [JsonRequired] public double Amount { get; set; } /// <summary> /// Currency code in ISO-4217 format. /// </summary> [JsonProperty("currency")] [JsonRequired] public string Currency { get; set; } /// <summary> /// List of payments. /// </summary> [JsonProperty("payments")] [JsonRequired] public IEnumerable<PaymentRequest> Payments { get; set; } /// <summary> /// DDP feature: Client language /// </summary> [JsonProperty("language")] [JsonRequired] public string Language { get; set; } /// <summary> /// DDP feature: Emailaddress /// </summary> [JsonProperty("email")] [JsonRequired] public string Email { get; set; } } }
25.085106
65
0.532655
[ "MIT" ]
Ryaden/payments-sdk-net
Source/CM.Payments.Client.Shared/Model/ChargeRequest.cs
1,181
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using PipelinedApi.Models; using Tumble.Core; namespace PipelinedApi.Handlers.DublinBikes { public class OrderStationsResponse : IPipelineHandler { private string[] orderIdentifiers = new string[] { "Number", "Name", "Available_bikes", "Available_bike_stands", "Last_update" }; public async Task InvokeAsync(PipelineContext context, PipelineDelegate next) { if (context.GetFirst(out IEnumerable<DublinBikeStation> response)) { if (context.Get("orderBy", out string value)) { var index = orderIdentifiers .Select((x, i) => new { index = i, identifer = x }) .Where(x => string.Compare(x.identifer, value, true) == 0) .Select(x => x.index) .FirstOrDefault(); switch (index) { case 1: response = response.OrderBy(x => x.Name); break; case 2: response = response.OrderByDescending(x => x.Available_bikes); break; case 3: response = response.OrderByDescending(x => x.Available_bike_stands); break; case 4: response = response.OrderByDescending(x => x.Last_update); break; default: response = response.OrderBy(x => x.Number); break; } context.AddOrReplace("response", response.Select(x => x)); } } await next.Invoke(); } } }
38.62963
137
0.435283
[ "MIT" ]
dazberry/Tumble
samples/PipelinedApi/PipelinedApi/Handlers/DublinBikes/OrderStationsResponse.cs
2,088
C#
#nullable enable namespace Gu.Units { using System; using System.ComponentModel; using System.ComponentModel.Design.Serialization; using System.Globalization; using System.Reflection; /// <summary> /// Provides a unified way of converting types of values to other types, as well as for accessing standard values and sub properties. /// </summary> /// <devdoc> /// <para>Provides a type converter to convert <see cref='Gu.Units.Wavenumber'/> /// objects to and from various /// other representations.</para> /// </devdoc> public class WavenumberTypeConverter : TypeConverter { /// <inheritdoc /> public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType) { if (sourceType == typeof(string)) { return true; } return base.CanConvertFrom(context, sourceType); } /// <inheritdoc /> public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType) { if (destinationType == typeof(InstanceDescriptor) || destinationType == typeof(string)) { return true; } return base.CanConvertTo(context, destinationType); } /// <inheritdoc /> public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) { var text = value as string; if (text != null) { return Wavenumber.Parse(text, culture); } return base.ConvertFrom(context, culture, value); } /// <inheritdoc /> public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) { if (value is Wavenumber && destinationType != null) { var wavenumber = (Wavenumber)value; if (destinationType == typeof(string)) { return wavenumber.ToString(culture); } else if (destinationType == typeof(InstanceDescriptor)) { var factoryMethod = typeof(Wavenumber).GetMethod(nameof(Wavenumber.FromReciprocalMetres), BindingFlags.Public | BindingFlags.Static, null, new Type[] { typeof(double) }, null); if (factoryMethod != null) { var args = new object[] { wavenumber.reciprocalMetres }; return new InstanceDescriptor(factoryMethod, args); } } } return base.ConvertTo(context, culture, value, destinationType); } } }
35.341772
196
0.571633
[ "MIT" ]
GuOrg/Gu.Units
Gu.Units/WavenumberTypeConverter.generated.cs
2,792
C#
using System; using System.Collections.Generic; using System.Text; namespace EntityLayer { public class Base { public int Id { get; set; } public short Status { get; set; } public int CreatedBy { get; set; } public DateTime CreatedDate { get; set; } public int UpdatedBy { get; set; } public DateTime UpdatedDate { get; set; } } }
23.117647
49
0.610687
[ "Apache-2.0" ]
neilvla/ProjectMVC
EntityLayer/Base.cs
395
C#
// This file is auto-generated, don't edit it. Thanks. using System; using System.Collections.Generic; using System.IO; using Tea; namespace AlibabaCloud.SDK.Ocr20191230.Models { public class RecognizeVINCodeRequest : TeaModel { [NameInMap("ImageURL")] [Validation(Required=true)] public string ImageURL { get; set; } } }
18.894737
54
0.690808
[ "Apache-2.0" ]
alibabacloud-sdk-swift/alibabacloud-sdk
ocr-20191230/csharp/core/Models/RecognizeVINCodeRequest.cs
359
C#
// // Authors: // Rafael Mizrahi <rafim@mainsoft.com> // Erez Lotan <erezl@mainsoft.com> // Vladimir Krasnov <vladimirk@mainsoft.com> // // // Copyright (c) 2002-2005 Mainsoft Corporation. // // 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.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.HtmlControls; using System.Drawing; namespace GHTTests.System_Web_dll.System_Web_UI_WebControls { public class DataList_FooterTemplate : GHTBaseWeb { #region Web Form Designer generated code override protected void OnInit(EventArgs e) { // // CODEGEN: This call is required by the ASP.NET Web Form Designer. // InitializeComponent(); base.OnInit(e); } /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.Load += new System.EventHandler(this.Page_Load); } #endregion protected System.Web.UI.WebControls.DataList DataList1; protected GHTWebControls.GHTSubTest GHTSubTest1; protected System.Web.UI.WebControls.DataList DataList2; protected GHTWebControls.GHTSubTest GHTSubTest2; protected System.Web.UI.WebControls.DataList Datalist3; protected GHTWebControls.GHTSubTest Ghtsubtest3; protected System.Web.UI.WebControls.DataList DataList4; protected GHTWebControls.GHTSubTest GHTSubTest4; protected System.Web.UI.WebControls.DataList DataList5; protected GHTWebControls.GHTSubTest GHTSubTest5; protected static string [] m_data = new String[] {"aaa", "bbb", "ccc", "ddd", "eee", "fff", "ggg"}; private void Page_Load(object sender, System.EventArgs e) { HtmlForm frm = (HtmlForm)FindControl("Form1"); GHTTestBegin(frm); GHTActiveSubTest = GHTSubTest1; try { DataList1.DataBind();; } catch (Exception ex) { GHTSubTestUnexpectedExceptionCaught(ex); } GHTActiveSubTest = Ghtsubtest3; try { Datalist3.DataBind(); } catch (Exception ex) { GHTSubTestUnexpectedExceptionCaught(ex); } GHTActiveSubTest = GHTSubTest4; try { DataList4.DataBind(); } catch (Exception ex) { GHTSubTestUnexpectedExceptionCaught(ex); } GHTActiveSubTest = GHTSubTest5; try { DataList5.ItemTemplate = new ItemTemplate(); DataList5.FooterTemplate = new FooterTemplate(); DataList5.DataBind(); } catch (Exception ex) { GHTSubTestUnexpectedExceptionCaught(ex); } GHTTestEnd(); } // Template for Footer item. private class FooterTemplate : ITemplate { private Label m_l; public void InstantiateIn(Control container) { this.m_l = new Label(); this.m_l.BackColor = Color.Aquamarine; this.m_l.Text = "Footer text"; container.Controls.Add(this.m_l); } } // Template for alternating item. private class ItemTemplate : ITemplate { private Label m_l; public void InstantiateIn(Control container) { this.m_l = new Label(); this.m_l.BackColor = Color.Coral; container.Controls.Add(this.m_l); m_l.DataBinding += new EventHandler(m_l_DataBinding); } private void m_l_DataBinding(object sender, EventArgs e) { DataListItem item1 = (DataListItem) ((Label) sender).NamingContainer; this.m_l.Text = (string)(item1.DataItem); } } } }
27.540373
101
0.714028
[ "Apache-2.0" ]
121468615/mono
mcs/class/System.Web/Test/mainsoft/MainsoftWebApp/System_Web_UI_WebControls/DataList/DataList_FooterTemplate.aspx.cs
4,434
C#
// Anthony Leland licenses this file to you under the MIT license. namespace Tonytins.Models { /// <summary> /// Basic hero profile contains the type, affilation and server. /// If no info is given, the model uses it's defualt values. /// </summary> public class HeroModel { const string NA = "N/A"; const string DEFAULT_SERVER = "Freedom"; public string Name { get; set; } = "Example Hero"; public string Origin { get; set; } = NA; public string Archetype { get; set; } = NA; // I'm not sure if Affilation needs to be an array public string Affilation { get; set; } = string.Empty; public string Primary { get; set; } = NA; public string Secondary { get; set; } = NA; public string Supplemental { get; set; } = string.Empty; public string Image { get; set; } = "coh-card.png"; public string Server { get; set; } = DEFAULT_SERVER; } }
36.961538
68
0.604579
[ "MIT" ]
tonytins/tonytins.xyz
src/Tonytins.Models/HeroModel.cs
961
C#
using DotXxlJob.Core; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; namespace ASPNetCoreExecutor { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } private IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940 public void ConfigureServices(IServiceCollection services) { services.AddXxlJobExecutor(Configuration); services.AddDefaultXxlJobHandlers(); // add httpHandler; services.AddSingleton<IJobHandler, DemoJobHandler>(); // 添加自定义的jobHandler services.AddAutoRegistry(); // 自动注册 //services.Configure<KestrelServerOptions>(x => x.AllowSynchronousIO = true) // .Configure<IISServerOptions>(x=> x.AllowSynchronousIO = true); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } //启用XxlExecutor app.UseXxlJobExecutor(); } } }
33.914894
122
0.663112
[ "MIT" ]
cdpidan/DotXxlJob
samples/ASPNetCoreExecutor/Startup.cs
1,620
C#
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Threading.Tasks; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Primitives; using Microsoft.Net.Http.Headers; using Moq; using Xunit; namespace Microsoft.AspNetCore.Antiforgery.Internal { public class DefaultAntiforgeryTokenStoreTest { private readonly string _cookieName = "cookie-name"; [Fact] public void GetCookieToken_CookieDoesNotExist_ReturnsNull() { // Arrange var httpContext = GetHttpContext(); var options = new AntiforgeryOptions { Cookie = { Name = _cookieName } }; var tokenStore = new DefaultAntiforgeryTokenStore(new TestOptionsManager(options)); // Act var token = tokenStore.GetCookieToken(httpContext); // Assert Assert.Null(token); } [Fact] public void GetCookieToken_CookieIsEmpty_ReturnsNull() { // Arrange var httpContext = GetHttpContext(_cookieName, string.Empty); var options = new AntiforgeryOptions { Cookie = { Name = _cookieName } }; var tokenStore = new DefaultAntiforgeryTokenStore(new TestOptionsManager(options)); // Act var token = tokenStore.GetCookieToken(httpContext); // Assert Assert.Null(token); } [Fact] public void GetCookieToken_CookieIsNotEmpty_ReturnsToken() { // Arrange var expectedToken = "valid-value"; var httpContext = GetHttpContext(_cookieName, expectedToken); var options = new AntiforgeryOptions { Cookie = { Name = _cookieName } }; var tokenStore = new DefaultAntiforgeryTokenStore(new TestOptionsManager(options)); // Act var token = tokenStore.GetCookieToken(httpContext); // Assert Assert.Equal(expectedToken, token); } [Fact] public async Task GetRequestTokens_CookieIsEmpty_ReturnsNullTokens() { // Arrange var httpContext = GetHttpContext(); httpContext.Request.Form = FormCollection.Empty; var options = new AntiforgeryOptions { Cookie = { Name = "cookie-name" }, FormFieldName = "form-field-name", }; var tokenStore = new DefaultAntiforgeryTokenStore(new TestOptionsManager(options)); // Act var tokenSet = await tokenStore.GetRequestTokensAsync(httpContext); // Assert Assert.Null(tokenSet.CookieToken); Assert.Null(tokenSet.RequestToken); } [Fact] public async Task GetRequestTokens_HeaderTokenTakensPriority_OverFormToken() { // Arrange var httpContext = GetHttpContext("cookie-name", "cookie-value"); httpContext.Request.ContentType = "application/x-www-form-urlencoded"; httpContext.Request.Form = new FormCollection(new Dictionary<string, StringValues> { { "form-field-name", "form-value" }, }); // header value has priority. httpContext.Request.Headers.Add("header-name", "header-value"); var options = new AntiforgeryOptions { Cookie = { Name = "cookie-name" }, FormFieldName = "form-field-name", HeaderName = "header-name", }; var tokenStore = new DefaultAntiforgeryTokenStore(new TestOptionsManager(options)); // Act var tokens = await tokenStore.GetRequestTokensAsync(httpContext); // Assert Assert.Equal("cookie-value", tokens.CookieToken); Assert.Equal("header-value", tokens.RequestToken); } [Fact] public async Task GetRequestTokens_NoHeaderToken_FallsBackToFormToken() { // Arrange var httpContext = GetHttpContext("cookie-name", "cookie-value"); httpContext.Request.ContentType = "application/x-www-form-urlencoded"; httpContext.Request.Form = new FormCollection(new Dictionary<string, StringValues> { { "form-field-name", "form-value" }, }); var options = new AntiforgeryOptions { Cookie = { Name = "cookie-name" }, FormFieldName = "form-field-name", HeaderName = "header-name", }; var tokenStore = new DefaultAntiforgeryTokenStore(new TestOptionsManager(options)); // Act var tokens = await tokenStore.GetRequestTokensAsync(httpContext); // Assert Assert.Equal("cookie-value", tokens.CookieToken); Assert.Equal("form-value", tokens.RequestToken); } [Fact] public async Task GetRequestTokens_NonFormContentType_UsesHeaderToken() { // Arrange var httpContext = GetHttpContext("cookie-name", "cookie-value"); httpContext.Request.ContentType = "application/json"; httpContext.Request.Headers.Add("header-name", "header-value"); // Will not be accessed httpContext.Request.Form = null; var options = new AntiforgeryOptions { Cookie = { Name = "cookie-name" }, FormFieldName = "form-field-name", HeaderName = "header-name", }; var tokenStore = new DefaultAntiforgeryTokenStore(new TestOptionsManager(options)); // Act var tokens = await tokenStore.GetRequestTokensAsync(httpContext); // Assert Assert.Equal("cookie-value", tokens.CookieToken); Assert.Equal("header-value", tokens.RequestToken); } [Fact] public async Task GetRequestTokens_NoHeaderToken_NonFormContentType_ReturnsNullToken() { // Arrange var httpContext = GetHttpContext("cookie-name", "cookie-value"); httpContext.Request.ContentType = "application/json"; // Will not be accessed httpContext.Request.Form = null; var options = new AntiforgeryOptions { Cookie = { Name = "cookie-name" }, FormFieldName = "form-field-name", HeaderName = "header-name", }; var tokenStore = new DefaultAntiforgeryTokenStore(new TestOptionsManager(options)); // Act var tokenSet = await tokenStore.GetRequestTokensAsync(httpContext); // Assert Assert.Equal("cookie-value", tokenSet.CookieToken); Assert.Null(tokenSet.RequestToken); } [Fact] public async Task GetRequestTokens_BothHeaderValueAndFormFieldsEmpty_ReturnsNullTokens() { // Arrange var httpContext = GetHttpContext("cookie-name", "cookie-value"); httpContext.Request.ContentType = "application/x-www-form-urlencoded"; httpContext.Request.Form = FormCollection.Empty; var options = new AntiforgeryOptions { Cookie = { Name = "cookie-name" }, FormFieldName = "form-field-name", HeaderName = "header-name", }; var tokenStore = new DefaultAntiforgeryTokenStore(new TestOptionsManager(options)); // Act var tokenSet = await tokenStore.GetRequestTokensAsync(httpContext); // Assert Assert.Equal("cookie-value", tokenSet.CookieToken); Assert.Null(tokenSet.RequestToken); } [Theory] [InlineData(false, CookieSecurePolicy.SameAsRequest, null)] [InlineData(true, CookieSecurePolicy.SameAsRequest, true)] [InlineData(false, CookieSecurePolicy.Always, true)] [InlineData(true, CookieSecurePolicy.Always, true)] [InlineData(false, CookieSecurePolicy.None, null)] [InlineData(true, CookieSecurePolicy.None, null)] public void SaveCookieToken_HonorsCookieSecurePolicy_OnOptions( bool isRequestSecure, CookieSecurePolicy policy, bool? expectedCookieSecureFlag) { // Arrange var token = "serialized-value"; bool defaultCookieSecureValue = expectedCookieSecureFlag ?? false; // pulled from config; set by ctor var cookies = new MockResponseCookieCollection(); var httpContext = new Mock<HttpContext>(); httpContext .Setup(hc => hc.Request.IsHttps) .Returns(isRequestSecure); httpContext .Setup(o => o.Response.Cookies) .Returns(cookies); httpContext .SetupGet(hc => hc.Request.PathBase) .Returns("/"); var options = new AntiforgeryOptions() { Cookie = { Name = _cookieName, SecurePolicy = policy }, }; var tokenStore = new DefaultAntiforgeryTokenStore(new TestOptionsManager(options)); // Act tokenStore.SaveCookieToken(httpContext.Object, token); // Assert Assert.Equal(1, cookies.Count); Assert.NotNull(cookies); Assert.Equal(_cookieName, cookies.Key); Assert.Equal("serialized-value", cookies.Value); Assert.True(cookies.Options.HttpOnly); Assert.Equal(defaultCookieSecureValue, cookies.Options.Secure); } [Theory] [InlineData(null, "/")] [InlineData("", "/")] [InlineData("/", "/")] [InlineData("/vdir1", "/vdir1")] [InlineData("/vdir1/vdir2", "/vdir1/vdir2")] public void SaveCookieToken_SetsCookieWithApproriatePathBase(string requestPathBase, string expectedCookiePath) { // Arrange var token = "serialized-value"; var cookies = new MockResponseCookieCollection(); var httpContext = new Mock<HttpContext>(); httpContext .Setup(hc => hc.Response.Cookies) .Returns(cookies); httpContext .SetupGet(hc => hc.Request.PathBase) .Returns(requestPathBase); httpContext .SetupGet(hc => hc.Request.Path) .Returns("/index.html"); var options = new AntiforgeryOptions { Cookie = { Name = _cookieName } }; var tokenStore = new DefaultAntiforgeryTokenStore(new TestOptionsManager(options)); // Act tokenStore.SaveCookieToken(httpContext.Object, token); // Assert Assert.Equal(1, cookies.Count); Assert.NotNull(cookies); Assert.Equal(_cookieName, cookies.Key); Assert.Equal("serialized-value", cookies.Value); Assert.True(cookies.Options.HttpOnly); Assert.Equal(expectedCookiePath, cookies.Options.Path); } [Fact] public void SaveCookieToken_NonNullAntiforgeryOptionsConfigureCookieOptionsPath_UsesCookieOptionsPath() { // Arrange var expectedCookiePath = "/"; var requestPathBase = "/vdir1"; var token = "serialized-value"; var cookies = new MockResponseCookieCollection(); var httpContext = new Mock<HttpContext>(); httpContext .Setup(hc => hc.Response.Cookies) .Returns(cookies); httpContext .SetupGet(hc => hc.Request.PathBase) .Returns(requestPathBase); httpContext .SetupGet(hc => hc.Request.Path) .Returns("/index.html"); var options = new AntiforgeryOptions { Cookie = { Name = _cookieName, Path = expectedCookiePath } }; var tokenStore = new DefaultAntiforgeryTokenStore(new TestOptionsManager(options)); // Act tokenStore.SaveCookieToken(httpContext.Object, token); // Assert Assert.Equal(1, cookies.Count); Assert.NotNull(cookies); Assert.Equal(_cookieName, cookies.Key); Assert.Equal("serialized-value", cookies.Value); Assert.True(cookies.Options.HttpOnly); Assert.Equal(expectedCookiePath, cookies.Options.Path); } [Fact] public void SaveCookieToken_NonNullAntiforgeryOptionsConfigureCookieOptionsDomain_UsesCookieOptionsDomain() { // Arrange var expectedCookieDomain = "microsoft.com"; var token = "serialized-value"; var cookies = new MockResponseCookieCollection(); var httpContext = new Mock<HttpContext>(); httpContext .Setup(hc => hc.Response.Cookies) .Returns(cookies); httpContext .SetupGet(hc => hc.Request.PathBase) .Returns("/vdir1"); httpContext .SetupGet(hc => hc.Request.Path) .Returns("/index.html"); var options = new AntiforgeryOptions { Cookie = { Name = _cookieName, Domain = expectedCookieDomain } }; var tokenStore = new DefaultAntiforgeryTokenStore(new TestOptionsManager(options)); // Act tokenStore.SaveCookieToken(httpContext.Object, token); // Assert Assert.Equal(1, cookies.Count); Assert.NotNull(cookies); Assert.Equal(_cookieName, cookies.Key); Assert.Equal("serialized-value", cookies.Value); Assert.True(cookies.Options.HttpOnly); Assert.Equal("/vdir1", cookies.Options.Path); Assert.Equal(expectedCookieDomain, cookies.Options.Domain); } private HttpContext GetHttpContext(string cookieName, string cookieValue) { var context = GetHttpContext(); context.Request.Headers[HeaderNames.Cookie] = $"{cookieName}={cookieValue}"; return context; } private HttpContext GetHttpContext() { var httpContext = new DefaultHttpContext(); return httpContext; } private class MockResponseCookieCollection : IResponseCookies { public string Key { get; set; } public string Value { get; set; } public CookieOptions Options { get; set; } public int Count { get; set; } public void Append(string key, string value, CookieOptions options) { Key = key; Value = value; Options = options; Count++; } public void Append(string key, string value) { throw new NotImplementedException(); } public void Delete(string key, CookieOptions options) { throw new NotImplementedException(); } public void Delete(string key) { throw new NotImplementedException(); } } } }
35.185022
119
0.562226
[ "Apache-2.0" ]
06b/AspNetCore
src/Antiforgery/test/DefaultAntiforgeryTokenStoreTest.cs
15,974
C#
using System; using Microsoft.Extensions.Logging; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using BTCPayServer.Services; using BTCPayServer.Services.Rates; using Microsoft.Extensions.Hosting; using BTCPayServer.Logging; using System.Runtime.CompilerServices; using System.IO; using System.Text; namespace BTCPayServer.HostedServices { public class RatesHostedService : BaseAsyncService { private SettingsRepository _SettingsRepository; private CoinAverageSettings _coinAverageSettings; RateProviderFactory _RateProviderFactory; public RatesHostedService(SettingsRepository repo, RateProviderFactory rateProviderFactory, CoinAverageSettings coinAverageSettings) { this._SettingsRepository = repo; _coinAverageSettings = coinAverageSettings; _RateProviderFactory = rateProviderFactory; } internal override Task[] InitializeTasks() { return new[] { CreateLoopTask(RefreshCoinAverageSupportedExchanges), CreateLoopTask(RefreshCoinAverageSettings), CreateLoopTask(RefreshRates) }; } async Task RefreshRates() { using (var timeout = CancellationTokenSource.CreateLinkedTokenSource(Cancellation)) { timeout.CancelAfter(TimeSpan.FromSeconds(20.0)); try { await Task.WhenAll(_RateProviderFactory.Providers .Select(p => (Fetcher: p.Value as BackgroundFetcherRateProvider, ExchangeName: p.Key)).Where(p => p.Fetcher != null) .Select(p => p.Fetcher.UpdateIfNecessary().ContinueWith(t => { if (t.Result.Exception != null) { Logs.PayServer.LogWarning($"Error while contacting {p.ExchangeName}: {t.Result.Exception.Message}"); } }, TaskScheduler.Default)) .ToArray()).WithCancellation(timeout.Token); } catch (OperationCanceledException) when (timeout.IsCancellationRequested) { } } await Task.Delay(TimeSpan.FromSeconds(30), Cancellation); } async Task RefreshCoinAverageSupportedExchanges() { var exchanges = new CoinAverageExchanges(); foreach (var item in (await new CoinAverageRateProvider() { Authenticator = _coinAverageSettings }.GetExchangeTickersAsync()) .Exchanges .Select(c => new CoinAverageExchange(c.Name, c.DisplayName))) { exchanges.Add(item); } _coinAverageSettings.AvailableExchanges = exchanges; await Task.Delay(TimeSpan.FromHours(5), Cancellation); } async Task RefreshCoinAverageSettings() { var rates = (await _SettingsRepository.GetSettingAsync<RatesSetting>()) ?? new RatesSetting(); _RateProviderFactory.CacheSpan = TimeSpan.FromMinutes(rates.CacheInMinutes); if (!string.IsNullOrWhiteSpace(rates.PrivateKey) && !string.IsNullOrWhiteSpace(rates.PublicKey)) { _coinAverageSettings.KeyPair = (rates.PublicKey, rates.PrivateKey); } else { _coinAverageSettings.KeyPair = null; } await _SettingsRepository.WaitSettingsChanged<RatesSetting>(Cancellation); } } }
40.705263
152
0.578485
[ "MIT" ]
spazzymoto/btcpayserver
BTCPayServer/HostedServices/RatesHostedService.cs
3,869
C#
namespace QA.TelerikAcademy.FrontEnd.Tests.UserSettings.EducationSettings { #region using directives using Core.Constants.Attributes; using Core.Constants.Pages; using Core.Facades; using Microsoft.VisualStudio.TestTools.UnitTesting; using TestingFramework.Core.Base; using TestingFramework.Core.Data; using TestingFramework.Core.Extensions; #endregion [TestClass] public class FacultyNameTests : BaseTest { private User currentUser; public SettingsService SettingsService { get; set; } public override void TestInit() { this.SettingsService = new SettingsService(); this.currentUser = new TestUser(); } [TestMethod, Owner(Owners.LyudmilNikodimov), Priority(Priorities.Medium), TestCategory(Modules.Settings)] public void EnteringValidFacultyNameShouldSuccessfullyUpdateUserSettings() { this.currentUser.FacultyName = FacultyNameConstants.ValidFacultyName; this.SettingsService.UpdateSettings(this.currentUser); } [TestMethod, Owner(Owners.LyudmilNikodimov), Priority(Priorities.Medium), TestCategory(Modules.Settings)] public void EnteringInvalidFacultyNameWithValueUnderLowerLimitShouldThrowValidationErrorMessage() { this.currentUser.FacultyName = FacultyNameConstants.InvalidFacultyNameWithValueUnderLowerLimit; this.SettingsService.EditingSettings(this.currentUser); this.SettingsService.SettingsPage.Map.FacultyNameError.AssertIsPresent(); } [TestMethod, Owner(Owners.LyudmilNikodimov), Priority(Priorities.Medium), TestCategory(Modules.Settings)] public void EnteringInvalidFacultyNameWithValueAboveUpperLimitShouldThrowValidationErrorMessage() { this.currentUser.FacultyName = FacultyNameConstants.InvalidFacultyNameWithValueAboveUpperLimit; this.SettingsService.EditingSettings(this.currentUser); this.SettingsService.SettingsPage.Map.FacultyNameError.AssertIsPresent(); } } }
39.698113
113
0.729087
[ "MIT" ]
Team-Griffin-SQA-2015/TelerikAcademyCustomTestFramework
TelerikAcademyCustomTestFramework/QA.TelerikAcademy.FrontEnd.Tests/UserSettings/EducationSettings/FacultyNameTests.cs
2,106
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> //------------------------------------------------------------------------------ using System; using System.Reflection; [assembly: System.Reflection.AssemblyCompanyAttribute("csudh")] [assembly: System.Reflection.AssemblyConfigurationAttribute("Debug")] [assembly: System.Reflection.AssemblyFileVersionAttribute("1.0.0.0")] [assembly: System.Reflection.AssemblyInformationalVersionAttribute("1.0.0")] [assembly: System.Reflection.AssemblyProductAttribute("csudh")] [assembly: System.Reflection.AssemblyTitleAttribute("csudh")] [assembly: System.Reflection.AssemblyVersionAttribute("1.0.0.0")] // Generated by the MSBuild WriteCodeFragment class.
41.166667
81
0.626518
[ "Apache-2.0" ]
Tomii0711/ProgGyak
OKJ_Vizsgafeladatok/csudh/csudh/obj/Debug/netcoreapp3.1/csudh.AssemblyInfo.cs
988
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Reflection; using System.Reflection.Emit; using System.Dynamic.Utils; namespace System.Linq.Expressions.Interpreter { internal abstract partial class CallInstruction : Instruction { /// <summary> /// The number of arguments including "this" for instance methods. /// </summary> public abstract int ArgumentCount { get; } #region Construction internal CallInstruction() { } public override string InstructionName { get { return "Call"; } } #if FEATURE_DLG_INVOKE private static readonly Dictionary<MethodInfo, CallInstruction> _cache = new Dictionary<MethodInfo, CallInstruction>(); #endif public static CallInstruction Create(MethodInfo info) { return Create(info, info.GetParameters()); } /// <summary> /// Creates a new ReflectedCaller which can be used to quickly invoke the provided MethodInfo. /// </summary> public static CallInstruction Create(MethodInfo info, ParameterInfo[] parameters) { int argumentCount = parameters.Length; if (!info.IsStatic) { argumentCount++; } // A workaround for CLR behavior (Unable to create delegates for Array.Get/Set): // T[]::Address - not supported by ETs due to T& return value if (info.DeclaringType != null && info.DeclaringType.IsArray && (info.Name == "Get" || info.Name == "Set")) { return GetArrayAccessor(info, argumentCount); } return new MethodInfoCallInstruction(info, argumentCount); #if FEATURE_DLG_INVOKE if (!info.IsStatic && info.DeclaringType.GetTypeInfo().IsValueType) { return new MethodInfoCallInstruction(info, argumentCount); } if (argumentCount >= MaxHelpers) { // no delegate for this size, fall back to reflection invoke return new MethodInfoCallInstruction(info, argumentCount); } foreach (ParameterInfo pi in parameters) { if (pi.ParameterType.IsByRef) { // we don't support ref args via generics. return new MethodInfoCallInstruction(info, argumentCount); } } // see if we've created one w/ a delegate CallInstruction res; if (ShouldCache(info)) { lock (_cache) { if (_cache.TryGetValue(info, out res)) { return res; } } } // create it try { #if FEATURE_FAST_CREATE if (argumentCount < MaxArgs) { res = FastCreate(info, parameters); } else #endif { res = SlowCreate(info, parameters); } } catch (TargetInvocationException tie) { if (!(tie.InnerException is NotSupportedException)) { throw; } res = new MethodInfoCallInstruction(info, argumentCount); } catch (NotSupportedException) { // if Delegate.CreateDelegate can't handle the method fall back to // the slow reflection version. For example this can happen w/ // a generic method defined on an interface and implemented on a class or // a virtual generic method. res = new MethodInfoCallInstruction(info, argumentCount); } // cache it for future users if it's a reasonable method to cache if (ShouldCache(info)) { lock (_cache) { _cache[info] = res; } } return res; #endif } private static CallInstruction GetArrayAccessor(MethodInfo info, int argumentCount) { Type arrayType = info.DeclaringType; bool isGetter = info.Name == "Get"; MethodInfo alternativeMethod = null; switch (arrayType.GetArrayRank()) { case 1: alternativeMethod = isGetter ? arrayType.GetMethod("GetValue", new[] { typeof(int) }) : typeof(CallInstruction).GetMethod("ArrayItemSetter1"); break; case 2: alternativeMethod = isGetter ? arrayType.GetMethod("GetValue", new[] { typeof(int), typeof(int) }) : typeof(CallInstruction).GetMethod("ArrayItemSetter2"); break; case 3: alternativeMethod = isGetter ? arrayType.GetMethod("GetValue", new[] { typeof(int), typeof(int), typeof(int) }) : typeof(CallInstruction).GetMethod("ArrayItemSetter3"); break; } if ((object)alternativeMethod == null) { return new MethodInfoCallInstruction(info, argumentCount); } return Create(alternativeMethod); } public static void ArrayItemSetter1(Array array, int index0, object value) { array.SetValue(value, index0); } public static void ArrayItemSetter2(Array array, int index0, int index1, object value) { array.SetValue(value, index0, index1); } public static void ArrayItemSetter3(Array array, int index0, int index1, int index2, object value) { array.SetValue(value, index0, index1, index2); } #if FEATURE_DLG_INVOKE private static bool ShouldCache(MethodInfo info) { return true; } #endif #if FEATURE_FAST_CREATE /// <summary> /// Gets the next type or null if no more types are available. /// </summary> private static Type TryGetParameterOrReturnType(MethodInfo target, ParameterInfo[] pi, int index) { if (!target.IsStatic) { index--; if (index < 0) { return target.DeclaringType; } } if (index < pi.Length) { // next in signature return pi[index].ParameterType; } if (target.ReturnType == typeof(void) || index > pi.Length) { // no more parameters return null; } // last parameter on Invoke is return type return target.ReturnType; } private static bool IndexIsNotReturnType(int index, MethodInfo target, ParameterInfo[] pi) { return pi.Length != index || (pi.Length == index && !target.IsStatic); } #endif #if FEATURE_DLG_INVOKE /// <summary> /// Uses reflection to create new instance of the appropriate ReflectedCaller /// </summary> private static CallInstruction SlowCreate(MethodInfo info, ParameterInfo[] pis) { List<Type> types = new List<Type>(); if (!info.IsStatic) types.Add(info.DeclaringType); foreach (ParameterInfo pi in pis) { types.Add(pi.ParameterType); } if (info.ReturnType != typeof(void)) { types.Add(info.ReturnType); } Type[] arrTypes = types.ToArray(); try { return (CallInstruction)Activator.CreateInstance(GetHelperType(info, arrTypes), info); } catch (TargetInvocationException e) { throw ExceptionHelpers.UpdateForRethrow(e.InnerException); } } #endif #endregion #region Instruction public override int ConsumedStack { get { return ArgumentCount; } } public override string ToString() { return "Call()"; } #endregion /// <summary> /// If the target of invocation happens to be a delegate /// over enclosed instance lightLambda, return that instance. /// We can interpret LightLambdas directly. /// </summary> /// <param name="instance"></param> /// <param name="lightLambda"></param> /// <returns></returns> protected static bool TryGetLightLambdaTarget(object instance, out LightLambda lightLambda) { var del = instance as Delegate; if ((object)del != null) { var thunk = del.Target as Func<object[], object>; if ((object)thunk != null) { lightLambda = thunk.Target as LightLambda; if (lightLambda != null) { return true; } } } lightLambda = null; return false; } protected object InterpretLambdaInvoke(LightLambda targetLambda, object[] args) { if (ProducedStack > 0) { return targetLambda.Run(args); } else { return targetLambda.RunVoid(args); } } } internal class MethodInfoCallInstruction : CallInstruction { protected readonly MethodInfo _target; protected readonly int _argumentCount; public override int ArgumentCount { get { return _argumentCount; } } internal MethodInfoCallInstruction(MethodInfo target, int argumentCount) { _target = target; _argumentCount = argumentCount; } public override int ProducedStack { get { return _target.ReturnType == typeof(void) ? 0 : 1; } } public override int Run(InterpretedFrame frame) { int first = frame.StackIndex - _argumentCount; object ret; if (_target.IsStatic) { var args = GetArgs(frame, first, 0); try { ret = _target.Invoke(null, args); } catch (TargetInvocationException e) { throw ExceptionHelpers.UpdateForRethrow(e.InnerException); } } else { var instance = frame.Data[first]; NullCheck(instance); var args = GetArgs(frame, first, 1); LightLambda targetLambda; if (TryGetLightLambdaTarget(instance, out targetLambda)) { // no need to Invoke, just interpret the lambda body ret = InterpretLambdaInvoke(targetLambda, args); } else { try { ret = _target.Invoke(instance, args); } catch (TargetInvocationException e) { throw ExceptionHelpers.UpdateForRethrow(e.InnerException); } } } if (_target.ReturnType != typeof(void)) { frame.Data[first] = ret; frame.StackIndex = first + 1; } else { frame.StackIndex = first; } return 1; } protected object[] GetArgs(InterpretedFrame frame, int first, int skip) { var count = _argumentCount - skip; if (count > 0) { var args = new object[count]; for (int i = 0; i < args.Length; i++) { args[i] = frame.Data[first + i + skip]; } return args; } else { return Array.Empty<object>(); } } } internal class ByRefMethodInfoCallInstruction : MethodInfoCallInstruction { private readonly ByRefUpdater[] _byrefArgs; internal ByRefMethodInfoCallInstruction(MethodInfo target, int argumentCount, ByRefUpdater[] byrefArgs) : base(target, argumentCount) { _byrefArgs = byrefArgs; } public override int ProducedStack { get { return (_target.ReturnType == typeof(void) ? 0 : 1); } } public sealed override int Run(InterpretedFrame frame) { int first = frame.StackIndex - _argumentCount; object[] args = null; object instance = null; try { object ret; if (_target.IsStatic) { args = GetArgs(frame, first, 0); try { ret = _target.Invoke(null, args); } catch (TargetInvocationException e) { throw ExceptionHelpers.UpdateForRethrow(e.InnerException); } } else { instance = frame.Data[first]; NullCheck(instance); args = GetArgs(frame, first, 1); LightLambda targetLambda; if (TryGetLightLambdaTarget(instance, out targetLambda)) { // no need to Invoke, just interpret the lambda body ret = InterpretLambdaInvoke(targetLambda, args); } else { try { ret = _target.Invoke(instance, args); } catch (TargetInvocationException e) { throw ExceptionHelpers.UpdateForRethrow(e.InnerException); } } } if (_target.ReturnType != typeof(void)) { frame.Data[first] = ret; frame.StackIndex = first + 1; } else { frame.StackIndex = first; } } finally { if (args != null) { foreach (var arg in _byrefArgs) { if (arg.ArgumentIndex == -1) { // instance param, just copy back the exact instance invoked with, which // gets passed by reference from reflection for value types. arg.Update(frame, instance); } else { arg.Update(frame, args[arg.ArgumentIndex]); } } } } return 1; } } }
31.89759
127
0.479635
[ "MIT" ]
chrisaut/corefx
src/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/CallInstruction.cs
15,885
C#
namespace Popstation { // Struct to store an ISO index public class IsoIndexLite { public int Offset { get; set; } public int Length { get; set; } } }
18.4
39
0.581522
[ "MIT" ]
KuromeSan/chovy-sign
CHOVY-SIGN/POPS/IsoIndexLite.cs
186
C#
// <auto-generated> // This file is generated by a T4 template. Make changes directly in the .tt file. // </auto-generated> #nullable enable using System; using FluentMvvm.Internals; namespace FluentMvvm { #if TEST internal class BackingFieldsCreationDisabled : IBackingFields #else internal sealed class BackingFieldsCreationDisabled : IBackingFields #endif { #if TEST public virtual Type OnType { get; } #else public Type OnType { get; } #endif #if TEST public BackingFieldsCreationDisabled() { this.OnType = default!; } #endif public BackingFieldsCreationDisabled(Type onType) { this.OnType = onType; } public T Get<T>(string propertyName) { ThrowHelper.ThrowNoBackingFieldsOfType<T>(this.OnType); return default; // to make the compiler happy } public Boolean GetBoolean(string propertyName) { ThrowHelper.ThrowNoBackingFieldsOfType<System.Boolean>(this.OnType); return default; // to make the compiler happy } public Byte GetByte(string propertyName) { ThrowHelper.ThrowNoBackingFieldsOfType<System.Byte>(this.OnType); return default; // to make the compiler happy } public SByte GetSByte(string propertyName) { ThrowHelper.ThrowNoBackingFieldsOfType<System.SByte>(this.OnType); return default; // to make the compiler happy } public Char GetChar(string propertyName) { ThrowHelper.ThrowNoBackingFieldsOfType<System.Char>(this.OnType); return default; // to make the compiler happy } public Decimal GetDecimal(string propertyName) { ThrowHelper.ThrowNoBackingFieldsOfType<System.Decimal>(this.OnType); return default; // to make the compiler happy } public Double GetDouble(string propertyName) { ThrowHelper.ThrowNoBackingFieldsOfType<System.Double>(this.OnType); return default; // to make the compiler happy } public Single GetSingle(string propertyName) { ThrowHelper.ThrowNoBackingFieldsOfType<System.Single>(this.OnType); return default; // to make the compiler happy } public Int16 GetInt16(string propertyName) { ThrowHelper.ThrowNoBackingFieldsOfType<System.Int16>(this.OnType); return default; // to make the compiler happy } public UInt16 GetUInt16(string propertyName) { ThrowHelper.ThrowNoBackingFieldsOfType<System.UInt16>(this.OnType); return default; // to make the compiler happy } public Int32 GetInt32(string propertyName) { ThrowHelper.ThrowNoBackingFieldsOfType<System.Int32>(this.OnType); return default; // to make the compiler happy } public UInt32 GetUInt32(string propertyName) { ThrowHelper.ThrowNoBackingFieldsOfType<System.UInt32>(this.OnType); return default; // to make the compiler happy } public Int64 GetInt64(string propertyName) { ThrowHelper.ThrowNoBackingFieldsOfType<System.Int64>(this.OnType); return default; // to make the compiler happy } public UInt64 GetUInt64(string propertyName) { ThrowHelper.ThrowNoBackingFieldsOfType<System.UInt64>(this.OnType); return default; // to make the compiler happy } public DateTime GetDateTime(string propertyName) { ThrowHelper.ThrowNoBackingFieldsOfType<System.DateTime>(this.OnType); return default; // to make the compiler happy } public String GetString(string propertyName) { ThrowHelper.ThrowNoBackingFieldsOfType<System.String>(this.OnType); return default; // to make the compiler happy } public bool Set<T>(T value, string propertyName) { ThrowHelper.ThrowNoBackingFieldsOfType<T>(this.OnType); return default; // to make the compiler happy } public bool Set(Boolean value, string propertyName) { ThrowHelper.ThrowNoBackingFieldsOfType<System.Boolean>(this.OnType); return default; // to make the compiler happy } public bool Set(Byte value, string propertyName) { ThrowHelper.ThrowNoBackingFieldsOfType<System.Byte>(this.OnType); return default; // to make the compiler happy } public bool Set(SByte value, string propertyName) { ThrowHelper.ThrowNoBackingFieldsOfType<System.SByte>(this.OnType); return default; // to make the compiler happy } public bool Set(Char value, string propertyName) { ThrowHelper.ThrowNoBackingFieldsOfType<System.Char>(this.OnType); return default; // to make the compiler happy } public bool Set(Decimal value, string propertyName) { ThrowHelper.ThrowNoBackingFieldsOfType<System.Decimal>(this.OnType); return default; // to make the compiler happy } public bool Set(Double value, string propertyName) { ThrowHelper.ThrowNoBackingFieldsOfType<System.Double>(this.OnType); return default; // to make the compiler happy } public bool Set(Single value, string propertyName) { ThrowHelper.ThrowNoBackingFieldsOfType<System.Single>(this.OnType); return default; // to make the compiler happy } public bool Set(Int16 value, string propertyName) { ThrowHelper.ThrowNoBackingFieldsOfType<System.Int16>(this.OnType); return default; // to make the compiler happy } public bool Set(UInt16 value, string propertyName) { ThrowHelper.ThrowNoBackingFieldsOfType<System.UInt16>(this.OnType); return default; // to make the compiler happy } public bool Set(Int32 value, string propertyName) { ThrowHelper.ThrowNoBackingFieldsOfType<System.Int32>(this.OnType); return default; // to make the compiler happy } public bool Set(UInt32 value, string propertyName) { ThrowHelper.ThrowNoBackingFieldsOfType<System.UInt32>(this.OnType); return default; // to make the compiler happy } public bool Set(Int64 value, string propertyName) { ThrowHelper.ThrowNoBackingFieldsOfType<System.Int64>(this.OnType); return default; // to make the compiler happy } public bool Set(UInt64 value, string propertyName) { ThrowHelper.ThrowNoBackingFieldsOfType<System.UInt64>(this.OnType); return default; // to make the compiler happy } public bool Set(DateTime value, string propertyName) { ThrowHelper.ThrowNoBackingFieldsOfType<System.DateTime>(this.OnType); return default; // to make the compiler happy } public bool Set(String value, string propertyName) { ThrowHelper.ThrowNoBackingFieldsOfType<System.String>(this.OnType); return default; // to make the compiler happy } } }
33.096491
82
0.625629
[ "MIT" ]
flinkow/fluentmvvm
fluentmvvm/BackingFieldsCreationDisabled.cs
7,548
C#
using System; using System.Collections.Generic; using Common; namespace Test { internal class Program { private static void Main(string[] args) { var owner = new Owner { Name = "Tim Apple", Businesses = new List<Business> { new Business { Name = "ProgramingExtreme", Address = "ProgramingLane", Employees = new List<Employee> { new Employee {Name = "Harry"}, new Employee {Name = "Sally"} } } } }; var ownerJson = UnsecureSerializer<Owner>.Serialize(owner); var EmployeeJson = UnsecureSerializer<DbEmployee>.Serialize(new DbEmployee("2")); var OwnerFromEmployer = UnsecureSerializer<Owner>.DeserializeToObject(EmployeeJson); Console.WriteLine("Hello World!"); } }° } }
28.657143
110
0.498504
[ "MIT" ]
Fingann/MasterThesis
Examples/Serialization/UnsecureDeserialisation/Test/Program.cs
1,006
C#
using System; using System.Reflection; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; // 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("AWSSDK.MediaLive")] #if BCL35 [assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (3.5) - AWS Elemental MediaLive. AWS Elemental MediaLive is a video service that lets you easily create live outputs for broadcast and streaming delivery.")] #elif BCL45 [assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (4.5) - AWS Elemental MediaLive. AWS Elemental MediaLive is a video service that lets you easily create live outputs for broadcast and streaming delivery.")] #elif NETSTANDARD13 [assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (NetStandard 1.3) - AWS Elemental MediaLive. AWS Elemental MediaLive is a video service that lets you easily create live outputs for broadcast and streaming delivery.")] #elif NETSTANDARD20 [assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (NetStandard 2.0) - AWS Elemental MediaLive. AWS Elemental MediaLive is a video service that lets you easily create live outputs for broadcast and streaming delivery.")] #elif NETCOREAPP3_1 [assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (.NET Core 3.1) - AWS Elemental MediaLive. AWS Elemental MediaLive is a video service that lets you easily create live outputs for broadcast and streaming delivery.")] #else #error Unknown platform constant - unable to set correct AssemblyDescription #endif [assembly: AssemblyConfiguration("")] [assembly: AssemblyProduct("Amazon Web Services SDK for .NET")] [assembly: AssemblyCompany("Amazon.com, Inc")] [assembly: AssemblyCopyright("Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.")] [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)] // 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("3.3")] [assembly: AssemblyFileVersion("3.5.8.15")] [assembly: System.CLSCompliant(true)] #if BCL [assembly: System.Security.AllowPartiallyTrustedCallers] #endif
52.245283
238
0.776092
[ "Apache-2.0" ]
PureKrome/aws-sdk-net
sdk/src/Services/MediaLive/Properties/AssemblyInfo.cs
2,769
C#
using System; using System.Collections.Generic; using System.Threading.Tasks; using DeezerSync.Model; using SoundCloud.Api.Entities; namespace DeezerSync.SoundCloud { public class playlist : Loader { public playlist() { init().Wait(); } /// <summary> /// Gets all playlists. /// </summary> /// <returns>The playlists.</returns> public async Task<IEnumerable<Playlist>> GetPlaylists() { IEnumerable<Playlist> list = await client.Users.GetPlaylistsAsync(user); return list; } /// <summary> /// Save all Playlist Data to Standard List /// </summary> public async Task<List<StandardPlaylist>> GetStandardPlaylists() { var playlistdata = await GetPlaylists(); List<StandardPlaylist> pl = new List<StandardPlaylist>(); foreach (var i in playlistdata){ var trackinfo = i.Tracks; List<StandardTitle> track = new List<StandardTitle>(); foreach(var a in trackinfo) { try { var userinfo = a.User; track.Add(new StandardTitle { username = userinfo.Username, description = a.Description, duration = a.Duration, genre = a.Genre, labelname = a.LabelName ?? string.Empty, title = a.Title, id = (long)i.Id }); } catch(Exception e) { throw new Exception(e.Message); } } pl.Add(new StandardPlaylist { description = i.Description ?? string.Empty, title = i.Title, provider = "soundcloud", tracks = track, id = i.Id.ToString() }); } return pl; } } }
31.830508
230
0.518104
[ "MIT" ]
xfischer/DeezerSync
DeezerSync/DeezerSync/SoundCloud/Playlist.cs
1,880
C#
using System; using System.IO; using System.Threading.Tasks; using Cosmos.Serialization.Json; using Xunit; namespace Cosmos.Test.Serialization.NewtonsoftTest { public class UnitTestAsync { [Fact] public async Task BytesTest() { var model = CreateNiceModel(); var bytes = await model.ToJsonAsync(); var backs = await bytes.FromJsonAsync<NiceModel>(); Assert.Equal( Tuple.Create(model.Id, model.Name, model.NiceType, model.Count, model.CreatedTime, model.IsValid), Tuple.Create(backs.Id, backs.Name, backs.NiceType, backs.Count, backs.CreatedTime, backs.IsValid)); } [Fact] public async Task NonGenericBytesTest() { var model = CreateNiceModel(); var bytes = await model.ToJsonAsync(); var backs = (NiceModel) await bytes.FromJsonAsync(typeof(NiceModel)); Assert.Equal( Tuple.Create(model.Id, model.Name, model.NiceType, model.Count, model.CreatedTime, model.IsValid), Tuple.Create(backs.Id, backs.Name, backs.NiceType, backs.Count, backs.CreatedTime, backs.IsValid)); } [Fact] public async Task StreamTest() { var model = CreateNiceModel(); var stream1 = await model.JsonPackAsync(); var stream2 = new MemoryStream(); await model.JsonPackToAsync(stream2); var stream3 = new MemoryStream(); await stream3.JsonPackByAsync(model); var back1 = await stream1.JsonUnpackAsync<NiceModel>(); var back2 = await stream2.JsonUnpackAsync<NiceModel>(); var back3 = await stream3.JsonUnpackAsync<NiceModel>(); Assert.Equal( Tuple.Create(model.Id, model.Name, model.NiceType, model.Count, model.CreatedTime, model.IsValid), Tuple.Create(back1.Id, back1.Name, back1.NiceType, back1.Count, back1.CreatedTime, back1.IsValid)); Assert.Equal( Tuple.Create(model.Id, model.Name, model.NiceType, model.Count, model.CreatedTime, model.IsValid), Tuple.Create(back2.Id, back2.Name, back2.NiceType, back2.Count, back2.CreatedTime, back2.IsValid)); Assert.Equal( Tuple.Create(model.Id, model.Name, model.NiceType, model.Count, model.CreatedTime, model.IsValid), Tuple.Create(back3.Id, back3.Name, back3.NiceType, back3.Count, back3.CreatedTime, back3.IsValid)); } [Fact] public async Task NonGenericStreamTest() { var model = CreateNiceModel(); var stream1 = await model.JsonPackAsync(); var stream2 = new MemoryStream(); await model.JsonPackToAsync(stream2); var stream3 = new MemoryStream(); await stream3.JsonPackByAsync(model); var back1 = (NiceModel) await stream1.JsonUnpackAsync(typeof(NiceModel)); var back2 = (NiceModel) await stream2.JsonUnpackAsync(typeof(NiceModel)); var back3 = (NiceModel) await stream3.JsonUnpackAsync(typeof(NiceModel)); Assert.Equal( Tuple.Create(model.Id, model.Name, model.NiceType, model.Count, model.CreatedTime, model.IsValid), Tuple.Create(back1.Id, back1.Name, back1.NiceType, back1.Count, back1.CreatedTime, back1.IsValid)); Assert.Equal( Tuple.Create(model.Id, model.Name, model.NiceType, model.Count, model.CreatedTime, model.IsValid), Tuple.Create(back2.Id, back2.Name, back2.NiceType, back2.Count, back2.CreatedTime, back2.IsValid)); Assert.Equal( Tuple.Create(model.Id, model.Name, model.NiceType, model.Count, model.CreatedTime, model.IsValid), Tuple.Create(back3.Id, back3.Name, back3.NiceType, back3.Count, back3.CreatedTime, back3.IsValid)); } [Fact] public async Task StringTest() { var model = CreateNiceModel(); var json1 = await model.ToJsonAsync(); var back1 = await json1.FromJsonAsync<NiceModel>(); Assert.Equal( Tuple.Create(model.Id, model.Name, model.NiceType, model.Count, model.CreatedTime, model.IsValid), Tuple.Create(back1.Id, back1.Name, back1.NiceType, back1.Count, back1.CreatedTime, back1.IsValid)); } [Fact] public async Task NonGenericStringTest() { var model = CreateNiceModel(); var json1 = await model.ToJsonAsync(); var back1 = (NiceModel) await json1.FromJsonAsync(typeof(NiceModel)); Assert.Equal( Tuple.Create(model.Id, model.Name, model.NiceType, model.Count, model.CreatedTime, model.IsValid), Tuple.Create(back1.Id, back1.Name, back1.NiceType, back1.Count, back1.CreatedTime, back1.IsValid)); } private static NiceModel CreateNiceModel() { return new NiceModel { Id = Guid.NewGuid(), Name = "nice", NiceType = NiceType.Yes, Count = new Random().Next(0, 100), CreatedTime = new DateTime(2019, 10, 1).ToUniversalTime(), IsValid = true }; } } }
45.706897
115
0.612599
[ "Apache-2.0" ]
alexinea/dotnet-static-pages
tests/Cosmos.Test.Serialization.NewtonsoftTest/UnitTestAsync.cs
5,302
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 Aliyun.Acs.Core; using Aliyun.Acs.Core.Http; using Aliyun.Acs.Core.Transform; using Aliyun.Acs.Core.Utils; using Aliyun.Acs.Cdn.Transform; using Aliyun.Acs.Cdn.Transform.V20141111; using System.Collections.Generic; namespace Aliyun.Acs.Cdn.Model.V20141111 { public class DescribeDomainCCDataRequest : RpcAcsRequest<DescribeDomainCCDataResponse> { public DescribeDomainCCDataRequest() : base("Cdn", "2014-11-11", "DescribeDomainCCData") { } private string securityToken; private string domainName; private string action; private string endTime; private string startTime; private long? ownerId; private string accessKeyId; public string SecurityToken { get { return securityToken; } set { securityToken = value; DictionaryUtil.Add(QueryParameters, "SecurityToken", value); } } public string DomainName { get { return domainName; } set { domainName = value; DictionaryUtil.Add(QueryParameters, "DomainName", value); } } public string Action { get { return action; } set { action = value; DictionaryUtil.Add(QueryParameters, "Action", value); } } public string EndTime { get { return endTime; } set { endTime = value; DictionaryUtil.Add(QueryParameters, "EndTime", value); } } public string StartTime { get { return startTime; } set { startTime = value; DictionaryUtil.Add(QueryParameters, "StartTime", value); } } public long? OwnerId { get { return ownerId; } set { ownerId = value; DictionaryUtil.Add(QueryParameters, "OwnerId", value.ToString()); } } public string AccessKeyId { get { return accessKeyId; } set { accessKeyId = value; DictionaryUtil.Add(QueryParameters, "AccessKeyId", value); } } public override DescribeDomainCCDataResponse GetResponse(Core.Transform.UnmarshallerContext unmarshallerContext) { return DescribeDomainCCDataResponseUnmarshaller.Unmarshall(unmarshallerContext); } } }
21.178082
120
0.653299
[ "Apache-2.0" ]
brightness007/unofficial-aliyun-openapi-net-sdk
aliyun-net-sdk-cdn/Cdn/Model/V20141111/DescribeDomainCCDataRequest.cs
3,092
C#
namespace SphereStudio.UI { partial class StringInputForm { /// <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.textBox = new System.Windows.Forms.TextBox(); this.okButton = new System.Windows.Forms.Button(); this.cancelButton = new System.Windows.Forms.Button(); this.header = new System.Windows.Forms.Label(); this.footer = new System.Windows.Forms.Panel(); this.textPanel = new System.Windows.Forms.Panel(); this.textHeading = new System.Windows.Forms.Label(); this.footer.SuspendLayout(); this.textPanel.SuspendLayout(); this.SuspendLayout(); // // textBox // this.textBox.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.textBox.Location = new System.Drawing.Point(9, 32); this.textBox.Name = "textBox"; this.textBox.Size = new System.Drawing.Size(345, 20); this.textBox.TabIndex = 1; this.textBox.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.textBox_KeyPress); // // okButton // this.okButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.okButton.DialogResult = System.Windows.Forms.DialogResult.OK; this.okButton.FlatStyle = System.Windows.Forms.FlatStyle.Flat; this.okButton.Location = new System.Drawing.Point(211, 13); this.okButton.Name = "okButton"; this.okButton.Size = new System.Drawing.Size(80, 25); this.okButton.TabIndex = 2; this.okButton.Text = "OK"; this.okButton.UseVisualStyleBackColor = true; // // cancelButton // this.cancelButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.cancelButton.DialogResult = System.Windows.Forms.DialogResult.Cancel; this.cancelButton.FlatStyle = System.Windows.Forms.FlatStyle.Flat; this.cancelButton.Location = new System.Drawing.Point(297, 13); this.cancelButton.Name = "cancelButton"; this.cancelButton.Size = new System.Drawing.Size(80, 25); this.cancelButton.TabIndex = 3; this.cancelButton.Text = "Cancel"; this.cancelButton.UseVisualStyleBackColor = true; // // header // this.header.Dock = System.Windows.Forms.DockStyle.Top; this.header.Location = new System.Drawing.Point(0, 0); this.header.Name = "header"; this.header.Size = new System.Drawing.Size(389, 23); this.header.TabIndex = 4; this.header.Text = "enter a value"; this.header.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; // // footer // this.footer.Controls.Add(this.cancelButton); this.footer.Controls.Add(this.okButton); this.footer.Dock = System.Windows.Forms.DockStyle.Bottom; this.footer.Location = new System.Drawing.Point(0, 112); this.footer.Name = "footer"; this.footer.Size = new System.Drawing.Size(389, 50); this.footer.TabIndex = 5; // // textPanel // this.textPanel.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.textPanel.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.textPanel.Controls.Add(this.textHeading); this.textPanel.Controls.Add(this.textBox); this.textPanel.Location = new System.Drawing.Point(12, 35); this.textPanel.Name = "textPanel"; this.textPanel.Size = new System.Drawing.Size(365, 63); this.textPanel.TabIndex = 6; // // textHeading // this.textHeading.Dock = System.Windows.Forms.DockStyle.Top; this.textHeading.Location = new System.Drawing.Point(0, 0); this.textHeading.Name = "textHeading"; this.textHeading.Size = new System.Drawing.Size(363, 23); this.textHeading.TabIndex = 2; this.textHeading.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; // // StringInputForm // this.AcceptButton = this.okButton; this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.CancelButton = this.cancelButton; this.ClientSize = new System.Drawing.Size(389, 162); this.Controls.Add(this.textPanel); this.Controls.Add(this.footer); this.Controls.Add(this.header); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog; this.MaximizeBox = false; this.MinimizeBox = false; this.Name = "StringInputForm"; this.ShowIcon = false; this.ShowInTaskbar = false; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; this.Text = "Set Value"; this.footer.ResumeLayout(false); this.textPanel.ResumeLayout(false); this.textPanel.PerformLayout(); this.ResumeLayout(false); } #endregion private System.Windows.Forms.TextBox textBox; private System.Windows.Forms.Button okButton; private System.Windows.Forms.Button cancelButton; private System.Windows.Forms.Label header; private System.Windows.Forms.Panel footer; private System.Windows.Forms.Panel textPanel; private System.Windows.Forms.Label textHeading; } }
46.86755
163
0.599689
[ "MIT" ]
fatcerberus/sphere-studio
SphereStudioBase/UI/StringInputForm.Designer.cs
7,079
C#
// <copyright file="ParentDirectoryFact.cs" company="Fubar Development Junker"> // Copyright (c) Fubar Development Junker. All rights reserved. // </copyright> namespace FubarDev.FtpServer.ListFormatters.Facts { /// <summary> /// The <c>pdir</c> fact. /// </summary> public class ParentDirectoryFact : TypeFact { /// <summary> /// Initializes a new instance of the <see cref="ParentDirectoryFact"/> class. /// </summary> public ParentDirectoryFact() : base("pdir") { } } }
26.571429
86
0.603943
[ "MIT" ]
40three/FtpServer
src/FubarDev.FtpServer.Abstractions/ListFormatters/Facts/ParentDirectoryFact.cs
558
C#
using System.Runtime.InteropServices; namespace Vulkan { [StructLayout(LayoutKind.Sequential)] public struct VkPhysicalDeviceSurfaceInfo2KHR { public VkStructureType SType; [NativeTypeName("const void *")] public nuint PNext; [NativeTypeName("VkSurfaceKHR")] public VkSurfaceKHR Surface; } }
22.333333
69
0.713433
[ "BSD-3-Clause" ]
trmcnealy/Vulkan
Vulkan/Structs/VkPhysicalDeviceSurfaceInfo2KHR.cs
335
C#
namespace V3.Objects.Sprite { public sealed class NecromancerSprite : AbstractSpriteCreature { protected override string TextureFile { get; } = "necromancer"; } }
26.142857
71
0.699454
[ "MIT" ]
sopra05/V3
V3/Objects/Sprite/NecromancerSprite.cs
185
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.ComponentModel; using Xunit; namespace System.Drawing.Imaging.Tests { public class BitmapDataTests { [ConditionalFact(Helpers.IsDrawingSupported)] public void Ctor_Default() { BitmapData bd = new BitmapData(); Assert.Equal(0, bd.Height); Assert.Equal(0, bd.Width); Assert.Equal(0, bd.Reserved); Assert.Equal(IntPtr.Zero, bd.Scan0); Assert.Equal(0, bd.Stride); Assert.Equal((PixelFormat)0, bd.PixelFormat); } [ConditionalTheory(Helpers.IsDrawingSupported)] [InlineData(int.MaxValue)] [InlineData(0)] [InlineData(int.MinValue)] public void Height_SetValid_ReturnsExpected(int value) { BitmapData bd = new BitmapData(); bd.Height = value; Assert.Equal(value, bd.Height); } [ConditionalTheory(Helpers.IsDrawingSupported)] [InlineData(int.MaxValue)] [InlineData(0)] [InlineData(int.MinValue)] public void Width_SetValid_ReturnsExpected(int value) { BitmapData bd = new BitmapData(); bd.Width = value; Assert.Equal(value, bd.Width); } [ConditionalTheory(Helpers.IsDrawingSupported)] [InlineData(int.MaxValue)] [InlineData(0)] [InlineData(int.MinValue)] public void Reserved_SetValid_ReturnsExpected(int value) { BitmapData bd = new BitmapData(); bd.Reserved = value; Assert.Equal(value, bd.Reserved); } [ConditionalTheory(Helpers.IsDrawingSupported)] [InlineData(int.MaxValue)] [InlineData(0)] [InlineData(int.MinValue)] public void Scan0_SetValid_ReturnsExpected(int value) { BitmapData bd = new BitmapData(); bd.Scan0 = new IntPtr(value); Assert.Equal(new IntPtr(value), bd.Scan0); } [ConditionalTheory(Helpers.IsDrawingSupported)] [InlineData(int.MaxValue)] [InlineData(0)] [InlineData(int.MinValue)] public void Stride_SetValid_ReturnsExpected(int value) { BitmapData bd = new BitmapData(); bd.Stride = value; Assert.Equal(value, bd.Stride); } [ConditionalTheory(Helpers.IsDrawingSupported)] [InlineData(PixelFormat.DontCare)] [InlineData(PixelFormat.Max)] [InlineData(PixelFormat.Indexed)] [InlineData(PixelFormat.Gdi)] [InlineData(PixelFormat.Format16bppRgb555)] [InlineData(PixelFormat.Format16bppRgb565)] [InlineData(PixelFormat.Format24bppRgb)] [InlineData(PixelFormat.Format32bppRgb)] [InlineData(PixelFormat.Format1bppIndexed)] [InlineData(PixelFormat.Format4bppIndexed)] [InlineData(PixelFormat.Format8bppIndexed)] [InlineData(PixelFormat.Alpha)] [InlineData(PixelFormat.Format16bppArgb1555)] [InlineData(PixelFormat.PAlpha)] [InlineData(PixelFormat.Format32bppPArgb)] [InlineData(PixelFormat.Extended)] [InlineData(PixelFormat.Format16bppGrayScale)] [InlineData(PixelFormat.Format48bppRgb)] [InlineData(PixelFormat.Format64bppPArgb)] [InlineData(PixelFormat.Canonical)] [InlineData(PixelFormat.Format32bppArgb)] [InlineData(PixelFormat.Format64bppArgb)] public void PixelFormat_SetValid_ReturnsExpected(PixelFormat pixelFormat) { BitmapData bd = new BitmapData(); bd.PixelFormat = pixelFormat; Assert.Equal(pixelFormat, bd.PixelFormat); } [ConditionalFact(Helpers.IsDrawingSupported)] public void PixelFormat_SetInvalid_ThrowsInvalidEnumException() { BitmapData bd = new BitmapData(); Assert.ThrowsAny<ArgumentException>(() => bd.PixelFormat = (PixelFormat)(-1)); } } }
35.820513
90
0.631114
[ "MIT" ]
06needhamt/runtime
src/libraries/System.Drawing.Common/tests/Imaging/BitmapDataTests.cs
4,193
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows.Media.Media3D; using System.Globalization; namespace DXFImportExport { ////////////////////////////////////////////////////////////////////////////////////////////////////////////// // ============================================= BASE TYPE: ENTITY ======================================== // ////////////////////////////////////////////////////////////////////////////////////////////////////////////// #region DXF_Entity public class DXFEntity { public bool entIsVisible; protected bool entHasEntities; public string EntName { get; protected set; } internal DXFConverter Converter { get; set; } // for printing text protected NumberFormatInfo nfi; public DXFEntity() { this.EntName = null; this.entIsVisible = true; this.entHasEntities = false; this.nfi = new NumberFormatInfo(); nfi.NumberDecimalSeparator = "."; nfi.NumberGroupSeparator = " "; } public virtual void Invoke(DXFConverterProc _proc, DXFIterate _params) { _proc(this); } public virtual void ReadPoperty() { switch(this.Converter.FCode) { case 0: // set the entity type (i.e. LINE) as name // CANNOT BE REACHED! this.EntName = this.Converter.FValue; break; case 60: int vis = this.Converter.IntValue(); if (vis == 0) // invisible this.entIsVisible &= false; break; case 67: int space = this.Converter.IntValue(); if (space == 1) // paper space this.entIsVisible &= false; break; } } public virtual void OnLoaded() { } public virtual bool AddEntity(DXFEntity e) { return false; } public override string ToString() { return this.GetType().ToString(); } public virtual DXFGeometry ConvertToDrawable(string _note = "") { return new DXFGeometry(); } public void ParseNext() { // start parsing next entity this.ReadProperties(); // if it contains entities itself, parse them next if (this.entHasEntities) this.ReadEntities(); } protected void ReadProperties() { while(this.Converter.HasNext()) { this.Converter.Next(); switch(this.Converter.FCode) { case 0: // reached next entity return; default: // otherwise continue parsing this.ReadPoperty(); break; } } } protected void ReadEntities() { // debug DXFInsert test = this as DXFInsert; int test2; if (test != null) test2 = test.ecEntities.Count; DXFEntity e; do { if (this.Converter.FValue == "EOF") { // end of file this.Converter.ReleaseRessources(); return; } e = this.Converter.CreateEntity(); if (e == null) { // reached end of complex entity this.Converter.Next(); break; } // ----------------------------------------------- // check for special case: Insert w/o attributes if (CurrentEntityInsertWoAttribs(e)) { // reached end of Insert w/o attributes // this.Converter.Next(); break; } // ----------------------------------------------- e.ParseNext(); if(e.GetType().IsSubclassOf(typeof(DXFEntity))) { // complete parsing e.OnLoaded(); // add to list of entities of this entity this.AddEntity(e); } } while (this.Converter.HasNext()); } private bool CurrentEntityInsertWoAttribs(DXFEntity e) { DXFInsert thisAsInsert = this as DXFInsert; if (thisAsInsert != null) { DXFAttribute eAsAttrib = e as DXFAttribute; if (eAsAttrib == null) return true; else return false; } else { return false; } } } #endregion #region DXF_Dummy_Entity public class DXFDummy : DXFEntity { public DXFDummy() { this.EntName = null; this.entIsVisible = false; this.entHasEntities = false; } public DXFDummy(string _name) { this.EntName = _name; this.entIsVisible = false; this.entHasEntities = false; } public override string ToString() { string dxfS = base.ToString(); if (this.EntName != null) dxfS += "[" + this.EntName + "]"; return dxfS; } } #endregion ////////////////////////////////////////////////////////////////////////////////////////////////////////////// // ============================================ SIMPLE ENTITY TYPES ======================================= // ////////////////////////////////////////////////////////////////////////////////////////////////////////////// // ------------------------------------------------- DXFLayer --------------------------------------------- // #region DXF_Layer public class DXFLayer : DXFEntity { private static int counterAutomatic = 0; protected DXFColor layerColor; protected DXFColor layerTrueColor; public DXFColor LayerColor { get { if (this.layerTrueColor != DXFColor.clNone) return this.layerTrueColor; else return this.layerColor; } } public DXFLayer() :base() { this.layerColor = DXFColor.clNone; this.layerTrueColor = DXFColor.clNone; } public DXFLayer(string _name) : base() { if (_name != null && _name.Count() > 0) this.EntName = _name; else { DXFLayer.counterAutomatic++; this.EntName = "$" + DXFLayer.counterAutomatic.ToString() + "_autoGen"; } this.layerColor = DXFColor.clNone; this.layerTrueColor = DXFColor.clNone; } public override void ReadPoperty() { base.ReadPoperty(); switch (this.Converter.FCode) { case 2: this.EntName = this.Converter.FValue; break; case 62: this.layerColor = DXFColor.Index2DXFColor(this.Converter.IntValue()); break; case 420: this.layerTrueColor = DXFColor.TrueColor2DXFColor(this.Converter.IntValue()); break; case 70: byte flags = this.Converter.ByteValue(); if (flags == 1) // frozen posLayer this.entIsVisible = false; break; } } public override void OnLoaded() { // set the layerColor of a frozen posLayer if (!this.entIsVisible) { this.layerColor = DXFColor.clNone; this.layerTrueColor = DXFColor.clNone; } } public override string ToString() { string dxfL = base.ToString(); dxfL += " " + this.EntName + " |color: " + this.LayerColor.ToString() + " |visible: " + this.entIsVisible.ToString(); return dxfL; } } #endregion // --------------------------------------------- DXFPositionable ------------------------------------------ // #region DXF_Positionable public class DXFPositionable : DXFEntity { protected DXFLayer posLayer; protected DXFColor posColor; private DXFColor posTrueColor; protected Point3D posBasePos; internal Point3D posPosStart; protected Vector3D posPlaneNormal; public DXFColor Color { get { return this.posColor; } } public DXFPositionable() : base() { this.posLayer = new DXFLayer(); this.posColor = DXFColor.clByLayer; this.posTrueColor = DXFColor.clNone; this.posBasePos = new Point3D(0, 0, 0); this.posPosStart = new Point3D(0, 0, 0); this.posPlaneNormal = new Vector3D(0, 0, 1); } public override void ReadPoperty() { base.ReadPoperty(); // codes 0(type), 60+67(visibility) switch(this.Converter.FCode) { case 8: this.posLayer = this.Converter.RetrieveLayer(this.Converter.FValue); break; case 62: this.posColor = DXFColor.Index2DXFColor(this.Converter.IntValue()); break; case 420: this.posTrueColor = DXFColor.TrueColor2DXFColor(this.Converter.IntValue()); break; case 10: this.posPosStart.X = this.Converter.FloatValue(); break; case 20: this.posPosStart.Y = this.Converter.FloatValue(); break; case 30: this.posPosStart.Z = this.Converter.FloatValue(); break; case 210: this.posPlaneNormal.X = this.Converter.FloatValue(); break; case 220: this.posPlaneNormal.Y = this.Converter.FloatValue(); break; case 230: this.posPlaneNormal.Z = this.Converter.FloatValue(); break; } } public override void OnLoaded() { // set the layerColor if (this.posColor == DXFColor.clByLayer) this.posColor = this.posLayer.LayerColor; if (this.posTrueColor != DXFColor.clNone) this.posColor = this.posTrueColor; // set the layerColor dependent on visibility if (!this.entIsVisible) this.posColor = DXFColor.clNone; } public override string ToString() { string dxfS = base.ToString(); dxfS += " |layer: " + this.posLayer.EntName + " |color: " + this.posColor.ToString() + "\n"; dxfS += " |posS: " + Extensions.Point3DToString(this.posPosStart); dxfS += " |posN: " + Extensions.Vector3DToString(this.posPlaneNormal); return dxfS; } public override DXFGeometry ConvertToDrawable(string _note = "") { DXFGeometry drawable = new DXFGeometry(); drawable.Color = this.Color; drawable.Name = _note + " Point"; drawable.AddVertex(this.posPosStart, false, 1f, this.posPosStart, this.posPlaneNormal); return drawable; } } #endregion ////////////////////////////////////////////////////////////////////////////////////////////////////////////// // =================== POSITIONABLE ENTITIES - I. E. GEOMETRIC OBJECT REPRESENTATIONS ===================== // ////////////////////////////////////////////////////////////////////////////////////////////////////////////// // ------------------------------------------------ DXFLine ----------------------------------------------- // #region DXF_Line public class DXFLine : DXFPositionable { protected Point3D linePosEnd; public DXFLine() : base() { this.linePosEnd = new Point3D(0, 0, 0); } public override void ReadPoperty() { switch(this.Converter.FCode) { case 11: this.linePosEnd.X = this.Converter.FloatValue(); break; case 21: this.linePosEnd.Y = this.Converter.FloatValue(); break; case 31: this.linePosEnd.Z = this.Converter.FloatValue(); break; default: // codes 0(type), 60+67(visibility), 8(posLayer), 62+420(layerColor), 10,20,30 (posPosStart) // 210,220,230 (posPlaneNormal) base.ReadPoperty(); break; } } public override string ToString() { string dxfS = base.ToString(); dxfS += " |posE: " + Extensions.Point3DToString(this.linePosEnd); return dxfS; } public override DXFGeometry ConvertToDrawable(string _note = "") { DXFGeometry drawable = new DXFGeometry(); drawable.LayerName = this.posLayer.EntName; drawable.Color = this.Color; drawable.Name = _note + " Line"; drawable.AddVertex(this.posPosStart, false, 0.25f); drawable.AddVertex(this.linePosEnd, false, 0.25f); return drawable; } } #endregion // --------------------------------------- DXFCircle (CIRCLE and ARC)-------------------------------------- // #region DXF_Circle public class DXFCircle : DXFPositionable { protected float circRadius; protected float circAngleStart; protected float circAngleEnd; public DXFCircle() : base() { this.circRadius = 1f; this.circAngleStart = 0; this.circAngleEnd = 360f; // (float)(2 * Math.PI); } public override void ReadPoperty() { base.ReadPoperty(); switch(this.Converter.FCode) { case 40: this.circRadius = this.Converter.FloatValue(); break; case 50: this.circAngleStart = this.Converter.FloatValue(); break; case 51: this.circAngleEnd = this.Converter.FloatValue(); break; default: base.ReadPoperty(); break; } } public override string ToString() { string dxfS = base.ToString(); dxfS += " |radius: " + String.Format(this.nfi, "{0:F2}", this.circRadius) + " |angS: " + String.Format(this.nfi, "{0:F2}", this.circAngleStart) + " |angE: " + String.Format(this.nfi, "{0:F2}", this.circAngleEnd); return dxfS; } public override DXFGeometry ConvertToDrawable(string _note = "") { DXFGeometry drawable = new DXFGeometry(); drawable.LayerName = this.posLayer.EntName; drawable.Color = this.Color; drawable.Name = _note + "Circle Arc"; drawable.AddCircleArc(this.posPosStart, this.posPlaneNormal, this.circRadius, this.circAngleStart, this.circAngleEnd, 0.25f, 18); return drawable; } } #endregion // ---------------------------------------------- DXFEllipse ---------------------------------------------- // #region DXF_Ellipse public class DXFEllipse : DXFPositionable { protected Vector3D ellPosMajAxisEnd; protected float ellMin2majRatio; protected float ellParamStart; protected float ellParamEnd; private float a; // for drawing the ellipse private float b; // for drawing the ellipse public DXFEllipse() : base() { this.ellPosMajAxisEnd = new Vector3D(0, 0, 0); this.ellMin2majRatio = 1f; this.ellParamStart = 0f; this.ellParamEnd = (float)(2 * Math.PI); } public override void ReadPoperty() { switch(this.Converter.FCode) { case 11: // realtive to posPosStart this.ellPosMajAxisEnd.X = this.Converter.FloatValue(); break; case 21: // realtive to posPosStart this.ellPosMajAxisEnd.Y = this.Converter.FloatValue(); break; case 31: // realtive to posPosStart this.ellPosMajAxisEnd.Z = this.Converter.FloatValue(); break; case 40: this.ellMin2majRatio = this.Converter.FloatValue(); break; case 41: this.ellParamStart = this.Converter.FloatValue(); break; case 42: this.ellParamEnd = this.Converter.FloatValue(); break; default: base.ReadPoperty(); break; } } public override void OnLoaded() { base.OnLoaded(); // calculate the coefficients for drawing the ellipse double majHalfLen = Math.Sqrt( this.ellPosMajAxisEnd.X * this.ellPosMajAxisEnd.X + this.ellPosMajAxisEnd.Y * this.ellPosMajAxisEnd.Y + this.ellPosMajAxisEnd.Z * this.ellPosMajAxisEnd.Z); this.a = (float)majHalfLen * (-1f); this.b = this.a * this.ellMin2majRatio; } public override string ToString() { string dxfS = base.ToString(); dxfS += " |a: " + String.Format(this.nfi, "{0:F2}", this.a) + " |b: " + String.Format(this.nfi, "{0:F2}", this.b) + " |uS: " + String.Format(this.nfi, "{0:F2}", this.ellParamStart) + " |uE: " + String.Format(this.nfi, "{0:F2}", this.ellParamEnd); return dxfS; } public override DXFGeometry ConvertToDrawable(string _note = "") { DXFGeometry drawable = new DXFGeometry(); drawable.LayerName = this.posLayer.EntName; drawable.Color = this.Color; drawable.Name = _note + " Ellipse Arc"; drawable.AddEllipseArc(this.posPosStart, this.posPlaneNormal, this.a, this.b, this.ellPosMajAxisEnd, this.ellParamStart, this.ellParamEnd, 0.25f, 24); return drawable; } } #endregion // ---------------------------------------------- DXFLWPolyLine ------------------------------------------- // #region DXF_LWpolyLine public class DXFLWPolyLine : DXFPositionable { protected int plNrVertices; protected bool plIsClosed; protected List<Point3D> plVertices; protected List<Point3D> plWidths; // for reading plVertices private List<bool> readVertices; private Point3D vertex; private List<bool> readVertexWidths; private Point3D width; private float widthGlobal; private float elevation; public DXFLWPolyLine() : base() { this.plNrVertices = 0; this.plIsClosed = false; this.plVertices = new List<Point3D>(); this.plWidths = new List<Point3D>(); this.readVertices = new List<bool>(); this.vertex = new Point3D(0, 0, 0); this.readVertexWidths = new List<bool>(); this.width = new Point3D(0, 0, 0); this.widthGlobal = 0f; this.elevation = 0f; } public override void ReadPoperty() { int nV = this.readVertices.Count; int nVW = this.readVertexWidths.Count; switch (this.Converter.FCode) { case 10: this.vertex.X = this.Converter.FloatValue(); this.ProcessVertex(nV); break; case 20: this.vertex.Y = this.Converter.FloatValue(); this.ProcessVertex(nV); break; case 38: this.elevation = this.Converter.FloatValue(); break; case 40: this.width.X = this.Converter.FloatValue(); this.ProcessVertexWidth(nVW); break; case 41: this.width.Y = this.Converter.FloatValue(); this.ProcessVertexWidth(nVW); break; case 43: this.widthGlobal = this.Converter.FloatValue(); break; case 70: byte flags = this.Converter.ByteValue(); if ((flags & 1) == 1) this.plIsClosed = true; break; case 90: // nr plVertices not necessary break; default: base.ReadPoperty(); break; } } private void ProcessVertex(int _nV) { if (_nV == 0 || this.readVertices[_nV - 1]) { // starts reading a new vertex this.readVertices.Add(false); this.plNrVertices++; } else { // completes reading a vertex this.readVertices[_nV - 1] = true; this.plVertices.Add(this.vertex); this.vertex = new Point3D(0, 0, 0); } } private void ProcessVertexWidth(int _nVW) { if (_nVW == 0 || this.readVertexWidths[_nVW - 1]) { // starts reading a new vertex Width this.readVertexWidths.Add(false); } else { // completes reading a vertex Width this.readVertexWidths[_nVW - 1] = true; this.plWidths.Add(this.width); this.width = new Point3D(0, 0, 0); } } public override void OnLoaded() { base.OnLoaded(); if (this.elevation != 0) { for (int i = 0; i < this.plNrVertices; i++) { Point3D tmp = this.plVertices[i]; tmp.Z = this.elevation; this.plVertices[i] = tmp; } } } public override string ToString() { string dxfS = base.ToString(); for (int i = 0; i < this.plNrVertices; i++ ) { dxfS += "\n" + Extensions.Point3DToString(this.plVertices[i]); if (this.plWidths.Count == this.plNrVertices) dxfS += " w: " + Extensions.Point3DToString(this.plWidths[i],2); } return dxfS; } public override DXFGeometry ConvertToDrawable(string _note = "") { DXFGeometry drawable = new DXFGeometry(); drawable.LayerName = this.posLayer.EntName; drawable.Color = this.Color; drawable.Name = _note + " Polyline"; List<Point3D> plVerticesOut = new List<Point3D>(this.plVertices); List<Point3D> plWidthsOut = new List<Point3D>(this.plWidths); if (this.plIsClosed) { plVerticesOut.Add(this.plVertices[0]); if (this.plWidths.Count > 0) plWidthsOut.Add(this.plWidths[0]); } if (this.plVertices.Count == this.plWidths.Count) drawable.AddLines(plVerticesOut, true, plWidthsOut, this.posPosStart, this.posPlaneNormal); else drawable.AddLines(plVerticesOut, true, this.widthGlobal, this.posPosStart, this.posPlaneNormal); return drawable; } } #endregion ////////////////////////////////////////////////////////////////////////////////////////////////////////////// // ========================= POSITIONABLE ENTITIES - TEXT OBJECT REPRESENTATIONS ========================== // ////////////////////////////////////////////////////////////////////////////////////////////////////////////// // ------------------------------------------------- DXFText ---------------------------------------------- // #region DXF_Text public class DXFText : DXFLine { protected float txtHeight; protected float txtScaleX; protected float txtAngle; // in degrees protected byte txtFlags; protected int txtJustH; protected int txtJustV; protected string txtContent; public DXFText() : base() { this.txtHeight = 1f; this.txtScaleX = 1f; this.txtAngle = 0f; this.txtFlags = 0; this.txtJustH = 0; this.txtJustV = 0; this.txtContent = ""; } public override void ReadPoperty() { switch(this.Converter.FCode) { case 1: this.txtContent = this.Converter.FValue; break; case 40: this.txtHeight = this.Converter.FloatValue(); break; case 41: this.txtScaleX = this.Converter.FloatValue(); break; case 50: this.txtAngle = this.Converter.FloatValue(); break; case 71: this.txtFlags = this.Converter.ByteValue(); break; case 72: this.txtJustH = this.Converter.IntValue(); break; case 73: this.txtJustV = this.Converter.IntValue(); break; default: // DXFEntity: codes 0(type), 60+67(visibility) // DXFPositionable: codes 8(posLayer), 62+420(posColor), 10,20,30 (posPosStart), 210,220,230 (posPlaneNormal) // DXFLine: codes 11,21,31 (linePosEnd) base.ReadPoperty(); break; } } public override void OnLoaded() { base.OnLoaded(); // adjust rotation if (this.linePosEnd == new Point3D(0,0,0)) { // take the rotation txtAngle } } public override string ToString() { string dxfS = base.ToString(); dxfS += "\n_cont: " + this.txtContent + " |txtH: " + String.Format(this.nfi, "{0:F2}", this.txtHeight) + " |txtScaleX: " + String.Format(this.nfi, "{0:F2}", this.txtScaleX) + " |txtAngle: " + String.Format(this.nfi, "{0:F2}", this.txtAngle) + " |txtJustH: " + this.txtJustH + " |txtJustV: " + this.txtJustV + " |txtFlags: " + this.txtFlags; return dxfS; } public override DXFGeometry ConvertToDrawable(string _note = "") { DXFGeometry drawable = new DXFGeometry(); drawable.LayerName = this.posLayer.EntName; drawable.Color = this.Color; drawable.Name = _note + " Text"; // assemble a rectangle as placeholder List<Point3D> verts = new List<Point3D>(); Point3D rectBL = this.posPosStart; float txtAngRad = this.txtAngle * (float)Math.PI / 180f; float txtLen = this.txtContent.Count() * this.txtScaleX; Point3D rectBR = rectBL + new Vector3D(1, 0, 0) * Math.Cos(txtAngRad) * txtLen + new Vector3D(0, 1, 0) * Math.Sin(txtAngRad) * txtLen; Point3D rectTR = rectBR + new Vector3D(1, 0, 0) * Math.Sin(txtAngRad) * this.txtHeight - new Vector3D(0, 1, 0) * Math.Cos(txtAngRad) * this.txtHeight; Point3D rectTL = rectBL + new Vector3D(1, 0, 0) * Math.Sin(txtAngRad) * this.txtHeight - new Vector3D(0, 1, 0) * Math.Cos(txtAngRad) * this.txtHeight; // pass geometry verts.AddRange(new Point3D[] { rectBL, rectBR, rectTR, rectTL, rectBL}); drawable.AddLines(verts, true, 0.25f, this.posPosStart, this.posPlaneNormal); // scale the text(based on verdana 1.2 regular) Matrix3D Mscale = Matrix3D.Identity; Mscale.ScaleAt(new Vector3D(this.txtHeight / 1.2f, this.txtHeight / 1.2f, 1), new Point3D(0, 0, 0)); // rotate Matrix3D Mrot = Matrix3D.Identity; Mrot.Rotate(new Quaternion(new Vector3D(0, 0, 1), this.txtAngle)); // pass text with the correct CS Vector3D axisX, axisY, axisZ; DXFGeometry.CalPlaneCS(this.posPosStart, this.posPlaneNormal, out axisX, out axisY, out axisZ); Matrix3D Mcs = new Matrix3D(); Mcs.M11 = axisX.X; Mcs.M12 = axisX.Y; Mcs.M13 = axisX.Z; Mcs.M21 = axisY.X; Mcs.M22 = axisY.Y; Mcs.M23 = axisY.Z; Mcs.M31 = axisZ.X; Mcs.M32 = axisZ.Y; Mcs.M33 = axisZ.Z; Vector3D oText = rectTL.X * axisX + rectTL.Y * axisY + rectTL.Z * axisZ; Mcs.OffsetX = oText.X; Mcs.OffsetY = oText.Y; Mcs.OffsetZ = oText.Z; drawable.AddText(this.txtContent, Mscale * Mrot * Mcs); return drawable; } } #endregion // ------------------------------------------------- DXFMText --------------------------------------------- // #region DXF_MText public class DXFMText : DXFText { protected float mtTxtLineSpacing; protected bool mtBgShow; protected DXFColor mtBgColor; protected Rect3D mtBgBox; private List<string> contentChunks; private string[] mtContentLines; private float textBoxHeight; private float fillBoxScale; public DXFMText() : base() { this.linePosEnd = new Point3D(1, 0, 0); this.mtTxtLineSpacing = 1f; this.mtBgShow = false; this.mtBgColor = DXFColor.clNone; this.mtBgBox = new Rect3D(0, 0, 0, 1, 1, 1); this.contentChunks = new List<string>(); this.textBoxHeight = 0f; this.fillBoxScale = 1f; } public override void ReadPoperty() { switch(this.Converter.FCode) { case 1: this.contentChunks.Add(this.Converter.FValue); break; case 3: this.contentChunks.Add(this.Converter.FValue); break; case 41: // override: absolute, not realtive! this.txtScaleX = this.Converter.FloatValue(); break; case 43: // actual height of the text field this.textBoxHeight = this.Converter.FloatValue(); break; case 44: // line spacing factor this.mtTxtLineSpacing = this.Converter.FloatValue(); break; case 45: // fill box scale this.fillBoxScale = this.Converter.FloatValue(); break; case 71: // override this.txtJustH = this.Converter.IntValue(); break; case 72: // override this.txtFlags = this.Converter.ByteValue(); break; case 73: // override: do nothing break; case 90: byte flag = this.Converter.ByteValue(); if ((flag & 1) == 1) this.mtBgShow = true; break; case 63: this.mtBgColor = DXFColor.Index2DXFColor(this.Converter.IntValue()); break; default: // DXFEntity: codes 0(type), 60+67(visibility) // DXFPositionable: codes 8(posLayer), 62+420(posColor), 10,20,30 (posPosStart), 210,220,230 (posPlaneNormal) // DXFLine: codes 11,21,31 (linePosEnd) - HERE X-axis Direction Vector!!! // DXFText: codes 1(content),40(char height),41(scaleX),50(angle),71(flags),72(justH),73(justV) base.ReadPoperty(); break; } } public override void OnLoaded() { base.OnLoaded(); // assemble content foreach(var chunk in this.contentChunks) { this.txtContent += chunk; } // adjust horizontal and vertical justification switch(this.txtJustH) { case 1: this.txtJustV = 3; // TOP this.txtJustH = 0; // LEFT break; case 2: this.txtJustV = 3; // TOP this.txtJustH = 1; // CENTER break; case 3: this.txtJustV = 3; // TOP this.txtJustH = 2; // RIGHT break; case 4: this.txtJustV = 2; // MIDDLE this.txtJustH = 0; // LEFT break; case 5: this.txtJustV = 2; // MIDDLE this.txtJustH = 1; // CENTER break; case 6: this.txtJustV = 2; // MIDDLE this.txtJustH = 2; // RIGHT break; case 7: this.txtJustV = 1; // BOTTOM this.txtJustH = 0; // LEFT break; case 8: this.txtJustV = 1; // BOTTOM this.txtJustH = 1; // CENTER break; case 9: this.txtJustV = 1; // BOTTOM this.txtJustH = 2; // RIGHT break; } // extract the actual text // remove the curly brackets, if any present int txtLen = this.txtContent.Count(); string clearText; if (txtLen > 0 && this.txtContent[0] == '{') clearText = this.txtContent.Substring(1, txtLen - 2); else clearText = this.txtContent; // separate lines of text string[] lineSeparators = new string[] { "\\P" }; string[] rawContentLines = clearText.Split(lineSeparators, StringSplitOptions.None); // determine the actual geometric length of each text line based on verdana 1.2 regular font // and actual char width float charW = 0.75f * this.txtHeight / 1.2f; // if any line is longer than the text box, break it this.mtContentLines = DXFGeometry.FitTextLines(rawContentLines, charW, this.txtScaleX); // determine vertical size if (this.textBoxHeight <= this.txtHeight) { int nrLines = this.mtContentLines.Count(); this.textBoxHeight = nrLines * this.txtHeight + nrLines * this.mtTxtLineSpacing * this.txtHeight * 0.8f; } // adjust the size of the background box: float offsetX = this.txtScaleX * (1f - this.fillBoxScale) * 0.5f; float offsetY = this.textBoxHeight * (1f - this.fillBoxScale) * 0.5f; this.mtBgBox = new Rect3D(this.posPosStart.X - offsetX, this.posPosStart.Y - offsetY, this.posPosStart.Z, this.txtScaleX * this.fillBoxScale, this.textBoxHeight * this.fillBoxScale, 1); } public override string ToString() { string dxfS = base.ToString(); dxfS += " |n_txtBox: " + this.mtBgShow.ToString() + " " + String.Format(this.nfi, "size: {0:F2}, {1:F2}, {2:F2}, {3:F2}", this.mtBgBox.Location.X, this.mtBgBox.Location.Y, this.mtBgBox.SizeX, this.mtBgBox.SizeY) + " |bgColor: " + this.mtBgColor.ToString(); return dxfS; } public override DXFGeometry ConvertToDrawable(string _note = "") { DXFGeometry drawable = new DXFGeometry(); drawable.LayerName = this.posLayer.EntName; drawable.Color = this.Color; drawable.Name = _note + " MText"; // assemble a rectangle as placeholder List<Point3D> verts = new List<Point3D>(); // calculate ist coordinate system Vector3D bottomV = new Vector3D(this.linePosEnd.X, this.linePosEnd.Y, this.linePosEnd.Z); Vector3D normal = this.posPlaneNormal; DXFGeometry.NormalizeVector(ref normal); Vector3D sideV = Vector3D.CrossProduct(normal, bottomV); DXFGeometry.NormalizeVector(ref sideV); Point3D rectTL = this.posPosStart; Point3D rectBL = rectTL - sideV * this.textBoxHeight; Point3D rectBR = rectBL + bottomV * this.txtScaleX; Point3D rectTR = rectBR + sideV * this.textBoxHeight; Matrix3D Mreflect = Matrix3D.Identity; if (this.txtFlags == 1) { // text right to left rectTL = this.posPosStart; rectBL = rectTL + sideV * this.textBoxHeight; rectBR = rectBL - bottomV * this.txtScaleX; rectTR = rectBR - sideV * this.textBoxHeight; Mreflect.M11 = -1; Mreflect.OffsetY = sideV.Y * this.textBoxHeight; } else if (this.txtFlags == 3) { // text bottom to top rectTL = this.posPosStart; rectBL = rectTL + sideV * this.textBoxHeight; rectBR = rectBL + bottomV * this.txtScaleX; rectTR = rectBR - sideV * this.textBoxHeight; Mreflect.M22 = -1; } // pass geometry verts.AddRange(new Point3D[] { rectBL, rectBR, rectTR, rectTL, rectBL }); drawable.AddLines(verts, true, 0.25f); // scale the text(based on verdana 1.2 regular) Matrix3D Mscale = Matrix3D.Identity; Mscale.ScaleAt(new Vector3D(this.txtHeight / 1.2f, this.txtHeight / 1.2f, 1), new Point3D(0, 0, 0)); // pass text with the correct CS Matrix3D Mcs = new Matrix3D(); Mcs.M11 = bottomV.X; Mcs.M12 = bottomV.Y; Mcs.M13 = bottomV.Z; Mcs.M21 = sideV.X; Mcs.M22 = sideV.Y; Mcs.M23 = sideV.Z; Mcs.M31 = normal.X; Mcs.M32 = normal.Y; Mcs.M33 = normal.Z; Mcs.OffsetX = rectTL.X - sideV.X * this.txtHeight; Mcs.OffsetY = rectTL.Y - sideV.Y * this.txtHeight; Mcs.OffsetZ = rectTL.Z - sideV.Z * this.txtHeight; drawable.AddText(this.mtContentLines, Mscale * Mreflect * Mcs); return drawable; } } #endregion // ------------------------------------- DXFAttribute (ATTDEF and ATTRIB) --------------------------------- // #region DXF_Attribute public class DXFAttribute : DXFText { private string attrTag; private string attrPrompt; private bool attrVisible; private float attrScaleX; private float attrFieldLen; private int attrJustV; public DXFAttribute() : base() { this.attrTag = ""; this.attrPrompt = ""; this.attrVisible = true; this.attrScaleX = 1f; this.attrFieldLen = 1f; this.attrJustV = 0; } public override void ReadPoperty() { switch(this.Converter.FCode) { case 2: this.attrTag = this.Converter.FValue; break; case 3: this.attrPrompt = this.Converter.FValue; break; case 70: byte flag = this.Converter.ByteValue(); if ((flag & 1) == 1) this.attrVisible = false; break; case 41: this.attrScaleX = this.Converter.FloatValue(); break; case 73: this.attrFieldLen = this.Converter.FloatValue(); break; case 74: this.attrJustV = this.Converter.IntValue(); break; default: // DXFEntity: codes 0(type), 60+67(visibility) // DXFPositionable: codes 8(posLayer), 62+420(layerColor), 10,20,30 (posPosStart), 210,220,230 (posPlaneNormal) // DXFLine: codes 11,21,31 (linePosEnd) // DXFText: codes 1(content),40(char height),41(scaleX),50(angle),71(flags),72(justH),73(justV) base.ReadPoperty(); break; } } public override void OnLoaded() { base.OnLoaded(); this.EntName += "_" + this.attrTag + "_(" + this.attrPrompt + "):"; this.entIsVisible &= this.attrVisible; this.txtScaleX = this.attrScaleX; this.txtJustV = this.attrJustV; // this.txtContent = this.attrTag + ": " + this.txtContent; } } #endregion ////////////////////////////////////////////////////////////////////////////////////////////////////////////// // ========================================= COLLECTIONS OF ENTITIES ====================================== // ////////////////////////////////////////////////////////////////////////////////////////////////////////////// // -------------------------------------------- DXFEntityContainer ---------------------------------------- // #region DXF_Entity_Container public class DXFEntityContainer : DXFPositionable { internal List<DXFEntity> ecEntities; public DXFEntityContainer() : base() { this.entHasEntities = true; this.ecEntities = new List<DXFEntity>(); } public override void ReadPoperty() { switch(this.Converter.FCode) { case 2: this.EntName = this.Converter.FValue; break; default: // DXFEntity: codes 0(type), 60+67(visibility) // DXFPositionable: codes 8(posLayer), 62+420(posColor), 10,20,30 (posPosStart), 210,220,230 (posPlaneNormal) base.ReadPoperty(); break; } } public override bool AddEntity(DXFEntity e) { if (e != null) this.ecEntities.Add(e); return (e != null); } public void Iterate(DXFConverterProc _proc, DXFIterate _params) { if (_proc == null || _params == null) return; foreach(DXFEntity e in this.ecEntities) { e.Invoke(_proc, _params); } } public override string ToString() { string dxfS = base.ToString(); if (this.EntName != null && this.EntName.Count() > 0) dxfS += ": " + this.EntName; int n = this.ecEntities.Count; dxfS += " has " + n.ToString() + " entities:\n"; for (int i = 0; i < n; i++ ) { dxfS += "_[ " + i + "]_" + this.ecEntities[i].ToString() + "\n"; } dxfS += "\n"; return dxfS; } } #endregion // ------------------------------------------------ DXFSection -------------------------------------------- // #region DXF_Section public class DXFSection : DXFEntityContainer { public override void ReadPoperty() { if ((this.EntName == null) && (this.Converter.FCode == 2)) { this.EntName = this.Converter.FValue; } switch (this.EntName) { case "BLOCKS": this.Converter.FBlocks = this; break; case "ENTITIES": this.Converter.FEntities = this; break; } } } #endregion // ------------------------------------------------- DXFTable --------------------------------------------- // // used as a Layer-table #region DXF_Table public class DXFTable : DXFEntityContainer { public override void ReadPoperty() { if ((this.EntName == null) && (this.Converter.FCode == 2)) { this.EntName = this.Converter.FValue.ToUpper(); } if (this.EntName == "LAYER") this.Converter.FLayers = this; } } #endregion // ------------------------------------------------- DXFBlock --------------------------------------------- // #region DXF_Block public class DXFBlock : DXFEntityContainer { private string blkDescr; public DXFBlock() : base() { this.blkDescr = ""; } public override void ReadPoperty() { switch(this.Converter.FCode) { case 4: this.blkDescr = this.Converter.FValue; break; default: // DXFEntity: codes 0(type), 60+67(visibility) // DXFPositionable: codes 8(posLayer), 62+420(posColor), 10,20,30 (posPosStart), 210,220,230 (posPlaneNormal) // DXFEntityContainer: codes 2 (EntName) base.ReadPoperty(); break; } } public override void OnLoaded() { base.OnLoaded(); // prevents the block from being found! //if (this.blkDescr.Count() > 0) // this.EntName += ": " + this.blkDescr; } } #endregion // ------------------------------------------------ DXFInsert --------------------------------------------- // #region DXF_Insert public class DXFInsert : DXFEntityContainer { protected static int NR_INSERTS = 0; protected int insNr; protected DXFBlock insBlock; protected Point3D insScale; protected float insRotation; protected Point3D insSpacing; protected int insNrRows; protected int insNrColumns; public DXFInsert() : base() { this.insNr = (++DXFInsert.NR_INSERTS); this.insScale = new Point3D(1, 1, 1); this.insRotation = 0f; this.insSpacing = new Point3D(0, 0, 0); this.insNrRows = 1; this.insNrColumns = 1; } public override void ReadPoperty() { switch(this.Converter.FCode) { case 41: this.insScale.X = this.Converter.FloatValue(); break; case 42: this.insScale.Y = this.Converter.FloatValue(); break; case 43: this.insScale.Z = this.Converter.FloatValue(); break; case 44: this.insSpacing.X = this.Converter.FloatValue(); break; case 45: this.insSpacing.Y = this.Converter.FloatValue(); break; case 50: this.insRotation = this.Converter.FloatValue(); break; case 70: this.insNrColumns = this.Converter.IntValue(); break; case 71: this.insNrRows = this.Converter.IntValue(); break; default: // DXFEntity: codes 0(type), 60+67(visibility) // DXFPositionable: codes 8(posLayer), 62+420(posColor), 10,20,30 (posPosStart), 210,220,230 (posPlaneNormal) // DXFEntityContainer: codes 2(EntName) base.ReadPoperty(); break; } } public override void OnLoaded() { base.OnLoaded(); // look for the block definiton this.insBlock = this.Converter.RetrieveBlock(this.EntName); } public override string ToString() { string dxfS = base.ToString(); dxfS += " |scale: " + Extensions.Point3DToString(this.insScale) + " |rotation: " + String.Format(this.nfi, "{0:F2}", this.insRotation) + " |spacing: " + Extensions.Point3DToString(this.insSpacing, 2) + " |nr rows: " + this.insNrRows + " |nr cols: " + this.insNrColumns + "\n"; if (this.insBlock != null) dxfS += "block\n" + "[\n" + this.insBlock.ToString() + "\n]"; return dxfS; } public List<DXFGeometry> ConvertToDrawables(string _note = "") { List<DXFGeometry> geometry = new List<DXFGeometry>(); if (this.insBlock == null) return geometry; // calculate instance transforms List<Matrix3D> transfs = DXFGeometry.CalInstanceTransforms(this.posPosStart, this.posPlaneNormal, this.insScale, this.insRotation, this.insNrRows, (float)this.insSpacing.Y, this.insNrColumns, (float)this.insSpacing.X); // add Attributes foreach(var e in this.ecEntities) { DXFGeometry eG = e.ConvertToDrawable("Block '" + this.insBlock.EntName + "'" + this.insNr.ToString() + ":"); if(!eG.IsEmpty()) geometry.Add(eG); } // add block components int n = this.insBlock.ecEntities.Count; for (int i = 0; i < n; i++ ) { DXFEntity e = this.insBlock.ecEntities[i]; Type t = e.GetType(); if (t == typeof(DXFAttribute)) continue; DXFPositionable eAsP = e as DXFPositionable; if (eAsP == null) continue; DXFColor eC = eAsP.Color; if (eC == DXFColor.clByBlock) eC = this.Color; DXFGeometry eG = e.ConvertToDrawable("Block '" + this.insBlock.EntName + "'" + this.insNr.ToString() + ":"); eG.Color = eC; if (!eG.IsEmpty()) { // transform by each matrix and add foreach (Matrix3D tr in transfs) { DXFGeometry eGtmp = new DXFGeometry(eG); eGtmp.Transform(tr); geometry.Add(eGtmp); } } } return geometry; } } #endregion // ----------------------------------------------- DXFPolyline -------------------------------------------- // #region DXF_Polyline public class DXFPolyLine : DXFEntityContainer { protected bool plIsClosed; public DXFPolyLine() : base() { this.plIsClosed = false; } public override void ReadPoperty() { switch (this.Converter.FCode) { case 70: byte flag = this.Converter.ByteValue(); if ((flag & 1) == 1) this.plIsClosed = true; break; default: // DXFEntity: codes 0(type), 60+67(visibility) // DXFPositionable: codes 8(posLayer), 62+420(posColor), 10,20,30 (posPosStart), 210,220,230 (posPlaneNormal) // DXFEntityContainer: codes 2 (EntName) base.ReadPoperty(); break; } } public override DXFGeometry ConvertToDrawable(string _note = "") { DXFGeometry drawable = new DXFGeometry(); drawable.LayerName = this.posLayer.EntName; drawable.Color = this.Color; drawable.Name = _note + " 3D Polyline"; int n = this.ecEntities.Count; List<Point3D> lines = new List<Point3D>(n); for (int i = 0; i < n; i++) { DXFPositionable p = this.ecEntities[i] as DXFPositionable; if (p != null) lines.Add(p.posPosStart); } drawable.AddLines(lines, true, 1f, this.posPosStart, this.posPlaneNormal); return drawable; } } #endregion }
36.028664
134
0.452246
[ "Unlicense" ]
bph-tuwien/SIMULTAN_Stand_29_09_2017
EngineTest/Apps/DXFImportExport/DXFEntities.cs
55,306
C#
using hw.UnitTest; using Reni.FeatureTest.Helper; namespace Reni.FeatureTest.Structure { [UnitTest] [SimpleAssignment] [TargetSet(@"(!mutable x: 10 , x := 4) dump_print", "(4, )")] public sealed class NamedSimpleAssignment : CompilerTest {} }
23.909091
65
0.684411
[ "MIT" ]
hahoyer/reni.cs
src/Reni/FeatureTest/Structure/NamedSimpleAssignment.cs
263
C#
/************************************************************************************* Toolkit for WPF Copyright (C) 2007-2018 Ssz.Xceed Software Inc. This program is provided to you under the terms of the Microsoft Public License (Ms-PL) as published at http://wpftoolkit.codeplex.com/license For more features, controls, and fast professional support, pick up the Plus Edition at https://xceed.com/xceed-toolkit-plus-for-wpf/ Stay informed: follow @datagrid on Twitter or Like http://facebook.com/datagrids ***********************************************************************************/ namespace Ssz.Xceed.Wpf.AvalonDock.Layout { internal interface ILayoutPreviousContainer { ILayoutContainer PreviousContainer { get; set; } string PreviousContainerId { get; set; } } }
34.56
87
0.559028
[ "MIT" ]
ru-petrovi4/Ssz.Utils
Ssz.Xceed.Wpf.Toolkit/Ssz.Xceed.Wpf.AvalonDock/Layout/ILayoutPreviousContainer.cs
864
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. // // Copyright (c) Jeff Hardy 2010-2012. // using System.Collections; using System.Collections.Generic; using System.Runtime.InteropServices; using System.Text.RegularExpressions; using Community.CsharpSqlite; using IronPython.Runtime; using IronPython.Runtime.Exceptions; using IronPython.Runtime.Operations; using Microsoft.Scripting.Runtime; using Microsoft.Scripting.Utils; using sqlite3_stmt = Community.CsharpSqlite.Sqlite3.Vdbe; namespace IronPython.SQLite { public static partial class PythonSQLite { [PythonType] public class Cursor : IEnumerable { public const string __doc__ = "SQLite database cursor class."; Statement statement; object next_row; bool resultsDone; int last_step_rc; List<object> row_cast_map = new List<object>(); public PythonTuple description { get; private set; } public int rowcount { get; private set; } public int? rownumber { get { return null; } } public long? lastrowid { get; private set; } public object row_factory { get; set; } public int arraysize { get; set; } public Connection connection { get; private set; } public object callproc(string procname) { throw PythonSQLite.MakeNotSupportedError(); } private CodeContext context; public Cursor(CodeContext context, Connection connection) { this.context = context; this.connection = connection; this.arraysize = 1; this.rowcount = -1; if(this.connection != null) this.connection.checkThread(); } ~Cursor() { if(this.statement != null) this.statement.Reset(); } [Documentation("Closes the cursor.")] public void close() { connection.checkThread(); connection.checkConnection(); if(this.statement != null) { this.statement.Reset(); } } [Documentation("Executes a SQL statement.")] public object execute(CodeContext context, object operation, [Optional][DefaultParameterValue(null)]object args) { return queryExecute(context, false, operation, args); } [Documentation("Repeatedly executes a SQL statement.")] public object executemany(CodeContext context, object operation, object args) { return queryExecute(context, true, operation, args); } private object queryExecute(CodeContext context, bool multiple, object operation_obj, object args) { if(!(operation_obj is string)) throw CreateThrowable(PythonExceptions.ValueError, "operation parameter must be str or unicode"); string operation = (string)operation_obj; if(string.IsNullOrEmpty(operation)) return null; int rc; connection.checkThread(); connection.checkConnection(); this.next_row = null; IEnumerator parameters_iter = null; if(multiple) { if(args != null) parameters_iter = PythonOps.CreatePythonEnumerator(args); } else { object[] parameters_list = { args }; if(parameters_list[0] == null) parameters_list[0] = new PythonTuple(); parameters_iter = parameters_list.GetEnumerator(); } if(this.statement != null) rc = this.statement.Reset(); this.description = null; this.rowcount = -1; // TODO: use stmt cache instead ? this.statement = (Statement)this.connection.__call__(operation); if(this.statement.in_use) this.statement = new Statement(connection, operation); this.statement.Reset(); this.statement.MarkDirty(); if(!string.IsNullOrEmpty(connection.begin_statement)) { switch(statement.StatementType) { case StatementType.Update: case StatementType.Insert: case StatementType.Delete: case StatementType.Replace: if(!connection.inTransaction) connection.begin(); break; case StatementType.Other: // it's a DDL statement or something similar // we better COMMIT first so it works for all cases if(connection.inTransaction) connection.commit(); break; case StatementType.Select: if(multiple) throw MakeProgrammingError("You cannot execute SELECT statements in executemany()."); break; default: break; } } while(true) { if(!parameters_iter.MoveNext()) break; object parameters = parameters_iter.Current; this.statement.MarkDirty(); this.statement.BindParameters(context, parameters); while(true) { rc = this.statement.RawStep(); if(rc == Sqlite3.SQLITE_DONE || rc == Sqlite3.SQLITE_ROW) break; rc = this.statement.Reset(); if(rc == Sqlite3.SQLITE_SCHEMA) { rc = this.statement.Recompile(context, parameters); if(rc == Sqlite3.SQLITE_OK) { continue; } else { this.statement.Reset(); throw GetSqliteError(this.connection.db, null); } } else { this.statement.Reset(); throw GetSqliteError(this.connection.db, null); } } if(!buildRowCastMap()) throw MakeOperationalError("Error while building row_cast_map"); if(rc == Sqlite3.SQLITE_ROW || (rc == Sqlite3.SQLITE_DONE && this.statement.StatementType == StatementType.Select)) { if(this.description == null) { int numcols = Sqlite3.sqlite3_column_count(this.statement.st); object[] new_description = new object[numcols]; for(int i = 0; i < numcols; ++i) { string name = buildColumnName(Sqlite3.sqlite3_column_name(this.statement.st, i)); object descriptor = new object[] { name, (object)null, (int?)null, (int?)null, (int?)null, (int?)null, (bool?)null }; new_description[i] = new PythonTuple(descriptor); } this.description = new PythonTuple(new_description); } } if(rc == Sqlite3.SQLITE_ROW) { if(multiple) throw MakeProgrammingError("executemany() can only execute DML statements."); this.next_row = fetchOneRow(context); } else if(rc == Sqlite3.SQLITE_DONE && !multiple) { this.statement.Reset(); } switch(this.statement.StatementType) { case StatementType.Update: case StatementType.Delete: case StatementType.Insert: case StatementType.Replace: if(this.rowcount == -1) this.rowcount = 0; this.rowcount += Sqlite3.sqlite3_changes(this.connection.db); break; } if(!multiple && this.statement.StatementType == StatementType.Insert) { this.lastrowid = Sqlite3.sqlite3_last_insert_rowid(this.connection.db); } else { this.lastrowid = null; } if(multiple) rc = this.statement.Reset(); } return this; } private string buildColumnName(string colname) { int n = colname.IndexOf('['); return n < 0 ? colname : colname.Substring(0, n).Trim(); } private object fetchOneRow(CodeContext context) { int numcols = Sqlite3.sqlite3_data_count(this.statement.st); object[] row = new object[numcols]; object converter = null; for(int i = 0; i < numcols; ++i) { object converted = null; if(this.connection.detect_types != 0) { converter = row_cast_map[i]; } else { converter = null; } if(converter != null) { byte[] val = Sqlite3.sqlite3_column_blob(this.statement.st, i); if(val == null) { converted = null; } else { string item = Latin1.GetString(val, 0, val.Length); converted = PythonCalls.Call(context, converter, item); } } else { int coltype = Sqlite3.sqlite3_column_type(this.statement.st, i); switch(coltype) { case Sqlite3.SQLITE_NULL: converted = null; break; case Sqlite3.SQLITE_INTEGER: long l = Sqlite3.sqlite3_column_int64(this.statement.st, i); if(l < int.MinValue || l > int.MaxValue) converted = l; else converted = (int)l; break; case Sqlite3.SQLITE_FLOAT: converted = Sqlite3.sqlite3_column_double(this.statement.st, i); break; case Sqlite3.SQLITE_TEXT: converted = Sqlite3.sqlite3_column_text(this.statement.st, i); break; case Sqlite3.SQLITE_BLOB: default: byte[] blob = Sqlite3.sqlite3_column_blob(this.statement.st, i) ?? new byte[0]; PythonBuffer buffer = new PythonBuffer(context, blob); converted = buffer; break; } } row[i] = converted; } return new PythonTuple(row); } public Cursor executescript(string operation) { connection.checkThread(); connection.checkConnection(); this.connection.commit(); sqlite3_stmt statement = null; string script = operation; bool statement_completed = false; while(true) { if(Sqlite3.sqlite3_complete(operation) == 0) break; statement_completed = true; int rc = Sqlite3.sqlite3_prepare(this.connection.db, operation, -1, ref statement, ref script); if(rc != Sqlite3.SQLITE_OK) throw GetSqliteError(this.connection.db, null); /* execute statement, and ignore results of SELECT statements */ rc = Sqlite3.SQLITE_ROW; while(rc == Sqlite3.SQLITE_ROW) rc = Sqlite3.sqlite3_step(statement); if(rc != Sqlite3.SQLITE_DONE) { Sqlite3.sqlite3_finalize(statement); throw GetSqliteError(this.connection.db, null); } rc = Sqlite3.sqlite3_finalize(statement); if(rc != Sqlite3.SQLITE_OK) throw GetSqliteError(this.connection.db, null); } if(!statement_completed) throw MakeProgrammingError("you did not provide a complete SQL statement"); return this; } public object __iter__() { return this; } public object next(CodeContext context) { object next_row_tuple, next_row; connection.checkThread(); connection.checkConnection(); if(this.next_row == null) { if(this.statement != null) { this.statement.Reset(); this.statement = null; } throw new StopIterationException(); } next_row_tuple = this.next_row; this.next_row = null; if(this.row_factory != null) { next_row = PythonCalls.Call(context, this.row_factory, this, next_row_tuple); } else { next_row = next_row_tuple; } if(this.statement != null) { int rc = this.statement.RawStep(); if(rc != Sqlite3.SQLITE_DONE && rc != Sqlite3.SQLITE_ROW) { this.statement.Reset(); throw GetSqliteError(this.connection.db, this.statement.st); } if(rc == Sqlite3.SQLITE_ROW) this.next_row = fetchOneRow(context); } return next_row; } [Documentation("Fetches one row from the resultset.")] public object fetchone(CodeContext context) { try { return this.next(context); } catch(StopIterationException) { return null; } } public object fetchmany(CodeContext context) { return fetchmany(context, this.arraysize); } [Documentation("Fetches several rows from the resultset.")] public object fetchmany(CodeContext context, int size) { List result = new List(); object item = fetchone(context); for(int i = 0; i < size && item != null; ++i, item = fetchone(context)) result.Add(item); return result; } [Documentation("Fetches all rows from the resultset.")] public object fetchall(CodeContext context) { List result = new List(); object item = fetchone(context); while(item != null) { result.Add(item); item = fetchone(context); } return result; } public object nextset() { return null; } [Documentation("Required by DB-API. Does nothing in IronPython.Sqlite3.")] public void setinputsizes(object sizes) { } [Documentation("Required by DB-API. Does nothing in IronPython.Sqlite3.")] public void setoutputsize(params object[] args) { } private bool buildRowCastMap() { if(this.connection.detect_types == 0) return true; row_cast_map = new List<object>(); object converter = null; for(int i = 0; i < Sqlite3.sqlite3_column_count(this.statement.st); ++i) { converter = null; if((this.connection.detect_types & PARSE_COLNAMES) != 0) { string colname = Sqlite3.sqlite3_column_name(this.statement.st, i); if(colname != null) { Regex matchColname = new Regex(@"\[(\w+)\]"); Match match = matchColname.Match(colname); if(match.Success) { string key = match.Groups[1].ToString(); converter = getConverter(key); } } } if((converter == null) && ((this.connection.detect_types & PARSE_DECLTYPES) != 0)) { string decltype = Sqlite3.sqlite3_column_decltype(this.statement.st, i); if(decltype != null) { Regex matchDecltype = new Regex(@"\b(\w+)\b"); Match match = matchDecltype.Match(decltype); if(match.Success) { string py_decltype = match.Groups[1].ToString(); converter = getConverter(py_decltype); } } } row_cast_map.Add(converter); } return true; } private object getConverter(string key) { object converter; return converters.TryGetValue(key.ToUpperInvariant(), out converter) ? converter : null; } #region IEnumerable Members public IEnumerator GetEnumerator() { List results = new List(); try { while(true) results.append(this.next(this.context)); } catch(StopIterationException) { } return results.GetEnumerator(); } #endregion } } }
35.541455
135
0.422899
[ "Apache-2.0" ]
AlexSeredenko/ironpython2
Src/IronPython.SQLite/Cursor.cs
21,007
C#
/* * Copyright (c) 2014-Present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ using System.ComponentModel; using System.Dynamic; using Sitecore.Extensions.StringExtensions; namespace Sitecore.Js.Presentation { using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text.RegularExpressions; using JavaScriptEngineSwitcher.Core; using Newtonsoft.Json; using Sitecore.Diagnostics; using Sitecore.Js.Presentation.Context; using Sitecore.Js.Presentation.Enum; using Sitecore.Js.Presentation.Managers; using Sitecore.Mvc.Pipelines; using Sitecore.Mvc.Pipelines.Response.RenderPlaceholder; using Sitecore.Mvc.Presentation; /// <summary> /// Represents a React JavaScript component. /// </summary> public class Component : IComponent { private const string JsFunctionToGetPlaceholdersInfo = @"(function(obj){{ if (typeof (obj) === 'undefined' || typeof (obj.getPlaceholders) === 'undefined' || typeof (obj.getPlaceholders) !== 'function' ) {{ return ''; }} return obj.getPlaceholders(); }})({0})"; private readonly Regex _dynamicPlaceholderRegex = new Regex("(\\.|_|-|#)dynamic$", RegexOptions.IgnoreCase); /// <summary> /// Regular expression used to validate JavaScript identifiers. Used to ensure component /// names are valid. /// Based off https://gist.github.com/Daniel15/3074365 /// </summary> private static readonly Regex IdentifierRegex = new Regex(@"^[a-zA-Z_$][0-9a-zA-Z_$]*(?:\[(?:"".+""|\'.+\'|\d+)\])*?$", RegexOptions.Compiled); private JsonSerializerSettings _jsonSerializerSettings; private readonly IJsEngineManager _manager; private readonly IPageContext _pageContext; private readonly Rendering _rendering; public Component( IJsEngineManager manager, IPageContext pageContext, string componentName, object model, Rendering rendering, JsonSerializerSettings serializerSetting = null, string site = null, string containerId = null, string containerTag = null, string containerClass = null) { this.ComponentName = EnsureComponentNameValid(componentName); this._manager = manager; this._pageContext = pageContext; this.Model = model; this._rendering = rendering; this.ContainerId = string.IsNullOrEmpty(containerId) ? GenerateId() : containerId; this.ContainerTag = string.IsNullOrEmpty(containerTag) ? "div" : containerTag; this.ContainerClass = containerClass; this._jsonSerializerSettings = serializerSetting ?? new JsonSerializerSettings(); } /// <summary> /// Gets or sets the name of the component /// </summary> public string ComponentName { get; } /// <summary> /// Gets or sets the HTML class for the container of this component /// </summary> public string ContainerClass { get; set; } /// <summary> /// Gets or sets the unique ID for the DIV container of this component /// </summary> public string ContainerId { get; } /// <summary> /// Gets or sets the HTML tag the component is wrapped in /// </summary> public string ContainerTag { get; set; } public object Model { get; set; } /// <summary> /// Gets or sets the props for this component /// </summary> public virtual string Render(RenderingOptions options) { var placeholders = this.GetPlaceholders() .ToDictionary(name => _dynamicPlaceholderRegex.Replace(name, string.Empty), placeholder => this.Placeholder(placeholder, this._rendering)); // Create ReactJS component props object dynamic props = ToDynamic(this.Model); props.placeholders = placeholders; var serializedProps = JsonConvert.SerializeObject(props, this._jsonSerializerSettings); var client = string.Empty; if (options != RenderingOptions.ServerOnly) { client = this.RenderJavaScript(serializedProps); } var server = this.RenderHtml(serializedProps, options); // Do not register in page context or return HTML rendered on server. this._pageContext.Add(client); return server; } /// <summary> /// Validates that the specified component name is valid /// </summary> /// <param name="componentName"></param> internal static string EnsureComponentNameValid(string componentName) { var isValid = componentName.Split('.').All(segment => IdentifierRegex.IsMatch(segment)); if (!isValid) { throw new Exception($"Invalid component name '{componentName}'"); } return componentName; } /// <summary> /// Ensures that this component exists in global scope /// </summary> protected virtual void EnsureComponentExists() { bool componentExists; // This is safe as componentName was validated via EnsureComponentNameValid() using (var engine = this._manager.GetEngine()) { componentExists = engine.Execute<bool>($"typeof {this.ComponentName} !== 'undefined'"); } if (!componentExists) { throw new Exception($"Could not find a component named '{this.ComponentName}'."); } } protected virtual IEnumerable<string> GetPlaceholders() { using (var engine = this._manager.GetEngine()) { var jsOutpout = engine.Execute<string>(string.Format(JsFunctionToGetPlaceholdersInfo, this.ComponentName)) ?? string.Empty; return JsonConvert.DeserializeObject<string[]>(jsOutpout) ?? new string[0]; } } protected virtual string Placeholder(string placeholderName, Rendering rendering) { Assert.ArgumentNotNull(placeholderName, "placeholderName"); Assert.ArgumentNotNull(rendering, "rendering"); var stringWriter = new StringWriter(); // Append placeholder name with "-dynamic", "_dynamic", ".dynamic" or "#dynamic" in JS component to treat this placeholder as Dynamic if (_dynamicPlaceholderRegex.IsMatch(placeholderName)) { // "-dynamic" part will be removed var placeholder = _dynamicPlaceholderRegex.Replace(placeholderName, string.Empty); // this will render placeholders with appended IDs, which is usually used for dynamic placeholders. // you do not need to specify dynamic placeholders in JS (as FE developer might not what is that) PipelineService.Get() .RunPipeline( "mvc.renderPlaceholder", new RenderPlaceholderArgs($"{placeholder}_{rendering.UniqueId.ToString("D").ToUpper()}", stringWriter, rendering)); // TODO: figure out how to get correct index to append placeholder PipelineService.Get() .RunPipeline( "mvc.renderPlaceholder", new RenderPlaceholderArgs($"{placeholder}-{rendering.UniqueId.ToString("B").ToUpper()}-0", stringWriter, rendering)); } else { // standard placeholder PipelineService.Get() .RunPipeline( "mvc.renderPlaceholder", new RenderPlaceholderArgs(placeholderName, stringWriter, rendering)); } return stringWriter.ToString(); } /// <summary> /// Renders the HTML for this component. This will execute the component server-side and /// return the rendered HTML. /// </summary> /// <returns>HTML</returns> protected virtual string RenderHtml(string serializedProps, RenderingOptions options) { var renderServerOnly = options == RenderingOptions.ServerOnly; var renderNotClientOnly = options != RenderingOptions.ClientOnly; if (renderNotClientOnly) { this.EnsureComponentExists(); } try { var html = string.Empty; if (renderNotClientOnly) { var reactRenderCommand = renderServerOnly ? $"{this.ComponentName}.renderToStaticMarkup({serializedProps})" : $"{this.ComponentName}.renderToString({serializedProps})"; using (var engine = this._manager.GetEngine()) { html = engine.Execute<string>(reactRenderCommand); } } if (renderServerOnly) { return html; } string attributes = $"id=\"{this.ContainerId}\""; if (!string.IsNullOrEmpty(this.ContainerClass)) { attributes += $" class=\"{this.ContainerClass}\""; } return string.Format("<{0} {1}>{2}</{0}>", this.ContainerTag, attributes, html); } catch (JsRuntimeException ex) { throw new Exception( $"Error while rendering '{ComponentName}' to '{ContainerId}': {ex.Message}"); } } /// <summary> /// Renders the JavaScript required to initialise this component client-side. This will /// initialise the React component, which includes attach event handlers to the /// server-rendered HTML. /// </summary> /// <returns>JavaScript</returns> protected virtual string RenderJavaScript(string serializedProps) { return $"{this.ComponentName}.renderToDOM({serializedProps}, '{this.ContainerId}')"; } /// <summary> /// Generates a unique identifier for this component, if one was not passed in. /// </summary> /// <returns></returns> private static string GenerateId() { var str = Convert.ToBase64String(Guid.NewGuid().ToByteArray()) .Replace("/", string.Empty) .Replace("+", string.Empty) .TrimEnd('='); return "react_" + str; } private ExpandoObject ToDynamic(object value) { IDictionary<string, object> expando = new ExpandoObject(); foreach (PropertyDescriptor property in TypeDescriptor.GetProperties(value.GetType())) expando.Add(property.Name, property.GetValue(value)); return expando as ExpandoObject; } } }
37.308917
155
0.571148
[ "MIT" ]
asmagin/Sitecore.Presentation.JavaScript
src/Sitecore.Js.Presentation/Component.cs
11,717
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System; using System.Collections.Generic; using System.IO; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Web; using Azure.Core; using Azure.Core.TestFramework; using Azure.Identity.Tests.Mock; using Microsoft.AspNetCore.Http; using NUnit.Framework; namespace Azure.Identity.Tests { public class ManagedIdentityCredentialTests : ClientTestBase { private string _expectedResourceId = $"/subscriptions/{Guid.NewGuid().ToString()}/locations/MyLocation"; public ManagedIdentityCredentialTests(bool isAsync) : base(isAsync) { } private const string ExpectedToken = "mock-msi-access-token"; [NonParallelizable] [Test] public async Task VerifyImdsRequestWithClientIdMockAsync() { using var environment = new TestEnvVar(new() { { "MSI_ENDPOINT", null }, { "MSI_SECRET", null }, { "IDENTITY_ENDPOINT", null }, { "IDENTITY_HEADER", null }, { "AZURE_POD_IDENTITY_AUTHORITY_HOST", null } }); var response = CreateMockResponse(200, ExpectedToken); var mockTransport = new MockTransport(response); var options = new TokenCredentialOptions() { Transport = mockTransport }; var pipeline = CredentialPipeline.GetInstance(options); ManagedIdentityCredential credential = InstrumentClient(new ManagedIdentityCredential("mock-client-id", pipeline)); AccessToken actualToken = await credential.GetTokenAsync(new TokenRequestContext(MockScopes.Default)); Assert.AreEqual(ExpectedToken, actualToken.Token); MockRequest request = mockTransport.Requests[0]; string query = request.Uri.Query; Assert.AreEqual(request.Uri.Host, "169.254.169.254"); Assert.AreEqual(request.Uri.Path, "/metadata/identity/oauth2/token"); Assert.IsTrue(query.Contains("api-version=2018-02-01")); Assert.IsTrue(query.Contains($"resource={Uri.EscapeDataString(ScopeUtilities.ScopesToResource(MockScopes.Default))}")); Assert.IsTrue(request.Headers.TryGetValue("Metadata", out string metadataValue)); Assert.IsTrue(query.Contains($"{Constants.ManagedIdentityClientId}=mock-client-id")); Assert.AreEqual("true", metadataValue); } [NonParallelizable] [Test] public async Task VerifyImdsRequestWithResourceIdMockAsync() { using var environment = new TestEnvVar(new() { { "MSI_ENDPOINT", null }, { "MSI_SECRET", null }, { "IDENTITY_ENDPOINT", null }, { "IDENTITY_HEADER", null }, { "AZURE_POD_IDENTITY_AUTHORITY_HOST", null } }); var response = CreateMockResponse(200, ExpectedToken); var mockTransport = new MockTransport(response); var options = new TokenCredentialOptions { Transport = mockTransport }; var pipeline = CredentialPipeline.GetInstance(options); ManagedIdentityCredential credential = InstrumentClient(new ManagedIdentityCredential(new ResourceIdentifier(_expectedResourceId), pipeline)); AccessToken actualToken = await credential.GetTokenAsync(new TokenRequestContext(MockScopes.Default)); Assert.AreEqual(ExpectedToken, actualToken.Token); MockRequest request = mockTransport.Requests[0]; string query = request.Uri.Query; Assert.AreEqual(request.Uri.Host, "169.254.169.254"); Assert.AreEqual(request.Uri.Path, "/metadata/identity/oauth2/token"); Assert.IsTrue(query.Contains("api-version=2018-02-01")); Assert.IsTrue(query.Contains($"resource={Uri.EscapeDataString(ScopeUtilities.ScopesToResource(MockScopes.Default))}")); Assert.IsTrue(request.Headers.TryGetValue("Metadata", out string metadataValue)); Assert.That(Uri.UnescapeDataString(query), Does.Contain($"{Constants.ManagedIdentityResourceId}={_expectedResourceId}")); Assert.AreEqual("true", metadataValue); } [NonParallelizable] [Test] public async Task VerifyServiceFabricRequestWithResourceIdMockAsync() { using var environment = new TestEnvVar( new() { { "MSI_ENDPOINT", null }, { "MSI_SECRET", null }, { "IDENTITY_ENDPOINT", "https://169.254.169.254/metadata/identity/oauth2/token?api-version=2018-02-01" }, { "IDENTITY_HEADER", "header" }, { "AZURE_POD_IDENTITY_AUTHORITY_HOST", null }, { "IDENTITY_SERVER_THUMBPRINT", "thumbprint" } }); var response = CreateMockResponse(200, ExpectedToken); var mockTransport = new MockTransport(response); var options = new TokenCredentialOptions { Transport = mockTransport }; var pipeline = CredentialPipeline.GetInstance(options); ManagedIdentityCredential credential = InstrumentClient(new ManagedIdentityCredential(new ResourceIdentifier(_expectedResourceId), pipeline, true)); AccessToken actualToken = await credential.GetTokenAsync(new TokenRequestContext(MockScopes.Default)); Assert.AreEqual(ExpectedToken, actualToken.Token); MockRequest request = mockTransport.Requests[0]; string query = request.Uri.Query; Assert.AreEqual(request.Uri.Host, "169.254.169.254"); Assert.AreEqual(request.Uri.Path, "/metadata/identity/oauth2/token"); Assert.IsTrue(query.Contains("api-version=2018-02-01")); Assert.That(query, Does.Contain($"{Constants.ManagedIdentityResourceId}={Uri.EscapeDataString(_expectedResourceId)}")); } [NonParallelizable] [Test] public void VerifyImdsRequestFailurePopulatesExceptionMessage() { using var environment = new TestEnvVar(new() { { "MSI_ENDPOINT", null }, { "MSI_SECRET", null }, { "IDENTITY_ENDPOINT", null }, { "IDENTITY_HEADER", null }, { "AZURE_POD_IDENTITY_AUTHORITY_HOST", null } }); var expectedMessage = "No MSI found for specified ClientId/ResourceId."; var response = CreateErrorMockResponse(400, expectedMessage); var mockTransport = new MockTransport(response); var options = new TokenCredentialOptions() { Transport = mockTransport }; var pipeline = CredentialPipeline.GetInstance(options); ManagedIdentityCredential credential = InstrumentClient(new ManagedIdentityCredential("mock-client-id", pipeline)); var ex = Assert.ThrowsAsync<CredentialUnavailableException>(async () => await credential.GetTokenAsync(new TokenRequestContext(MockScopes.Default))); Assert.That(ex.Message, Does.Contain(expectedMessage)); } [NonParallelizable] [Test] [TestCase(400, ImdsManagedIdentitySource.IdentityUnavailableError)] [TestCase(502, ImdsManagedIdentitySource.GatewayError)] public void VerifyImdsRequestHandlesFailedRequestWithCredentialUnavailableExceptionMockAsync(int responseCode, string expectedMessage) { using var environment = new TestEnvVar(new() { { "MSI_ENDPOINT", null }, { "MSI_SECRET", null }, { "IDENTITY_ENDPOINT", null }, { "IDENTITY_HEADER", null }, { "AZURE_POD_IDENTITY_AUTHORITY_HOST", null } }); var response = CreateMockResponse(responseCode, ExpectedToken); var mockTransport = new MockTransport(response); var options = new TokenCredentialOptions() { Transport = mockTransport }; var pipeline = CredentialPipeline.GetInstance(options); ManagedIdentityCredential credential = InstrumentClient(new ManagedIdentityCredential("mock-client-id", pipeline)); var ex = Assert.ThrowsAsync<CredentialUnavailableException>(async () => await credential.GetTokenAsync(new TokenRequestContext(MockScopes.Default))); Assert.That(ex.Message, Does.Contain(expectedMessage)); } [NonParallelizable] [Test] [TestCase(null)] [TestCase("mock-client-id")] public async Task VerifyIMDSRequestWithPodIdentityEnvVarMockAsync(string clientId) { using var environment = new TestEnvVar(new() { { "MSI_ENDPOINT", null }, { "MSI_SECRET", null }, { "IDENTITY_ENDPOINT", null }, { "IDENTITY_HEADER", null }, { "AZURE_POD_IDENTITY_AUTHORITY_HOST", "https://mock.podid.endpoint/" } }); var response = CreateMockResponse(200, ExpectedToken); var mockTransport = new MockTransport(response); var options = new TokenCredentialOptions() { Transport = mockTransport }; var pipeline = CredentialPipeline.GetInstance(options); ManagedIdentityCredential credential = InstrumentClient(new ManagedIdentityCredential(clientId, pipeline)); AccessToken actualToken = await credential.GetTokenAsync(new TokenRequestContext(MockScopes.Default)); Assert.AreEqual(ExpectedToken, actualToken.Token); MockRequest request = mockTransport.SingleRequest; Assert.IsTrue(request.Uri.ToString().StartsWith("https://mock.podid.endpoint" + ImdsManagedIdentitySource.imddsTokenPath)); string query = request.Uri.Query; Assert.That(query, Does.Contain("api-version=2018-02-01")); Assert.That(query, Does.Contain($"resource={Uri.EscapeDataString(ScopeUtilities.ScopesToResource(MockScopes.Default))}")); if (clientId != null) { Assert.That(query, Does.Contain($"{Constants.ManagedIdentityClientId}=mock-client-id")); } Assert.IsTrue(request.Headers.TryGetValue("Metadata", out string actMetadataValue)); Assert.AreEqual("true", actMetadataValue); } [NonParallelizable] [Test] public async Task VerifyIMDSRequestWithPodIdentityEnvVarResourceIdMockAsync() { using var environment = new TestEnvVar(new() { { "MSI_ENDPOINT", null }, { "MSI_SECRET", null }, { "IDENTITY_ENDPOINT", null }, { "IDENTITY_HEADER", null }, { "AZURE_POD_IDENTITY_AUTHORITY_HOST", "https://mock.podid.endpoint/" } }); var response = CreateMockResponse(200, ExpectedToken); var mockTransport = new MockTransport(response); var options = new TokenCredentialOptions() { Transport = mockTransport }; var pipeline = CredentialPipeline.GetInstance(options); ManagedIdentityCredential credential = InstrumentClient(new ManagedIdentityCredential(new ResourceIdentifier(_expectedResourceId), pipeline)); AccessToken actualToken = await credential.GetTokenAsync(new TokenRequestContext(MockScopes.Default)); Assert.AreEqual(ExpectedToken, actualToken.Token); MockRequest request = mockTransport.SingleRequest; Assert.IsTrue(request.Uri.ToString().StartsWith("https://mock.podid.endpoint" + ImdsManagedIdentitySource.imddsTokenPath)); string query = request.Uri.Query; Assert.That(query, Does.Contain("api-version=2018-02-01")); Assert.That(query, Does.Contain($"resource={Uri.EscapeDataString(ScopeUtilities.ScopesToResource(MockScopes.Default))}")); Assert.That(Uri.UnescapeDataString(query), Does.Contain($"{Constants.ManagedIdentityResourceId}={_expectedResourceId}")); Assert.IsTrue(request.Headers.TryGetValue("Metadata", out string actMetadataValue)); Assert.AreEqual("true", actMetadataValue); } [NonParallelizable] [Test] [TestCase(null)] [TestCase("mock-client-id")] public async Task VerifyAppService2017RequestWithClientIdMockAsync(string clientId) { using var environment = new TestEnvVar(new() { { "MSI_ENDPOINT", "https://mock.msi.endpoint/" }, { "MSI_SECRET", "mock-msi-secret" }, { "IDENTITY_ENDPOINT", null }, { "IDENTITY_HEADER", null }, { "AZURE_POD_IDENTITY_AUTHORITY_HOST", null } }); var response = CreateMockResponse(200, ExpectedToken); var mockTransport = new MockTransport(response); var options = new TokenCredentialOptions() { Transport = mockTransport }; ManagedIdentityCredential credential = InstrumentClient(new ManagedIdentityCredential(clientId, options)); AccessToken actualToken = await credential.GetTokenAsync(new TokenRequestContext(MockScopes.Default)); Assert.AreEqual(ExpectedToken, actualToken.Token); MockRequest request = mockTransport.SingleRequest; Assert.IsTrue(request.Uri.ToString().StartsWith("https://mock.msi.endpoint/")); string query = request.Uri.Query; Assert.IsTrue(query.Contains("api-version=2017-09-01")); Assert.IsTrue(query.Contains($"resource={Uri.EscapeDataString(ScopeUtilities.ScopesToResource(MockScopes.Default))}")); if (clientId != null) { Assert.IsTrue(query.Contains($"clientid=mock-client-id")); } Assert.IsTrue(request.Headers.TryGetValue("secret", out string actSecretValue)); Assert.AreEqual("mock-msi-secret", actSecretValue); } [NonParallelizable] [Ignore("This test is disabled as we have disabled AppService MI version 2019-08-01 due to issue https://github.com/Azure/azure-sdk-for-net/issues/16278. The test should be re-enabled if and when support for this api version is added back")] [Test] public async Task VerifyAppService2019RequestMockAsync() { using var environment = new TestEnvVar(new() { { "MSI_ENDPOINT", null }, { "MSI_SECRET", null }, { "IDENTITY_ENDPOINT", "https://identity.endpoint/" }, { "IDENTITY_HEADER", "mock-identity-header" }, { "AZURE_POD_IDENTITY_AUTHORITY_HOST", null } }); var response = CreateMockResponse(200, ExpectedToken); var mockTransport = new MockTransport(response); var options = new TokenCredentialOptions { Transport = mockTransport }; ManagedIdentityCredential credential = InstrumentClient(new ManagedIdentityCredential(options: options)); AccessToken token = await credential.GetTokenAsync(new TokenRequestContext(MockScopes.Default)); Assert.AreEqual(ExpectedToken, token.Token); MockRequest request = mockTransport.Requests[0]; Assert.IsTrue(request.Uri.ToString().StartsWith(EnvironmentVariables.IdentityEndpoint)); string query = request.Uri.Query; Assert.IsTrue(query.Contains("api-version=2019-08-01")); Assert.IsTrue(query.Contains($"resource={Uri.EscapeDataString(ScopeUtilities.ScopesToResource(MockScopes.Default))}")); Assert.IsTrue(request.Headers.TryGetValue("X-IDENTITY-HEADER", out string identityHeader)); Assert.AreEqual(EnvironmentVariables.IdentityHeader, identityHeader); } [NonParallelizable] [Test] // This test has been added to ensure as we have disabled AppService MI version 2019-08-01 due to issue https://github.com/Azure/azure-sdk-for-net/issues/16278. // The test should be removed if and when support for this api version is added back public async Task VerifyAppService2017RequestWith2019EnvVarsMockAsync() { using var environment = new TestEnvVar(new() { { "MSI_ENDPOINT", "https://mock.msi.endpoint/" }, { "MSI_SECRET", "mock-msi-secret" }, { "IDENTITY_ENDPOINT", "https://identity.endpoint/" }, { "IDENTITY_HEADER", "mock-identity-header" }, { "AZURE_POD_IDENTITY_AUTHORITY_HOST", null } }); var response = CreateMockResponse(200, ExpectedToken); var mockTransport = new MockTransport(response); var options = new TokenCredentialOptions() { Transport = mockTransport }; ManagedIdentityCredential credential = InstrumentClient(new ManagedIdentityCredential(options: options)); AccessToken actualToken = await credential.GetTokenAsync(new TokenRequestContext(MockScopes.Default)); Assert.AreEqual(ExpectedToken, actualToken.Token); MockRequest request = mockTransport.Requests[0]; Assert.IsTrue(request.Uri.ToString().StartsWith("https://mock.msi.endpoint/")); string query = request.Uri.Query; Assert.IsTrue(query.Contains("api-version=2017-09-01")); Assert.IsTrue(query.Contains($"resource={Uri.EscapeDataString(ScopeUtilities.ScopesToResource(MockScopes.Default))}")); Assert.IsTrue(request.Headers.TryGetValue("secret", out string actSecretValue)); Assert.AreEqual("mock-msi-secret", actSecretValue); } [NonParallelizable] [Ignore("This test is disabled as we have disabled AppService MI version 2019-08-01 due to issue https://github.com/Azure/azure-sdk-for-net/issues/16278. The test should be re-enabled if and when support for this api version is added back")] [Test] public async Task VerifyAppService2019RequestWithClientIdMockAsync() { using var environment = new TestEnvVar(new() { { "MSI_ENDPOINT", null }, { "MSI_SECRET", null }, { "IDENTITY_ENDPOINT", "https://identity.endpoint/" }, { "IDENTITY_HEADER", "mock-identity-header" }, { "AZURE_POD_IDENTITY_AUTHORITY_HOST", null } }); var response = CreateMockResponse(200, ExpectedToken); var mockTransport = new MockTransport(response); var options = new TokenCredentialOptions { Transport = mockTransport }; ManagedIdentityCredential credential = InstrumentClient(new ManagedIdentityCredential("mock-client-id", options)); AccessToken actualToken = await credential.GetTokenAsync(new TokenRequestContext(MockScopes.Default)); Assert.AreEqual(ExpectedToken, actualToken.Token); MockRequest request = mockTransport.SingleRequest; Assert.IsTrue(request.Uri.ToString().StartsWith(EnvironmentVariables.IdentityEndpoint)); string query = request.Uri.Query; Assert.IsTrue(query.Contains("api-version=2019-08-01")); Assert.IsTrue(query.Contains($"{Constants.ManagedIdentityClientId}=mock-client-id")); Assert.IsTrue(query.Contains($"resource={Uri.EscapeDataString(ScopeUtilities.ScopesToResource(MockScopes.Default))}")); Assert.IsTrue(request.Headers.TryGetValue("X-IDENTITY-HEADER", out string identityHeader)); Assert.AreEqual(EnvironmentVariables.IdentityHeader, identityHeader); } [NonParallelizable] [Test] public async Task VerifyCloudShellMsiRequestMockAsync() { using var environment = new TestEnvVar(new() { { "MSI_ENDPOINT", "https://mock.msi.endpoint/" }, { "MSI_SECRET", null }, { "IDENTITY_ENDPOINT", null }, { "IDENTITY_HEADER", null }, { "AZURE_POD_IDENTITY_AUTHORITY_HOST", null } }); var response = CreateMockResponse(200, ExpectedToken); var mockTransport = new MockTransport(response); var options = new TokenCredentialOptions() { Transport = mockTransport }; ManagedIdentityCredential credential = InstrumentClient(new ManagedIdentityCredential(options: options)); AccessToken actualToken = await credential.GetTokenAsync(new TokenRequestContext(MockScopes.Default)); Assert.AreEqual(ExpectedToken, actualToken.Token); MockRequest request = mockTransport.Requests[0]; Assert.IsTrue(request.Uri.ToString().StartsWith("https://mock.msi.endpoint/")); Assert.IsTrue(request.Content.TryComputeLength(out long contentLen)); var content = new byte[contentLen]; MemoryStream contentBuff = new MemoryStream(content); request.Content.WriteTo(contentBuff, default); string body = Encoding.UTF8.GetString(content); Assert.IsTrue(body.Contains($"resource={Uri.EscapeDataString(ScopeUtilities.ScopesToResource(MockScopes.Default))}")); Assert.IsTrue(request.Headers.TryGetValue("Metadata", out string actMetadata)); Assert.AreEqual("true", actMetadata); } [NonParallelizable] [Test] [TestCase(null)] [TestCase("mock-client-id")] public async Task VerifyCloudShellMsiRequestWithClientIdMockAsync(string clientId) { using var environment = new TestEnvVar(new() { { "MSI_ENDPOINT", "https://mock.msi.endpoint/" }, { "MSI_SECRET", null }, { "IDENTITY_ENDPOINT", null }, { "IDENTITY_HEADER", null }, { "AZURE_POD_IDENTITY_AUTHORITY_HOST", null } }); var response = CreateMockResponse(200, ExpectedToken); var mockTransport = new MockTransport(response); var options = new TokenCredentialOptions() { Transport = mockTransport }; ManagedIdentityCredential client = InstrumentClient(new ManagedIdentityCredential(clientId, options)); AccessToken actualToken = await client.GetTokenAsync(new TokenRequestContext(MockScopes.Default)); Assert.AreEqual(ExpectedToken, actualToken.Token); MockRequest request = mockTransport.Requests[0]; Assert.IsTrue(request.Uri.ToString().StartsWith("https://mock.msi.endpoint/")); Assert.IsTrue(request.Content.TryComputeLength(out long contentLen)); var content = new byte[contentLen]; MemoryStream contentBuff = new MemoryStream(content); request.Content.WriteTo(contentBuff, default); string body = Encoding.UTF8.GetString(content); Assert.IsTrue(body.Contains($"resource={Uri.EscapeDataString(ScopeUtilities.ScopesToResource(MockScopes.Default))}")); if (clientId != null) { Assert.IsTrue(body.Contains($"{Constants.ManagedIdentityClientId}=mock-client-id")); } Assert.IsTrue(request.Headers.TryGetValue("Metadata", out string actMetadata)); Assert.AreEqual("true", actMetadata); } [NonParallelizable] [Test] public async Task VerifyMsiUnavailableOnIMDSAggregateExcpetion() { using var environment = new TestEnvVar(new() { { "MSI_ENDPOINT", null }, { "MSI_SECRET", null }, { "IDENTITY_ENDPOINT", null }, { "IDENTITY_HEADER", null }, { "AZURE_POD_IDENTITY_AUTHORITY_HOST", "http://169.254.169.001/" } }); // setting the delay to 1ms and retry mode to fixed to speed up test var options = new TokenCredentialOptions() { Retry = { Delay = TimeSpan.FromMilliseconds(1), Mode = RetryMode.Fixed, NetworkTimeout = TimeSpan.FromMilliseconds(100) } }; var credential = InstrumentClient(new ManagedIdentityCredential(options: options)); var ex = Assert.ThrowsAsync<CredentialUnavailableException>(async () => await credential.GetTokenAsync(new TokenRequestContext(MockScopes.Default))); Assert.That(ex.Message, Does.Contain(ImdsManagedIdentitySource.AggregateError)); await Task.CompletedTask; } [NonParallelizable] [Test] public async Task VerifyMsiUnavailableOnIMDSRequestFailedExcpetion() { using var environment = new TestEnvVar(new() { { "MSI_ENDPOINT", null }, { "MSI_SECRET", null }, { "IDENTITY_ENDPOINT", null }, { "IDENTITY_HEADER", null }, { "AZURE_POD_IDENTITY_AUTHORITY_HOST", "http://169.254.169.001/" } }); var options = new TokenCredentialOptions() { Retry = { MaxRetries = 0, NetworkTimeout = TimeSpan.FromMilliseconds(100) } }; var credential = InstrumentClient(new ManagedIdentityCredential(options: options)); var ex = Assert.ThrowsAsync<CredentialUnavailableException>(async () => await credential.GetTokenAsync(new TokenRequestContext(MockScopes.Default))); Assert.That(ex.Message, Does.Contain(ImdsManagedIdentitySource.NoResponseError)); await Task.CompletedTask; } [NonParallelizable] [Test] public async Task VerifyMsiUnavailableOnIMDSGatewayErrorResponse([Values(502, 504)]int statusCode) { using var server = new TestServer(context => { context.Response.StatusCode = statusCode; }); using var environment = new TestEnvVar(new() { { "MSI_ENDPOINT", null }, { "MSI_SECRET", null }, { "IDENTITY_ENDPOINT", null }, { "IDENTITY_HEADER", null }, { "AZURE_POD_IDENTITY_AUTHORITY_HOST", server.Address.AbsoluteUri } }); // setting the delay to 1ms and retry mode to fixed to speed up test var options = new TokenCredentialOptions() { Retry = { Delay = TimeSpan.FromMilliseconds(0), Mode = RetryMode.Fixed } }; var credential = InstrumentClient(new ManagedIdentityCredential(options: options)); var ex = Assert.ThrowsAsync<CredentialUnavailableException>(async () => await credential.GetTokenAsync(new TokenRequestContext(MockScopes.Default))); Assert.That(ex.Message, Does.Contain(ImdsManagedIdentitySource.GatewayError)); await Task.CompletedTask; } [NonParallelizable] [Test] public async Task VerifyInitialImdsConnectionTimeoutHonored() { using var server = new TestServer(async context => { await Task.Delay(1000); context.Response.StatusCode = 418; }); using var environment = new TestEnvVar(new() { { "MSI_ENDPOINT", null }, { "MSI_SECRET", null }, { "IDENTITY_ENDPOINT", null }, { "IDENTITY_HEADER", null }, { "AZURE_POD_IDENTITY_AUTHORITY_HOST", server.Address.AbsoluteUri } }); // setting the delay to 1ms and retry mode to fixed to speed up test var options = new TokenCredentialOptions() { Retry = { Delay = TimeSpan.FromMilliseconds(0), Mode = RetryMode.Fixed } }; var pipeline = CredentialPipeline.GetInstance(options); var miClientOptions = new ManagedIdentityClientOptions { InitialImdsConnectionTimeout = TimeSpan.FromMilliseconds(100), Pipeline = pipeline }; var credential = InstrumentClient(new ManagedIdentityCredential(new ManagedIdentityClient(miClientOptions))); var startTime = DateTimeOffset.UtcNow; var ex = Assert.ThrowsAsync<CredentialUnavailableException>(async () => await credential.GetTokenAsync(new TokenRequestContext(MockScopes.Default))); Assert.That(ex.Message, Does.Contain(ImdsManagedIdentitySource.AggregateError)); Assert.Less(DateTimeOffset.UtcNow - startTime, TimeSpan.FromSeconds(2)); await Task.CompletedTask; } [NonParallelizable] [Test] public async Task VerifyInitialImdsConnectionTimeoutRelaxed() { string token = Guid.NewGuid().ToString(); int callCount = 0; using var server = new TestServer(async context => { if (Interlocked.Increment(ref callCount) > 1) { await Task.Delay(2000); } await context.Response.WriteAsync($"{{ \"access_token\": \"{token}\", \"expires_on\": \"3600\" }}"); }); using var environment = new TestEnvVar(new() { { "MSI_ENDPOINT", null }, { "MSI_SECRET", null }, { "IDENTITY_ENDPOINT", null }, { "IDENTITY_HEADER", null }, { "AZURE_POD_IDENTITY_AUTHORITY_HOST", server.Address.AbsoluteUri } }); // setting the delay to 1ms and retry mode to fixed to speed up test var options = new TokenCredentialOptions() { Retry = { Delay = TimeSpan.FromMilliseconds(0), Mode = RetryMode.Fixed } }; var pipeline = CredentialPipeline.GetInstance(options); var miClientOptions = new ManagedIdentityClientOptions { InitialImdsConnectionTimeout = TimeSpan.FromMilliseconds(1000), Pipeline = pipeline }; var credential = InstrumentClient(new ManagedIdentityCredential(new ManagedIdentityClient(miClientOptions))); var at = await credential.GetTokenAsync(new TokenRequestContext(MockScopes.Default)); Assert.AreEqual(token, at.Token); var at2 = await credential.GetTokenAsync(new TokenRequestContext(MockScopes.Default)); Assert.AreEqual(token, at.Token); Assert.AreEqual(2, callCount); } [Test] public async Task VerifyClientAuthenticateThrows() { using var environment = new TestEnvVar(new() { { "MSI_ENDPOINT", null }, { "MSI_SECRET", null }, { "IDENTITY_ENDPOINT", null }, { "IDENTITY_HEADER", null }, { "AZURE_POD_IDENTITY_AUTHORITY_HOST", null } }); var mockClient = new MockManagedIdentityClient(CredentialPipeline.GetInstance(null)) { TokenFactory = () => throw new MockClientException("message") }; var credential = InstrumentClient(new ManagedIdentityCredential(mockClient)); var ex = Assert.ThrowsAsync<AuthenticationFailedException>(async () => await credential.GetTokenAsync(new TokenRequestContext(MockScopes.Default))); Assert.IsInstanceOf(typeof(MockClientException), ex.InnerException); await Task.CompletedTask; } [Test] public async Task VerifyClientAuthenticateReturnsInvalidJson([Values(200, 404)] int status) { using var environment = new TestEnvVar( new() { { "MSI_ENDPOINT", null }, { "MSI_SECRET", null }, { "IDENTITY_ENDPOINT", null }, { "IDENTITY_HEADER", null }, { "AZURE_POD_IDENTITY_AUTHORITY_HOST", null } }); var mockTransport = new MockTransport(request => CreateInvalidJsonResponse(status)); var options = new TokenCredentialOptions() { Transport = mockTransport }; options.Retry.MaxDelay = TimeSpan.Zero; var pipeline = CredentialPipeline.GetInstance(options); ManagedIdentityCredential credential = InstrumentClient(new ManagedIdentityCredential("mock-client-id", pipeline)); var ex = Assert.ThrowsAsync<AuthenticationFailedException>(async () => await credential.GetTokenAsync(new TokenRequestContext(MockScopes.Default))); Assert.IsInstanceOf(typeof(RequestFailedException), ex.InnerException); Assert.That(ex.Message, Does.Contain(ManagedIdentitySource.UnexpectedResponse)); await Task.CompletedTask; } [Test] public async Task VerifyClientAuthenticateReturnsErrorResponse() { using var environment = new TestEnvVar( new() { { "MSI_ENDPOINT", null }, { "MSI_SECRET", null }, { "IDENTITY_ENDPOINT", null }, { "IDENTITY_HEADER", null }, { "AZURE_POD_IDENTITY_AUTHORITY_HOST", null } }); var errorMessage = "Some error happened"; var mockTransport = new MockTransport(request => CreateErrorMockResponse(404, errorMessage)); var options = new TokenCredentialOptions { Transport = mockTransport}; options.Retry.MaxDelay = TimeSpan.Zero; var pipeline = CredentialPipeline.GetInstance(options); ManagedIdentityCredential credential = InstrumentClient(new ManagedIdentityCredential("mock-client-id", pipeline)); var ex = Assert.ThrowsAsync<AuthenticationFailedException>(async () => await credential.GetTokenAsync(new TokenRequestContext(MockScopes.Default))); Assert.IsInstanceOf(typeof(RequestFailedException), ex.InnerException); Assert.That(ex.Message, Does.Contain(errorMessage)); await Task.CompletedTask; } [Test] [TestCaseSource("ExceptionalEnvironmentConfigs")] public async Task VerifyAuthenticationFailedExceptionsAreDeferredToGetToken(Dictionary<string, string> environmentVariables) { using var environment = new TestEnvVar(environmentVariables); var credential = InstrumentClient(new ManagedIdentityCredential()); var ex = Assert.ThrowsAsync<AuthenticationFailedException>(async () => await credential.GetTokenAsync(new TokenRequestContext(MockScopes.Default))); await Task.CompletedTask; } private static IEnumerable<TestCaseData> ExceptionalEnvironmentConfigs() { // AppServiceV2017ManagedIdentitySource should throw yield return new TestCaseData(new Dictionary<string, string>() { { "MSI_ENDPOINT", "http::@/bogusuri" }, { "MSI_SECRET", "mocksecret" }, { "IDENTITY_ENDPOINT", null }, { "IDENTITY_HEADER", null }, { "AZURE_POD_IDENTITY_AUTHORITY_HOST", null } }); // CloudShellManagedIdentitySource should throw yield return new TestCaseData(new Dictionary<string, string>() { { "MSI_ENDPOINT", "http::@/bogusuri" }, { "MSI_SECRET", null }, { "IDENTITY_ENDPOINT", null }, { "IDENTITY_HEADER", null }, { "AZURE_POD_IDENTITY_AUTHORITY_HOST", null } }); // AzureArcManagedIdentitySource should throw yield return new TestCaseData(new Dictionary<string, string>() { { "MSI_ENDPOINT", null }, { "MSI_SECRET", null }, { "IDENTITY_ENDPOINT", "http::@/bogusuri" }, { "IMDS_ENDPOINT", "mockvalue" }, { "IDENTITY_HEADER", null }, { "AZURE_POD_IDENTITY_AUTHORITY_HOST", null } }); // ServiceFabricManagedIdentitySource should throw yield return new TestCaseData(new Dictionary<string, string>() { { "MSI_ENDPOINT", null }, { "MSI_SECRET", null }, { "IDENTITY_ENDPOINT", "http::@/bogusuri" }, { "IDENTITY_HEADER", "mockvalue" }, { "IDENTITY_SERVER_THUMBPRINT", "mockvalue"}, { "AZURE_POD_IDENTITY_AUTHORITY_HOST", null } }); // ImdsManagedIdentitySource should throw yield return new TestCaseData(new Dictionary<string, string>() { { "MSI_ENDPOINT", null }, { "MSI_SECRET", null }, { "IDENTITY_ENDPOINT", null }, { "IDENTITY_HEADER", null }, { "IDENTITY_SERVER_THUMBPRINT", "null" }, { "AZURE_POD_IDENTITY_AUTHORITY_HOST", "http::@/bogusuri" } }); } private MockResponse CreateMockResponse(int responseCode, string token) { var response = new MockResponse(responseCode); response.SetContent($"{{ \"access_token\": \"{token}\", \"expires_on\": \"3600\" }}"); return response; } private MockResponse CreateErrorMockResponse(int responseCode, string message) { var response = new MockResponse(responseCode); response.SetContent($"{{\"StatusCode\":400,\"Message\":\"{message}\",\"CorrelationId\":\"f3c9aec0-7fa2-4184-ad0f-0c68ce5fc748\"}}"); return response; } private static MockResponse CreateInvalidJsonResponse(int status) { var response = new MockResponse(status); response.SetContent("invalid json"); return response; } } }
53.309774
303
0.666441
[ "MIT" ]
AikoBB/azure-sdk-for-net
sdk/identity/Azure.Identity/tests/ManagedIdentityCredentialTests.cs
35,453
C#
using System; using System.Collections.Immutable; using System.Configuration; using Akka.Actor; using Akka.Cluster.Routing; using Akka.Configuration; using Akka.Configuration.Hocon; using Akka.Routing; using Akka.Util.Internal; namespace Samples.Cluster.ConsistentHashRouting { class Program { private static Config _clusterConfig; static void Main(string[] args) { var section = (AkkaConfigurationSection)ConfigurationManager.GetSection("akka"); _clusterConfig = section.AkkaConfig; LaunchBackend(new[] { "2551" }); LaunchBackend(new[] { "2552" }); LaunchBackend(new string[0]); LaunchFrontend(new string[0]); LaunchFrontend(new string[0]); Console.WriteLine("Press any key to exit."); Console.ReadKey(); } static void LaunchBackend(string[] args) { var port = args.Length > 0 ? args[0] : "0"; var config = ConfigurationFactory.ParseString("akka.remote.helios.tcp.port=" + port) .WithFallback(ConfigurationFactory.ParseString("akka.cluster.roles = [backend]")) .WithFallback(_clusterConfig); var system = ActorSystem.Create("ClusterSystem", config); system.ActorOf(Props.Create<BackendActor>(), "backend"); } static void LaunchFrontend(string[] args) { var port = args.Length > 0 ? args[0] : "0"; var config = ConfigurationFactory.ParseString("akka.remote.helios.tcp.port=" + port) .WithFallback(ConfigurationFactory.ParseString("akka.cluster.roles = [frontend]")) .WithFallback(_clusterConfig); var system = ActorSystem.Create("ClusterSystem", config); var backendRouter = system.ActorOf( Props.Empty.WithRouter(new ClusterRouterGroup(new ConsistentHashingGroup("/user/backend"), new ClusterRouterGroupSettings(10, false, "backend", ImmutableHashSet.Create("/user/backend"))))); var frontend = system.ActorOf(Props.Create(() => new FrontendActor(backendRouter)), "frontend"); var interval = TimeSpan.FromSeconds(12); var counter = new AtomicCounter(); system.Scheduler.Advanced.ScheduleRepeatedly(interval, interval,() => frontend.Tell(new StartCommand("hello-" + counter.GetAndIncrement()))); } } }
40.983871
153
0.609603
[ "Apache-2.0" ]
HCanber/akka.net
src/examples/Cluster/Routing/Samples.Cluster.ConsistentHashRouting/Program.cs
2,543
C#
using System; using System.Collections.Generic; using System.IO; using System.Xml; using System.Xml.Serialization; namespace ClassLibrary { public class Game { /// <summary> /// Licznik ruchów, inkrementowany przy sprawdzaniu odpowiedzi /// </summary> public int MoveCounter { get; set; } /// <summary> /// Status gry, wartości pobierane z enuma (W trakcie, zakończona - przegrana, zakończona - wygrana) /// </summary> public GameStatus GameStatus { get; set; } /// <summary> /// Tablica kolorów (enum) przechowująca docelowy wzór odgadywany przez gracza /// </summary> public Color[] TargetPattern { get; set; } /// <summary> /// Lista odpowiedzi (obiektów typu answer) /// </summary> public List<Answer> AnswerList; /// <summary> /// Długość zgadywanego kodu, parametr wejściowy podawany przez gracza /// </summary> public int CodeLength; /// <summary> /// Typ Gry: przyjmuje wartość 1 (domyślnie) gdy gra oparta na kolorach, 2 gdy gra oparta na liczbach /// </summary> public int GameType { get; set; } /// <summary> /// Określa limit ruchów dostępnych w danej grze: 9 dla gry opartej na kolorach, 15 dla gry opartej na cyfrach, ustawiane na podstawie wartości GameType /// </summary> public int MoveLimit { get; set; } /// <summary> /// Ilość możliwych kolorów, parametr wejściowy podawany przez gracza /// </summary> public int ColorsNumber; /// <summary> /// Obiekt przedstawiający odpowiedź udzielaną przez gracza, przechowywany w liście odpowiedzi /// </summary> public class Answer { /// <summary> /// Numer ruchu, w którym odzielono tej odpowiedzi /// </summary> public int MoveNumber { get; set; } /// <summary> /// Ilość prawidłowych kolorów odgadniętych w ramach tej odpowiedzi /// </summary> public int GoodAnswers { get; set; } /// <summary> /// Ciąg kolorów podany przez gracza w ramach tej odpowiedzi /// </summary> public Color[] AnswerPattern { get; set; } /// <summary> /// Metoda zwracająca tablicę kolorów w formie tekstowej, konieczna do wyświetlenia odpowiedzi w interfejsie GUI (ListView) /// </summary> public string AnswerArrayString { get { var foo = ""; for (int i = 0; i < AnswerPattern.Length; i++) { if (i != AnswerPattern.Length - 1) { foo = foo + AnswerPattern[i] + ", "; } else { foo += AnswerPattern[i]; } } return foo; } } /// <summary> /// Metoda zwracająca tablicę liczb odpowiadających danym kolorom w formie tekstowej, konieczna do wyświetlenia odpowiedzi w interfejsie GUI (ListView) /// </summary> public string IntArrayString { get { var foo = ""; for (int i = 0; i < AnswerPattern.Length; i++) { if (i != AnswerPattern.Length - 1) { foo = foo + (int)AnswerPattern[i] + ", "; } else { foo += (int)AnswerPattern[i]; } } return foo; } } /// <summary> /// Konstruktor najbardziej typowy /// </summary> /// <param name="goodAnswers"> ilość prawidłowych odpowiedzi </param> /// <param name="moveNumber"> numer ruchu </param> /// <param name="answer"> tablica z kolorami - odpowiedź gracza </param> public Answer(int goodAnswers, int moveNumber, Color[] answer) { this.GoodAnswers = goodAnswers; this.MoveNumber = moveNumber; this.AnswerPattern = answer; } /// <summary> /// konstruktor bezargumentowy, domyślny /// Zalożenie: podstawowy wariant rozgrywki: odgadujemy ciąg długości 4 znaków, 6 kolorów do wyboru /// </summary> public Answer() { this.GoodAnswers = 0; this.MoveNumber = MoveNumber; this.AnswerPattern = new Color[4]; } /// <summary> /// Tekstowe przedstawienie całego obiektu Answer /// </summary> /// <returns> string z wszystkimi elementami obiektu </returns> public override string ToString() { string foo = $"{this.MoveNumber}. "; for (int i = 0; i < this.AnswerPattern.Length; i++) { if (i != this.AnswerPattern.Length - 1) { foo = foo + this.AnswerPattern[i] + ", "; } else { foo += this.AnswerPattern[i]; } } foo += $", Prawidłowych: {this.GoodAnswers}"; return foo; } } /// <summary> /// konstruktor bezargumentowy, domyślny /// Zakłada podstawowy wariant rozgrywki - odgadujemy ciąg długości 4 znaków, 6 kolorów do wyboru, wariant gry używający nazw kolorów /// </summary> public Game() { this.GameStatus = GameStatus.Pending; this.TargetPattern = new Color[4]; this.ColorsNumber = 6; this.MoveCounter = 0; this.TargetPattern = Generate(TargetPattern, ColorsNumber); this.AnswerList = new List<Answer>(); this.CodeLength = 4; this.GameType = 1; this.MoveLimit = 9; } /// <summary> /// Konstruktor 3-argumentowy, pozwalający graczowi wybrać dłogość odgadywanego ciągu i ilość kolorów /// </summary> /// <param name="colors"> ilość kolorów dostępna w rozgrywce </param> /// <param name="codeLength"> długość odgadywanego kodu </param> /// <param name="gameType"> typ gry, 1 gdy oparta na kolorach, 2 gdy oparta na liczbach </param> public Game(int colors, int codeLength, int gameType) { this.GameStatus = GameStatus.Pending; this.TargetPattern = new Color[codeLength]; this.ColorsNumber = colors; this.MoveCounter = 0; this.TargetPattern = Generate(TargetPattern, ColorsNumber); this.AnswerList = new List<Answer>(); this.CodeLength = codeLength; this.GameType = gameType; if(this.GameType == 1) { this.MoveLimit = 9; } else { this.MoveLimit = 15; } } /// <summary> /// Konstruktor 1-argumentowy: jeśli typ gry jest liczbowy, to jasne jest, że CodeLength=4 oraz ColorsNumber-10, więc nie trzeba tego parametryzować /// </summary> /// <param name="gameType"> typ gry, 1 gdy oparta na kolorach, 2 gdy oparta na liczbach </param> public Game(int gameType) { this.GameStatus = GameStatus.Pending; this.TargetPattern = new Color[4]; this.ColorsNumber = 10; this.MoveCounter = 0; this.TargetPattern = Generate(TargetPattern, ColorsNumber); this.AnswerList = new List<Answer>(); this.CodeLength = 4; this.GameType = gameType; if (this.GameType == 1) { this.MoveLimit = 9; } else { this.MoveLimit = 15; } } /// <summary> /// Konstruktor wykorzystywany przez metodę deserializującą /// </summary> /// <param name="game"> obiekt game utworzony z pliku XML </param> public Game(Game game) { this.GameStatus = game.GameStatus; this.TargetPattern = game.TargetPattern; this.MoveCounter = game.MoveCounter; this.AnswerList = game.AnswerList; this.ColorsNumber = game.ColorsNumber; this.CodeLength = game.CodeLength; this.GameType = game.GameType; this.MoveLimit = game.MoveLimit; } /// <summary> /// Metoda wypełniająca pustą tablicę kolorów, kolorami z zakresu podanego przy inicjalizacji nowej gry /// </summary> /// <param name="arr"> pysta tablica kolorów </param> /// <param name="maxValue"> maksymalny używany numer koloru </param> /// <returns> tablica wypełniona wartościami enuma Color </returns> public Color[] Generate(Color[] arr, int maxValue) { var values = Enum.GetValues(typeof(Color)); Random random = new Random(); for (int index = 0; index < arr.Length; index++) { arr[index] = (Color)values.GetValue(random.Next(maxValue)); } return arr; } /// <summary> /// Metoda sprawdająca odpowiedź. Zwiększa licznik ruchów, liczy prawidłowo odgadnięte kolory, umieszcza odpowiedź na liście odpowiedzi (wywołuje metodę PushAnswerToList) /// </summary> /// <param name="arr"> tablica kolorów- odpowiedź gracza </param> /// <returns> wiadomość zwrotna z oceną odpowiedzi </returns> public string Check(Color[] arr) { this.MoveCounter++; string message; int goodAnswerCounter = 0; for (int index = 0; index < arr.Length; index++) { if (arr[index] == this.TargetPattern[index]) { goodAnswerCounter++; } } if(goodAnswerCounter == this.CodeLength && this.MoveCounter <=this.MoveLimit) { this.GameStatus = GameStatus.FinishedWithWin; message = $"WYGRAŁEŚ! Wykorzystałeś: {this.MoveCounter} ruchów"; PushAnswerToList(goodAnswerCounter, MoveCounter, arr); } else if (this.MoveCounter >= this.MoveLimit) { this.GameStatus = GameStatus.FinishedWithLose; message = $"PRZEGRAŁEŚ, pozostało: {this.MoveLimit-this.MoveCounter} ruchów"; PushAnswerToList(goodAnswerCounter, MoveCounter, arr); } else { message = $"GRAMY DALEJ, zgadłeś {goodAnswerCounter} elementów, pozostało: {this.MoveLimit-this.MoveCounter} ruchów"; PushAnswerToList(goodAnswerCounter, MoveCounter, arr); } return message; } /// <summary> /// Metoda tworząca obiekt Answer na podstawie otrzymanych parametrów i umieszczająca go na liście odpowiedzi (obiektów Answer) /// </summary> /// <param name="goodAnswers"> ilość prawidłowo odgadniętych kolorów </param> /// <param name="moveNumber"> numer ruchu </param> /// <param name="answer"> tablica z kolorami - odpowiedź gracza </param> public void PushAnswerToList(int goodAnswers, int moveNumber, Color[] answer) { this.AnswerList.Add(new Answer(goodAnswers, moveNumber, answer)); this.SerializeObject<Game>(this, "savegame.xml"); } /// <summary> /// Metoda zapisująca stan gry - serializuje obiekt game do pliku /// </summary> /// <typeparam name="T"> typ serializowanego obiektu - w tym przypadku zawsze Game </typeparam> /// <param name="serializableObject"> obiekt zapisywany - konkretna instancja gry </param> /// <param name="fileName"> nazwa pliku docelowego </param> /// <returns> plik XML w którym zapisana jest instancja obiektu Game oraz wiadomość zwrotna </returns> public string SerializeObject<T>(T serializableObject, string fileName) { string message; if (serializableObject == null) { return "Nie można zapisać w tej chwili"; } try { XmlDocument xmlDocument = new XmlDocument(); XmlSerializer serializer = new XmlSerializer(serializableObject.GetType()); using (MemoryStream stream = new MemoryStream()) { serializer.Serialize(stream, serializableObject); stream.Position = 0; xmlDocument.Load(stream); xmlDocument.Save(fileName); } message = "Stan gry zapisano pomyślnie"; } catch (Exception ex) { message = ex.Message; } return message; } /// <summary> /// Metoda wczytująca stan gry - tworzy obiekt game z pliku /// </summary> /// <typeparam name="T"> typ deserializowanego obiektu - w tym przypadku zawsze Game </typeparam> /// <param name="fileName"> nazwa pliku z którego obiekt jest tworzony </param> /// <returns> obiekt typu Game </returns> public static T DeSerializeObject<T>(string fileName) { if (string.IsNullOrEmpty(fileName)) { return default; } T objectOut = default; try { XmlDocument xmlDocument = new XmlDocument(); xmlDocument.Load(fileName); string xmlString = xmlDocument.OuterXml; using (StringReader read = new StringReader(xmlString)) { Type outType = typeof(T); XmlSerializer serializer = new XmlSerializer(outType); using (XmlReader reader = new XmlTextReader(read)) { objectOut = (T)serializer.Deserialize(reader); } } } catch (Exception ex) { Console.WriteLine(ex.Message); } return objectOut; } /// <summary> /// Metoda odpowiadająca za konsolowy interfejs użytkownika /// </summary> public void CLI_Logic() { while (this.GameStatus != GameStatus.FinishedWithLose && this.GameStatus != GameStatus.FinishedWithWin) { Color[] answer = new Color[this.CodeLength]; if(this.GameType == 1) { Console.WriteLine("Legenda: "); foreach (Color foo in Enum.GetValues(typeof(Color))) { if ((int)foo < this.ColorsNumber) { Console.ForegroundColor = (ConsoleColor)Enum.Parse(typeof(ConsoleColor), foo.ToString()); Console.WriteLine($"{(int)foo} - {foo}"); } } Console.ForegroundColor = ConsoleColor.White; } Console.WriteLine("Wpisz cyfrę odpowiadającą danemu elementowi"); for (int i = 0; i < this.TargetPattern.Length; i++) { int foo; bool shouldStop = false; Console.WriteLine($"Zgadnij co znajduje się w polu nr: {i + 1}"); while (!shouldStop) { shouldStop = true; try { string foobar = Console.ReadLine(); if (!int.TryParse(foobar, out int valuee)) { throw new ArgumentException("Podano nieprawidłową wartość"); } else { foo = int.Parse(foobar); } if (foo < 0 || foo >= this.ColorsNumber) { throw new ArgumentException($"Błędna wartość, podaj wartość pola nr {i + 1} jeszcze raz"); } else { answer[i] = (Color)foo; } } catch (Exception ex) { shouldStop = false; Console.WriteLine(ex.Message); } } } Console.Write("Twoja odpowiedź: "); CLI_ShowColoredValues(answer, this.GameType); Console.WriteLine(); Console.WriteLine(Check(answer)); } Console.WriteLine($"Prawidłowa odpowiedź:"); CLI_ShowColoredValues(this.TargetPattern, this.GameType); Console.WriteLine(); } /// <summary> /// Metoda wyświetlająca w konsoli odpowiednio pokolorowane elementy tablicy kolorów /// </summary> /// <param name="arr"> tablica kolorów </param> /// <param name="gameType"> typ gry, 1 gdy oparta na kolorach, 2 gdy oparta na liczbach </param> public void CLI_ShowColoredValues(Color[] arr, int gameType) { if (gameType == 1) { for (int i = 0; i < arr.Length; i++) { Console.ForegroundColor = (ConsoleColor)Enum.Parse(typeof(ConsoleColor), arr[i].ToString()); if (i != arr.Length - 1) { Console.Write(arr[i] + ", "); } else { Console.Write(arr[i]); Console.ForegroundColor = ConsoleColor.White; } } } else { for (int i = 0; i < arr.Length; i++) { Console.ForegroundColor = (ConsoleColor)Enum.Parse(typeof(ConsoleColor), arr[i].ToString()); if (i != arr.Length - 1) { Console.Write((int)arr[i] + ", "); } else { Console.Write((int)arr[i]); Console.ForegroundColor = ConsoleColor.White; } } } } /// <summary> /// Metoda używana po wczytaniu gry, wyświetlająca historię udzielonych odpowiedzi wraz z kolorowaniem /// </summary> public void CLI_ShowAnswerHistory() { foreach (var item in this.AnswerList) { Console.Write($"Odpowiedź nr {item.MoveNumber}, "); CLI_ShowColoredValues(item.AnswerPattern, this.GameType); Console.WriteLine($", Prawidłowych odpowiedzi: {item.GoodAnswers}"); } } /// <summary> /// Metoda wypełniająca pola Comboboxa wartościami enuma Color lub liczbami, w zależności od typu gry /// </summary> /// <param name="colors"> Ilość kolorów która ma zostać wprowadzona do enuma (wybierana przy inicjalizacji nowej gry) </param> /// <returns> tablica zawierająca stosowną ilość wartości enuma Color </returns> public Array GUI_FillComboBox(int colors) { if (this.GameType == 1) { Color[] arr = (Color[])Enum.GetValues(typeof(Color)); Array.Resize(ref arr, arr.Length - 2); if (colors < 8) { Array.Resize(ref arr, arr.Length - 1); } if (colors < 7) { Array.Resize(ref arr, arr.Length - 1); } return arr; } else { int[] arr = new int[10]; for (int i = 0; i < 10; i++) { arr[i] = i; } return arr; } } /// <summary> /// Zwraca prawidłową odpowiedź, metoda bliźniacza do CLI_ShowColoredValues, ale bez kolorowania tekstu na konsoli /// </summary> /// <param name="arr"> tablica kolorów </param> /// <returns> tekstowa forma tablicy kolorów </returns> public string GUI_ShowCorrectAnswer(Color[] arr) { string foo = ""; if (this.GameType == 1) { for (int i = 0; i < arr.Length; i++) { if (i != arr.Length - 1) { foo += (arr[i] + ", "); } else { foo += arr[i]; } } } else { for (int i = 0; i < arr.Length; i++) { if (i != arr.Length - 1) { foo += ((int)arr[i] + ", "); } else { foo += (int)arr[i]; } } } return foo; } } }
40.753676
178
0.47889
[ "MIT" ]
P-Sakowski/MasterMind
ClassLibrary/Game.cs
22,370
C#
#region Copyright // Copyright Hitachi Consulting // // 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. #endregion using System; using System.Collections; using System.Net; using System.Net.Sockets; using System.Net.Security; using System.Security.Authentication; using System.Text; using System.Security.Cryptography.X509Certificates; using System.IO; using System.Collections.Generic; using System.Collections.Concurrent; using System.Net.Http; using System.Threading.Tasks; using System.Linq; namespace Xigadee { /// <summary> /// This message class is used for body type that have a set of headers and a single body that /// is defined by a specific delimiter. Examples of this are internet and mime based messages. /// </summary> public class HeaderBodyMessage: Message { #region Declarations /// <summary> /// This is the collection of header positions within the message. This is required because certain /// headers may appears multiple times. /// </summary> protected Dictionary<string, int[]> mHeaderCollection = null; protected object syncHeaderCol = new object(); protected bool mHeaderCollectionAlreadyBuilt; /// <summary> /// This is the main body fragment. /// </summary> protected IMessage mBody; #endregion // Declarations #region Constructor /// <summary> /// The default constructor /// </summary> public HeaderBodyMessage() : base() { mBody = null; mHeaderCollectionAlreadyBuilt = false; } #endregion #region FragmentHeaderType /// <summary> /// This method returns the generic fragment header type. /// </summary> protected virtual Type FragmentHeaderType { get { return typeof(HeaderFragment); } } #endregion // FragmentHeader #region FragmentHeaderInitialType /// <summary> /// This is the fragment type for the outgoing message. /// </summary> protected override Type FragmentHeaderInitialType { get { return typeof(HeaderFragment<MessageTerminatorCRLFFolding>); } } #endregion #region FragmentBodyType /// <summary> /// This is the fragment body type for the message. /// </summary> protected virtual Type FragmentBodyType { get { throw new NotImplementedException("FragmentBodyType is not implemented."); } } #endregion // FragmentInitialType #region Body /// <summary> /// This message is the last fragment in the message that contains the message body. /// If there is no body in the message this property will be blank. /// </summary> public virtual IMessage Body { get { if (!Initializing && mBody == null) { FragmentCollectionBuild(); } return mBody; } set { if (!Initializing) throw new MessageException("The message body can only be set when the message is initializing."); mBody = value; } } #endregion // Body #region HeaderFragments() /// <summary> /// This method extracts the header value for the particular key. /// </summary> /// <returns>The collection of strings.</returns> public virtual IEnumerable<HeaderFragment> HeaderFragments() { if (!mHeaderCollectionAlreadyBuilt) yield break; foreach (string key in mHeaderCollection.Keys) { if (mHeaderCollection.ContainsKey(key)) { int[] values = mHeaderCollection[key]; if (values.Length == 0) continue; foreach (int i in values) { HeaderFragment frag = mMessageParts[i] as HeaderFragment; if (frag != null) yield return frag; } } } } #endregion #region Headers(string keyValue) /// <summary> /// This method extracts the header value for the particular key. /// </summary> /// <param name="keyValue">The key to retrieve.</param> /// <returns>The collection of strings.</returns> public virtual IEnumerable<string> Headers(string keyValue) { if (keyValue == null) throw new ArgumentNullException("keyValue", "keyValue cannot be null."); if (!mHeaderCollectionAlreadyBuilt) yield break; string key = keyValue.Trim().ToLower(); if (mHeaderCollection.ContainsKey(key)) { int[] values = mHeaderCollection[key]; if (values.Length > 0) { foreach (int i in values) { HeaderFragment frag = mMessageParts[i] as HeaderFragment; if (frag != null) yield return frag.FieldData; } } } } #endregion #region HeaderExists(string key) /// <summary> /// This method returns true if the header is already in the message. /// </summary> /// <param name="key">The header key to check.</param> /// <returns>Returns true if the header exists.</returns> public virtual bool HeaderExists(string key) { if (!mHeaderCollectionAlreadyBuilt) throw new NotSupportedException("The header collection has not been built"); return mHeaderCollection.ContainsKey(key); } #endregion // HeaderExists(string key) #region HeaderAdd public virtual void HeaderAdd(string Header, string Body) { HeaderAdd(FragmentHeaderType, Header, Body); } public virtual void HeaderAdd(Type headerType, string Header, string HeaderData) { if (!Initializing) throw new MessageException("The HeaderAdd instruction can only be called when the message is initializing."); HeaderFragment newFrag = Activator.CreateInstance(headerType) as HeaderFragment; newFrag.BeginInit(); newFrag.Field = Header; newFrag.FieldData = HeaderData ?? ""; HeaderAdd(newFrag); } public virtual void HeaderAdd(IMessage fragment) { if (!Initializing) throw new MessageException("The HeaderAdd instruction can only be called when the message is initializing."); FragmentAddInternal(fragment); } #endregion #region HeaderCollectionBuild() /// <summary> /// This method builds the header collection based on the header field. /// The collection is built based on the lower case definition of the header. /// Multiple identical headers are supported, with the header position stored as an integer collection. /// </summary> protected virtual void HeaderCollectionBuild() { if (mHeaderCollectionAlreadyBuilt) return; lock (syncHeaderCol) { if (mHeaderCollectionAlreadyBuilt) return; if (mHeaderCollection == null) mHeaderCollection = new Dictionary<string, int[]>(); int id = -1; foreach (IMessage fragment in mMessageParts.Values) { id++; if (!(fragment is IMessageHeaderFragment)) continue; var header = fragment as IMessageHeaderFragment; if (header == null || header.Field == null) continue; if (!mHeaderCollection.ContainsKey(header.Field.ToLower())) { mHeaderCollection.Add(header.Field.ToLower(), new int[] { id }); } else { int[] fields = mHeaderCollection[header.Field.ToLower()]; if (Array.IndexOf(fields, id) > -1) continue; Array.Resize(ref fields, fields.Length + 1); fields[fields.Length - 1] = id; mHeaderCollection[header.Field.ToLower()] = fields; } } mHeaderCollectionAlreadyBuilt = true; } } #endregion // BuildHeaderCollection() #region HeaderSingle(string keyValue) /// <summary> /// This is the header host. /// </summary> public virtual string HeaderSingle(string keyValue) { if (keyValue == null) throw new ArgumentNullException("keyValue", "keyValue cannot be null."); if (!mHeaderCollectionAlreadyBuilt) return null; string key = keyValue.Trim().ToLower(); int[] values = mHeaderCollection[key]; if (values.Length > 1) throw new ArgumentOutOfRangeException("keyValue", "There are multiple headers for " + keyValue); HeaderFragment frag = mMessageParts[values[0]] as HeaderFragment; if (frag == null) return null; return frag.FieldData; } #endregion } }
34.142395
125
0.546066
[ "Apache-2.0" ]
xigadee/Microservice
Src/Xigadee.Platform/Communication/FabricBridge/TcpTlsChannel/Messaging/Header/HeaderBodyMessage.cs
10,554
C#
// Copyright © Neodymium, carmineos and contributors. See LICENSE.md in the repository root for more information. using RageLib.Data; using RageLib.Resources.GTA5.PC.Meta; namespace RageLib.GTA5.ResourceWrappers.PC.Meta.Types { public class MetaFlagsInt32 : IMetaValue { public EnumInfo info; public uint Value { get; set; } public MetaFlagsInt32() { } public MetaFlagsInt32(EnumInfo info, uint value) { this.info = info; this.Value = value; } public void Read(DataReader reader) { this.Value = reader.ReadUInt32(); } public void Write(DataWriter writer) { writer.Write(this.Value); } } }
23.030303
114
0.594737
[ "MIT" ]
carmineos/gta-toolkit
RageLib.GTA5/ResourceWrappers/PC/Meta/Types/MetaFlagsInt32.cs
763
C#
using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using Tippy.Core.Models; using Tippy.Ctrl; namespace Tippy.Pages.Miners { public class GenerateBlockModel : PageModelBase { public GenerateBlockModel(Tippy.Core.Data.TippyDbContext context) : base(context) { } [BindProperty] public Project? Project { get; set; } public void OnGet() { } public async Task<IActionResult> OnPostAsync(int? id) { if (id == null) { return NotFound(); } Project = await DbContext.Projects .Include(p => p.DeniedTransactions) .Where(p => p.Id == id) .FirstOrDefaultAsync(); if (Project != null) { try { ProcessManager.StartMiner(Project, ProcessManager.MinerMode.SingleBlock); } catch (System.InvalidOperationException e) { TempData["ErrorMessage"] = e.Message; } } var referer = Request.GetTypedHeaders().Referer.ToString().ToLower(); return Redirect(referer); } } }
27.134615
94
0.513111
[ "MIT" ]
DavidChild/tippy
src/Tippy/Pages/Miners/GenerateBlock.cshtml.cs
1,411
C#
// ----------------------------------------------------------------- // <copyright file="PlayerInventorySetSlotPacketWriter.cs" company="2Dudes"> // Copyright (c) | Jose L. Nunez de Caceres et al. // https://linkedin.com/in/nunezdecaceres // // All Rights Reserved. // // Licensed under the MIT License. See LICENSE in the project root for license information. // </copyright> // ----------------------------------------------------------------- namespace Fibula.Protocol.V772.PacketWriters { using Fibula.Communications; using Fibula.Communications.Contracts.Abstractions; using Fibula.Communications.Packets.Contracts.Abstractions; using Fibula.Communications.Packets.Outgoing; using Fibula.Protocol.V772.Extensions; using Microsoft.Extensions.Logging; /// <summary> /// Class that represents an inventory set slot packet writer for the game server. /// </summary> public class PlayerInventorySetSlotPacketWriter : BasePacketWriter { /// <summary> /// Initializes a new instance of the <see cref="PlayerInventorySetSlotPacketWriter"/> class. /// </summary> /// <param name="logger">A reference to the logger in use.</param> public PlayerInventorySetSlotPacketWriter(ILogger<PlayerInventorySetSlotPacketWriter> logger) : base(logger) { } /// <summary> /// Writes a packet to the given <see cref="INetworkMessage"/>. /// </summary> /// <param name="packet">The packet to write.</param> /// <param name="message">The message to write into.</param> public override void WriteToMessage(IOutboundPacket packet, ref INetworkMessage message) { if (!(packet is PlayerInventorySetSlotPacket setSlotPacket)) { this.Logger.LogWarning($"Invalid packet {packet.GetType().Name} routed to {this.GetType().Name}"); return; } message.AddByte(setSlotPacket.PacketType.ToByte()); message.AddByte((byte)setSlotPacket.Slot); message.AddItem(setSlotPacket.Item); } } }
38.196429
114
0.616643
[ "MIT" ]
Codinablack/fibula-server
src/Fibula.Protocol.V772/PacketWriters/PlayerInventorySetSlotPacketWriter.cs
2,141
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 puck.core.Globalisation { using System; /// <summary> /// A strongly-typed resource class, for looking up localized strings, etc. /// </summary> // This class was auto-generated by the StronglyTypedResourceBuilder // class via a tool like ResGen or Visual Studio. // To add or remove a member, edit your .ResX file then rerun ResGen // with the /str option, or rebuild your VS project. [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "16.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] public class PuckLabels { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal PuckLabels() { } /// <summary> /// Returns the cached ResourceManager instance used by this class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] public static global::System.Resources.ResourceManager ResourceManager { get { if (object.ReferenceEquals(resourceMan, null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("puck.core.Globalisation.PuckLabels", typeof(PuckLabels).Assembly); resourceMan = temp; } return resourceMan; } } /// <summary> /// Overrides the current thread's CurrentUICulture property for all /// resource lookups using this strongly typed resource class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] public static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } /// <summary> /// Looks up a localized string similar to Redirects. /// </summary> public static string SettingsRedirect { get { return ResourceManager.GetString("SettingsRedirect", resourceCulture); } } } }
42.205479
180
0.6037
[ "MIT" ]
AmilkarDev/puck-core
core/Globalisation/PuckLabels.Designer.cs
3,083
C#
namespace osf { public class DataGridColumnStyle : Component { public System.Windows.Forms.DataGridColumnStyle M_DataGridColumnStyle; public DataGridColumnStyle() { } public DataGridColumnStyle(osf.DataGridColumnStyle p1) { M_DataGridColumnStyle = p1.M_DataGridColumnStyle; base.M_Component = M_DataGridColumnStyle; } public DataGridColumnStyle(System.Windows.Forms.DataGridColumnStyle p1) { M_DataGridColumnStyle = p1; base.M_Component = M_DataGridColumnStyle; } public int Alignment { get { return (int)M_DataGridColumnStyle.Alignment; } set { M_DataGridColumnStyle.Alignment = (System.Windows.Forms.HorizontalAlignment)value; } } public string HeaderText { get { return M_DataGridColumnStyle.HeaderText; } set { M_DataGridColumnStyle.HeaderText = value; } } public string MappingName { get { return M_DataGridColumnStyle.MappingName; } set { M_DataGridColumnStyle.MappingName = value; } } public bool ReadOnly { get { return M_DataGridColumnStyle.ReadOnly; } set { M_DataGridColumnStyle.ReadOnly = value; } } public int Width { get { return M_DataGridColumnStyle.Width; } set { M_DataGridColumnStyle.Width = value; } } } }
28.055556
102
0.59934
[ "MPL-2.0" ]
Nivanchenko/OneScriptForms
OneScriptForms/OneScriptForms/DataGridColumnStyle.cs
1,517
C#
using System.Text; using Dealership.Engine; using Dealership.Common.Enums; namespace Dealership.CommandHandler { public class ShowUsersCommandHandler : BaseCommandHandler { private const string HandleableCommandName = "ShowUsers"; private const string YouAreNotAnAdmin = "You are not an admin!"; protected override bool CanHandle(ICommand command) { return command.Name == HandleableCommandName; } protected override string Handle(ICommand command, IEngine engine) { if (engine.LoggedUser.Role != Role.Admin) { return YouAreNotAnAdmin; } var builder = new StringBuilder(); builder.AppendLine("--USERS--"); var counter = 1; foreach (var user in engine.Users) { builder.AppendLine(string.Format("{0}. {1}", counter, user.ToString())); counter++; } return builder.ToString().Trim(); } } }
28.324324
88
0.578244
[ "MIT" ]
dushka-dragoeva/TelerikSeson2016
Programing C#/Design Patterns/Dealership-AuthorSolution/Dealership/CommandHandler/ShowUsersCommandHandler.cs
1,050
C#
using System; using System.Collections.Generic; using System.IO; using System.Text; using UnityEngine; namespace IlyaGutnikov.LogSaver { public class LogSaver : MonoBehaviour { [Header("Mark true to activate log on awake")] public bool EnableLoggingOnAwake; [Header("Mark true to activate log on DEVELOPMENT_BUILD")] public bool EnableLoggingOnDevBuild; private bool _isLoggingEnable; private LogsKeeper _logsKeeper; private void Awake() { DontDestroyOnLoad(this); var isActiveOnDevBuild = Debug.isDebugBuild && EnableLoggingOnDevBuild; if (isActiveOnDevBuild || EnableLoggingOnAwake) { SetLoggingEnabled(true); } } private void OnDestroy() { SetLoggingEnabled(false); WriteLogsToFile(); } public void SetLoggingEnabled(bool isEnabled) { if (isEnabled) { EnableLogging(); } else { DisableLogging(); } } private void EnableLogging() { if (_isLoggingEnable) { Debug.Log("Logging is already enabled!"); return; } Application.logMessageReceived += LogMessage; _logsKeeper = new LogsKeeper(); _isLoggingEnable = true; } private void DisableLogging() { if (_isLoggingEnable == false) { Debug.Log("Logging is already disabled!"); return; } Application.logMessageReceived -= LogMessage; _isLoggingEnable = false; } private void LogMessage(string condition, string stackTrace, LogType type) { var logInfo = new Log(condition, stackTrace, type, DateTime.Now.ToString("yyyy-MM-ddTHH:mm:sszzz")); _logsKeeper.Logs.Add(logInfo); } public void WriteLogsToFile() { if (_logsKeeper == null || _logsKeeper.Logs == null || _logsKeeper.Logs.Count == 0) { Debug.LogWarning("Can't find logs to write!"); return; } string jsonLogs = JsonUtility.ToJson(_logsKeeper, true); var path = Path.Combine(Application.persistentDataPath, "Logs"); path = Path.Combine(path, "Log_" + DateTime.Now.ToString("yyyy-MM-dd_HH-mm-ss") + ".txt"); var dirPath = Path.GetDirectoryName(path); if (string.IsNullOrEmpty(dirPath)) { Debug.LogError("Can't get directory path for file: " + path); return; } if (!Directory.Exists(dirPath)) { Directory.CreateDirectory(dirPath); } File.WriteAllText(path, jsonLogs, Encoding.UTF8); } } }
27.247788
112
0.519324
[ "MIT" ]
IlyaGutnikov/UnityLogSaver
LogSaver.cs
3,081
C#
// Copyright (C) 2018-2021 Fievus // // This software may be modified and distributed under the terms // of the MIT license. See the LICENSE file for details. using System; using System.Windows.Forms; using Charites.Windows.Mvc; using Charites.Windows.Samples.SimpleLoginDemo.Presentation.Login; namespace Charites.Windows.Samples.SimpleLoginDemo.Presentation.Home { [View(Key = nameof(HomeContent))] public class HomeController { private readonly IContentNavigator navigator; public HomeController(IContentNavigator navigator) { this.navigator = navigator ?? throw new ArgumentNullException(nameof(navigator)); } [EventHandler(ElementName = "logoutButton", Event = nameof(Control.Click))] private void OnLogoutButtonClick() { navigator.NavigateTo(new LoginContent()); } } }
30.482759
93
0.701357
[ "MIT" ]
averrunci/WindowsFormsMvc
Samples/SimpleLoginDemo/SimpleLoginDemo.Presentation/Home/HomeController.cs
886
C#
using Gemini.Framework; using Gemini.Framework.Commands; using SMAStudiovNext.Core; using SMAStudiovNext.Models; using SMAStudiovNext.Modules.Shell.Commands; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using SMAStudiovNext.Services; using System.Windows; using SMAStudiovNext.Commands; using SMAStudiovNext.Exceptions; namespace SMAStudiovNext.Modules.WindowModule.ViewModels { public sealed class ModuleViewModel : Document, IViewModel, ICommandHandler<SaveCommandDefinition> { private readonly ModuleModelProxy model; public ModuleViewModel(ModuleModelProxy module) { model = module; UnsavedChanges = true; Owner = module.Context.Service; if (module.ModuleName != null) ModuleName = module.ModuleName; else ModuleName = string.Empty; ModuleVersion = "1.0.0.0"; LongRunningOperation.Stop(); } public override void CanClose(Action<bool> callback) { if (UnsavedChanges) { var result = MessageBox.Show("There are unsaved changes in the module object, changes will be lost. Do you want to continue?", "Unsaved changes", MessageBoxButton.YesNo, MessageBoxImage.Question); if (result != MessageBoxResult.Yes) { callback(false); return; } } callback(true); } public override string DisplayName { get { if (!UnsavedChanges) { return model.ModuleName; } return ModuleName.Length > 0 ? ModuleName + "*" : "New Module*"; } } public string ModuleName { get; set; } public string ModuleUrl { get; set; } public string ModuleVersion { get; set; } public string Content { get { return string.Empty; } } public object Model { get { return model; } set { throw new NotSupportedException(); // NOTE: Why not make set private? } } public IBackendService Owner { private get; set; } public bool UnsavedChanges { get; set; } async Task ICommandHandler<SaveCommandDefinition>.Run(Command command) { await Task.Run(delegate () { LongRunningOperation.Start(); model.ViewModel = this; model.ModuleName = ModuleName; model.ModuleUrl = ModuleUrl; model.ModuleVersion = ModuleVersion; try { Owner.Save(this, command); Owner.Context.AddToModules(model); } catch (ApplicationException ex) { GlobalExceptionHandler.Show(ex); } // Update the UI to notify that the changes has been saved UnsavedChanges = false; NotifyOfPropertyChange(() => DisplayName); LongRunningOperation.Stop(); }); } void ICommandHandler<SaveCommandDefinition>.Update(Command command) { if (UnsavedChanges) command.Enabled = true; else command.Enabled = false; } } }
26.244755
212
0.515055
[ "Apache-2.0" ]
icanos/SMAStudio
SMAStudiovNext/Modules/Workspaces/WindowModule/ViewModels/ModuleViewModel.cs
3,755
C#
using System; using System.Linq; using System.IO; using System.Text; using System.Text.RegularExpressions; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using System.ComponentModel.DataAnnotations; using SwaggerDateConverter = TrustPayments.Client.SwaggerDateConverter; namespace TrustPayments.Model { /// <summary> /// Defines SubscriptionChargeState /// </summary> [JsonConverter(typeof(StringEnumConverter))] public enum SubscriptionChargeState { /// <summary> /// Enum SCHEDULED for value: SCHEDULED /// </summary> [EnumMember(Value = "SCHEDULED")] SCHEDULED, /// <summary> /// Enum DISCARDED for value: DISCARDED /// </summary> [EnumMember(Value = "DISCARDED")] DISCARDED, /// <summary> /// Enum PROCESSING for value: PROCESSING /// </summary> [EnumMember(Value = "PROCESSING")] PROCESSING, /// <summary> /// Enum SUCCESSFUL for value: SUCCESSFUL /// </summary> [EnumMember(Value = "SUCCESSFUL")] SUCCESSFUL, /// <summary> /// Enum FAILED for value: FAILED /// </summary> [EnumMember(Value = "FAILED")] FAILED } }
24.982759
71
0.605245
[ "Apache-2.0" ]
TrustPayments/csharp-sdk
src/TrustPayments/Model/SubscriptionChargeState.cs
1,449
C#
using ConsoleGUI; using ConsoleGUI.Input; using Prompton.Steps; using Prompton.Steps.StepResults; using Prompton.UI.Views; namespace Prompton.UI.Listeners; public class WhileListener : StepListener { private readonly WhileView whileView; private readonly WhileResult result; private readonly UIProvider ui; public WhileListener(WhileView whileView, UIProvider ui) { this.whileView = whileView; this.ui = ui; result = new WhileResult { StepId = whileView.Step.Id, Result = new List<List<StepResult>>() }; } public override StepResult GetResult() => result; public override void OnInput(InputEvent inputEvent) { switch (inputEvent.Key.Key) { case ConsoleKey.Enter: { result.Prompt = whileView.Step.Prompt; StepListener listener; var resultList = new List<StepResult>(); var breakLoop = false; var repeats = 0; while (!breakLoop) { repeats++; foreach (var step in whileView.Step.Steps) { var view = ui.GetView(step); var listeners = ui.GetListeners(view); var listenerList = listeners.Select(x => x.Value).ToArray(); ui.ViewArea.Content = view; while (!view.Complete) { Thread.Sleep(10); ConsoleManager.ReadInput(listenerList); } listener = listeners[Constants.StepListenerKey] as StepListener; resultList.Add(listener.GetResult()); } var choiceStep = new Choice { Prompt = $"Would you like to repeat again: {whileView.Step.Prompt} (current count: {repeats})", Choices = new() { { "Yes", null }, { "No", null } } }; var choiceView = ui.GetView(choiceStep); var choiceListeners = ui.GetListeners(choiceView); var choiceListenerList = choiceListeners.Select(x => x.Value).ToArray(); ui.ViewArea.Content = choiceView; while (!choiceView.Complete) { Thread.Sleep(10); ConsoleManager.ReadInput(choiceListenerList); } listener = choiceListeners[Constants.StepListenerKey] as StepListener; var stepResult = listener.GetResult() as ChoiceResult; breakLoop = stepResult.Choice == "No"; } result.Repeats = repeats; result.Result.Add(resultList); whileView.Complete = true; inputEvent.Handled = true; return; } } } }
38.139535
123
0.467073
[ "MIT" ]
DanBiscotti/Prompton
Prompton/UI/Listeners/StepListeners/WhileListener.cs
3,282
C#
using System; using Windows.UI.ViewManagement; namespace Uno.Devices.Sensors { public interface INativeDualScreenProvider { bool? IsSpanned { get; } } }
14.545455
43
0.75625
[ "Apache-2.0" ]
AnshSSonkhia/uno
src/Uno.UWP/Devices/Sensors/Helpers/INativeDualScreenProvider.cs
162
C#
// // ExpressionList.cs // // Author: // Aaron Bockover <abock@xamarin.com> // // Copyright 2015 Xamarin Inc. All rights reserved. namespace Xamarin.Pmcs.CSharp.Ast { public class ExpressionList : Node { public TokenType Delimiter { get; set; } public override void AcceptVisitor (IAstVisitor visitor) { visitor.VisitExpressionList (this); } } }
18.2
58
0.706044
[ "BSD-3-Clause" ]
Acidburn0zzz/xamarin-macios
tools/pmcs/CSharp/Ast/ExpressionList.cs
366
C#
using System; using System.Collections.Generic; using System.Text; namespace SOLID_Principles._4_I { class Developer : ILead { public void AssginTask() { throw new Exception("Developer can't Assign Task"); } public void CreateTask() { throw new Exception("Developer can't Create Task"); } public void WorkOnTask() { /* Code to work on a task*/ } } }
18.96
63
0.548523
[ "MIT" ]
Technosaviour/SOLID-principles-.Net
4 I/Developer.cs
476
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Option_i_rolling : MonoBehaviour { public float rotate_s = 1.0f; void Update() { transform.Rotate(0, 0, this.rotate_s); } }
18.538462
46
0.697095
[ "MIT" ]
CD-mon/QAZE-main
Assets/Scripts/Start/Option_i_rolling.cs
241
C#
using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Reflection; using System.Reflection.Emit; using AltV.Net.Native; using HarmonyLib; namespace AltV.Net.Mock2 { public class Mock { public Mock() { //var harmony = HarmonyInstance.Create("AltV.Net"); var methodBase = AccessTools.Method(typeof(AltNative.Player),"Player_GetID", new []{typeof(IntPtr)}); Console.WriteLine("methodbase:" + methodBase); MethodBase getIdMethodBase = typeof(Mock).GetMethod("GetId"); var originalInstructions2 = PatchProcessor.GetCurrentInstructions(methodBase); var originalInstructions = PatchProcessor.GetCurrentInstructions(getIdMethodBase); Console.WriteLine(originalInstructions.ToString()); Console.WriteLine(originalInstructions.Count); foreach (var instruction in originalInstructions) { Console.WriteLine(instruction); } Console.WriteLine(originalInstructions2.ToString()); Console.WriteLine(originalInstructions2.Count); foreach (var instruction in originalInstructions2) { Console.WriteLine(instruction); } var harmony = new Harmony("AltV.Net"); harmony.PatchAll(Assembly.GetExecutingAssembly()); var bla = AltNative.Player.Player_GetID(IntPtr.Zero); Console.WriteLine(bla); } public static ushort GetId(IntPtr intPtr) { Console.WriteLine(intPtr); return 1337; } } //[HarmonyPatch] [HarmonyPatch(typeof(AltNative.Player))] [HarmonyPatch("Player_GetID")] [HarmonyPatch(new Type[] {typeof(IntPtr)})] //[SuppressMessage("ReSharper", "RedundantAssignment")] //[SuppressMessage("ReSharper", "InconsistentNaming")] class Patch { /*[HarmonyPrefix] static bool Prefix(IntPtr entityPointer, ref ushort __result) { __result = 1337; return false; }*/ /*static MethodBase TargetMethod() => AccessTools.Method(typeof(AltNative.Player),"Player_GetID", new []{typeof(IntPtr)}); [HarmonyTranspiler] static IEnumerable<CodeInstruction> Transpiler(IntPtr entityPointer, ref ushort __result) { Console.WriteLine("Test"); //__result = 1337; ushort id = 1337; var codeInstructions = new CodeInstruction[2];//2s //codeInstructions[0] = new CodeInstruction(OpCodes.Ldnull); //codeInstructions[0] = new CodeInstruction(OpCodes.Ldc_I4_S, id); codeInstructions[0] = new CodeInstruction(OpCodes.Ldc_I4, id); codeInstructions[1] = new CodeInstruction(OpCodes.Ret); return codeInstructions; }*/ //static MethodBase TargetMethod() => AccessTools.Method(typeof(AltNative.Player),"Player_GetID", new []{typeof(IntPtr)}); /*[HarmonyTranspiler] static IEnumerable<CodeInstruction> Transpiler(IntPtr entityPointer, ref ushort __result) { __result = 1337; Console.WriteLine("Transpiler"); var codeInstructions = new CodeInstruction[2];//2s //codeInstructions[0] = new CodeInstruction(OpCodes.Ldnull); //codeInstructions[0] = new CodeInstruction(OpCodes.Ldc_I4_S, id); codeInstructions[0] = new CodeInstruction(OpCodes.Ldc_I4, 1337); codeInstructions[1] = new CodeInstruction(OpCodes.Ret); return codeInstructions; }*/ [HarmonyTranspiler] static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions) { Console.WriteLine("Transpiler"); /*var codeInstructions = new CodeInstruction[2];//2s //codeInstructions[0] = new CodeInstruction(OpCodes.Ldnull); //codeInstructions[0] = new CodeInstruction(OpCodes.Ldc_I4_S, id); //codeInstructions[0] = new CodeInstruction(OpCodes.Ldc_I4, 1337); codeInstructions[1] = new CodeInstruction(OpCodes.Ret); return codeInstructions;*/ foreach (var instruction in instructions) { Console.WriteLine(instruction); } /*var codeInstructions = new CodeInstruction[2]; codeInstructions[0] = new CodeInstruction(OpCodes.Ldnull); codeInstructions[1] = new CodeInstruction(OpCodes.Ret); return codeInstructions;*/ return Enumerable.Empty<CodeInstruction>(); } } }
42.205357
130
0.626402
[ "MIT" ]
Apokalypser/coreclr-module
api/AltV.Net.Mock2/Mock.cs
4,729
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated from a template. // // Manual changes to this file may cause unexpected behavior in your application. // Manual changes to this file will be overwritten if the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace SurvayArm.Data.Model { using System; using System.Collections.Generic; public partial class Province { [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")] public Province() { this.Districts = new HashSet<District>(); this.SurvayTargets = new HashSet<SurvayTarget>(); } public int Id { get; set; } public string Name { get; set; } public System.DateTime CreatedDate { get; set; } public string CreatedBy { get; set; } public System.DateTime UpdatedDate { get; set; } public string UpdatedBy { get; set; } public bool IsActive { get; set; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public virtual ICollection<District> Districts { get; set; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public virtual ICollection<SurvayTarget> SurvayTargets { get; set; } } }
41.763158
128
0.606175
[ "MIT" ]
dush88c/WEBAPI-MVC
SurvayArm.Data/Model/Province.cs
1,587
C#
using System; using System.IO; using System.Collections.Generic; namespace UnityFS.Editor { using UnityEngine; using UnityEditor; public partial class BundleBuilderData { [Serializable] public class BundleSlice { public string name; public int capacity; public bool streamingAssets; // 是否进入 StreamingAssets public PackagePlatform platform; // 打包资源的平台性质 public List<string> assetPathHistroy = new List<string>(); public long totalRawSize; // 原始资源大小统计 (不准确, 目前没统计依赖) public long lastBuildSize; // 最近一次打包的实际大小 // 最终进入打包的所有资源对象 public List<string> _assetPaths = new List<string>(); public int GetAssetCount() { return _assetPaths.Count; } public string GetAssetPath(int index) { return _assetPaths[index]; } public BundleSlice(string name, int capacity, bool streamingAssets, PackagePlatform platform) { this.name = name; this.capacity = capacity; this.streamingAssets = streamingAssets; this.platform = platform; } public void ForEachAsset(Action<string> visitor) { for (int i = 0, size = GetAssetCount(); i < size; i++) { visitor(GetAssetPath(i)); } } public bool LookupAssetPath(string assetPath) { return _assetPaths.Contains(assetPath); } // 是否为指定平台打包 public bool IsBuild(PackagePlatform buildPlatform) { return this.platform == PackagePlatform.Any || this.platform == buildPlatform; } // 完全重置此分包 (丢弃历史记录) public void Reset() { assetPathHistroy.Clear(); Cleanup(); } public void Cleanup() { totalRawSize = 0; _assetPaths.Clear(); } private void _AddAssetPath(string assetPath) { _assetPaths.Add(assetPath); var fileInfo = new FileInfo(assetPath); if (fileInfo.Exists) { totalRawSize += fileInfo.Length; } } // 如果是历史资源, 将加入; 否则返回 false public bool AddHistory(string assetPath, bool streamingAssets, PackagePlatform platform) { if (assetPathHistroy.Contains(assetPath)) { if (this.streamingAssets == streamingAssets && this.IsBuild(platform)) { _AddAssetPath(assetPath); return true; } // 此处的判定规则影响包的性质改变, 进而影响分包切分布局, 导致额外的包变更 if (GetAssetCount() == 0 && assetPathHistroy.Count == 1) { this.streamingAssets = streamingAssets; this.platform = platform; _AddAssetPath(assetPath); return true; } } return false; } // 尝试添加资源 // 仅历史数量在切分容量剩余时可以加入 public bool AddNewAssetPath(string assetPath) { if (capacity <= 0 || assetPathHistroy.Count < capacity) { _AddAssetPath(assetPath); assetPathHistroy.Add(assetPath); return true; } return false; } } } }
31.230159
106
0.458704
[ "MIT" ]
ialex32x/unityfs
Assets/UnityFS/Editor/BundleBuilderData+BundleSlice.cs
4,231
C#
using System; namespace Xamarin.Forms.PlatformConfiguration.iOSSpecific { using FormsElement = Forms.Entry; public static class Entry { public static readonly BindableProperty AdjustsFontSizeToFitWidthProperty = BindableProperty.Create("AdjustsFontSizeToFitWidthEnabled", typeof(bool), typeof(Entry), false); public static bool GetAdjustsFontSizeToFitWidth(BindableObject element) { return (bool)element.GetValue(AdjustsFontSizeToFitWidthProperty); } public static void SetAdjustsFontSizeToFitWidth(BindableObject element, bool value) { element.SetValue(AdjustsFontSizeToFitWidthProperty, value); } public static bool IsAdjustsFontSizeToFitWidthEnabled(this IPlatformElementConfiguration<iOS, FormsElement> config) { return GetAdjustsFontSizeToFitWidth(config.Element); } public static IPlatformElementConfiguration<iOS, FormsElement> SetAdjustsFontSizeToFitWidthEnabled(this IPlatformElementConfiguration<iOS, FormsElement> config, bool value) { SetAdjustsFontSizeToFitWidth(config.Element, value); return config; } public static IPlatformElementConfiguration<iOS, FormsElement> EnableAdjustsFontSizeToFitWidth(this IPlatformElementConfiguration<iOS, FormsElement> config) { SetAdjustsFontSizeToFitWidth(config.Element, true); return config; } public static IPlatformElementConfiguration<iOS, FormsElement> DisableAdjustsFontSizeToFitWidth(this IPlatformElementConfiguration<iOS, FormsElement> config) { SetAdjustsFontSizeToFitWidth(config.Element, false); return config; } } }
33.255319
174
0.814459
[ "MIT" ]
nosami/xamlprovider
Xamarin.Forms.Core/PlatformConfiguration/iOSSpecific/Entry.cs
1,565
C#
using System.Collections.Generic; using System.Net.Http; using SFA.Roatp.Api.Types; using SFA.Roatp.Api.Types.Exceptions; namespace SFA.Roatp.Api.Client { public interface IRoatpClient { /// <summary> /// Get a provider details /// GET /providers/{ukprn} /// </summary> /// <param name="ukprn">the provider ukprn this should be 8 numbers long</param> /// <returns>a provider details based on ukprn</returns> /// <exception cref="EntityNotFoundException">when the resource you requested doesn't exist</exception> /// <exception cref="HttpRequestException">There was an unexpected error</exception> Provider Get(string ukprn); /// <summary> /// Get a provider details /// GET /providers/{ukprn} /// </summary> /// <param name="ukprn">the provider ukprn this should be 8 numbers long</param> /// <returns></returns> /// <exception cref="EntityNotFoundException">when the resource you requested doesn't exist</exception> /// <exception cref="HttpRequestException">There was an unexpected error</exception> Provider Get(long ukprn); /// <summary> /// Get a provider details /// GET /providers/{ukprn} /// </summary> /// <param name="ukprn">the provider ukprn this should be 8 numbers long</param> /// <returns></returns> /// <exception cref="EntityNotFoundException">when the resource you requested doesn't exist</exception> /// <exception cref="HttpRequestException">There was an unexpected error</exception> Provider Get(int ukprn); /// <summary> /// Check if a provider exists /// HEAD /providers/{ukprn} /// </summary> /// <param name="ukprn">the provider ukprn this should be 8 numbers long</param> /// <returns>bool</returns> /// <exception cref="EntityNotFoundException">when the resource you requested doesn't exist</exception> /// <exception cref="HttpRequestException">There was an unexpected error</exception> bool Exists(string ukprn); /// <summary> /// Check if a provider exists /// HEAD /providers/{ukprn} /// </summary> /// <param name="ukprn">the provider ukprn this should be 8 numbers long</param> /// <returns>bool</returns> /// <exception cref="EntityNotFoundException">when the resource you requested doesn't exist</exception> /// <exception cref="HttpRequestException">There was an unexpected error</exception> bool Exists(int ukprn); /// <summary> /// Check if a provider exists /// HEAD /providers/{ukprn} /// </summary> /// <param name="ukprn">the provider ukprn this should be 8 numbers long</param> /// <returns>bool</returns> /// <exception cref="EntityNotFoundException">when the resource you requested doesn't exist</exception> /// <exception cref="HttpRequestException">There was an unexpected error</exception> bool Exists(long ukprn); /// <summary> /// Get a list of active providers on ROATP /// GET /providers /// </summary> /// <returns></returns> /// <exception cref="EntityNotFoundException">when the resource you requested doesn't exist</exception> /// <exception cref="HttpRequestException">There was an unexpected error</exception> IEnumerable<Provider> FindAll(); } }
46.893333
111
0.628092
[ "MIT" ]
SkillsFundingAgency/roatp-register
src/SFA.Roatp.Api.Client/IRoatpClient.cs
3,519
C#
// Copyright 2022 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.Analytics.Admin.V1Alpha.Snippets { // [START analyticsadmin_v1alpha_generated_AnalyticsAdminService_ListCustomDimensions_sync] using Google.Analytics.Admin.V1Alpha; using Google.Api.Gax; using System; public sealed partial class GeneratedAnalyticsAdminServiceClientSnippets { /// <summary>Snippet for ListCustomDimensions</summary> /// <remarks> /// This snippet has been automatically generated for illustrative purposes only. /// It may require modifications to work in your environment. /// </remarks> public void ListCustomDimensionsRequestObject() { // Create client AnalyticsAdminServiceClient analyticsAdminServiceClient = AnalyticsAdminServiceClient.Create(); // Initialize request argument(s) ListCustomDimensionsRequest request = new ListCustomDimensionsRequest { ParentAsPropertyName = PropertyName.FromProperty("[PROPERTY]"), }; // Make the request PagedEnumerable<ListCustomDimensionsResponse, CustomDimension> response = analyticsAdminServiceClient.ListCustomDimensions(request); // Iterate over all response items, lazily performing RPCs as required foreach (CustomDimension item in response) { // Do something with each item Console.WriteLine(item); } // Or iterate over pages (of server-defined size), performing one RPC per page foreach (ListCustomDimensionsResponse page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (CustomDimension item in page) { // Do something with each item Console.WriteLine(item); } } // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<CustomDimension> singlePage = response.ReadPage(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (CustomDimension item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; } } // [END analyticsadmin_v1alpha_generated_AnalyticsAdminService_ListCustomDimensions_sync] }
43.307692
144
0.648609
[ "Apache-2.0" ]
AlexandrTrf/google-cloud-dotnet
apis/Google.Analytics.Admin.V1Alpha/Google.Analytics.Admin.V1Alpha.GeneratedSnippets/AnalyticsAdminServiceClient.ListCustomDimensionsRequestObjectSnippet.g.cs
3,378
C#
namespace Microsoft.Marketplace.SaasKit.Client.DataAccess.Services { using Microsoft.EntityFrameworkCore; using Microsoft.Marketplace.SaasKit.Client.DataAccess.Context; using Microsoft.Marketplace.SaasKit.Client.DataAccess.Contracts; using Microsoft.Marketplace.SaasKit.Client.DataAccess.Entities; using System; using System.Collections.Generic; using System.Linq; /// <summary> /// Metered Dimensions Repository /// </summary> /// <seealso cref="Microsoft.Marketplace.SaasKit.Client.DataAccess.Contracts.IMeteredDimensionsRepository" /> public class MeteredDimensionsRepository : IMeteredDimensionsRepository { /// <summary> /// The context /// </summary> private readonly SaasKitContext Context; /// <summary> /// Initializes a new instance of the <see cref="PlansRepository" /> class. /// </summary> /// <param name="context">The context.</param> public MeteredDimensionsRepository(SaasKitContext context) { Context = context; } /// <summary> /// The disposed /// </summary> private bool disposed = false; /// <summary> /// Releases unmanaged and - optionally - managed resources. /// </summary> /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param> protected virtual void Dispose(bool disposing) { if (!this.disposed) { if (disposing) { Context.Dispose(); } } this.disposed = true; } /// <summary> /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. /// </summary> public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } /// <summary> /// Gets this instance. /// </summary> /// <returns></returns> public IEnumerable<MeteredDimensions> Get() { return Context.MeteredDimensions.Include(s => s.Plan); } /// <summary> /// Gets the specified identifier. /// </summary> /// <param name="id">The identifier.</param> /// <returns></returns> public MeteredDimensions Get(int id) { return Context.MeteredDimensions.Include(s => s.Plan).Where(s => s.Id == id).FirstOrDefault(); } /// <summary> /// Adds the specified dimension details. /// </summary> /// <param name="dimensionDetails">The dimension details.</param> /// <returns></returns> public int Add(MeteredDimensions dimensionDetails) { if (dimensionDetails != null && !string.IsNullOrEmpty(dimensionDetails.Dimension)) { var existingDimension = Context.MeteredDimensions.Where(s => s.Dimension == dimensionDetails.Dimension).FirstOrDefault(); if (existingDimension != null) { existingDimension.Description = dimensionDetails.Description; Context.MeteredDimensions.Update(existingDimension); Context.SaveChanges(); return existingDimension.Id; } else { Context.MeteredDimensions.Add(dimensionDetails); Context.SaveChanges(); return dimensionDetails.Id; } } return 0; } /// <summary> /// Removes the specified dimension details. /// </summary> /// <param name="dimensionDetails">The dimension details.</param> public void Remove(MeteredDimensions dimensionDetails) { Context.MeteredDimensions.Remove(dimensionDetails); Context.SaveChanges(); } /// <summary> /// Gets the dimensions from plan identifier. /// </summary> /// <param name="planId">The plan identifier.</param> /// <returns></returns> public List<MeteredDimensions> GetDimensionsFromPlanId(string planId) { return Context.MeteredDimensions.Include(s => s.Plan).Where(s => s.Plan != null && s.Plan.PlanId == planId).ToList(); } } }
35.25
154
0.565381
[ "MIT" ]
ankisho/Microsoft-commercial-marketplace-transactable-SaaS-offer-SDK
src/SaaS.SDK.Client.DataAccess/Services/MeteredDimensionsRepository.cs
4,514
C#
/* * BombBomb * * We make it easy to build relationships using simple videos. * * OpenAPI spec version: 2.0.24005 * * Generated by: https://github.com/swagger-api/swagger-codegen.git * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.IO; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Reflection; using RestSharp; using NUnit.Framework; using IO.Swagger.Client; using IO.Swagger.Api; namespace IO.Swagger.Test { /// <summary> /// Class for testing ContactsApi /// </summary> /// <remarks> /// This file is automatically generated by Swagger Codegen. /// Please update the test case below to test the API endpoint. /// </remarks> [TestFixture] public class ContactsApiTests { private ContactsApi instance; /// <summary> /// Setup before each unit test /// </summary> [SetUp] public void Init() { instance = new ContactsApi(); } /// <summary> /// Clean up after each unit test /// </summary> [TearDown] public void Cleanup() { } /// <summary> /// Test an instance of ContactsApi /// </summary> [Test] public void InstanceTest() { // TODO uncomment below to test 'IsInstanceOfType' ContactsApi //Assert.IsInstanceOfType(typeof(ContactsApi), instance, "instance is a ContactsApi"); } /// <summary> /// Test DeleteContacts /// </summary> [Test] public void DeleteContactsTest() { // TODO uncomment below to test the method and replace null with proper value //string listId = null; //instance.DeleteContacts(listId); } } }
25.935484
98
0.61194
[ "Apache-2.0" ]
bombbomb/bombbomb-csharp-openapi
src/IO.Swagger.Test/Api/ContactsApiTests.cs
2,412
C#
// ------------------------------------------------------------------------------ // <auto-generated> // Generated by Xsd2Code. Version 3.4.0.18239 Microsoft Reciprocal License (Ms-RL) // <NameSpace>Mim.V6301</NameSpace><Collection>Array</Collection><codeType>CSharp</codeType><EnableDataBinding>False</EnableDataBinding><EnableLazyLoading>False</EnableLazyLoading><TrackingChangesEnable>False</TrackingChangesEnable><GenTrackingClasses>False</GenTrackingClasses><HidePrivateFieldInIDE>False</HidePrivateFieldInIDE><EnableSummaryComment>True</EnableSummaryComment><VirtualProp>False</VirtualProp><IncludeSerializeMethod>True</IncludeSerializeMethod><UseBaseClass>False</UseBaseClass><GenBaseClass>False</GenBaseClass><GenerateCloneMethod>True</GenerateCloneMethod><GenerateDataContracts>False</GenerateDataContracts><CodeBaseTag>Net35</CodeBaseTag><SerializeMethodName>Serialize</SerializeMethodName><DeserializeMethodName>Deserialize</DeserializeMethodName><SaveToFileMethodName>SaveToFile</SaveToFileMethodName><LoadFromFileMethodName>LoadFromFile</LoadFromFileMethodName><GenerateXMLAttributes>True</GenerateXMLAttributes><OrderXMLAttrib>False</OrderXMLAttrib><EnableEncoding>False</EnableEncoding><AutomaticProperties>False</AutomaticProperties><GenerateShouldSerialize>False</GenerateShouldSerialize><DisableDebug>False</DisableDebug><PropNameSpecified>Default</PropNameSpecified><Encoder>UTF8</Encoder><CustomUsings></CustomUsings><ExcludeIncludedTypes>True</ExcludeIncludedTypes><EnableInitializeFields>False</EnableInitializeFields> // </auto-generated> // ------------------------------------------------------------------------------ namespace Mim.V6301 { using System; using System.Diagnostics; using System.Xml.Serialization; using System.Collections; using System.Xml.Schema; using System.ComponentModel; using System.IO; using System.Text; [System.CodeDom.Compiler.GeneratedCodeAttribute("Xsd2Code", "3.4.0.18239")] [System.SerializableAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Xml.Serialization.XmlTypeAttribute(TypeName="REPC_MT150007UK05.PertinentInformation2", Namespace="urn:hl7-org:v3")] [System.Xml.Serialization.XmlRootAttribute("REPC_MT150007UK05.PertinentInformation2", Namespace="urn:hl7-org:v3")] public partial class REPC_MT150007UK05PertinentInformation2 { private REPC_MT150007UK05PertinentInformation2TemplateId templateIdField; private REPC_MT150007UK05PertinentInformation2SeperatableInd seperatableIndField; private REPC_MT150007UK05CREType pertinentCRETypeField; private string nullFlavorField; private cs_UpdateMode updateModeField; private bool updateModeFieldSpecified; private string typeCodeField; private bool inversionIndField; private bool contextConductionIndField; private bool negationIndField; private static System.Xml.Serialization.XmlSerializer serializer; public REPC_MT150007UK05PertinentInformation2() { this.typeCodeField = "PERT"; this.inversionIndField = false; this.contextConductionIndField = true; this.negationIndField = false; } public REPC_MT150007UK05PertinentInformation2TemplateId templateId { get { return this.templateIdField; } set { this.templateIdField = value; } } public REPC_MT150007UK05PertinentInformation2SeperatableInd seperatableInd { get { return this.seperatableIndField; } set { this.seperatableIndField = value; } } public REPC_MT150007UK05CREType pertinentCREType { get { return this.pertinentCRETypeField; } set { this.pertinentCRETypeField = value; } } [System.Xml.Serialization.XmlAttributeAttribute()] public string nullFlavor { get { return this.nullFlavorField; } set { this.nullFlavorField = value; } } [System.Xml.Serialization.XmlAttributeAttribute()] public cs_UpdateMode updateMode { get { return this.updateModeField; } set { this.updateModeField = value; } } [System.Xml.Serialization.XmlIgnoreAttribute()] public bool updateModeSpecified { get { return this.updateModeFieldSpecified; } set { this.updateModeFieldSpecified = value; } } [System.Xml.Serialization.XmlAttributeAttribute(DataType="token")] public string typeCode { get { return this.typeCodeField; } set { this.typeCodeField = value; } } [System.Xml.Serialization.XmlAttributeAttribute()] public bool inversionInd { get { return this.inversionIndField; } set { this.inversionIndField = value; } } [System.Xml.Serialization.XmlAttributeAttribute()] public bool contextConductionInd { get { return this.contextConductionIndField; } set { this.contextConductionIndField = value; } } [System.Xml.Serialization.XmlAttributeAttribute()] public bool negationInd { get { return this.negationIndField; } set { this.negationIndField = value; } } private static System.Xml.Serialization.XmlSerializer Serializer { get { if ((serializer == null)) { serializer = new System.Xml.Serialization.XmlSerializer(typeof(REPC_MT150007UK05PertinentInformation2)); } return serializer; } } #region Serialize/Deserialize /// <summary> /// Serializes current REPC_MT150007UK05PertinentInformation2 object into an XML document /// </summary> /// <returns>string XML value</returns> public virtual string Serialize() { System.IO.StreamReader streamReader = null; System.IO.MemoryStream memoryStream = null; try { memoryStream = new System.IO.MemoryStream(); Serializer.Serialize(memoryStream, this); memoryStream.Seek(0, System.IO.SeekOrigin.Begin); streamReader = new System.IO.StreamReader(memoryStream); return streamReader.ReadToEnd(); } finally { if ((streamReader != null)) { streamReader.Dispose(); } if ((memoryStream != null)) { memoryStream.Dispose(); } } } /// <summary> /// Deserializes workflow markup into an REPC_MT150007UK05PertinentInformation2 object /// </summary> /// <param name="xml">string workflow markup to deserialize</param> /// <param name="obj">Output REPC_MT150007UK05PertinentInformation2 object</param> /// <param name="exception">output Exception value if deserialize failed</param> /// <returns>true if this XmlSerializer can deserialize the object; otherwise, false</returns> public static bool Deserialize(string xml, out REPC_MT150007UK05PertinentInformation2 obj, out System.Exception exception) { exception = null; obj = default(REPC_MT150007UK05PertinentInformation2); try { obj = Deserialize(xml); return true; } catch (System.Exception ex) { exception = ex; return false; } } public static bool Deserialize(string xml, out REPC_MT150007UK05PertinentInformation2 obj) { System.Exception exception = null; return Deserialize(xml, out obj, out exception); } public static REPC_MT150007UK05PertinentInformation2 Deserialize(string xml) { System.IO.StringReader stringReader = null; try { stringReader = new System.IO.StringReader(xml); return ((REPC_MT150007UK05PertinentInformation2)(Serializer.Deserialize(System.Xml.XmlReader.Create(stringReader)))); } finally { if ((stringReader != null)) { stringReader.Dispose(); } } } /// <summary> /// Serializes current REPC_MT150007UK05PertinentInformation2 object into file /// </summary> /// <param name="fileName">full path of outupt xml file</param> /// <param name="exception">output Exception value if failed</param> /// <returns>true if can serialize and save into file; otherwise, false</returns> public virtual bool SaveToFile(string fileName, out System.Exception exception) { exception = null; try { SaveToFile(fileName); return true; } catch (System.Exception e) { exception = e; return false; } } public virtual void SaveToFile(string fileName) { System.IO.StreamWriter streamWriter = null; try { string xmlString = Serialize(); System.IO.FileInfo xmlFile = new System.IO.FileInfo(fileName); streamWriter = xmlFile.CreateText(); streamWriter.WriteLine(xmlString); streamWriter.Close(); } finally { if ((streamWriter != null)) { streamWriter.Dispose(); } } } /// <summary> /// Deserializes xml markup from file into an REPC_MT150007UK05PertinentInformation2 object /// </summary> /// <param name="fileName">string xml file to load and deserialize</param> /// <param name="obj">Output REPC_MT150007UK05PertinentInformation2 object</param> /// <param name="exception">output Exception value if deserialize failed</param> /// <returns>true if this XmlSerializer can deserialize the object; otherwise, false</returns> public static bool LoadFromFile(string fileName, out REPC_MT150007UK05PertinentInformation2 obj, out System.Exception exception) { exception = null; obj = default(REPC_MT150007UK05PertinentInformation2); try { obj = LoadFromFile(fileName); return true; } catch (System.Exception ex) { exception = ex; return false; } } public static bool LoadFromFile(string fileName, out REPC_MT150007UK05PertinentInformation2 obj) { System.Exception exception = null; return LoadFromFile(fileName, out obj, out exception); } public static REPC_MT150007UK05PertinentInformation2 LoadFromFile(string fileName) { System.IO.FileStream file = null; System.IO.StreamReader sr = null; try { file = new System.IO.FileStream(fileName, FileMode.Open, FileAccess.Read); sr = new System.IO.StreamReader(file); string xmlString = sr.ReadToEnd(); sr.Close(); file.Close(); return Deserialize(xmlString); } finally { if ((file != null)) { file.Dispose(); } if ((sr != null)) { sr.Dispose(); } } } #endregion #region Clone method /// <summary> /// Create a clone of this REPC_MT150007UK05PertinentInformation2 object /// </summary> public virtual REPC_MT150007UK05PertinentInformation2 Clone() { return ((REPC_MT150007UK05PertinentInformation2)(this.MemberwiseClone())); } #endregion } }
40.805732
1,358
0.582377
[ "MIT" ]
Kusnaditjung/MimDms
src/Mim.V6301/Generated/REPC_MT150007UK05PertinentInformation2.cs
12,813
C#
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AzureNative.Synapse.V20210301 { /// <summary> /// Integration runtime resource type. /// </summary> [AzureNativeResourceType("azure-native:synapse/v20210301:IntegrationRuntime")] public partial class IntegrationRuntime : Pulumi.CustomResource { /// <summary> /// Resource Etag. /// </summary> [Output("etag")] public Output<string> Etag { get; private set; } = null!; /// <summary> /// The name of the resource /// </summary> [Output("name")] public Output<string> Name { get; private set; } = null!; /// <summary> /// Integration runtime properties. /// </summary> [Output("properties")] public Output<Union<Outputs.ManagedIntegrationRuntimeResponse, Outputs.SelfHostedIntegrationRuntimeResponse>> Properties { get; private set; } = null!; /// <summary> /// The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" /// </summary> [Output("type")] public Output<string> Type { get; private set; } = null!; /// <summary> /// Create a IntegrationRuntime resource with the given unique name, arguments, and options. /// </summary> /// /// <param name="name">The unique name of the resource</param> /// <param name="args">The arguments used to populate this resource's properties</param> /// <param name="options">A bag of options that control this resource's behavior</param> public IntegrationRuntime(string name, IntegrationRuntimeArgs args, CustomResourceOptions? options = null) : base("azure-native:synapse/v20210301:IntegrationRuntime", name, args ?? new IntegrationRuntimeArgs(), MakeResourceOptions(options, "")) { } private IntegrationRuntime(string name, Input<string> id, CustomResourceOptions? options = null) : base("azure-native:synapse/v20210301:IntegrationRuntime", name, null, MakeResourceOptions(options, id)) { } private static CustomResourceOptions MakeResourceOptions(CustomResourceOptions? options, Input<string>? id) { var defaultOptions = new CustomResourceOptions { Version = Utilities.Version, Aliases = { new Pulumi.Alias { Type = "azure-nextgen:synapse/v20210301:IntegrationRuntime"}, new Pulumi.Alias { Type = "azure-native:synapse:IntegrationRuntime"}, new Pulumi.Alias { Type = "azure-nextgen:synapse:IntegrationRuntime"}, new Pulumi.Alias { Type = "azure-native:synapse/latest:IntegrationRuntime"}, new Pulumi.Alias { Type = "azure-nextgen:synapse/latest:IntegrationRuntime"}, new Pulumi.Alias { Type = "azure-native:synapse/v20190601preview:IntegrationRuntime"}, new Pulumi.Alias { Type = "azure-nextgen:synapse/v20190601preview:IntegrationRuntime"}, new Pulumi.Alias { Type = "azure-native:synapse/v20201201:IntegrationRuntime"}, new Pulumi.Alias { Type = "azure-nextgen:synapse/v20201201:IntegrationRuntime"}, }, }; var merged = CustomResourceOptions.Merge(defaultOptions, options); // Override the ID if one was specified for consistency with other language SDKs. merged.Id = id ?? merged.Id; return merged; } /// <summary> /// Get an existing IntegrationRuntime resource's state with the given name, ID, and optional extra /// properties used to qualify the lookup. /// </summary> /// /// <param name="name">The unique name of the resulting resource.</param> /// <param name="id">The unique provider ID of the resource to lookup.</param> /// <param name="options">A bag of options that control this resource's behavior</param> public static IntegrationRuntime Get(string name, Input<string> id, CustomResourceOptions? options = null) { return new IntegrationRuntime(name, id, options); } } public sealed class IntegrationRuntimeArgs : Pulumi.ResourceArgs { /// <summary> /// Integration runtime name /// </summary> [Input("integrationRuntimeName")] public Input<string>? IntegrationRuntimeName { get; set; } /// <summary> /// Integration runtime properties. /// </summary> [Input("properties", required: true)] public InputUnion<Inputs.ManagedIntegrationRuntimeArgs, Inputs.SelfHostedIntegrationRuntimeArgs> Properties { get; set; } = null!; /// <summary> /// The name of the resource group. The name is case insensitive. /// </summary> [Input("resourceGroupName", required: true)] public Input<string> ResourceGroupName { get; set; } = null!; /// <summary> /// The name of the workspace. /// </summary> [Input("workspaceName", required: true)] public Input<string> WorkspaceName { get; set; } = null!; public IntegrationRuntimeArgs() { } } }
43.890625
159
0.619438
[ "Apache-2.0" ]
pulumi-bot/pulumi-azure-native
sdk/dotnet/Synapse/V20210301/IntegrationRuntime.cs
5,618
C#
using System; namespace Elebris.Library.Units { public class Character{ int startingLevel = 1; public int currentLevel; public event Action onLevelUp; private CharacterResourceSystem characterResources= null; private CharacterGear characterGear = null; private Experience characterExperience = null; public CharacterResourceSystem CharacterResources { get => characterResources; set => characterResources = value; } public CharacterGear CharacterGear { get => characterGear; set => characterGear = value; } public Experience CharacterExperience { get => characterExperience; set => characterExperience = value; } } }
33.952381
123
0.69986
[ "MIT" ]
baidenx7/Elebris-Adventures
Pulled Resources/Scripts/Units/Character.cs
713
C#
using System; using System.Collections.Generic; using System.Linq; namespace Humanizer.Localisation.CollectionFormatters { internal class DefaultCollectionFormatter : ICollectionFormatter { protected string DefaultSeparator = ""; public DefaultCollectionFormatter(string defaultSeparator) { DefaultSeparator = defaultSeparator; } public virtual string Humanize<T>(IEnumerable<T> collection) { return Humanize(collection, o => o?.ToString(), DefaultSeparator); } public virtual string Humanize<T>(IEnumerable<T> collection, Func<T, string> objectFormatter) { return Humanize(collection, objectFormatter, DefaultSeparator); } public string Humanize<T>(IEnumerable<T> collection, Func<T, object> objectFormatter) { return Humanize(collection, objectFormatter, DefaultSeparator); } public virtual string Humanize<T>(IEnumerable<T> collection, string separator) { return Humanize(collection, o => o?.ToString(), separator); } public virtual string Humanize<T>(IEnumerable<T> collection, Func<T, string> objectFormatter, string separator) { if (collection == null) { throw new ArgumentNullException(nameof(collection)); } if (objectFormatter == null) { throw new ArgumentNullException(nameof(objectFormatter)); } return HumanizeDisplayStrings( collection.Select(objectFormatter), separator); } public string Humanize<T>(IEnumerable<T> collection, Func<T, object> objectFormatter, string separator) { if (collection == null) { throw new ArgumentNullException(nameof(collection)); } if (objectFormatter == null) { throw new ArgumentNullException(nameof(objectFormatter)); } return HumanizeDisplayStrings( collection.Select(objectFormatter).Select(o => o?.ToString()), separator); } private string HumanizeDisplayStrings(IEnumerable<string> strings, string separator) { var itemsArray = strings .Select(item => item == null ? string.Empty : item.Trim()) .Where(item => !string.IsNullOrWhiteSpace(item)) .ToArray(); var count = itemsArray.Length; if (count == 0) { return ""; } if (count == 1) { return itemsArray[0]; } var itemsBeforeLast = itemsArray.Take(count - 1); var lastItem = itemsArray.Skip(count - 1).First(); return string.Format(GetConjunctionFormatString(count), string.Join(", ", itemsBeforeLast), separator, lastItem); } protected virtual string GetConjunctionFormatString(int itemCount) => "{0} {1} {2}"; } }
32.39604
120
0.550428
[ "MIT" ]
0xced/Humanizer
src/Humanizer/Localisation/CollectionFormatters/DefaultCollectionFormatter.cs
3,174
C#
namespace VendorWebClient { using System; using System.Diagnostics; using System.Windows.Forms; using BusinessEntity; public partial class Form1 : Form { public Form1() { InitializeComponent(); } private Stopwatch _timer; private void checkInventoryButton_Click(object sender, EventArgs e) { InventoryServiceSoapClient client = new InventoryServiceSoapClient(); client.CheckInventoryCompleted += CheckInventoryCompleted; _timer = Stopwatch.StartNew(); client.CheckInventoryAsync(partNumberBox.Text); } private void CheckInventoryCompleted(object sender, CheckInventoryCompletedEventArgs e) { _timer.Stop(); if(e.Error != null) { MessageBox.Show(e.Error.Message, "Inventory Service Error"); onHandBox.Text = "ERROR"; onOrderBox.Text = "ERROR"; return; } if (e.Result != null) { responsePartNumber.Text = e.Result.PartNumber; onHandBox.Text = e.Result.QuantityOnHand.ToString(); onOrderBox.Text = e.Result.QuantityOnOrder.ToString(); responseTime.Text = string.Format("{0}ms", _timer.ElapsedMilliseconds); } } } }
28.78
96
0.556637
[ "Apache-2.0" ]
DavidChristiansen/MassTransit
src/Samples/WebServiceBridge/VendorWebClient/Form1.cs
1,441
C#
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace Microsoft.Azure.Devices { using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Globalization; using System.IO; using System.Linq; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Threading; using System.Threading.Tasks; using System.Text; using Microsoft.Azure.Devices.Common; using Microsoft.Azure.Devices.Common.Exceptions; using Microsoft.Azure.Devices.Common.Extensions; using Microsoft.Azure.Devices.Shared; using Newtonsoft.Json; #if NET451 using System.Net.Http.Formatting; #endif sealed class HttpClientHelper : IHttpClientHelper { #if !NETSTANDARD1_3 && !NETSTANDARD2_0 static readonly JsonMediaTypeFormatter JsonFormatter = new JsonMediaTypeFormatter(); #endif readonly Uri baseAddress; readonly IAuthorizationHeaderProvider authenticationHeaderProvider; readonly IReadOnlyDictionary<HttpStatusCode, Func<HttpResponseMessage, Task<Exception>>> defaultErrorMapping; HttpClient httpClientObj; HttpClient httpClientObjWithPerRequestTimeout; bool isDisposed; readonly TimeSpan defaultOperationTimeout; public HttpClientHelper( Uri baseAddress, IAuthorizationHeaderProvider authenticationHeaderProvider, IDictionary<HttpStatusCode, Func<HttpResponseMessage, Task<Exception>>> defaultErrorMapping, TimeSpan timeout, Action<HttpClient> preRequestActionForAllRequests) { this.baseAddress = baseAddress; this.authenticationHeaderProvider = authenticationHeaderProvider; this.defaultErrorMapping = new ReadOnlyDictionary<HttpStatusCode, Func<HttpResponseMessage, Task<Exception>>>(defaultErrorMapping); this.defaultOperationTimeout = timeout; this.httpClientObj = new HttpClient(); this.httpClientObj.BaseAddress = this.baseAddress; this.httpClientObj.Timeout = timeout; this.httpClientObj.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(CommonConstants.MediaTypeForDeviceManagementApis)); this.httpClientObj.DefaultRequestHeaders.ExpectContinue = false; this.httpClientObjWithPerRequestTimeout = new HttpClient(); this.httpClientObjWithPerRequestTimeout.BaseAddress = this.baseAddress; this.httpClientObjWithPerRequestTimeout.Timeout = Timeout.InfiniteTimeSpan; this.httpClientObjWithPerRequestTimeout.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(CommonConstants.MediaTypeForDeviceManagementApis)); this.httpClientObjWithPerRequestTimeout.DefaultRequestHeaders.ExpectContinue = false; if (preRequestActionForAllRequests != null) { preRequestActionForAllRequests(this.httpClientObj); preRequestActionForAllRequests(this.httpClientObjWithPerRequestTimeout); } } public Task<T> GetAsync<T>( Uri requestUri, IDictionary<HttpStatusCode, Func<HttpResponseMessage, Task<Exception>>> errorMappingOverrides, IDictionary<string, string> customHeaders, CancellationToken cancellationToken) { return this.GetAsync<T>(requestUri, this.defaultOperationTimeout, errorMappingOverrides, customHeaders, true, cancellationToken); } public Task<T> GetAsync<T>( Uri requestUri, IDictionary<HttpStatusCode, Func<HttpResponseMessage, Task<Exception>>> errorMappingOverrides, IDictionary<string, string> customHeaders, bool throwIfNotFound, CancellationToken cancellationToken) { return this.GetAsync<T>(requestUri, this.defaultOperationTimeout, errorMappingOverrides, customHeaders, throwIfNotFound, cancellationToken); } public async Task<T> GetAsync<T>( Uri requestUri, TimeSpan operationTimeout, IDictionary<HttpStatusCode, Func<HttpResponseMessage, Task<Exception>>> errorMappingOverrides, IDictionary<string, string> customHeaders, bool throwIfNotFound, CancellationToken cancellationToken) { T result = default(T); if (operationTimeout != this.defaultOperationTimeout && operationTimeout > TimeSpan.Zero) { if (throwIfNotFound) { await this.ExecuteWithOperationTimeoutAsync( HttpMethod.Get, new Uri(this.baseAddress, requestUri), operationTimeout, (requestMsg, token) => AddCustomHeaders(requestMsg, customHeaders), IsMappedToException, async (message, token) => result = await ReadResponseMessageAsync<T>(message, token).ConfigureAwait(false), errorMappingOverrides, cancellationToken).ConfigureAwait(false); } else { await this.ExecuteWithOperationTimeoutAsync( HttpMethod.Get, new Uri(this.baseAddress, requestUri), operationTimeout, (requestMsg, token) => AddCustomHeaders(requestMsg, customHeaders), message => !(message.IsSuccessStatusCode || message.StatusCode == HttpStatusCode.NotFound), async (message, token) => result = message.StatusCode == HttpStatusCode.NotFound ? (default(T)) : await ReadResponseMessageAsync<T>(message, token).ConfigureAwait(false), errorMappingOverrides, cancellationToken).ConfigureAwait(false); } } else { if (throwIfNotFound) { await this.ExecuteAsync( HttpMethod.Get, new Uri(this.baseAddress, requestUri), (requestMsg, token) => AddCustomHeaders(requestMsg, customHeaders), async (message, token) => result = await ReadResponseMessageAsync<T>(message, token).ConfigureAwait(false), errorMappingOverrides, cancellationToken).ConfigureAwait(false); } else { await this.ExecuteAsync( this.httpClientObj, HttpMethod.Get, new Uri(this.baseAddress, requestUri), (requestMsg, token) => AddCustomHeaders(requestMsg, customHeaders), message => !(message.IsSuccessStatusCode || message.StatusCode == HttpStatusCode.NotFound), async (message, token) => result = message.StatusCode == HttpStatusCode.NotFound ? (default(T)) : await ReadResponseMessageAsync<T>(message, token).ConfigureAwait(false), errorMappingOverrides, cancellationToken).ConfigureAwait(false); } } return result; } public async Task<T> PutAsync<T>( Uri requestUri, T entity, PutOperationType operationType, IDictionary<HttpStatusCode, Func<HttpResponseMessage, Task<Exception>>> errorMappingOverrides, CancellationToken cancellationToken) where T : IETagHolder { T result = default(T); await this.ExecuteAsync( HttpMethod.Put, new Uri(this.baseAddress, requestUri), (requestMsg, token) => { InsertEtag(requestMsg, entity, operationType); #if NETSTANDARD1_3 || NETSTANDARD2_0 var str = Newtonsoft.Json.JsonConvert.SerializeObject(entity); requestMsg.Content = new StringContent(str, System.Text.Encoding.UTF8, "application/json"); #else requestMsg.Content = new ObjectContent<T>(entity, JsonFormatter); #endif return Task.FromResult(0); }, async (httpClient, token) => result = await ReadResponseMessageAsync<T>(httpClient, token).ConfigureAwait(false), errorMappingOverrides, cancellationToken).ConfigureAwait(false); return result; } public async Task<T2> PutAsync<T, T2>( Uri requestUri, T entity, IDictionary<HttpStatusCode, Func<HttpResponseMessage, Task<Exception>>> errorMappingOverrides, CancellationToken cancellationToken) { T2 result = default(T2); await this.ExecuteAsync( HttpMethod.Put, new Uri(this.baseAddress, requestUri), (requestMsg, token) => { #if NETSTANDARD1_3 || NETSTANDARD2_0 var str = Newtonsoft.Json.JsonConvert.SerializeObject(entity); requestMsg.Content = new StringContent(str, System.Text.Encoding.UTF8, "application/json"); #else requestMsg.Content = new ObjectContent<T>(entity, JsonFormatter); #endif return Task.FromResult(0); }, async (httpClient, token) => result = await ReadResponseMessageAsync<T2>(httpClient, token).ConfigureAwait(false), errorMappingOverrides, cancellationToken).ConfigureAwait(false); return result; } public async Task PutAsync<T>( Uri requestUri, T entity, string etag, PutOperationType operationType, IDictionary<HttpStatusCode, Func<HttpResponseMessage, Task<Exception>>> errorMappingOverrides, CancellationToken cancellationToken) { await this.ExecuteAsync( HttpMethod.Put, new Uri(this.baseAddress, requestUri), (requestMsg, token) => { InsertEtag(requestMsg, etag, operationType); #if NETSTANDARD1_3 || NETSTANDARD2_0 var str = Newtonsoft.Json.JsonConvert.SerializeObject(entity); requestMsg.Content = new StringContent(str, System.Text.Encoding.UTF8, "application/json"); #else requestMsg.Content = new ObjectContent<T>(entity, JsonFormatter); #endif return Task.FromResult(0); }, null, errorMappingOverrides, cancellationToken).ConfigureAwait(false); } public async Task<T2> PutAsync<T, T2>( Uri requestUri, T entity, string etag, PutOperationType operationType, IDictionary<HttpStatusCode, Func<HttpResponseMessage, Task<Exception>>> errorMappingOverrides, CancellationToken cancellationToken) { T2 result = default(T2); await this.ExecuteAsync( HttpMethod.Put, new Uri(this.baseAddress, requestUri), (requestMsg, token) => { // TODO: skintali: Use string etag when service side changes are ready InsertEtag(requestMsg, etag, operationType); #if NETSTANDARD1_3 || NETSTANDARD2_0 var str = Newtonsoft.Json.JsonConvert.SerializeObject(entity); requestMsg.Content = new StringContent(str, System.Text.Encoding.UTF8, "application/json"); #else requestMsg.Content = new ObjectContent<T>(entity, JsonFormatter); #endif return Task.FromResult(0); }, async (httpClient, token) => result = await ReadResponseMessageAsync<T2>(httpClient, token).ConfigureAwait(false), errorMappingOverrides, cancellationToken).ConfigureAwait(false); return result; } public async Task PatchAsync<T>(Uri requestUri, T entity, string etag, IDictionary<HttpStatusCode, Func<HttpResponseMessage, Task<Exception>>> errorMappingOverrides, CancellationToken cancellationToken) { await this.ExecuteAsync( new HttpMethod("PATCH"), new Uri(this.baseAddress, requestUri), (requestMsg, token) => { InsertEtag(requestMsg, etag, PutOperationType.UpdateEntity); #if NETSTANDARD1_3 || NETSTANDARD2_0 var str = Newtonsoft.Json.JsonConvert.SerializeObject(entity); requestMsg.Content = new StringContent(str, System.Text.Encoding.UTF8, "application/json"); #else requestMsg.Content = new ObjectContent<T>(entity, JsonFormatter); #endif return Task.FromResult(0); }, null, errorMappingOverrides, cancellationToken).ConfigureAwait(false); } public async Task<T2> PatchAsync<T, T2>(Uri requestUri, T entity, string etag, PutOperationType putOperationType, IDictionary<HttpStatusCode, Func<HttpResponseMessage, Task<Exception>>> errorMappingOverrides, CancellationToken cancellationToken) { T2 result = default(T2); await this.ExecuteAsync( new HttpMethod("PATCH"), new Uri(this.baseAddress, requestUri), (requestMsg, token) => { InsertEtag(requestMsg, etag, putOperationType); #if NETSTANDARD1_3 || NETSTANDARD2_0 var str = Newtonsoft.Json.JsonConvert.SerializeObject(entity); requestMsg.Content = new StringContent(str, System.Text.Encoding.UTF8, "application/json"); #else requestMsg.Content = new ObjectContent<T>(entity, JsonFormatter); #endif return Task.FromResult(0); }, async (httpClient, token) => result = await ReadResponseMessageAsync<T2>(httpClient, token).ConfigureAwait(false), errorMappingOverrides, cancellationToken).ConfigureAwait(false); return result; } static async Task<T> ReadResponseMessageAsync<T>(HttpResponseMessage message, CancellationToken token) { if (typeof(T) == typeof(HttpResponseMessage)) { return (T)(object)message; } #if NETSTANDARD1_3 || NETSTANDARD2_0 var str = await message.Content.ReadAsStringAsync().ConfigureAwait(false); T entity = Newtonsoft.Json.JsonConvert.DeserializeObject<T>(str); #else T entity = await message.Content.ReadAsAsync<T>(token).ConfigureAwait(false); #endif // Etag in the header is considered authoritative var eTagHolder = entity as IETagHolder; if (eTagHolder != null) { if (message.Headers.ETag != null && !string.IsNullOrWhiteSpace(message.Headers.ETag.Tag)) { // RDBug 3429280:Make the version field of Device object internal eTagHolder.ETag = message.Headers.ETag.Tag; } } return entity; } static Task AddCustomHeaders(HttpRequestMessage requestMessage, IDictionary<string, string> customHeaders) { if (customHeaders != null) { foreach (var header in customHeaders) { requestMessage.Headers.Add(header.Key, header.Value); } } return Task.FromResult(0); } static void InsertEtag(HttpRequestMessage requestMessage, IETagHolder entity, PutOperationType operationType) { if (operationType == PutOperationType.CreateEntity) { return; } if (operationType == PutOperationType.ForceUpdateEntity) { const string etag = "\"*\""; requestMessage.Headers.IfMatch.Add(new EntityTagHeaderValue(etag)); } else { InsertEtag(requestMessage, entity.ETag); } } static void InsertEtag(HttpRequestMessage requestMessage, string etag, PutOperationType operationType) { if (operationType == PutOperationType.CreateEntity) { return; } string etagString = "\"*\""; if (operationType == PutOperationType.ForceUpdateEntity) { requestMessage.Headers.IfMatch.Add(new EntityTagHeaderValue(etagString)); } else { InsertEtag(requestMessage, etag); } } static void InsertEtag(HttpRequestMessage requestMessage, string etag) { if (string.IsNullOrWhiteSpace(etag)) { throw new ArgumentException("The entity does not have its ETag set."); } if (!etag.StartsWith("\"", StringComparison.OrdinalIgnoreCase)) { etag = "\"" + etag; } if (!etag.EndsWith("\"", StringComparison.OrdinalIgnoreCase)) { etag = etag + "\""; } requestMessage.Headers.IfMatch.Add(new EntityTagHeaderValue(etag)); } IDictionary<HttpStatusCode, Func<HttpResponseMessage, Task<Exception>>> MergeErrorMapping( IDictionary<HttpStatusCode, Func<HttpResponseMessage, Task<Exception>>> errorMappingOverrides) { var mergedMapping = this.defaultErrorMapping.ToDictionary(mapping => mapping.Key, mapping => mapping.Value); if (errorMappingOverrides != null) { foreach (var @override in errorMappingOverrides) { mergedMapping[@override.Key] = @override.Value; } } return mergedMapping; } public Task PostAsync<T>( Uri requestUri, T entity, IDictionary<HttpStatusCode, Func<HttpResponseMessage, Task<Exception>>> errorMappingOverrides, IDictionary<string, string> customHeaders, CancellationToken cancellationToken) { return this.PostAsyncHelper( requestUri, entity, TimeSpan.Zero, errorMappingOverrides, customHeaders, null, null, ReadResponseMessageAsync<HttpResponseMessage>, cancellationToken); } public Task PostAsync<T>( Uri requestUri, T entity, IDictionary<HttpStatusCode, Func<HttpResponseMessage, Task<Exception>>> errorMappingOverrides, IDictionary<string, string> customHeaders, TimeSpan operationTimeout, CancellationToken cancellationToken) { return this.PostAsyncHelper( requestUri, entity, operationTimeout, errorMappingOverrides, customHeaders, null, null, ReadResponseMessageAsync<HttpResponseMessage>, cancellationToken); } public async Task<T2> PostAsync<T1, T2>( Uri requestUri, T1 entity, IDictionary<HttpStatusCode, Func<HttpResponseMessage, Task<Exception>>> errorMappingOverrides, IDictionary<string, string> customHeaders, CancellationToken cancellationToken) { T2 result = default(T2); await this.PostAsyncHelper( requestUri, entity, TimeSpan.Zero, errorMappingOverrides, customHeaders, null, null, async (message, token) => result = await ReadResponseMessageAsync<T2>(message, token).ConfigureAwait(false), cancellationToken).ConfigureAwait(false); return result; } public async Task<T2> PostAsync<T, T2>( Uri requestUri, T entity, TimeSpan operationTimeout, IDictionary<HttpStatusCode, Func<HttpResponseMessage, Task<Exception>>> errorMappingOverrides, IDictionary<string, string> customHeaders, CancellationToken cancellationToken) { T2 result = default(T2); await this.PostAsyncHelper( requestUri, entity, operationTimeout, errorMappingOverrides, customHeaders, null, null, async (message, token) => result = await ReadResponseMessageAsync<T2>(message, token).ConfigureAwait(false), cancellationToken).ConfigureAwait(false); return result; } public async Task<T2> PostAsync<T, T2>( Uri requestUri, T entity, IDictionary<HttpStatusCode, Func<HttpResponseMessage, Task<Exception>>> errorMappingOverrides, IDictionary<string, string> customHeaders, MediaTypeHeaderValue customContentType, ICollection<string> customContentEncoding, CancellationToken cancellationToken) { T2 result = default(T2); await this.PostAsyncHelper( requestUri, entity, TimeSpan.Zero, errorMappingOverrides, customHeaders, customContentType, customContentEncoding, async (message, token) => result = await ReadResponseMessageAsync<T2>(message, token).ConfigureAwait(false), cancellationToken).ConfigureAwait(false); return result; } public async Task<HttpResponseMessage> PostAsync<T>( Uri requestUri, T entity, IDictionary<HttpStatusCode, Func<HttpResponseMessage, Task<Exception>>> errorMappingOverrides, IDictionary<string, string> customHeaders, MediaTypeHeaderValue customContentType, ICollection<string> customContentEncoding, CancellationToken cancellationToken) { HttpResponseMessage result = default(HttpResponseMessage); await this.PostAsyncHelper( requestUri, entity, TimeSpan.Zero, errorMappingOverrides, customHeaders, customContentType, customContentEncoding, async (message, token) => result = message, cancellationToken).ConfigureAwait(false); return result; } Task PostAsyncHelper<T1>( Uri requestUri, T1 entity, TimeSpan operationTimeout, IDictionary<HttpStatusCode, Func<HttpResponseMessage, Task<Exception>>> errorMappingOverrides, IDictionary<string, string> customHeaders, MediaTypeHeaderValue customContentType, ICollection<string> customContentEncoding, Func<HttpResponseMessage, CancellationToken, Task> processResponseMessageAsync, CancellationToken cancellationToken) { Func<HttpRequestMessage, CancellationToken, Task> modifyRequestMessageFunc = (requestMsg, token) => { AddCustomHeaders(requestMsg, customHeaders); if (entity != null) { if (typeof(T1) == typeof(byte[])) { requestMsg.Content = new ByteArrayContent((byte[])(object)entity); } else if (typeof(T1) == typeof(string)) { // only used to send batched messages on Http runtime requestMsg.Content = new StringContent((string)(object)entity); requestMsg.Content.Headers.ContentType = new MediaTypeHeaderValue(CommonConstants.BatchedMessageContentType); } else { var str = Newtonsoft.Json.JsonConvert.SerializeObject(entity); requestMsg.Content = new StringContent(str, System.Text.Encoding.UTF8, "application/json"); } } if (customContentType != null) { requestMsg.Content.Headers.ContentType = customContentType; } if (customContentEncoding != null && customContentEncoding.Count > 0) { foreach (string contentEncoding in customContentEncoding) { requestMsg.Content.Headers.ContentEncoding.Add(contentEncoding); } } return Task.FromResult(0); }; if (operationTimeout != this.defaultOperationTimeout && operationTimeout > TimeSpan.Zero) { return this.ExecuteWithOperationTimeoutAsync( HttpMethod.Post, new Uri(this.baseAddress, requestUri), operationTimeout, modifyRequestMessageFunc, IsMappedToException, processResponseMessageAsync, errorMappingOverrides, cancellationToken); } else { return this.ExecuteAsync( HttpMethod.Post, new Uri(this.baseAddress, requestUri), modifyRequestMessageFunc, processResponseMessageAsync, errorMappingOverrides, cancellationToken); } } public Task DeleteAsync<T>( Uri requestUri, T entity, IDictionary<HttpStatusCode, Func<HttpResponseMessage, Task<Exception>>> errorMappingOverrides, IDictionary<string, string> customHeaders, CancellationToken cancellationToken) where T : IETagHolder { return this.ExecuteAsync( HttpMethod.Delete, new Uri(this.baseAddress, requestUri), (requestMsg, token) => { InsertEtag(requestMsg, entity.ETag); AddCustomHeaders(requestMsg, customHeaders); return TaskHelpers.CompletedTask; }, null, errorMappingOverrides, cancellationToken); } public async Task<T> DeleteAsync<T>( Uri requestUri, IDictionary<HttpStatusCode, Func<HttpResponseMessage, Task<Exception>>> errorMappingOverrides, IDictionary<string, string> customHeaders, CancellationToken cancellationToken) { T result = default(T); await this.ExecuteAsync( HttpMethod.Delete, new Uri(this.baseAddress, requestUri), (requestMsg, token) => { AddCustomHeaders(requestMsg, customHeaders); return TaskHelpers.CompletedTask; }, async (message, token) => result = await ReadResponseMessageAsync<T>(message, token).ConfigureAwait(false), errorMappingOverrides, cancellationToken).ConfigureAwait(false); return result; } Task ExecuteAsync( HttpMethod httpMethod, Uri requestUri, Func<HttpRequestMessage, CancellationToken, Task> modifyRequestMessageAsync, Func<HttpResponseMessage, CancellationToken, Task> processResponseMessageAsync, IDictionary<HttpStatusCode, Func<HttpResponseMessage, Task<Exception>>> errorMappingOverrides, CancellationToken cancellationToken) { return this.ExecuteAsync( this.httpClientObj, httpMethod, requestUri, modifyRequestMessageAsync, IsMappedToException, processResponseMessageAsync, errorMappingOverrides, cancellationToken); } Task ExecuteWithOperationTimeoutAsync( HttpMethod httpMethod, Uri requestUri, TimeSpan operationTimeout, Func<HttpRequestMessage, CancellationToken, Task> modifyRequestMessageAsync, Func<HttpResponseMessage, bool> isMappedToException, Func<HttpResponseMessage, CancellationToken, Task> processResponseMessageAsync, IDictionary<HttpStatusCode, Func<HttpResponseMessage, Task<Exception>>> errorMappingOverrides, CancellationToken cancellationToken) { var cts = new CancellationTokenSource(operationTimeout); CancellationTokenSource linkedCts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, cts.Token); return this.ExecuteAsync( this.httpClientObjWithPerRequestTimeout, httpMethod, requestUri, modifyRequestMessageAsync, IsMappedToException, processResponseMessageAsync, errorMappingOverrides, linkedCts.Token); } public static bool IsMappedToException(HttpResponseMessage message) { bool isMappedToException = !message.IsSuccessStatusCode; // Get any IotHubErrorCode information from the header for special case exemption of exception throwing string iotHubErrorCodeAsString = message.Headers.GetFirstValueOrNull(CommonConstants.IotHubErrorCode); ErrorCode iotHubErrorCode; if (Enum.TryParse(iotHubErrorCodeAsString, out iotHubErrorCode)) { switch (iotHubErrorCode) { case ErrorCode.BulkRegistryOperationFailure: isMappedToException = false; break; } } return isMappedToException; } async Task ExecuteAsync( HttpClient httpClient, HttpMethod httpMethod, Uri requestUri, Func<HttpRequestMessage, CancellationToken, Task> modifyRequestMessageAsync, Func<HttpResponseMessage, bool> isMappedToException, Func<HttpResponseMessage, CancellationToken, Task> processResponseMessageAsync, IDictionary<HttpStatusCode, Func<HttpResponseMessage, Task<Exception>>> errorMappingOverrides, CancellationToken cancellationToken) { IDictionary<HttpStatusCode, Func<HttpResponseMessage, Task<Exception>>> mergedErrorMapping = this.MergeErrorMapping(errorMappingOverrides); using (var msg = new HttpRequestMessage(httpMethod, requestUri)) { msg.Headers.Add(HttpRequestHeader.Authorization.ToString(), this.authenticationHeaderProvider.GetAuthorizationHeader()); msg.Headers.Add(HttpRequestHeader.UserAgent.ToString(), Utils.GetClientVersion()); if (modifyRequestMessageAsync != null) await modifyRequestMessageAsync(msg, cancellationToken).ConfigureAwait(false); // TODO: pradeepc - find out the list of exceptions that HttpClient can throw. HttpResponseMessage responseMsg; try { responseMsg = await httpClient.SendAsync(msg, cancellationToken).ConfigureAwait(false); if (responseMsg == null) { throw new InvalidOperationException("The response message was null when executing operation {0}.".FormatInvariant(httpMethod)); } if (!isMappedToException(responseMsg)) { if (processResponseMessageAsync != null) { await processResponseMessageAsync(responseMsg, cancellationToken).ConfigureAwait(false); } } } catch (AggregateException ex) { var innerExceptions = ex.Flatten().InnerExceptions; if (innerExceptions.Any(Fx.IsFatal)) { throw; } // Apparently HttpClient throws AggregateException when a timeout occurs. // TODO: pradeepc - need to confirm this with ASP.NET team if (innerExceptions.Any(e => e is TimeoutException)) { throw new IotHubCommunicationException(ex.Message, ex); } throw new IotHubException(ex.Message, ex); } catch (TimeoutException ex) { throw new IotHubCommunicationException(ex.Message, ex); } catch (IOException ex) { throw new IotHubCommunicationException(ex.Message, ex); } catch (HttpRequestException ex) { throw new IotHubCommunicationException(ex.Message, ex); } catch (TaskCanceledException ex) { // Unfortunately TaskCanceledException is thrown when HttpClient times out. if (cancellationToken.IsCancellationRequested) { throw new IotHubException(ex.Message, ex); } throw new IotHubCommunicationException(string.Format(CultureInfo.InvariantCulture, "The {0} operation timed out.", httpMethod), ex); } catch (Exception ex) { if (Fx.IsFatal(ex)) throw; throw new IotHubException(ex.Message, ex); } if (isMappedToException(responseMsg)) { Exception mappedEx = await MapToExceptionAsync(responseMsg, mergedErrorMapping).ConfigureAwait(false); throw mappedEx; } } } static async Task<Exception> MapToExceptionAsync( HttpResponseMessage response, IDictionary<HttpStatusCode, Func<HttpResponseMessage, Task<Exception>>> errorMapping) { Func<HttpResponseMessage, Task<Exception>> func; if (!errorMapping.TryGetValue(response.StatusCode, out func)) { return new IotHubException( await ExceptionHandlingHelper.GetExceptionMessageAsync(response).ConfigureAwait(false), isTransient: true); } var mapToExceptionFunc = errorMapping[response.StatusCode]; var exception = mapToExceptionFunc(response); return await exception.ConfigureAwait(false); } public void Dispose() { if (!this.isDisposed) { this.httpClientObj?.Dispose(); this.httpClientObjWithPerRequestTimeout?.Dispose(); this.httpClientObj = null; this.httpClientObjWithPerRequestTimeout = null; } this.isDisposed = true; } } }
42.12313
193
0.572354
[ "MIT" ]
StannieV/IoTHubDeviceExplorer
common/src/service/HttpClientHelper.cs
36,607
C#
/* * TreeListView - A listview that can show a tree of objects in a column * * Author: Phillip Piper * Date: 23/09/2008 11:15 AM * * Change log: * 2014-10-08 JPP - Fixed an issue where pre-expanded branches would not initially expand properly * 2014-09-29 JPP - Fixed issue where RefreshObject() on a root object could cause exceptions * - Fixed issue where CollapseAll() while filtering could cause exception * 2014-03-09 JPP - Fixed issue where removing a branches only child and then calling RefreshObject() * could throw an exception. * v2.7 * 2014-02-23 JPP - Added Reveal() method to show a deeply nested models. * 2014-02-05 JPP - Fix issue where refreshing a non-root item would collapse all expanded children of that item * 2014-02-01 JPP - ClearObjects() now actually, you know, clears objects :) * - Corrected issue where Expanded event was being raised twice. * - RebuildChildren() no longer checks if CanExpand is true before rebuilding. * 2014-01-16 JPP - Corrected an off-by-1 error in hit detection, which meant that clicking in the last 16 pixels * of an items label was being ignored. * 2013-11-20 JPP - Moved event triggers into Collapse() and Expand() so that the events are always triggered. * - CheckedObjects now includes objects that are in a branch that is currently collapsed * - CollapseAll() and ExpandAll() now trigger cancellable events * 2013-09-29 JPP - Added TreeFactory to allow the underlying Tree to be replaced by another implementation. * 2013-09-23 JPP - Fixed long standing issue where RefreshObject() would not work on root objects * which overrode Equals()/GetHashCode(). * 2013-02-23 JPP - Added HierarchicalCheckboxes. When this is true, the checkedness of a parent * is an synopsis of the checkedness of its children. When all children are checked, * the parent is checked. When all children are unchecked, the parent is unchecked. * If some children are checked and some are not, the parent is indeterminate. * v2.6 * 2012-10-25 JPP - Circumvent annoying issue in ListView control where changing * selection would leave artifacts on the control. * 2012-08-10 JPP - Don't trigger selection changed events during expands * * v2.5.1 * 2012-04-30 JPP - Fixed issue where CheckedObjects would return model objects that had been filtered out. * - Allow any column to render the tree, not just column 0 (still not sure about this one) * v2.5.0 * 2011-04-20 JPP - Added ExpandedObjects property and RebuildAll() method. * 2011-04-09 JPP - Added Expanding, Collapsing, Expanded and Collapsed events. * The ..ing events are cancellable. These are only fired in response * to user actions. * v2.4.1 * 2010-06-15 JPP - Fixed issue in Tree.RemoveObjects() which resulted in removed objects * being reported as still existing. * v2.3 * 2009-09-01 JPP - Fixed off-by-one error that was messing up hit detection * 2009-08-27 JPP - Fixed issue when dragging a node from one place to another in the tree * v2.2.1 * 2009-07-14 JPP - Clicks to the left of the expander in tree cells are now ignored. * v2.2 * 2009-05-12 JPP - Added tree traverse operations: GetParent and GetChildren. * - Added DiscardAllState() to completely reset the TreeListView. * 2009-05-10 JPP - Removed all unsafe code * 2009-05-09 JPP - Fixed issue where any command (Expand/Collapse/Refresh) on a model * object that was once visible but that is currently in a collapsed branch * would cause the control to crash. * 2009-05-07 JPP - Fixed issue where RefreshObjects() would fail when none of the given * objects were present/visible. * 2009-04-20 JPP - Fixed issue where calling Expand() on an already expanded branch confused * the display of the children (SF#2499313) * 2009-03-06 JPP - Calculate edit rectangle on column 0 more accurately * v2.1 * 2009-02-24 JPP - All commands now work when the list is empty (SF #2631054) * - TreeListViews can now be printed with ListViewPrinter * 2009-01-27 JPP - Changed to use new Renderer and HitTest scheme * 2009-01-22 JPP - Added RevealAfterExpand property. If this is true (the default), * after expanding a branch, the control scrolls to reveal as much of the * expanded branch as possible. * 2009-01-13 JPP - Changed TreeRenderer to work with visual styles are disabled * v2.0.1 * 2009-01-07 JPP - Made all public and protected methods virtual * - Changed some classes from 'internal' to 'protected' so that they * can be accessed by subclasses of TreeListView. * 2008-12-22 JPP - Added UseWaitCursorWhenExpanding property * - Made TreeRenderer public so that it can be subclassed * - Added LinePen property to TreeRenderer to allow the connection drawing * pen to be changed * - Fixed some rendering issues where the text highlight rect was miscalculated * - Fixed connection line problem when there is only a single root * v2.0 * 2008-12-10 JPP - Expand/collapse with mouse now works when there is no SmallImageList. * 2008-12-01 JPP - Search-by-typing now works. * 2008-11-26 JPP - Corrected calculation of expand/collapse icon (SF#2338819) * - Fixed ugliness with dotted lines in renderer (SF#2332889) * - Fixed problem with custom selection colors (SF#2338805) * 2008-11-19 JPP - Expand/collapse now preserve the selection -- more or less :) * - Overrode RefreshObjects() to rebuild the given objects and their children * 2008-11-05 JPP - Added ExpandAll() and CollapseAll() commands * - CanExpand is no longer cached * - Renamed InitialBranches to RootModels since it deals with model objects * 2008-09-23 JPP Initial version * * TO DO: * * Copyright (C) 2006-2014 Phillip Piper * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * If you wish to use this code in a closed source application, please contact phillip_piper@bigfoot.com. */ using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Windows.Forms; namespace BrightIdeasSoftware { /// <summary> /// A TreeListView combines an expandable tree structure with list view columns. /// </summary> /// <remarks> /// <para>To support tree operations, two delegates must be provided:</para> /// <list type="table"> /// <item> /// <term> /// CanExpandGetter /// </term> /// <description> /// This delegate must accept a model object and return a boolean indicating /// if that model should be expandable. /// </description> /// </item> /// <item> /// <term> /// ChildrenGetter /// </term> /// <description> /// This delegate must accept a model object and return an IEnumerable of model /// objects that will be displayed as children of the parent model. This delegate will only be called /// for a model object if the CanExpandGetter has already returned true for that model. /// </description> /// </item> /// <item> /// <term> /// ParentGetter /// </term> /// <description> /// This delegate must accept a model object and return the parent model. /// This delegate will only be called when HierarchicalCheckboxes is true OR when Reveal() is called. /// </description> /// </item> /// </list> /// <para> /// The top level branches of the tree are set via the Roots property. SetObjects(), AddObjects() /// and RemoveObjects() are interpreted as operations on this collection of roots. /// </para> /// <para> /// To add new children to an existing branch, make changes to your model objects and then /// call RefreshObject() on the parent. /// </para> /// <para>The tree must be a directed acyclic graph -- no cycles are allowed. Put more mundanely, /// each model object must appear only once in the tree. If the same model object appears in two /// places in the tree, the control will become confused.</para> /// </remarks> public partial class TreeListView : VirtualObjectListView { /// <summary> /// Make a default TreeListView /// </summary> public TreeListView() { this.OwnerDraw = true; this.View = View.Details; this.CheckedObjectsMustStillExistInList = false; // ReSharper disable DoNotCallOverridableMethodsInConstructor this.RegenerateTree(); this.TreeColumnRenderer = new TreeRenderer(); // ReSharper restore DoNotCallOverridableMethodsInConstructor // This improves hit detection even if we don't have any state image this.SmallImageList = new ImageList(); // this.StateImageList.ImageSize = new Size(6, 6); } //------------------------------------------------------------------------------------------ // Properties /// <summary> /// This is the delegate that will be used to decide if a model object can be expanded. /// </summary> [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public virtual CanExpandGetterDelegate CanExpandGetter { get { return this.TreeModel.CanExpandGetter; } set { this.TreeModel.CanExpandGetter = value; } } /// <summary> /// Gets whether or not this listview is capable of showing groups /// </summary> [Browsable(false)] public override bool CanShowGroups { get { return false; } } /// <summary> /// This is the delegate that will be used to fetch the children of a model object /// </summary> /// <remarks>This delegate will only be called if the CanExpand delegate has /// returned true for the model object.</remarks> [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public virtual ChildrenGetterDelegate ChildrenGetter { get { return this.TreeModel.ChildrenGetter; } set { this.TreeModel.ChildrenGetter = value; } } /// <summary> /// This is the delegate that will be used to fetch the parent of a model object /// </summary> /// <returns>The parent of the given model, or null if the model doesn't exist or /// if the model is a root</returns> [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public ParentGetterDelegate ParentGetter { get { return parentGetter; } set { parentGetter = value; } } private ParentGetterDelegate parentGetter; /// <summary> /// Get or set the collection of model objects that are checked. /// When setting this property, any row whose model object isn't /// in the given collection will be unchecked. Setting to null is /// equivalent to unchecking all. /// </summary> /// <remarks> /// <para> /// This property returns a simple collection. Changes made to the returned /// collection do NOT affect the list. This is different to the behaviour of /// CheckedIndicies collection. /// </para> /// <para> /// When getting CheckedObjects, the performance of this method is O(n) where n is the number of checked objects. /// When setting CheckedObjects, the performance of this method is O(n) where n is the number of checked objects plus /// the number of objects to be checked. /// </para> /// <para> /// If the ListView is not currently showing CheckBoxes, this property does nothing. It does /// not remember any check box settings made. /// </para> /// </remarks> public override IList CheckedObjects { get { return base.CheckedObjects; } set { ArrayList objectsToRecalculate = new ArrayList(this.CheckedObjects); if (value != null) objectsToRecalculate.AddRange(value); base.CheckedObjects = value; if (this.HierarchicalCheckboxes) RecalculateHierarchicalCheckBoxGraph(objectsToRecalculate); } } /// <summary> /// Gets or sets the model objects that are expanded. /// </summary> /// <remarks> /// <para>This can be used to expand model objects before they are seen.</para> /// <para> /// Setting this does *not* force the control to rebuild /// its display. You need to call RebuildAll(true). /// </para> /// </remarks> [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public IEnumerable ExpandedObjects { get { return this.TreeModel.mapObjectToExpanded.Keys; } set { this.TreeModel.mapObjectToExpanded.Clear(); if (value != null) { foreach (object x in value) this.TreeModel.SetModelExpanded(x, true); } } } /// <summary> /// Gets or sets the filter that is applied to our whole list of objects. /// TreeListViews do not currently support whole list filters. /// </summary> [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public override IListFilter ListFilter { get { return null; } set { System.Diagnostics.Debug.Assert(value == null, "TreeListView do not support ListFilters"); } } /// <summary> /// Gets or sets whether this tree list view will display hierarchical checkboxes. /// Hierarchical checkboxes is when a parent's "checkedness" is calculated from /// the "checkedness" of its children. If all children are checked, the parent /// will be checked. If all children are unchecked, the parent will also be unchecked. /// If some children are checked and others are not, the parent will be indeterminate. /// </summary> [Category("ObjectListView"), Description("Show hierarchical checkboxes be enabled?"), DefaultValue(false)] public virtual bool HierarchicalCheckboxes { get { return this.hierarchicalCheckboxes; } set { if (this.hierarchicalCheckboxes == value) return; this.hierarchicalCheckboxes = value; this.CheckBoxes = value; if (value) this.TriStateCheckBoxes = false; } } private bool hierarchicalCheckboxes; /// <summary> /// Gets or sets the collection of root objects of the tree /// </summary> [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public override IEnumerable Objects { get { return this.Roots; } set { this.Roots = value; } } /// <summary> /// Gets the collection of objects that will be considered when creating clusters /// (which are used to generate Excel-like column filters) /// </summary> [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public override IEnumerable ObjectsForClustering { get { for (int i = 0; i < this.TreeModel.GetObjectCount(); i++) yield return this.TreeModel.GetNthObject(i); } } /// <summary> /// After expanding a branch, should the TreeListView attempts to show as much of the /// revealed descendents as possible. /// </summary> [Category("ObjectListView"), Description("Should the parent of an expand subtree be scrolled to the top revealing the children?"), DefaultValue(true)] public bool RevealAfterExpand { get { return revealAfterExpand; } set { revealAfterExpand = value; } } private bool revealAfterExpand = true; /// <summary> /// The model objects that form the top level branches of the tree. /// </summary> /// <remarks>Setting this does <b>NOT</b> reset the state of the control. /// In particular, it does not collapse branches.</remarks> [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public virtual IEnumerable Roots { get { return this.TreeModel.RootObjects; } set { this.TreeColumnRenderer = this.TreeColumnRenderer; this.TreeModel.RootObjects = value ?? new ArrayList(); this.UpdateVirtualListSize(); } } /// <summary> /// Make sure that at least one column is displaying a tree. /// If no columns is showing the tree, make column 0 do it. /// </summary> protected virtual void EnsureTreeRendererPresent(TreeRenderer renderer) { if (this.Columns.Count == 0) return; foreach (OLVColumn col in this.Columns) { if (col.Renderer is TreeRenderer) { col.Renderer = renderer; return; } } // No column held a tree renderer, so give column 0 one OLVColumn columnZero = this.GetColumn(0); columnZero.Renderer = renderer; columnZero.WordWrap = columnZero.WordWrap; } /// <summary> /// Gets or sets the renderer that will be used to draw the tree structure. /// Setting this to null resets the renderer to default. /// </summary> /// <remarks>If a column is currently rendering the tree, the renderer /// for that column will be replaced. If no column is rendering the tree, /// column 0 will be given this renderer.</remarks> [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public virtual TreeRenderer TreeColumnRenderer { get { return treeRenderer ?? (treeRenderer = new TreeRenderer()); } set { treeRenderer = value ?? new TreeRenderer(); EnsureTreeRendererPresent(treeRenderer); } } private TreeRenderer treeRenderer; /// <summary> /// This is the delegate that will be used to create the underlying Tree structure /// that the TreeListView uses to manage the information about the tree. /// </summary> /// <remarks> /// <para>The factory must not return null. </para> /// <para> /// Most users of TreeListView will never have to use this delegate. /// </para> /// </remarks> [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public TreeFactoryDelegate TreeFactory { get { return treeFactory; } set { treeFactory = value; } } private TreeFactoryDelegate treeFactory; /// <summary> /// Should a wait cursor be shown when a branch is being expanded? /// </summary> /// <remarks>When this is true, the wait cursor will be shown whilst the children of the /// branch are being fetched. If the children of the branch have already been cached, /// the cursor will not change.</remarks> [Category("ObjectListView"), Description("Should a wait cursor be shown when a branch is being expanded?"), DefaultValue(true)] public virtual bool UseWaitCursorWhenExpanding { get { return useWaitCursorWhenExpanding; } set { useWaitCursorWhenExpanding = value; } } private bool useWaitCursorWhenExpanding = true; /// <summary> /// Gets the model that is used to manage the tree structure /// </summary> /// <remarks> /// Don't mess with this property unless you really know what you are doing. /// If you don't already know what it's for, you don't need it.</remarks> [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public Tree TreeModel { get { return this.treeModel; } protected set { this.treeModel = value; } } private Tree treeModel; //------------------------------------------------------------------------------------------ // Accessing /// <summary> /// Return true if the branch at the given model is expanded /// </summary> /// <param name="model"></param> /// <returns></returns> public virtual bool IsExpanded(Object model) { Branch br = this.TreeModel.GetBranch(model); return (br != null && br.IsExpanded); } //------------------------------------------------------------------------------------------ // Commands /// <summary> /// Collapse the subtree underneath the given model /// </summary> /// <param name="model"></param> public virtual void Collapse(Object model) { if (this.GetItemCount() == 0) return; OLVListItem item = this.ModelToItem(model); TreeBranchCollapsingEventArgs args = new TreeBranchCollapsingEventArgs(model, item); this.OnCollapsing(args); if (args.Canceled) return; IList selection = this.SelectedObjects; int index = this.TreeModel.Collapse(model); if (index >= 0) { this.UpdateVirtualListSize(); this.SelectedObjects = selection; if (index < this.GetItemCount()) this.RedrawItems(index, this.GetItemCount() - 1, true); this.OnCollapsed(new TreeBranchCollapsedEventArgs(model, item)); } } /// <summary> /// Collapse all subtrees within this control /// </summary> public virtual void CollapseAll() { if (this.GetItemCount() == 0) return; TreeBranchCollapsingEventArgs args = new TreeBranchCollapsingEventArgs(null, null); this.OnCollapsing(args); if (args.Canceled) return; IList selection = this.SelectedObjects; int index = this.TreeModel.CollapseAll(); if (index >= 0) { this.UpdateVirtualListSize(); this.SelectedObjects = selection; if (index < this.GetItemCount()) this.RedrawItems(index, this.GetItemCount() - 1, true); this.OnCollapsed(new TreeBranchCollapsedEventArgs(null, null)); } } /// <summary> /// Remove all items from this list /// </summary> /// <remark>This method can safely be called from background threads.</remark> public override void ClearObjects() { if (this.InvokeRequired) this.Invoke(new MethodInvoker(this.ClearObjects)); else { this.Roots = null; this.DiscardAllState(); } } /// <summary> /// Collapse all roots and forget everything we know about all models /// </summary> public virtual void DiscardAllState() { this.CheckStateMap.Clear(); this.RebuildAll(false); } /// <summary> /// Expand the subtree underneath the given model object /// </summary> /// <param name="model"></param> public virtual void Expand(Object model) { if (this.GetItemCount() == 0) return; // Give the world a chance to cancel the expansion OLVListItem item = this.ModelToItem(model); TreeBranchExpandingEventArgs args = new TreeBranchExpandingEventArgs(model, item); this.OnExpanding(args); if (args.Canceled) return; // Remember the selection so we can put it back later IList selection = this.SelectedObjects; // Expand the model first int index = this.TreeModel.Expand(model); if (index < 0) return; // Update the size of the list and restore the selection this.UpdateVirtualListSize(); using (this.SuspendSelectionEventsDuring()) this.SelectedObjects = selection; // Redraw the items that were changed by the expand operation this.RedrawItems(index, this.GetItemCount() - 1, true); this.OnExpanded(new TreeBranchExpandedEventArgs(model, item)); if (this.RevealAfterExpand && index > 0) { // TODO: This should be a separate method this.BeginUpdate(); try { int countPerPage = NativeMethods.GetCountPerPage(this); int descedentCount = this.TreeModel.GetVisibleDescendentCount(model); // If all of the descendents can be shown in the window, make sure that last one is visible. // If all the descendents can't fit into the window, move the model to the top of the window // (which will show as many of the descendents as possible) if (descedentCount < countPerPage) { this.EnsureVisible(index + descedentCount); } else { this.TopItemIndex = index; } } finally { this.EndUpdate(); } } } /// <summary> /// Expand all the branches within this tree recursively. /// </summary> /// <remarks>Be careful: this method could take a long time for large trees.</remarks> public virtual void ExpandAll() { if (this.GetItemCount() == 0) return; // Give the world a chance to cancel the expansion TreeBranchExpandingEventArgs args = new TreeBranchExpandingEventArgs(null, null); this.OnExpanding(args); if (args.Canceled) return; IList selection = this.SelectedObjects; int index = this.TreeModel.ExpandAll(); if (index < 0) return; this.UpdateVirtualListSize(); using (this.SuspendSelectionEventsDuring()) this.SelectedObjects = selection; this.RedrawItems(index, this.GetItemCount() - 1, true); this.OnExpanded(new TreeBranchExpandedEventArgs(null, null)); } /// <summary> /// Completely rebuild the tree structure /// </summary> /// <param name="preserveState">If true, the control will try to preserve selection and expansion</param> public virtual void RebuildAll(bool preserveState) { int previousTopItemIndex = preserveState ? this.TopItemIndex : -1; this.RebuildAll( preserveState ? this.SelectedObjects : null, preserveState ? this.ExpandedObjects : null, preserveState ? this.CheckedObjects : null); if (preserveState) this.TopItemIndex = previousTopItemIndex; } /// <summary> /// Completely rebuild the tree structure /// </summary> /// <param name="selected">If not null, this list of objects will be selected after the tree is rebuilt</param> /// <param name="expanded">If not null, this collection of objects will be expanded after the tree is rebuilt</param> /// <param name="checkedObjects">If not null, this collection of objects will be checked after the tree is rebuilt</param> protected virtual void RebuildAll(IList selected, IEnumerable expanded, IList checkedObjects) { // Remember the bits of info we don't want to forget (anyone ever see Memento?) IEnumerable roots = this.Roots; CanExpandGetterDelegate canExpand = this.CanExpandGetter; ChildrenGetterDelegate childrenGetter = this.ChildrenGetter; try { this.BeginUpdate(); // Give ourselves a new data structure this.RegenerateTree(); // Put back the bits we didn't want to forget this.CanExpandGetter = canExpand; this.ChildrenGetter = childrenGetter; if (expanded != null) this.ExpandedObjects = expanded; this.Roots = roots; if (selected != null) this.SelectedObjects = selected; if (checkedObjects != null) this.CheckedObjects = checkedObjects; } finally { this.EndUpdate(); } } /// <summary> /// Unroll all the ancestors of the given model and make sure it is then visible. /// </summary> /// <remarks>This works best when a ParentGetter is installed.</remarks> /// <param name="modelToReveal">The object to be revealed</param> /// <param name="selectAfterReveal">If true, the model will be selected and focused after being revealed</param> /// <returns>True if the object was found and revealed. False if it was not found.</returns> public virtual void Reveal(object modelToReveal, bool selectAfterReveal) { // Collect all the ancestors of the model ArrayList ancestors = new ArrayList(); foreach (object ancestor in this.GetAncestors(modelToReveal)) ancestors.Add(ancestor); // Arrange them from root down to the model's immediate parent ancestors.Reverse(); try { this.BeginUpdate(); foreach (object ancestor in ancestors) this.Expand(ancestor); this.EnsureModelVisible(modelToReveal); if (selectAfterReveal) this.SelectObject(modelToReveal, true); } finally { this.EndUpdate(); } } /// <summary> /// Update the rows that are showing the given objects /// </summary> public override void RefreshObjects(IList modelObjects) { if (this.InvokeRequired) { this.Invoke((MethodInvoker) delegate { this.RefreshObjects(modelObjects); }); return; } // There is no point in refreshing anything if the list is empty if (this.GetItemCount() == 0) return; // Remember the selection so we can put it back later IList selection = this.SelectedObjects; // We actually need to refresh the parents. // Refreshes on root objects have to be handled differently ArrayList updatedRoots = new ArrayList(); Hashtable modelsAndParents = new Hashtable(); foreach (Object model in modelObjects) { if (model == null) continue; modelsAndParents[model] = true; object parent = GetParent(model); if (parent == null) { updatedRoots.Add(model); } else { modelsAndParents[parent] = true; } } // Update any changed roots if (updatedRoots.Count > 0) { ArrayList newRoots = ObjectListView.EnumerableToArray(this.Roots, false); bool changed = false; foreach (Object model in updatedRoots) { int index = newRoots.IndexOf(model); if (index >= 0 && !ReferenceEquals(newRoots[index], model)) { newRoots[index] = model; changed = true; } } if (changed) this.Roots = newRoots; } // Refresh each object, remembering where the first update occurred int firstChange = Int32.MaxValue; foreach (Object model in modelsAndParents.Keys) { if (model != null) { int index = this.TreeModel.RebuildChildren(model); if (index >= 0) firstChange = Math.Min(firstChange, index); } } // If we didn't refresh any objects, don't do anything else if (firstChange >= this.GetItemCount()) return; this.ClearCachedInfo(); this.UpdateVirtualListSize(); this.SelectedObjects = selection; // Redraw everything from the first update to the end of the list this.RedrawItems(firstChange, this.GetItemCount() - 1, true); } /// <summary> /// Change the check state of the given object to be the given state. /// </summary> /// <remarks> /// If the given model object isn't in the list, we still try to remember /// its state, in case it is referenced in the future.</remarks> /// <param name="modelObject"></param> /// <param name="state"></param> /// <returns>True if the checkedness of the model changed</returns> protected override bool SetObjectCheckedness(object modelObject, CheckState state) { // If the checkedness of the given model changes AND this tree has // hierarchical checkboxes, then we need to update the checkedness of // its children, and recalculate the checkedness of the parent (recursively) if (!base.SetObjectCheckedness(modelObject, state)) return false; if (!this.HierarchicalCheckboxes) return true; // Give each child the same checkedness as the model CheckState? checkedness = this.GetCheckState(modelObject); if (!checkedness.HasValue || checkedness.Value == CheckState.Indeterminate) return true; foreach (object child in this.GetChildrenWithoutExpanding(modelObject)) { this.SetObjectCheckedness(child, checkedness.Value); } ArrayList args = new ArrayList(); args.Add(modelObject); this.RecalculateHierarchicalCheckBoxGraph(args); return true; } private IEnumerable GetChildrenWithoutExpanding(Object model) { Branch br = this.TreeModel.GetBranch(model); if (br == null || !br.CanExpand) return new ArrayList(); return br.Children; } /// <summary> /// Toggle the expanded state of the branch at the given model object /// </summary> /// <param name="model"></param> public virtual void ToggleExpansion(Object model) { if (this.IsExpanded(model)) this.Collapse(model); else this.Expand(model); } //------------------------------------------------------------------------------------------ // Commands - Tree traversal /// <summary> /// Return whether or not the given model can expand. /// </summary> /// <param name="model"></param> /// <remarks>The given model must have already been seen in the tree</remarks> public virtual bool CanExpand(Object model) { Branch br = this.TreeModel.GetBranch(model); return (br != null && br.CanExpand); } /// <summary> /// Return the model object that is the parent of the given model object. /// </summary> /// <param name="model"></param> /// <returns></returns> /// <remarks>The given model must have already been seen in the tree.</remarks> public virtual Object GetParent(Object model) { Branch br = this.TreeModel.GetBranch(model); return br == null || br.ParentBranch == null ? null : br.ParentBranch.Model; } /// <summary> /// Return the collection of model objects that are the children of the /// given model as they exist in the tree at the moment. /// </summary> /// <param name="model"></param> /// <remarks> /// <para> /// This method returns the collection of children as the tree knows them. If the given /// model has never been presented to the user (e.g. it belongs to a parent that has /// never been expanded), then this method will return an empty collection.</para> /// <para> /// Because of this, if you want to traverse the whole tree, this is not the method to use. /// It's better to traverse the your data model directly. /// </para> /// <para> /// If the given model has not already been seen in the tree or /// if it is not expandable, an empty collection will be returned. /// </para> /// </remarks> public virtual IEnumerable GetChildren(Object model) { Branch br = this.TreeModel.GetBranch(model); if (br == null || !br.CanExpand) return new ArrayList(); br.FetchChildren(); return br.Children; } //------------------------------------------------------------------------------------------ // Delegates /// <summary> /// Delegates of this type are use to decide if the given model object can be expanded /// </summary> /// <param name="model">The model under consideration</param> /// <returns>Can the given model be expanded?</returns> public delegate bool CanExpandGetterDelegate(Object model); /// <summary> /// Delegates of this type are used to fetch the children of the given model object /// </summary> /// <param name="model">The parent whose children should be fetched</param> /// <returns>An enumerable over the children</returns> public delegate IEnumerable ChildrenGetterDelegate(Object model); /// <summary> /// Delegates of this type are used to fetch the parent of the given model object. /// </summary> /// <param name="model">The child whose parent should be fetched</param> /// <returns>The parent of the child or null if the child is a root</returns> public delegate Object ParentGetterDelegate(Object model); /// <summary> /// Delegates of this type are used to create a new underlying Tree structure. /// </summary> /// <param name="view">The view for which the Tree is being created</param> /// <returns>A subclass of Tree</returns> public delegate Tree TreeFactoryDelegate(TreeListView view); //------------------------------------------------------------------------------------------ #region Implementation /// <summary> /// Handle a left button down event /// </summary> /// <param name="hti"></param> /// <returns></returns> protected override bool ProcessLButtonDown(OlvListViewHitTestInfo hti) { // Did they click in the expander? if (hti.HitTestLocation == HitTestLocation.ExpandButton) { this.PossibleFinishCellEditing(); this.ToggleExpansion(hti.RowObject); return true; } return base.ProcessLButtonDown(hti); } /// <summary> /// Create a OLVListItem for given row index /// </summary> /// <param name="itemIndex">The index of the row that is needed</param> /// <returns>An OLVListItem</returns> /// <remarks>This differs from the base method by also setting up the IndentCount property.</remarks> public override OLVListItem MakeListViewItem(int itemIndex) { OLVListItem olvItem = base.MakeListViewItem(itemIndex); Branch br = this.TreeModel.GetBranch(olvItem.RowObject); if (br != null) olvItem.IndentCount = br.Level; return olvItem; } /// <summary> /// Reinitialize the Tree structure /// </summary> protected virtual void RegenerateTree() { this.TreeModel = this.TreeFactory == null ? new Tree(this) : this.TreeFactory(this); Trace.Assert(this.TreeModel != null); this.VirtualListDataSource = this.TreeModel; } /// <summary> /// Recalculate the state of the checkboxes of all the items in the given list /// and their ancestors. /// </summary> /// <remarks>This only makes sense when HierarchicalCheckboxes is true.</remarks> /// <param name="toCheck"></param> protected virtual void RecalculateHierarchicalCheckBoxGraph(IList toCheck) { if (toCheck == null || toCheck.Count == 0) return; // Avoid recursive calculations if (isRecalculatingHierarchicalCheckBox) return; try { isRecalculatingHierarchicalCheckBox = true; foreach (object ancestor in CalculateDistinctAncestors(toCheck)) this.RecalculateSingleHierarchicalCheckBox(ancestor); } finally { isRecalculatingHierarchicalCheckBox = false; } } private bool isRecalculatingHierarchicalCheckBox; /// <summary> /// Recalculate the hierarchy state of the given item and its ancestors /// </summary> /// <remarks>This only makes sense when HierarchicalCheckboxes is true.</remarks> /// <param name="modelObject"></param> protected virtual void RecalculateSingleHierarchicalCheckBox(object modelObject) { if (modelObject == null) return; // Only branches have calculated check states. Leaf node checkedness is not calculated if (!this.CanExpand(modelObject)) return; // Set the checkedness of the given model based on the state of its children. CheckState? aggregate = null; foreach (object child in this.GetChildren(modelObject)) { CheckState? checkedness = this.GetCheckState(child); if (!checkedness.HasValue) continue; if (aggregate.HasValue) { if (aggregate.Value != checkedness.Value) { aggregate = CheckState.Indeterminate; break; } } else aggregate = checkedness; } base.SetObjectCheckedness(modelObject, aggregate ?? CheckState.Indeterminate); } /// <summary> /// Yield the unique ancestors of the given collection of objects. /// The order of the ancestors is guaranteed to be deeper objects first. /// Roots will always be last. /// </summary> /// <param name="toCheck"></param> /// <returns>Unique ancestors of the given objects</returns> protected virtual IEnumerable CalculateDistinctAncestors(IList toCheck) { if (toCheck.Count == 1) { foreach (object ancestor in this.GetAncestors(toCheck[0])) { yield return ancestor; } } else { // WARNING - Clever code // Example: Calculate ancestors of A, B, X and Y // A and B are children of P, child of GP, child of Root // X and Y are children of Q, child of GP, child of Root // Build a list of all ancestors of all objects we need to check ArrayList allAncestors = new ArrayList(); foreach (object child in toCheck) { foreach (object ancestor in this.GetAncestors(child)) { allAncestors.Add(ancestor); } } // allAncestors = { P, GP, Root, P, GP, Root, Q, GP, Root, Q, GP, Root } ArrayList uniqueAncestors = new ArrayList(); Dictionary<object, bool> alreadySeen = new Dictionary<object, bool>(); allAncestors.Reverse(); foreach (object ancestor in allAncestors) { if (!alreadySeen.ContainsKey(ancestor)) { alreadySeen[ancestor] = true; uniqueAncestors.Add(ancestor); } } // uniqueAncestors = { Root, GP, Q, P } uniqueAncestors.Reverse(); foreach (object x in uniqueAncestors) yield return x; } } /// <summary> /// Return all the ancestors of the given model /// </summary> /// <remarks> /// <para> /// This uses ParentGetter if possible. /// </para> /// <para>If the given model is a root OR if the model doesn't exist, the collection will be empty</para> /// </remarks> /// <param name="model">The model whose ancestors should be calculated</param> /// <returns>Return a collection of ancestors of the given model.</returns> protected virtual IEnumerable GetAncestors(object model) { ParentGetterDelegate parentGetterDelegate = this.ParentGetter ?? this.GetParent; object parent = parentGetterDelegate(model); while (parent != null) { yield return parent; parent = parentGetterDelegate(parent); } } #endregion //------------------------------------------------------------------------------------------ #region Event handlers /// <summary> /// The application is idle and a SelectionChanged event has been scheduled /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected override void HandleApplicationIdle(object sender, EventArgs e) { base.HandleApplicationIdle(sender, e); // There is an annoying redraw issue on ListViews that use indentation and // that have full row select enabled. When the selection reduces to a subset // of previously selected rows, or when the selection is extended using // shift-pageup/down, then the space occupied by the indentation is not // invalidated, and hence remains highlighted. // Ideally we'd want to know exactly which rows were selected or deselected // and then invalidate just the indentation region of those rows, // but that's too much work. So just redraw the control. // Actually... the selection issues show just slightly for non-full row select // controls as well. So, always redraw the control after the selection // changes. this.Invalidate(); } /// <summary> /// Decide if the given key event should be handled as a normal key input to the control? /// </summary> /// <param name="keyData"></param> /// <returns></returns> protected override bool IsInputKey(Keys keyData) { // We want to handle Left and Right keys within the control Keys key = keyData & Keys.KeyCode; if (key == Keys.Left || key == Keys.Right) return true; return base.IsInputKey(keyData); } /// <summary> /// Handle the keyboard input to mimic a TreeView. /// </summary> /// <param name="e"></param> /// <returns>Was the key press handled?</returns> protected override void OnKeyDown(KeyEventArgs e) { OLVListItem focused = this.FocusedItem as OLVListItem; if (focused == null) { base.OnKeyDown(e); return; } Object modelObject = focused.RowObject; Branch br = this.TreeModel.GetBranch(modelObject); switch (e.KeyCode) { case Keys.Left: // If the branch is expanded, collapse it. If it's collapsed, // select the parent of the branch. if (br.IsExpanded) this.Collapse(modelObject); else { if (br.ParentBranch != null && br.ParentBranch.Model != null) this.SelectObject(br.ParentBranch.Model, true); } e.Handled = true; break; case Keys.Right: // If the branch is expanded, select the first child. // If it isn't expanded and can be, expand it. if (br.IsExpanded) { List<Branch> filtered = br.FilteredChildBranches; if (filtered.Count > 0) this.SelectObject(filtered[0].Model, true); } else { if (br.CanExpand) this.Expand(modelObject); } e.Handled = true; break; } base.OnKeyDown(e); } #endregion //------------------------------------------------------------------------------------------ // Support classes /// <summary> /// A Tree object represents a tree structure data model that supports both /// tree and flat list operations as well as fast access to branches. /// </summary> /// <remarks>If you create a subclass of Tree, you must install it in the TreeListView /// via the TreeFactory delegate.</remarks> public class Tree : IVirtualListDataSource, IFilterableDataSource { /// <summary> /// Create a Tree /// </summary> /// <param name="treeView"></param> public Tree(TreeListView treeView) { this.treeView = treeView; this.trunk = new Branch(null, this, null); this.trunk.IsExpanded = true; } //------------------------------------------------------------------------------------------ // Properties /// <summary> /// This is the delegate that will be used to decide if a model object can be expanded. /// </summary> public CanExpandGetterDelegate CanExpandGetter { get { return canExpandGetter; } set { canExpandGetter = value; } } private CanExpandGetterDelegate canExpandGetter; /// <summary> /// This is the delegate that will be used to fetch the children of a model object /// </summary> /// <remarks>This delegate will only be called if the CanExpand delegate has /// returned true for the model object.</remarks> public ChildrenGetterDelegate ChildrenGetter { get { return childrenGetter; } set { childrenGetter = value; } } private ChildrenGetterDelegate childrenGetter; /// <summary> /// Get or return the top level model objects in the tree /// </summary> public IEnumerable RootObjects { get { return this.trunk.Children; } set { this.trunk.Children = value; foreach (Branch br in this.trunk.ChildBranches) br.RefreshChildren(); this.RebuildList(); } } /// <summary> /// What tree view is this Tree the model for? /// </summary> public TreeListView TreeView { get { return this.treeView; } } //------------------------------------------------------------------------------------------ // Commands /// <summary> /// Collapse the subtree underneath the given model /// </summary> /// <param name="model">The model to be collapsed. If the model isn't in the tree, /// or if it is already collapsed, the command does nothing.</param> /// <returns>The index of the model in flat list version of the tree</returns> public virtual int Collapse(Object model) { Branch br = this.GetBranch(model); if (br == null || !br.IsExpanded) return -1; // Remember that the branch is collapsed, even if it's currently not visible if (!br.Visible) { br.Collapse(); return -1; } int count = br.NumberVisibleDescendents; br.Collapse(); // Remove the visible descendents from after the branch itself int index = this.GetObjectIndex(model); this.objectList.RemoveRange(index + 1, count); this.RebuildObjectMap(index + 1); return index; } /// <summary> /// Collapse all branches in this tree /// </summary> /// <returns>Nothing useful</returns> public virtual int CollapseAll() { this.trunk.CollapseAll(); this.RebuildList(); return 0; } /// <summary> /// Expand the subtree underneath the given model object /// </summary> /// <param name="model">The model to be expanded.</param> /// <returns>The index of the model in flat list version of the tree</returns> /// <remarks> /// If the model isn't in the tree, /// if it cannot be expanded or if it is already expanded, the command does nothing. /// </remarks> public virtual int Expand(Object model) { Branch br = this.GetBranch(model); if (br == null || !br.CanExpand || br.IsExpanded) return -1; // Remember that the branch is expanded, even if it's currently not visible br.Expand(); if (!br.Visible) { return -1; } int index = this.GetObjectIndex(model); this.InsertChildren(br, index + 1); return index; } /// <summary> /// Expand all branches in this tree /// </summary> /// <returns>Return the index of the first branch that was expanded</returns> public virtual int ExpandAll() { this.trunk.ExpandAll(); this.Sort(this.lastSortColumn, this.lastSortOrder); return 0; } /// <summary> /// Return the Branch object that represents the given model in the tree /// </summary> /// <param name="model">The model whose branches is to be returned</param> /// <returns>The branch that represents the given model, or null if the model /// isn't in the tree.</returns> public virtual Branch GetBranch(object model) { if (model == null) return null; Branch br; this.mapObjectToBranch.TryGetValue(model, out br); return br; } /// <summary> /// Return the number of visible descendents that are below the given model. /// </summary> /// <param name="model">The model whose descendent count is to be returned</param> /// <returns>The number of visible descendents. 0 if the model doesn't exist or is collapsed</returns> public virtual int GetVisibleDescendentCount(object model) { Branch br = this.GetBranch(model); return br == null || !br.IsExpanded ? 0 : br.NumberVisibleDescendents; } /// <summary> /// Rebuild the children of the given model, refreshing any cached information held about the given object /// </summary> /// <param name="model"></param> /// <returns>The index of the model in flat list version of the tree</returns> public virtual int RebuildChildren(Object model) { Branch br = this.GetBranch(model); if (br == null || !br.Visible) return -1; int count = br.NumberVisibleDescendents; // Remove the visible descendents from after the branch itself int index = this.GetObjectIndex(model); if (count > 0) this.objectList.RemoveRange(index + 1, count); // Refresh our knowledge of our children (do this even if CanExpand is false, because // the branch have already collected some children and that information could be stale) br.RefreshChildren(); // Insert the refreshed children if the branch can expand and is expanded if (br.CanExpand && br.IsExpanded) this.InsertChildren(br, index + 1); return index; } //------------------------------------------------------------------------------------------ // Implementation /// <summary> /// Is the given model expanded? /// </summary> /// <param name="model"></param> /// <returns></returns> internal bool IsModelExpanded(object model) { // Special case: model == null is the container for the roots. This is always expanded if (model == null) return true; bool isExpanded; this.mapObjectToExpanded.TryGetValue(model, out isExpanded); return isExpanded; } /// <summary> /// Remember whether or not the given model was expanded /// </summary> /// <param name="model"></param> /// <param name="isExpanded"></param> internal void SetModelExpanded(object model, bool isExpanded) { if (model == null) return; if (isExpanded) this.mapObjectToExpanded[model] = true; else this.mapObjectToExpanded.Remove(model); } /// <summary> /// Insert the children of the given branch into the given position /// </summary> /// <param name="br">The branch whose children should be inserted</param> /// <param name="index">The index where the children should be inserted</param> protected virtual void InsertChildren(Branch br, int index) { // Expand the branch br.Expand(); br.Sort(this.GetBranchComparer()); // Insert the branch's visible descendents after the branch itself this.objectList.InsertRange(index, br.Flatten()); this.RebuildObjectMap(index); } /// <summary> /// Rebuild our flat internal list of objects. /// </summary> protected virtual void RebuildList() { this.objectList = ArrayList.Adapter(this.trunk.Flatten()); List<Branch> filtered = this.trunk.FilteredChildBranches; if (filtered.Count > 0) { filtered[0].IsFirstBranch = true; filtered[0].IsOnlyBranch = (filtered.Count == 1); } this.RebuildObjectMap(0); } /// <summary> /// Rebuild our reverse index that maps an object to its location /// in the filteredObjectList array. /// </summary> /// <param name="startIndex"></param> protected virtual void RebuildObjectMap(int startIndex) { if (startIndex == 0) this.mapObjectToIndex.Clear(); for (int i = startIndex; i < this.objectList.Count; i++) this.mapObjectToIndex[this.objectList[i]] = i; } /// <summary> /// Create a new branch within this tree /// </summary> /// <param name="parent"></param> /// <param name="model"></param> /// <returns></returns> internal Branch MakeBranch(Branch parent, object model) { Branch br = new Branch(parent, this, model); // Remember that the given branch is part of this tree. this.mapObjectToBranch[model] = br; return br; } //------------------------------------------------------------------------------------------ #region IVirtualListDataSource Members /// <summary> /// /// </summary> /// <param name="n"></param> /// <returns></returns> public virtual object GetNthObject(int n) { return this.objectList[n]; } /// <summary> /// /// </summary> /// <returns></returns> public virtual int GetObjectCount() { return this.trunk.NumberVisibleDescendents; } /// <summary> /// /// </summary> /// <param name="model"></param> /// <returns></returns> public virtual int GetObjectIndex(object model) { int index; if (model != null && this.mapObjectToIndex.TryGetValue(model, out index)) return index; return -1; } /// <summary> /// /// </summary> /// <param name="first"></param> /// <param name="last"></param> public virtual void PrepareCache(int first, int last) { } /// <summary> /// /// </summary> /// <param name="value"></param> /// <param name="first"></param> /// <param name="last"></param> /// <param name="column"></param> /// <returns></returns> public virtual int SearchText(string value, int first, int last, OLVColumn column) { return AbstractVirtualListDataSource.DefaultSearchText(value, first, last, column, this); } /// <summary> /// Sort the tree on the given column and in the given order /// </summary> /// <param name="column"></param> /// <param name="order"></param> public virtual void Sort(OLVColumn column, SortOrder order) { this.lastSortColumn = column; this.lastSortOrder = order; // TODO: Need to raise an AboutToSortEvent here // Sorting is going to change the order of the branches so clear // the "first branch" flag foreach (Branch b in this.trunk.ChildBranches) b.IsFirstBranch = false; this.trunk.Sort(this.GetBranchComparer()); this.RebuildList(); } /// <summary> /// /// </summary> /// <returns></returns> protected virtual BranchComparer GetBranchComparer() { if (this.lastSortColumn == null) return null; return new BranchComparer(new ModelObjectComparer( this.lastSortColumn, this.lastSortOrder, this.treeView.SecondarySortColumn ?? this.treeView.GetColumn(0), this.treeView.SecondarySortColumn == null ? this.lastSortOrder : this.treeView.SecondarySortOrder)); } /// <summary> /// Add the given collection of objects to the roots of this tree /// </summary> /// <param name="modelObjects"></param> public virtual void AddObjects(ICollection modelObjects) { ArrayList newRoots = ObjectListView.EnumerableToArray(this.treeView.Roots, true); foreach (Object x in modelObjects) newRoots.Add(x); this.SetObjects(newRoots); } /// <summary> /// Remove all of the given objects from the roots of the tree. /// Any objects that is not already in the roots collection is ignored. /// </summary> /// <param name="modelObjects"></param> public virtual void RemoveObjects(ICollection modelObjects) { ArrayList newRoots = new ArrayList(); foreach (Object x in this.treeView.Roots) newRoots.Add(x); foreach (Object x in modelObjects) { newRoots.Remove(x); this.mapObjectToIndex.Remove(x); } this.SetObjects(newRoots); } /// <summary> /// Set the roots of this tree to be the given collection /// </summary> /// <param name="collection"></param> public virtual void SetObjects(IEnumerable collection) { // We interpret a SetObjects() call as setting the roots of the tree this.treeView.Roots = collection; } /// <summary> /// Update/replace the nth object with the given object /// </summary> /// <param name="index"></param> /// <param name="modelObject"></param> public void UpdateObject(int index, object modelObject) { ArrayList newRoots = ObjectListView.EnumerableToArray(this.treeView.Roots, false); if (index < newRoots.Count) newRoots[index] = modelObject; SetObjects(newRoots); } #endregion #region IFilterableDataSource Members /// <summary> /// /// </summary> /// <param name="mFilter"></param> /// <param name="lFilter"></param> public void ApplyFilters(IModelFilter mFilter, IListFilter lFilter) { this.modelFilter = mFilter; this.listFilter = lFilter; this.RebuildList(); } /// <summary> /// Is this list currently being filtered? /// </summary> internal bool IsFiltering { get { return this.treeView.UseFiltering && (this.modelFilter != null || this.listFilter != null); } } /// <summary> /// Should the given model be included in this control? /// </summary> /// <param name="model">The model to consider</param> /// <returns>True if it will be included</returns> internal bool IncludeModel(object model) { if (!this.treeView.UseFiltering) return true; if (this.modelFilter == null) return true; return this.modelFilter.Filter(model); } #endregion //------------------------------------------------------------------------------------------ // Private instance variables private OLVColumn lastSortColumn; private SortOrder lastSortOrder; private readonly Dictionary<Object, Branch> mapObjectToBranch = new Dictionary<object, Branch>(); // ReSharper disable once InconsistentNaming internal Dictionary<Object, bool> mapObjectToExpanded = new Dictionary<object, bool>(); private readonly Dictionary<Object, int> mapObjectToIndex = new Dictionary<object, int>(); private ArrayList objectList = new ArrayList(); private readonly TreeListView treeView; private readonly Branch trunk; /// <summary> /// /// </summary> // ReSharper disable once InconsistentNaming protected IModelFilter modelFilter; /// <summary> /// /// </summary> // ReSharper disable once InconsistentNaming protected IListFilter listFilter; } /// <summary> /// A Branch represents a sub-tree within a tree /// </summary> public class Branch { /// <summary> /// Indicators for branches /// </summary> [Flags] public enum BranchFlags { /// <summary> /// FirstBranch of tree /// </summary> FirstBranch = 1, /// <summary> /// LastChild of parent /// </summary> LastChild = 2, /// <summary> /// OnlyBranch of tree /// </summary> OnlyBranch = 4 } #region Life and death /// <summary> /// Create a Branch /// </summary> /// <param name="parent"></param> /// <param name="tree"></param> /// <param name="model"></param> public Branch(Branch parent, Tree tree, Object model) { this.ParentBranch = parent; this.Tree = tree; this.Model = model; } #endregion #region Public properties //------------------------------------------------------------------------------------------ // Properties /// <summary> /// Get the ancestor branches of this branch, with the 'oldest' ancestor first. /// </summary> public virtual IList<Branch> Ancestors { get { List<Branch> ancestors = new List<Branch>(); if (this.ParentBranch != null) this.ParentBranch.PushAncestors(ancestors); return ancestors; } } private void PushAncestors(IList<Branch> list) { // This is designed to ignore the trunk (which has no parent) if (this.ParentBranch != null) { this.ParentBranch.PushAncestors(list); list.Add(this); } } /// <summary> /// Can this branch be expanded? /// </summary> public virtual bool CanExpand { get { if (this.Tree.CanExpandGetter == null || this.Model == null) return false; return this.Tree.CanExpandGetter(this.Model); } } /// <summary> /// Gets or sets our children /// </summary> public List<Branch> ChildBranches { get { return this.childBranches; } set { this.childBranches = value; } } private List<Branch> childBranches = new List<Branch>(); /// <summary> /// Get/set the model objects that are beneath this branch /// </summary> public virtual IEnumerable Children { get { ArrayList children = new ArrayList(); foreach (Branch x in this.ChildBranches) children.Add(x.Model); return children; } set { this.ChildBranches.Clear(); TreeListView treeListView = this.Tree.TreeView; CheckState? checkedness = null; if (treeListView != null && treeListView.HierarchicalCheckboxes) checkedness = treeListView.GetCheckState(this.Model); foreach (Object x in value) { this.AddChild(x); // If the tree view is showing hierarchical checkboxes, then // when a child object is first added, it has the same checkedness as this branch if (checkedness.HasValue && checkedness.Value == CheckState.Checked) treeListView.SetObjectCheckedness(x, checkedness.Value); } } } private void AddChild(object childModel) { Branch br = this.Tree.GetBranch(childModel); if (br == null) br = this.Tree.MakeBranch(this, childModel); else { br.ParentBranch = this; br.Model = childModel; br.ClearCachedInfo(); } this.ChildBranches.Add(br); } /// <summary> /// Gets a list of all the branches that survive filtering /// </summary> public List<Branch> FilteredChildBranches { get { if (!this.IsExpanded) return new List<Branch>(); if (!this.Tree.IsFiltering) return this.ChildBranches; List<Branch> filtered = new List<Branch>(); foreach (Branch b in this.ChildBranches) { if (this.Tree.IncludeModel(b.Model)) filtered.Add(b); else { // Also include this branch if it has any filtered branches (yes, its recursive) if (b.FilteredChildBranches.Count > 0) filtered.Add(b); } } return filtered; } } /// <summary> /// Gets or set whether this branch is expanded /// </summary> public bool IsExpanded { get { return this.Tree.IsModelExpanded(this.Model); } set { this.Tree.SetModelExpanded(this.Model, value); } } /// <summary> /// Return true if this branch is the first branch of the entire tree /// </summary> public virtual bool IsFirstBranch { get { return ((this.flags & Branch.BranchFlags.FirstBranch) != 0); } set { if (value) this.flags |= Branch.BranchFlags.FirstBranch; else this.flags &= ~Branch.BranchFlags.FirstBranch; } } /// <summary> /// Return true if this branch is the last child of its parent /// </summary> public virtual bool IsLastChild { get { return ((this.flags & Branch.BranchFlags.LastChild) != 0); } set { if (value) this.flags |= Branch.BranchFlags.LastChild; else this.flags &= ~Branch.BranchFlags.LastChild; } } /// <summary> /// Return true if this branch is the only top level branch /// </summary> public virtual bool IsOnlyBranch { get { return ((this.flags & Branch.BranchFlags.OnlyBranch) != 0); } set { if (value) this.flags |= Branch.BranchFlags.OnlyBranch; else this.flags &= ~Branch.BranchFlags.OnlyBranch; } } /// <summary> /// Gets the depth level of this branch /// </summary> public int Level { get { if (this.ParentBranch == null) return 0; return this.ParentBranch.Level + 1; } } /// <summary> /// Gets or sets which model is represented by this branch /// </summary> public Object Model { get { return model; } set { model = value; } } private Object model; /// <summary> /// Return the number of descendents of this branch that are currently visible /// </summary> /// <returns></returns> public virtual int NumberVisibleDescendents { get { if (!this.IsExpanded) return 0; List<Branch> filtered = this.FilteredChildBranches; int count = filtered.Count; foreach (Branch br in filtered) count += br.NumberVisibleDescendents; return count; } } /// <summary> /// Gets or sets our parent branch /// </summary> public Branch ParentBranch { get { return parentBranch; } set { parentBranch = value; } } private Branch parentBranch; /// <summary> /// Gets or sets our overall tree /// </summary> public Tree Tree { get { return tree; } set { tree = value; } } private Tree tree; /// <summary> /// Is this branch currently visible? A branch is visible /// if it has no parent (i.e. it's a root), or its parent /// is visible and expanded. /// </summary> public virtual bool Visible { get { if (this.ParentBranch == null) return true; return this.ParentBranch.IsExpanded && this.ParentBranch.Visible; } } #endregion #region Commands //------------------------------------------------------------------------------------------ // Commands /// <summary> /// Clear any cached information that this branch is holding /// </summary> public virtual void ClearCachedInfo() { this.Children = new ArrayList(); this.alreadyHasChildren = false; } /// <summary> /// Collapse this branch /// </summary> public virtual void Collapse() { this.IsExpanded = false; } /// <summary> /// Expand this branch /// </summary> public virtual void Expand() { if (this.CanExpand) { this.IsExpanded = true; this.FetchChildren(); } } /// <summary> /// Expand this branch recursively /// </summary> public virtual void ExpandAll() { this.Expand(); foreach (Branch br in this.ChildBranches) { if (br.CanExpand) br.ExpandAll(); } } /// <summary> /// Collapse all branches in this tree /// </summary> /// <returns>Nothing useful</returns> public virtual void CollapseAll() { this.Collapse(); foreach (Branch br in this.ChildBranches) { if (br.IsExpanded) br.CollapseAll(); } } /// <summary> /// Fetch the children of this branch. /// </summary> /// <remarks>This should only be called when CanExpand is true.</remarks> public virtual void FetchChildren() { if (this.alreadyHasChildren) return; this.alreadyHasChildren = true; if (this.Tree.ChildrenGetter == null) return; Cursor previous = Cursor.Current; try { if (this.Tree.TreeView.UseWaitCursorWhenExpanding) Cursor.Current = Cursors.WaitCursor; this.Children = this.Tree.ChildrenGetter(this.Model); } finally { Cursor.Current = previous; } } /// <summary> /// Collapse the visible descendents of this branch into list of model objects /// </summary> /// <returns></returns> public virtual IList Flatten() { ArrayList flatList = new ArrayList(); if (this.IsExpanded) this.FlattenOnto(flatList); return flatList; } /// <summary> /// Flatten this branch's visible descendents onto the given list. /// </summary> /// <param name="flatList"></param> /// <remarks>The branch itself is <b>not</b> included in the list.</remarks> public virtual void FlattenOnto(IList flatList) { Branch lastBranch = null; foreach (Branch br in this.FilteredChildBranches) { lastBranch = br; br.IsLastChild = false; flatList.Add(br.Model); if (br.IsExpanded) { br.FetchChildren(); // make sure we have the branches children br.FlattenOnto(flatList); } } if (lastBranch != null) lastBranch.IsLastChild = true; } /// <summary> /// Force a refresh of all children recursively /// </summary> public virtual void RefreshChildren() { // Forget any previous children. We always do this so that if // IsExpanded or CanExpand have changed, we aren't left with stale information. this.ClearCachedInfo(); if (!this.IsExpanded || !this.CanExpand) return; this.FetchChildren(); foreach (Branch br in this.ChildBranches) br.RefreshChildren(); } /// <summary> /// Sort the sub-branches and their descendents so they are ordered according /// to the given comparer. /// </summary> /// <param name="comparer">The comparer that orders the branches</param> public virtual void Sort(BranchComparer comparer) { if (this.ChildBranches.Count == 0) return; if (comparer != null) this.ChildBranches.Sort(comparer); foreach (Branch br in this.ChildBranches) br.Sort(comparer); } #endregion //------------------------------------------------------------------------------------------ // Private instance variables private bool alreadyHasChildren; private BranchFlags flags; } /// <summary> /// This class sorts branches according to how their respective model objects are sorted /// </summary> public class BranchComparer : IComparer<Branch> { /// <summary> /// Create a BranchComparer /// </summary> /// <param name="actualComparer"></param> public BranchComparer(IComparer actualComparer) { this.actualComparer = actualComparer; } /// <summary> /// Order the two branches /// </summary> /// <param name="x"></param> /// <param name="y"></param> /// <returns></returns> public int Compare(Branch x, Branch y) { return this.actualComparer.Compare(x.Model, y.Model); } private readonly IComparer actualComparer; } } }
41.045561
130
0.530394
[ "Apache-2.0" ]
lockieluke/VisualStudioCodeLauncher
ObjectListViewDemo/ObjectListView/TreeListView.cs
87,386
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using AutoMapper; using System; using System.Collections.Generic; using System.Data.Entity; using System.Linq; using System.Linq.Expressions; using System.Reflection; using System.Threading.Tasks; using Trackable.Common; using Trackable.EntityFramework; using Trackable.Models.Helpers; namespace Trackable.Repositories { internal abstract class DbRepositoryBase<TKey1, TKey2, TData, TModel> : IRepository<TKey1, TKey2, TModel> where TData : EntityBase<TKey1, TKey2> where TKey1 : IEquatable<TKey1> where TKey2 : IEquatable<TKey2> { /// <summary> /// Gets the model converter. /// </summary> protected IMapper ObjectMapper { get; set; } protected TrackableDbContext Db { get; } public DbRepositoryBase(TrackableDbContext db, IMapper mapper) { this.ObjectMapper = mapper.ThrowIfNull(nameof(mapper)); this.Db = db.ThrowIfNull(nameof(db)); } /// <summary> /// Adds a model asynchronously. /// </summary> /// <param name="model">The business model.</param> /// <returns>The async task.</returns> public virtual async Task<TModel> AddAsync(TModel model) { model.ThrowIfNull(nameof(model)); var data = this.ObjectMapper.Map<TData>(model); this.Db.Set<TData>().Add(data); await this.Db.SaveChangesAsync(); return this.ObjectMapper.Map<TModel>(data); } /// <summary> /// Adds a model asynchronously. /// </summary> /// <param name="models">The business models.</param> /// <returns>The async task.</returns> public virtual async Task AddAsync(IEnumerable<TModel> models) { models.ThrowIfNull(nameof(models)); this.Db.Set<TData>().AddRange( models.Select(m => this.ObjectMapper.Map<TData>(m))); await this.Db.SaveChangesAsync(); } /// <summary> /// Deletes a model asynchronously. /// </summary> /// <param name="model">The model ID.</param> /// <returns>The async task.</returns> public async Task DeleteAsync(TKey1 key1, TKey2 key2) { var data = await this.FindAsync(key1, key2); data.Deleted = true; await this.Db.SaveChangesAsync(); } /// <summary> /// Gets a model asynchronously by ID. /// </summary> /// <param name="model">The model ID.</param> /// <returns>The model async task.</returns> public async Task<TModel> GetAsync(TKey1 key1, TKey2 key2) { var data = await this.FindAsync(key1, key2); if (data == null) { return default(TModel); } return this.ObjectMapper.Map<TModel>(data); } /// <summary> /// Gets all models asynchronously. /// </summary> /// <returns>The models async task.</returns> public async Task<IEnumerable<TModel>> GetAllAsync() { var data = await this.Db.Set<TData>() .Where(d => !d.Deleted) .ToListAsync(); return data.Select(d => this.ObjectMapper.Map<TModel>(d)); } /// <summary> /// Updates a model asynchronously. /// </summary> /// <param name="model">The model to be updated.</param> /// <returns>The async task.</returns> public async Task<TModel> UpdateAsync(TKey1 key1, TKey2 key2, TModel model) { var data = await this.FindAsync(key1, key2); UpdateData(data, model); await this.Db.SaveChangesAsync(); return this.ObjectMapper.Map<TModel>(data); } /// <summary> /// Finds a data model by key. /// </summary> /// <param name="id"></param> /// <returns></returns> protected async Task<TData> FindAsync(TKey1 key1, TKey2 key2) { return await this.FindBy(data => data.Key1.Equals(key1) && data.Key2.Equals(key2)).SingleOrDefaultAsync(); } /// <summary> /// Returns a queryable of valid elements after applying the specified predicate. /// </summary> /// <param name="predicate">The predicate expression.</param> /// <returns>The found queryable.</returns> protected IQueryable<TData> FindBy(Expression<Func<TData, bool>> predicate, params Expression<Func<TData, object>>[] includes) { var query = this.Db.Set<TData>() .Where(d => !d.Deleted) .Where(predicate); if (includes != null) { query = includes.Aggregate(query, (current, include) => current.Include(include)); } return query; } /// <summary> /// Updates the data model with the required properties from the business model. /// </summary> /// <param name="data">The data model.</param> /// <param name="model">The business model.</param> public void UpdateData(TData data, TModel model) { var clonedModel = this.ObjectMapper.Map<TModel>(data); var modelProperties = typeof(TModel).GetProperties(); foreach (var property in modelProperties) { var attributes = property.GetCustomAttributes(); if (attributes.Any(a => a.GetType() == typeof(MutableAttribute))) { property.SetValue(clonedModel, property.GetValue(model)); } } var intermediaryData = this.ObjectMapper.Map<TData>(clonedModel); var dataProperties = typeof(TData).GetProperties(); foreach (var property in dataProperties) { property.SetValue(data, property.GetValue(intermediaryData)); } } } }
33.277174
134
0.564429
[ "MIT" ]
Ankeetshkk/Bing-Maps-Fleet-Tracker
Backend/src/Trackable.Repositories/Repositories/DbCompositeRepositoryBase.cs
6,123
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace Pandora_Box { /// <summary> /// UserControl1.xaml 的交互逻辑 /// </summary> public partial class UserControl1 : UserControl { public UserControl1() { InitializeComponent(); } } }
21.655172
51
0.714968
[ "MIT" ]
AuntYang/Pandora-Box
Pandora-Box/UserControl1.xaml.cs
640
C#
using Microsoft.Extensions.Logging; using System; using System.IO; using System.Text; namespace Hyperspace.Redis.Internal { public class RedisConnectionMultiplexerLogger : TextWriter, ILogger { private readonly ILogger _logger; private readonly StringBuilder _buffer; public RedisConnectionMultiplexerLogger(ILogger logger) { _logger = logger; _buffer = new StringBuilder(); Encoding = Encoding.UTF8; DefualtLogLevel = LogLevel.Debug; } public override Encoding Encoding { get; } public LogLevel DefualtLogLevel { get; set; } public void Log(LogLevel logLevel, int eventId, object state, Exception exception, Func<object, Exception, string> formatter) { _logger.Log(logLevel, eventId, state, exception, formatter); } public bool IsEnabled(LogLevel logLevel) { return _logger.IsEnabled(logLevel); } public IDisposable BeginScopeImpl(object state) { return _logger.BeginScopeImpl(state); } public override void Write(char value) { _buffer.Append(value); if (_buffer.Length >= NewLine.Length) { var isNewLine = true; for (var i = 0; i < NewLine.Length; i++) { if (NewLine[i] == _buffer[_buffer.Length - NewLine.Length + i]) continue; isNewLine = false; break; } if (isNewLine) { var log = _buffer.ToString(); _buffer.Clear(); _logger.Log(DefualtLogLevel, 0, log, null, (o, e) => (string)o); } } } public override void WriteLine(string value) { if (_buffer.Length > 0) { var log = _buffer.ToString(); _buffer.Clear(); _logger.Log(DefualtLogLevel, 0, log + value, null, (o, e) => (string) o); } else { _logger.Log(DefualtLogLevel, 0, value, null, (o, e) => (string) o); } } } }
28.487805
133
0.502568
[ "MIT" ]
Hyperspaces/Hyperspace.Redis
src/Hyperspace.Redis/Internal/RedisConnectionMultiplexerLogger.cs
2,338
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using Microsoft.AspNetCore.Components; using Microsoft.AspNetCore.Components.Routing; using Microsoft.AspNetCore.Components.WebView.Services; using Microsoft.Extensions.DependencyInjection.Extensions; using Microsoft.JSInterop; namespace Microsoft.Extensions.DependencyInjection { /// <summary> /// Extensions for adding component webview services to the <see cref="IServiceCollection"/>. /// </summary> public static class ComponentsWebViewServiceCollectionExtensions { /// <summary> /// Adds component webview services to the <paramref name="services"/> collection. /// </summary> /// <param name="services">The <see cref="IServiceCollection"/> to add the component webview services to.</param> /// <returns></returns> public static IServiceCollection AddBlazorWebView(this IServiceCollection services) { services.AddLogging(); services.TryAddScoped<IJSRuntime, WebViewJSRuntime>(); services.TryAddScoped<INavigationInterception, WebViewNavigationInterception>(); services.TryAddScoped<NavigationManager, WebViewNavigationManager>(); return services; } } }
42.0625
121
0.71471
[ "MIT" ]
48355746/AspNetCore
src/Components/WebView/WebView/src/ComponentsWebViewServiceCollectionExtensions.cs
1,346
C#
using System; using System.IO; using System.Linq; using Xamarin.UITest; using Xamarin.UITest.Queries; namespace WeddingConnect.UITests { public class AppInitializer { public static IApp StartApp(Platform platform) { if (platform == Platform.Android) { return ConfigureApp.Android.StartApp(); } return ConfigureApp.iOS.StartApp(); } } }
19.954545
55
0.601367
[ "MIT" ]
rsepulveda210/Wedding-Connect
WeddingConnect/UITests/AppInitializer.cs
441
C#
using System.Collections.Generic; using System.Text.RegularExpressions; using AdiIRCAPIv2.Interfaces; namespace Twitch___AdiIRC { class TwitchRawEventHandlers { /* * Twitch includes irv3 tags in most of its messsages, wand we want to be able to use those * Here is an example of such a tagset in a message * @badges=global_mod/1,turbo/1;color=#0D4200;display-name=dallas;emotes=25:0-4,12-16/1902:6-10;mod=0;room-id=1337;subscriber=0;turbo=1;user-id=1337;user-type=global_mod :ronni!ronni@ronni.tmi.twitch.tv PRIVMSG #dallas :Kappa Keepo Kappa */ public static Dictionary<string, string> ParseTagsFromString(string rawMessage) { var tags = new Dictionary<string,string>(); //Grab the Tag section of the Message var tagsGroupRegex = @"^@(.+?) :.+ [A-Z]+"; var tagsGroupMatch = Regex.Match(rawMessage, tagsGroupRegex); if (tagsGroupMatch.Success) { var tagsString = tagsGroupMatch.Groups[1].ToString(); //Split into seperate key=value pairs var tagPairs = tagsString.Split(';'); foreach (var tagPair in tagPairs) { //Seperate key from value var data = tagPair.Split('='); //Twitch uses \s to indicate a space in a Tag Value var tagContent = data[1].Replace(@"\s", " "); tags.Add(data[0], tagContent); } } return tags; } /* * NOTICE is a normal irc message but due to how twitch sends them * they don't arrive in the channel windows, but in the server. */ public static bool Notice(IServer server, string rawMessage) { //Check if its a usable notice message var noticeRegex = @".+ :tmi.twitch.tv NOTICE (#.+) :(.+)"; var noticeMatch = Regex.Match(rawMessage, noticeRegex); if (noticeMatch.Success) { var channel = noticeMatch.Groups[1].ToString(); var message = noticeMatch.Groups[2].ToString(); //Send a fake regular irc notice var notice = $":Twitch!Twitch@tmi.twitch.tv NOTICE {channel} :{message}"; server.SendFakeRaw(notice); //Handled the NOTICE message. return true; } //Not recognized as a NOTICE message, didn't handle it. return false; } /* * CLEARCHAT is a message used by twitch to Timeout/Ban people, and clear their * Text lines, We won't clear the text but will display the ban information */ public static bool ClearChat(IServer server, string rawMessage, bool showTimeOut, Dictionary<string, string> tags) { var clearChatRegex = @".+ :tmi.twitch.tv CLEARCHAT (#.+) :(.+)"; var clearChatMatch = Regex.Match(rawMessage, clearChatRegex); if (clearChatMatch.Success) { if (!showTimeOut) { //It is definitly a CLEARCHAT message but the settings say not to display it. return true; } var time = "∞"; var message = "No Reason Given"; var channel = clearChatMatch.Groups[1].ToString(); var target = clearChatMatch.Groups[2].ToString(); //Display Ban-Duration if there was any in the tags. if(tags.ContainsKey("ban-duration")) { if (!string.IsNullOrWhiteSpace(tags["ban-duration"])) { time = tags["ban-duration"]; } } //Display Ban-Message if there was any in the tags. if (tags.ContainsKey("ban-reason")) { if (!string.IsNullOrWhiteSpace(tags["ban-reason"])) { message = tags["ban-reason"]; } } //Construct and send a tranditional irc NOTICE Message var notice = $":Twitch!Twitch@tmi.twitch.tv NOTICE {channel} :{target} was banned: {message} [ {time} seconds ]"; server.SendFakeRaw(notice); //We found a CLEARCHAT message and turned it into a NOTICE, return true to indicate we handled the message return true; } //We did not find a CLEARCHAT message, return false to indicate we did not handle the message return false; } /* * USERNOTICE is a message used by twitch to by twitch to inform about (Re-)Subscriptions * It can take two forms with or without a user message attached. */ public static bool Usernotice(IServer server, string rawMessage, bool showSubs, Dictionary<string, string> tags) { var subRegexMessage = @".*USERNOTICE (#\w+)\s*(:.+)?"; var subMessageMatch = Regex.Match(rawMessage, subRegexMessage); if (subMessageMatch.Success) { if (!showSubs) { //It is definitly a USERNOTICE message but the settings say not to display it. return true; } //Grab the channel part of the message, its always included. var channel = subMessageMatch.Groups[1].ToString(); var userMessage = ""; //Check for the usermessage section, it has an included : as the first charcter so that needs to be removed. if (subMessageMatch.Groups.Count >= 3 && !string.IsNullOrWhiteSpace(subMessageMatch.Groups[2].ToString()) ) { userMessage = $" [ { subMessageMatch.Groups[2].ToString().TrimStart(':')} ]"; } //Construct the notice, twitch includes a detailed message for us about the nature of the subscription in the tags var notice = $":Twitch!Twitch@tmi.twitch.tv NOTICE {channel} :{tags["system-msg"]}{userMessage}"; server.SendFakeRaw(notice); return true; } //We did not find a USERNOTICE message, return false to indicate we did not handle the message return false; } //WHISPER is a message used by twitch to handle private messsages between users ( and bots ) //But its not a normal IRC message type, so they have to be rewritten into PRIVMSG's public static bool WhisperReceived(IServer server, string rawMessage) { var whisperRegex = @".*(\x3A[^!@ ]+![^@ ]+@\S+) WHISPER (\S+) (\x3A.*)"; var whisperMatch = Regex.Match(rawMessage, whisperRegex); if (whisperMatch.Success) { var sender = whisperMatch.Groups[1]; var target = whisperMatch.Groups[2]; var message = whisperMatch.Groups[3]; //Construct and send a proper PRIVSMG instead of the WHISPER var privmsg = $"{sender} PRIVMSG {target} {message}"; server.SendFakeRaw(privmsg); return true; } //We did not find a WHISPER message, return false to indicate we did not handle the message return false; } } }
41.929348
245
0.534802
[ "MIT" ]
Tzarnal/AdiIRC-Twitch
Twitch @ AdiIRC/Twitch @ AdiIRC/TwitchRawEventHandlers.cs
7,719
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("InterrogatorLibTest")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Microsoft")] [assembly: AssemblyProduct("InterrogatorLibTest")] [assembly: AssemblyCopyright("Copyright © Microsoft 2014")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("fb884e10-0d94-48ae-a50f-492cc0cc0fce")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // [assembly: AssemblyVersion("1.0.0.0")] // Below attribute is to suppress FxCop warning "CA2232 : Microsoft.Usage : Add STAThreadAttribute to assembly" // as Device app does not support STA thread. [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2232:MarkWindowsFormsEntryPointsWithStaThread")]
40.810811
129
0.770861
[ "MIT" ]
rfid-applied/InterrogatorLib
vs2008/InterrogatorLib.IntegrationTest/Properties/AssemblyInfo.cs
1,513
C#
// -------------------------------------------------------------------------------------------------------------------- // <auto-generated> // Generated using OBeautifulCode.CodeGen.ModelObject (1.0.0.0) // </auto-generated> // -------------------------------------------------------------------------------------------------------------------- namespace OBeautifulCode.CodeGen.ModelObject.Test { using global::System; using global::System.CodeDom.Compiler; using global::System.Collections.Concurrent; using global::System.Collections.Generic; using global::System.Collections.ObjectModel; using global::System.Diagnostics.CodeAnalysis; using global::System.Globalization; using global::System.Linq; using global::OBeautifulCode.Cloning.Recipes; using global::OBeautifulCode.Equality.Recipes; using global::OBeautifulCode.Type; using global::OBeautifulCode.Type.Recipes; using static global::System.FormattableString; [Serializable] public partial class ModelEqualityPrivateSetMiscParent : IEquatable<ModelEqualityPrivateSetMiscParent> { /// <summary> /// Determines whether two objects of type <see cref="ModelEqualityPrivateSetMiscParent"/> are equal. /// </summary> /// <param name="left">The object to the left of the equality operator.</param> /// <param name="right">The object to the right of the equality operator.</param> /// <returns>true if the two items are equal; otherwise false.</returns> public static bool operator ==(ModelEqualityPrivateSetMiscParent left, ModelEqualityPrivateSetMiscParent right) { if (ReferenceEquals(left, right)) { return true; } if (ReferenceEquals(left, null) || ReferenceEquals(right, null)) { return false; } var result = left.Equals((object)right); return result; } /// <summary> /// Determines whether two objects of type <see cref="ModelEqualityPrivateSetMiscParent"/> are not equal. /// </summary> /// <param name="left">The object to the left of the equality operator.</param> /// <param name="right">The object to the right of the equality operator.</param> /// <returns>true if the two items are not equal; otherwise false.</returns> public static bool operator !=(ModelEqualityPrivateSetMiscParent left, ModelEqualityPrivateSetMiscParent right) => !(left == right); /// <inheritdoc /> public bool Equals(ModelEqualityPrivateSetMiscParent other) => this == other; /// <inheritdoc /> [SuppressMessage("Microsoft.Design", "CA1065:DoNotRaiseExceptionsInUnexpectedLocations")] public override bool Equals(object obj) { throw new NotImplementedException("This method should be abstract. It was generated as virtual so that you aren't forced to override it when you create a new model that derives from this model. It will be overridden in the generated designer file."); } } }
45.347826
264
0.619048
[ "MIT" ]
OBeautifulCode/OBeautifulCode.CodeGen
OBeautifulCode.CodeGen.ModelObject.Test/Models/Scripted/Equality/PrivateSet/Misc/ModelEqualityPrivateSetMiscParent.designer.cs
3,131
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace EngineeringMath.Calculations.Components.Selectors { /// <summary> /// Allows user to picker from a list of consecutive integers /// </summary> public class IntegerSpinner : SimplePicker<int> { internal IntegerSpinner(int low, int high, string title = null) : base( Enumerable.Range(low, high).ToDictionary(x => x.ToString(), x => x), title) { this.SelectedIndex = 0; } } }
28.05
155
0.668449
[ "MIT" ]
jfkonecn/Open-Chemical-Engineer-App
Backend/EngineeringMath/Calculations/Components/Selectors/IntegerSpinner.cs
563
C#
namespace BackboneTemplate.Models { using System.ComponentModel.DataAnnotations; public class CreateUser { [Required] [RegularExpression(@"^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$", ErrorMessage = "Invalid email format.")] public string Email { get; set; } [Required] [StringLength(64, MinimumLength = 6)] public string Password { get; set; } [Compare("Password", ErrorMessage = "The password and confirmation password do not match.")] public string ConfirmPassword { get; set; } } }
32.777778
135
0.605085
[ "MIT" ]
kazimanzurrashid/AspNetMvcBackboneJsSpa
source/Template/Models/CreateUser.cs
592
C#
/* * Copyright (c) 2017-2019 Håkan Edling * * This software may be modified and distributed under the terms * of the MIT license. See the LICENSE file for details. * * http://github.com/piranhacms/piranha * */ using System; using System.Collections.Generic; namespace Piranha.Models { [Serializable] public sealed class Media : Media<Guid> { /// <summary> /// Gets/sets the optional folder id. /// </summary> public Guid? FolderId { get; set; } /// <summary> /// Gets/sets the available versions. /// </summary> public IList<MediaVersion> Versions { get; set; } = new List<MediaVersion>(); } [Serializable] public abstract class Media<TKey> { /// <summary> /// Gets/sets the unique id. /// </summary> public TKey Id { get; set; } /// <summary> /// Gets/sets the media type. /// </summary> public MediaType Type { get; set; } /// <summary> /// Gets/sets the filename. /// </summary> public string Filename { get; set; } /// <summary> /// Gets/sets the content type. /// </summary> /// <returns></returns> public string ContentType { get; set; } /// <summary> /// Gets/sets the file size in bytes. /// </summary> public long Size { get; set; } /// <summary> /// Gets/sets the public url. /// </summary> public string PublicUrl { get; set; } /// <summary> /// Gets/sets the optional width. This only applies /// if the media asset is an image. /// </summary> public int? Width { get; set; } /// <summary> /// Gets/sets the optional height. This only applies /// if the media asset is an image. /// </summary> public int? Height { get; set; } /// <summary> /// Gets/sets the created date. /// </summary> public DateTime Created { get; set; } /// <summary> /// Gets/sets the last modification date. /// </summary> public DateTime LastModified { get; set; } } }
25.77907
85
0.525936
[ "MIT" ]
Bia10/piranha.core
core/Piranha/Models/Media.cs
2,218
C#
using System; using WildFarm.Models; namespace WildFarm.Animals { public class Mouse : Mammal { public Mouse(string name, double weight, string livingRegion) : base(name, weight, livingRegion) { WeightGain = 0.1; } public override void ProduceSound() { Console.WriteLine("Squeak"); } public override string ToString() { return $"{GetType().Name} [{Name}, {Weight}, {LivingRegion}, {FoodEaten}]"; } } }
21.916667
104
0.557034
[ "MIT" ]
teodortenchev/C-Sharp-Advanced-Coursework
C# OOP Basics/Polymorphism/P3_WildFarm/Animals/Mouse.cs
528
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class ChasePlayer : MonoBehaviour { public bool attackInRange = false; public float attackSpeed = 1f; public float movementSpeed = 3f; private bool _isInRange = false; private bool _isAttacking = false; private float startingZ; private void Awake() { startingZ = transform.position.z; } // Update is called once per frame void Update() { if ((Util.Player.transform.position - transform.position).magnitude > 1.2f) { _isInRange = false; transform.up = (Util.Player.transform.position - transform.position).normalized; transform.position += transform.up * Time.deltaTime * movementSpeed; transform.position = new Vector3(transform.position.x, transform.position.y, startingZ); } else { _isInRange = true; transform.up = (Util.Player.transform.position - transform.position).normalized; transform.position += transform.up * Time.deltaTime * movementSpeed / 2f; transform.position = new Vector3(transform.position.x, transform.position.y, startingZ); if (attackInRange && !_isAttacking) { StartCoroutine(Attack()); } } } private IEnumerator Attack() { _isAttacking = true; yield return new WaitForSeconds(attackSpeed); if (_isInRange) { Util.Player.Damage(GetComponent<UnitBase>().Stats.attackPower); } _isAttacking = false; } }
28.912281
100
0.616505
[ "Apache-2.0" ]
TwinGhosts/LudumDare41
LudumDare41/Assets/Scripts/AI Behaviour/ChasePlayer.cs
1,650
C#
using Newtonsoft.Json; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net.Http; using System.Text; using System.Threading.Tasks; using WordPressPCL.Interfaces; using WordPressPCL.Models; using WordPressPCL.Utility; namespace WordPressPCL.Client { /// <summary> /// Client class for interaction with Media endpoint WP REST API /// </summary> public class Media : IUpdateOperation<MediaItem>, IReadOperation<MediaItem>, IDeleteOperation, IQueryOperation<MediaItem, MediaQueryBuilder> { #region Init private readonly string _defaultPath; private const string _methodPath = "media"; private readonly HttpHelper _httpHelper; /// <summary> /// Constructor /// </summary> /// <param name="HttpHelper">reference to HttpHelper class for interaction with HTTP</param> /// <param name="defaultPath">path to site, EX. http://demo.com/wp-json/ </param> public Media(ref HttpHelper HttpHelper, string defaultPath) { _httpHelper = HttpHelper; _defaultPath = defaultPath; } #endregion Init /// <summary> /// Create Media entity with attachment /// </summary> /// <param name="fileStream">stream with file content</param> /// <param name="filename">Name of file in WP Media Library</param> /// <returns>Created media object</returns> public async Task<MediaItem> Create(Stream fileStream, string filename) { using (StreamContent content = new StreamContent(fileStream)) { string extension = filename.Split('.').Last(); content.Headers.TryAddWithoutValidation("Content-Type", MimeTypeHelper.GetMIMETypeFromExtension(extension)); content.Headers.TryAddWithoutValidation("Content-Disposition", $"attachment; filename={filename}"); return (await _httpHelper.PostRequest<MediaItem>($"{_defaultPath}{_methodPath}", content).ConfigureAwait(false)).Item1; } } #if NETSTANDARD2_0 /// <summary> /// Create Media entity with attachment /// </summary> /// <param name="filePath">Local Path to file</param> /// <param name="filename">Name of file in WP Media Library</param> /// <returns>Created media object</returns> public async Task<MediaItem> Create(string filePath, string filename) { if (File.Exists(filePath)) { using (StreamContent content = new StreamContent(File.OpenRead(filePath))) { string extension = filename.Split('.').Last(); content.Headers.TryAddWithoutValidation("Content-Type", MimeTypeHelper.GetMIMETypeFromExtension(extension)); content.Headers.TryAddWithoutValidation("Content-Disposition", $"attachment; filename={filename}"); return (await _httpHelper.PostRequest<MediaItem>($"{_defaultPath}{_methodPath}", content).ConfigureAwait(false)).Item1; } } else { throw new FileNotFoundException($"{filePath} was not found"); } } #endif /// <summary> /// Delete Entity /// </summary> /// <param name="ID">Entity Id</param> /// <returns>Result of operation</returns> public Task<bool> Delete(int ID) { return _httpHelper.DeleteRequest($"{_defaultPath}{_methodPath}/{ID}?force=true"); } /// <summary> /// Get latest /// </summary> /// <param name="embed">include embed info</param> /// <param name="useAuth">Send request with authentication header</param> /// <returns>Latest media items</returns> public Task<IEnumerable<MediaItem>> Get(bool embed = false, bool useAuth = false) { return _httpHelper.GetRequest<IEnumerable<MediaItem>>($"{_defaultPath}{_methodPath}", embed, useAuth); } /// <summary> /// Get All /// </summary> /// <param name="embed">Include embed info</param> /// <param name="useAuth">Send request with authentication header</param> /// <returns>List of all result</returns> public async Task<IEnumerable<MediaItem>> GetAll(bool embed = false, bool useAuth = false) { //100 - Max posts per page in WordPress REST API, so this is hack with multiple requests List<MediaItem> entities = new List<MediaItem>(); entities = (await _httpHelper.GetRequest<IEnumerable<MediaItem>>($"{_defaultPath}{_methodPath}?per_page=100&page=1", embed, useAuth).ConfigureAwait(false))?.ToList<MediaItem>(); if (_httpHelper.LastResponseHeaders.Contains("X-WP-TotalPages") && System.Convert.ToInt32(_httpHelper.LastResponseHeaders.GetValues("X-WP-TotalPages").FirstOrDefault()) > 1) { int totalpages = System.Convert.ToInt32(_httpHelper.LastResponseHeaders.GetValues("X-WP-TotalPages").FirstOrDefault()); for (int page = 2; page <= totalpages; page++) { entities.AddRange((await _httpHelper.GetRequest<IEnumerable<MediaItem>>($"{_defaultPath}{_methodPath}?per_page=100&page={page}", embed, useAuth).ConfigureAwait(false))?.ToList<MediaItem>()); } } return entities; } /// <summary> /// Get Entity by Id /// </summary> /// <param name="ID">ID</param> /// <param name="embed">include embed info</param> /// <param name="useAuth">Send request with authentication header</param> /// <returns>Entity by Id</returns> public Task<MediaItem> GetByID(object ID, bool embed = false, bool useAuth = false) { return _httpHelper.GetRequest<MediaItem>($"{_defaultPath}{_methodPath}/{ID}", embed, useAuth); } /// <summary> /// Create a parametrized query and get a result /// </summary> /// <param name="queryBuilder">Query builder with specific parameters</param> /// <param name="useAuth">Send request with authentication header</param> /// <returns>List of filtered result</returns> public Task<IEnumerable<MediaItem>> Query(MediaQueryBuilder queryBuilder, bool useAuth = false) { return _httpHelper.GetRequest<IEnumerable<MediaItem>>($"{_defaultPath}{_methodPath}{queryBuilder.BuildQueryURL()}", false, useAuth); } /// <summary> /// Update Entity /// </summary> /// <param name="Entity">Entity object</param> /// <returns>Updated object</returns> public async Task<MediaItem> Update(MediaItem Entity) { var entity = _httpHelper.JsonSerializerSettings == null ? JsonConvert.SerializeObject(Entity) : JsonConvert.SerializeObject(Entity, _httpHelper.JsonSerializerSettings); var postBody = new StringContent(entity, Encoding.UTF8, "application/json"); return (await _httpHelper.PostRequest<MediaItem>($"{_defaultPath}{_methodPath}/{(Entity as Base)?.Id}", postBody).ConfigureAwait(false)).Item1; } } }
45.962264
210
0.620005
[ "MIT" ]
284247028/WordPressPCL
WordPressPCL/Client/Media.cs
7,310
C#
using System; namespace ReverseArrayOfStrings { class ReverseArrayOfStrings { static void Main(string[] args) { string[] arrStrings = Console.ReadLine().Split(); ReverseStringArray(arrStrings); foreach (var str in arrStrings) { Console.Write(str + " "); } } public static void ReverseStringArray(string[] arrStrings) { for (int i = 0; i < (arrStrings.Length /2); i++) { string temp = arrStrings[i]; int rightIndex = arrStrings.Length - 1 - i; arrStrings[i] = arrStrings[rightIndex]; arrStrings[rightIndex] = temp; } } } }
25.4
66
0.497375
[ "MIT" ]
Zdravko-Kardzhaliyski/Technology-Fundamentals
3.ArraysLab/ArraysLab/ReverseArrayOfStrings/ReverseArrayOfStrings.cs
764
C#
using Android.Content; using Android.Util; using Android.Views; using DialogMessaging; using MvvmCross.Platforms.Android.Binding.Binders; namespace SimpleMenu.Droid.Helper { public class ViewBinder : MvxAndroidViewBinder { #region Public Methods public override void BindView(View view, Context context, IAttributeSet attrs) { base.BindView(view, context, attrs); MessagingService.OnViewInflated(view, attrs); } #endregion #region Constructors public ViewBinder(object source) : base(source) { } #endregion } }
23.777778
86
0.643302
[ "Apache-2.0" ]
lewisbennett/simple-menu-net
src/SimpleMenu.Droid/Helper/ViewBinder.cs
644
C#
// Crest Ocean System // This file is subject to the MIT License as seen in the root of this folder structure (LICENSE) using UnityEngine; namespace Crest { /// <summary> /// Registers a custom input to the wave shape. Attach this GameObjects that you want to render into the displacmeent textures to affect ocean shape. /// </summary> [ExecuteAlways] [AddComponentMenu(MENU_PREFIX + "Animated Waves Input")] [HelpURL(Internal.Constants.HELP_URL_BASE_USER + "ocean-simulation.html" + Internal.Constants.HELP_URL_RP + "#animated-waves")] public class RegisterAnimWavesInput : RegisterLodDataInputWithSplineSupport<LodDataMgrAnimWaves> { /// <summary> /// The version of this asset. Can be used to migrate across versions. This value should /// only be changed when the editor upgrades the version. /// </summary> [SerializeField, HideInInspector] #pragma warning disable 414 int _version = 0; #pragma warning restore 414 public override bool Enabled => true; [Header("Anim Waves Input Settings")] [SerializeField, Tooltip("Which octave to render into, for example set this to 2 to use render into the 2m-4m octave. These refer to the same octaves as the wave spectrum editor. Set this value to 0 to render into all LODs.")] float _octaveWavelength = 0f; public override float Wavelength => _octaveWavelength; public readonly static Color s_gizmoColor = new Color(0f, 1f, 0f, 0.5f); protected override Color GizmoColor => s_gizmoColor; protected override string ShaderPrefix => "Crest/Inputs/Animated Waves"; protected override string SplineShaderName => "Crest/Inputs/Animated Waves/Set Base Water Height Using Geometry"; protected override Vector2 DefaultCustomData => Vector2.zero; [SerializeField, Tooltip(k_displacementCorrectionTooltip)] bool _followHorizontalMotion = true; protected override bool FollowHorizontalMotion => _followHorizontalMotion; [SerializeField, Tooltip("Inform ocean how much this input will displace the ocean surface vertically. This is used to set bounding box heights for the ocean tiles.")] float _maxDisplacementVertical = 0f; [SerializeField, Tooltip("Inform ocean how much this input will displace the ocean surface horizontally. This is used to set bounding box widths for the ocean tiles.")] float _maxDisplacementHorizontal = 0f; [SerializeField, Tooltip("Use the bounding box of an attached renderer component to determine the max vertical displacement.")] [Predicated(typeof(MeshRenderer)), DecoratedField] bool _reportRendererBoundsToOceanSystem = false; protected override void Update() { base.Update(); if (OceanRenderer.Instance == null) { return; } var maxDispVert = _maxDisplacementVertical; // let ocean system know how far from the sea level this shape may displace the surface if (_reportRendererBoundsToOceanSystem) { var minY = _renderer.bounds.min.y; var maxY = _renderer.bounds.max.y; var seaLevel = OceanRenderer.Instance.SeaLevel; maxDispVert = Mathf.Max(maxDispVert, Mathf.Abs(seaLevel - minY), Mathf.Abs(seaLevel - maxY)); } if (_maxDisplacementHorizontal > 0f || maxDispVert > 0f) { OceanRenderer.Instance.ReportMaxDisplacementFromShape(_maxDisplacementHorizontal, maxDispVert, 0f); } } } }
45.345679
234
0.680915
[ "MIT" ]
Libertus-Lab/crest
crest/Assets/Crest/Crest/Scripts/LodData/RegisterAnimWavesInput.cs
3,675
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // <auto-generated/> #nullable disable using System; using System.Collections.Generic; using Azure.Core; namespace Azure.Messaging.EventGrid.SystemEvents { /// <summary> Schema of the Data property of an EventGridEvent for an Microsoft.Communication.ChatThreadCreatedWithUser event. </summary> public partial class ACSChatThreadCreatedWithUserEventData : ACSChatThreadEventBaseProperties { /// <summary> Initializes a new instance of ACSChatThreadCreatedWithUserEventData. </summary> internal ACSChatThreadCreatedWithUserEventData() { Properties = new ChangeTrackingDictionary<string, object>(); Members = new ChangeTrackingList<ACSChatThreadMemberProperties>(); } /// <summary> Initializes a new instance of ACSChatThreadCreatedWithUserEventData. </summary> /// <param name="recipientId"> The MRI of the target user. </param> /// <param name="transactionId"> The transaction id will be used as co-relation vector. </param> /// <param name="threadId"> The chat thread id. </param> /// <param name="createTime"> The original creation time of the thread. </param> /// <param name="version"> The version of the thread. </param> /// <param name="createdBy"> The MRI of the creator of the thread. </param> /// <param name="properties"> The thread properties. </param> /// <param name="members"> The list of properties of users who are part of the thread. </param> internal ACSChatThreadCreatedWithUserEventData(string recipientId, string transactionId, string threadId, DateTimeOffset? createTime, int? version, string createdBy, IReadOnlyDictionary<string, object> properties, IReadOnlyList<ACSChatThreadMemberProperties> members) : base(recipientId, transactionId, threadId, createTime, version) { CreatedBy = createdBy; Properties = properties; Members = members; } /// <summary> The MRI of the creator of the thread. </summary> public string CreatedBy { get; } /// <summary> The thread properties. </summary> public IReadOnlyDictionary<string, object> Properties { get; } /// <summary> The list of properties of users who are part of the thread. </summary> public IReadOnlyList<ACSChatThreadMemberProperties> Members { get; } } }
51.729167
341
0.695127
[ "MIT" ]
bquantump/azure-sdk-for-net
sdk/eventgrid/Azure.Messaging.EventGrid/src/Generated/Models/ACSChatThreadCreatedWithUserEventData.cs
2,483
C#