content
stringlengths
5
1.04M
avg_line_length
float64
1.75
12.9k
max_line_length
int64
2
244k
alphanum_fraction
float64
0
0.98
licenses
list
repository_name
stringlengths
7
92
path
stringlengths
3
249
size
int64
5
1.04M
lang
stringclasses
2 values
using System; using System.Collections.Generic; using Cosmos.Common; using IL2CPU.API.Attribs; namespace Cosmos.System_Plugs.System; [Plug(Target = typeof(double))] public static class DoubleImpl { public static string ToString(ref double aThis) => StringHelper.GetNumberString(aThis); public static string ToString(ref double aThis, string format, IFormatProvider provider) => aThis.ToString(); public static double Parse(string s) { //Format of Double string: [whitespace][sign][integral-digits[,]]integral-digits[.[fractional-digits]][E[sign]exponential-digits][whitespace] //Validate input if (s is null) { throw new ArgumentNullException("s can not be null"); } //Remove leading whitespaces while (s.Length != 0 && (s[0] == ' ' || s[0] == '\n' || s[0] == '\t')) { s = s.Substring(1); } //Check that string is not finished too early if (s.Length == 0) { throw new FormatException(); } //Check for sign short sign = 1; if (s[0] == '-') { s = s.Substring(1); sign = -1; } else if (s[0] == '+') { s = s.Substring(1); } //Check that string is not finished too early if (s.Length == 0) { throw new FormatException(); } //Read in number var internalDigits = new List<int>(); var fractionalDigits = new List<int>(); var foundDecimal = false; //Iterate until fully parsed or an E/Whitespace is found //Assume english standard, so . == decimal seperator and , == thousands seperator while (s.Length != 0) { var active = s[0]; if (active == 'E' || active == 'e' || active == ' ' || active == '\n' || active == '\t') { break; } s = s.Substring(1); if (active == '.') { foundDecimal = true; } else if (active == ',') { } else if (active >= '0' && active <= '9') { if (foundDecimal) { fractionalDigits.Add(Int32.Parse(active.ToString())); } else { internalDigits.Add(Int32.Parse(active.ToString())); } } else { throw new FormatException(); } } //Iterate through rest of string double multiplier = 0; while (s.Length != 0) { //Check for exponential notation i.e. 8.1E10 = 8.1 * 10^10 + Whitespaces //E can only be followed by integers if (s[0] == 'E' || s[0] == 'e') { multiplier = Double.Parse(s.Substring(1)); break; } if (s[0] == ' ' || s[0] == '\n' || s[0] == '\t') { s = s.Substring(1); } else { throw new FormatException(); } } //Create double double parsed = 0; for (var i = 0; i < internalDigits.Count; i++) { parsed += internalDigits[i] * Math.Pow(10, internalDigits.Count - (i + 1)); } for (var i = 0; i < fractionalDigits.Count; i++) { parsed += fractionalDigits[i] * Math.Pow(10, -1 * (i + 1)); } parsed *= Math.Pow(10, multiplier); parsed *= sign; return parsed; } public static bool TryParse(string s, out double result) { try { result = Parse(s); return true; } catch (Exception) { result = 0; return false; } } }
26.225166
149
0.451263
[ "BSD-3-Clause" ]
Kiirx/Cosmos
source/Cosmos.System2_Plugs/System/DoubleImpl.cs
3,960
C#
// ****************************************************************************************************************************** // // Copyright (c) 2018-2021 InterlockLedger Network // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met // // * Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of the copyright holder nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES, LOSS OF USE, DATA, OR PROFITS, OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // ****************************************************************************************************************************** using System.Globalization; namespace InterlockLedger.Tags; public static class TagProvider { public static ILTag DeserializeFrom(Stream s) { if (s.HasBytes()) { var tagId = s.DecodeTagId(); return !_deserializers.ContainsKey(tagId) ? new ILTagUnknown(tagId, s) : _deserializers[tagId].fromStream(s); } return ILTagNull.Instance; } public static ILTag DeserializeFrom(byte[] bytes) { using var ms = new MemoryStream(bytes); return DeserializeFrom(ms); } public static ILTag DeserializeFromJson(ulong tagId, object payload) => payload is null ? ILTagNull.Instance : !_deserializers.ContainsKey(tagId) ? throw new ArgumentException($"Unknown tagId: {tagId}", nameof(tagId)) : _deserializers[tagId].fromJson(payload); public static bool HasDeserializer(ulong id) => _deserializers.ContainsKey(id); public static ILTag NoJson(object json) => throw new InvalidOperationException($"Can't deserialize from json"); public static void RegisterDeserializer(ulong id, Func<Stream, ILTag> deserializer, Func<object, ILTag> jsonDeserializer = null) { if (HasDeserializer(id)) throw new ArgumentException($"Can't redefine deserializer for id: {id}", nameof(id)); _deserializers[id] = ( deserializer.Required(), jsonDeserializer ?? NoJson ); } public static void RegisterDeserializersFrom(params ITagDeserializersProvider[] providers) { foreach (var provider in providers) foreach (var (id, deserializer, jsonDeserializer) in provider.Deserializers) RegisterDeserializer(id, deserializer, jsonDeserializer); } private static readonly Dictionary<ulong, (Func<Stream, ILTag> fromStream, Func<object, ILTag> fromJson)> _deserializers = new() { [ILTagId.Null] = (_ => ILTagNull.Instance, _ => ILTagNull.Instance), [ILTagId.Bool] = (s => s.ReadSingleByte() != 0 ? ILTagBool.True : ILTagBool.False, o => (bool)o ? ILTagBool.True : ILTagBool.False), [ILTagId.Int8] = (s => new ILTagInt8(s, ILTagId.Int8), o => new ILTagInt8(Convert.ToSByte(o, CultureInfo.InvariantCulture))), [ILTagId.UInt8] = (s => new ILTagUInt8(s, ILTagId.UInt8), o => new ILTagUInt8(Convert.ToByte(o, CultureInfo.InvariantCulture))), [ILTagId.Int16] = (s => new ILTagInt16(s, ILTagId.Int16), o => new ILTagInt16(Convert.ToInt16(o, CultureInfo.InvariantCulture))), [ILTagId.UInt16] = (s => new ILTagUInt16(s, ILTagId.UInt16), o => new ILTagUInt16(Convert.ToUInt16(o, CultureInfo.InvariantCulture))), [ILTagId.Int32] = (s => new ILTagInt32(s, ILTagId.Int32), o => new ILTagInt32(Convert.ToInt32(o, CultureInfo.InvariantCulture))), [ILTagId.UInt32] = (s => new ILTagUInt32(s, ILTagId.UInt32), o => new ILTagUInt32(Convert.ToUInt32(o, CultureInfo.InvariantCulture))), [ILTagId.Int64] = (s => new ILTagInt64(s, ILTagId.Int64), o => new ILTagInt64(Convert.ToInt64(o, CultureInfo.InvariantCulture))), [ILTagId.UInt64] = (s => new ILTagUInt64(s, ILTagId.UInt64), o => new ILTagUInt64(Convert.ToUInt64(o, CultureInfo.InvariantCulture))), [ILTagId.ILInt] = (s => new ILTagILInt(s, ILTagId.ILInt), o => new ILTagILInt(Convert.ToUInt64(o, CultureInfo.InvariantCulture))), [ILTagId.ILIntSigned] = (s => new ILTagILIntSigned(s, ILTagId.ILIntSigned), o => new ILTagILIntSigned(Convert.ToInt64(o, CultureInfo.InvariantCulture))), [ILTagId.Binary32] = (s => new ILTagBinary32(s), NoJson), [ILTagId.Binary64] = (s => new ILTagBinary64(s), NoJson), [ILTagId.Binary128] = (s => new ILTagBinary128(s), NoJson), [ILTagId.ByteArray] = (s => new ILTagByteArray(s), o => new ILTagByteArray(o)), [ILTagId.String] = (s => new ILTagString(s), o => new ILTagString(o as string)), [ILTagId.BigInteger] = (s => new ILTagBigInteger(s), NoJson), [ILTagId.BigDecimal] = (s => new ILTagBigDecimal(s), NoJson), [ILTagId.ILIntArray] = (s => new ILTagArrayOfILInt(s), o => ILTagArrayOfILInt.FromJson(o)), [ILTagId.ILTagArray] = (s => new ILTagArrayOfILTag<ILTag>(s), o => ILTagArrayOfILTag<ILTag>.FromJson(o)), [ILTagId.Sequence] = (s => new ILTagSequence(s), o => new ILTagSequence(o)), [ILTagId.Version] = (s => new ILTagVersion(s), o => ILTagVersion.FromJson(o)), [ILTagId.Range] = (s => new ILTagRange(s), o => new ILTagRange(new LimitedRange((string)o))), [ILTagId.Dictionary] = (s => new ILTagDictionary<ILTag>(s), o => new ILTagDictionary<ILTag>(o)), [ILTagId.StringDictionary] = (s => new ILTagStringDictionary(s), o => new ILTagStringDictionary(o)), [ILTagId.PubKey] = (s => TagPubKey.Resolve(s), o => TagPubKey.Resolve((string)o)), [ILTagId.Signature] = (s => new TagSignature(s), NoJson), [ILTagId.Hash] = (s => new TagHash(s), o => TagHash.From((string)o)), [ILTagId.PublicRSAParameters] = (s => new TagPublicRSAParameters(s), NoJson), [ILTagId.RSAParameters] = (s => new TagRSAParameters(s), NoJson), [ILTagId.Encrypted] = (s => new TagEncrypted(s), NoJson), [ILTagId.InterlockId] = (s => InterlockId.DeserializeAndResolve(s), o => InterlockId.Resolve((string)o)), [ILTagId.InterlockKey] = (s => new InterlockKey(s), NoJson), [ILTagId.InterlockSigningKey] = (s => new InterlockSigningKeyData(s), NoJson), [ILTagId.InterlockUpdatableSigningKey] = (s => new InterlockUpdatableSigningKeyData(s), NoJson), [ILTagId.Hmac] = (s => new TagHmac(s), o => new TagHmac((string)o)), [ILTagId.Certificate] = (s => new TagCertificate(s), NoJson), [ILTagId.SignedValue] = (s => s.SignedValueFromStream(), NoJson), [ILTagId.IdentifiedSignature] = (s => new IdentifiedSignature.Payload(ILTagId.IdentifiedSignature, s), NoJson), [ILTagId.Reader] = (s => new TagReader(s), NoJson), [ILTagId.ReadingKey] = (s => new TagReadingKey(s), NoJson), [ILTagId.EncryptedBlob] = (s => new EncryptedBlob.Payload(ILTagId.EncryptedBlob, s), NoJson), [ILTagId.InterlockKeyAppPermission] = (s => new AppPermissions.Tag(s), NoJson), [ILTagId.EncryptedText] = (s => new EncryptedText.Payload(ILTagId.EncryptedText, s), NoJson), [ILTagId.ECParameters] = (s => new ECDsaParameters.Payload(ILTagId.ECParameters, s), NoJson), [ILTagId.DataModel] = (s => new ILTagDataModel(s), NoJson), [ILTagId.DataField] = (s => new ILTagDataField(s), NoJson), [ILTagId.DataIndex] = (s => new ILTagDataIndex(s), NoJson), }; }
65.282443
161
0.657156
[ "BSD-3-Clause" ]
interlockledger/il2tags
InterlockLedger.Tags/Core/Tags/TagProvider.cs
8,552
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.Linq; using System.Numerics; using System.Text.RegularExpressions; using Microsoft.Graphics.Canvas; using Microsoft.Graphics.Canvas.Brushes; using Microsoft.Toolkit.Uwp.UI.Media.Geometry.Core; namespace Microsoft.Toolkit.Uwp.UI.Media.Geometry.Elements.Brush { /// <summary> /// Represents a CanvasLinearGradientBrush with GradientStopHdrs /// </summary> internal sealed class LinearGradientHdrBrushElement : AbstractCanvasBrushElement { private Vector2 _startPoint; private Vector2 _endPoint; private CanvasAlphaMode _alphaMode; private CanvasBufferPrecision _bufferPrecision; private CanvasEdgeBehavior _edgeBehavior; private CanvasColorSpace _preInterpolationColorSpace; private CanvasColorSpace _postInterpolationColorSpace; private List<CanvasGradientStopHdr> _gradientStopHdrs; /// <summary> /// Initializes a new instance of the <see cref="LinearGradientHdrBrushElement"/> class. /// </summary> /// <param name="capture">Capture object</param> public LinearGradientHdrBrushElement(Capture capture) { // Set the default values _startPoint = Vector2.Zero; _endPoint = Vector2.Zero; _opacity = 1f; _alphaMode = (CanvasAlphaMode)0; _bufferPrecision = (CanvasBufferPrecision)0; _edgeBehavior = (CanvasEdgeBehavior)0; // Default ColorSpace is sRGB _preInterpolationColorSpace = CanvasColorSpace.Srgb; _postInterpolationColorSpace = CanvasColorSpace.Srgb; _gradientStopHdrs = new List<CanvasGradientStopHdr>(); // Initialize Initialize(capture); } /// <summary> /// Creates the CanvasLinearGradientBrush from the parsed data /// </summary> /// <param name="resourceCreator">ICanvasResourceCreator object</param> /// <returns>Instance of <see cref="ICanvasBrush"/></returns> public override ICanvasBrush CreateBrush(ICanvasResourceCreator resourceCreator) { var brush = CanvasLinearGradientBrush.CreateHdr( resourceCreator, _gradientStopHdrs.ToArray(), _edgeBehavior, _alphaMode, _preInterpolationColorSpace, _postInterpolationColorSpace, _bufferPrecision); brush.StartPoint = _startPoint; brush.EndPoint = _endPoint; brush.Opacity = _opacity; return brush; } /// <summary> /// Gets the Regex for extracting Brush Element Attributes /// </summary> /// <returns>Regex</returns> protected override Regex GetAttributesRegex() { return RegexFactory.GetAttributesRegex(BrushType.LinearGradientHdr); } /// <summary> /// Gets the Brush Element Attributes from the Match /// </summary> /// <param name="match">Match object</param> protected override void GetAttributes(Match match) { // Start Point float.TryParse(match.Groups["StartX"].Value, out var startX); float.TryParse(match.Groups["StartY"].Value, out var startY); _startPoint = new Vector2(startX, startY); // End Point float.TryParse(match.Groups["EndX"].Value, out var endX); float.TryParse(match.Groups["EndY"].Value, out var endY); _endPoint = new Vector2(endX, endY); // Opacity (optional) var group = match.Groups["Opacity"]; if (group.Success) { float.TryParse(group.Value, out _opacity); } // Alpha Mode (optional) group = match.Groups["AlphaMode"]; if (group.Success) { Enum.TryParse(group.Value, out _alphaMode); } // Buffer Precision (optional) group = match.Groups["BufferPrecision"]; if (group.Success) { Enum.TryParse(group.Value, out _bufferPrecision); } // Edge Behavior (optional) group = match.Groups["EdgeBehavior"]; if (group.Success) { Enum.TryParse(group.Value, out _edgeBehavior); } // Pre Interpolation ColorSpace (optional) group = match.Groups["PreColorSpace"]; if (group.Success) { Enum.TryParse(group.Value, out _preInterpolationColorSpace); } // Post Interpolation ColorSpace (optional) group = match.Groups["PostColorSpace"]; if (group.Success) { Enum.TryParse(group.Value, out _postInterpolationColorSpace); } // GradientStopHdrs group = match.Groups["GradientStops"]; if (group.Success) { _gradientStopHdrs.Clear(); foreach (Capture capture in group.Captures) { var gradientMatch = RegexFactory.GradientStopHdrRegex.Match(capture.Value); if (!gradientMatch.Success) { continue; } // Main Attributes var main = gradientMatch.Groups["Main"]; if (main.Success) { var mainMatch = RegexFactory.GetAttributesRegex(GradientStopAttributeType.MainHdr) .Match(main.Value); float.TryParse(mainMatch.Groups["Position"].Value, out float position); float.TryParse(mainMatch.Groups["X"].Value, out float x); float.TryParse(mainMatch.Groups["Y"].Value, out float y); float.TryParse(mainMatch.Groups["Z"].Value, out float z); float.TryParse(mainMatch.Groups["W"].Value, out float w); var color = new Vector4(x, y, z, w); _gradientStopHdrs.Add(new CanvasGradientStopHdr() { Color = color, Position = position }); } // Additional Attributes var additional = gradientMatch.Groups["Additional"]; if (!additional.Success) { continue; } foreach (Capture addCapture in additional.Captures) { var addMatch = RegexFactory.GetAttributesRegex(GradientStopAttributeType.AdditionalHdr) .Match(addCapture.Value); float.TryParse(addMatch.Groups["Position"].Value, out float position); float.TryParse(addMatch.Groups["X"].Value, out float x); float.TryParse(addMatch.Groups["Y"].Value, out float y); float.TryParse(addMatch.Groups["Z"].Value, out float z); float.TryParse(addMatch.Groups["W"].Value, out float w); var color = new Vector4(x, y, z, w); _gradientStopHdrs.Add(new CanvasGradientStopHdr() { Color = color, Position = position }); } } // Sort the stops based on their position if (_gradientStopHdrs.Any()) { _gradientStopHdrs = _gradientStopHdrs.OrderBy(g => g.Position).ToList(); } } } } }
38.877358
111
0.540403
[ "MIT" ]
ArchieCoder/WindowsCommunityToolkit
Microsoft.Toolkit.Uwp.UI.Media/Geometry/Elements/Brush/LinearGradientHdrBrushElement.cs
8,242
C#
namespace Skribble { internal readonly struct DoubleToken : IToken { public double Value { get; } public DoubleToken(double value) { Value = value; } public override string ToString() { return $"DOUBLE {Value}"; } } }
23.384615
52
0.523026
[ "Apache-2.0" ]
k-boyle/Skribble
src/Skribble.Interpreter/Lexing/Tokens/DoubleToken.cs
306
C#
using System; using System.Windows; namespace MaterialDesignThemes.Wpf.AddOns { /// <summary> /// A banner to display messages with one or two action buttons. /// </summary> /// <remarks>Overrides MD's snackbar, which has the similar behavior.</remarks> public class Banner : Snackbar { #region Private attributes and properties private Action _messageQueueRegistrationCleanUp; // used for base attribute override. #endregion #region Constructors /// <summary> /// Creates a new instance of <see cref="Banner"/>. /// </summary> public Banner() { if (DismissOnActionButtonClick) // auto close banner when button is click by default RegisterDismissOnClickEvents(); } /// <summary> /// Static constructor for <see cref="Banner"/> type. /// Override some base dependency properties. /// </summary> static Banner() { DefaultStyleKeyProperty.OverrideMetadata(typeof(Banner), new FrameworkPropertyMetadata(typeof(Banner))); } #endregion #region Protected methods /// <summary> /// Called when the banner must be closed. /// </summary> protected static void Close(object sender, RoutedEventArgs e) { if (sender is Banner banner) banner.SetCurrentValue(IsActiveProperty, false); } #endregion #region Dependency properties /// <summary> /// MessageQueue property override to match our own message queue <see cref="InformationMessageQueue"/> type. /// </summary> public new InformationMessageQueue MessageQueue { get => (InformationMessageQueue)GetValue(MessageQueueProperty); set { if (!(value is null) && value.Dispatcher != Dispatcher) throw new InvalidOperationException("Objects must be created by the same thread."); SetValue(MessageQueueProperty, value); } } /// <summary> /// Registers <see cref="MessageQueue"/> as a dependency property. /// </summary> public new static readonly DependencyProperty MessageQueueProperty = DependencyProperty.Register( nameof(MessageQueue), typeof(InformationMessageQueue), typeof(Banner), new PropertyMetadata(default(InformationMessageQueue), MessageQueuePropertyChangedCallback)); /// <summary> /// Override of base private handler so we correctly pair to our own definition of <see cref="InformationMessageQueue"/>. /// </summary> /// <param name="dependencyObject">Banner that triggered the event.</param> /// <param name="dependencyPropertyChangedEventArgs">New property value information.</param> private static void MessageQueuePropertyChangedCallback(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs dependencyPropertyChangedEventArgs) { var snackbar = (Banner)dependencyObject; snackbar._messageQueueRegistrationCleanUp?.Invoke(); var messageQueue = dependencyPropertyChangedEventArgs.NewValue as InformationMessageQueue; snackbar._messageQueueRegistrationCleanUp = messageQueue?.Pair(snackbar); } /// <summary> /// Gets or sets the style to be applied to the secondary button. /// </summary> public Style SecondaryActionButtonStyle { get => (Style)GetValue(SecondaryActionButtonStyleProperty); set => SetValue(SecondaryActionButtonStyleProperty, value); } /// <summary> /// Registers <see cref="SecondaryActionButtonStyle"/> as a dependency property. /// </summary> public static readonly DependencyProperty SecondaryActionButtonStyleProperty = DependencyProperty.Register( nameof(SecondaryActionButtonStyle), typeof(Style), typeof(Banner), new PropertyMetadata(default(Style))); /// <summary> /// Gets or sets a value indicating if the action buttons must be inverted in template. /// </summary> public bool AreActionButtonPositionsInverted { get => (bool)GetValue(AreActionButtonPositionsInvertedProperty); set => SetValue(AreActionButtonPositionsInvertedProperty, value); } /// <summary> /// Registers <see cref="AreActionButtonPositionsInverted"/> as a dependency property. /// </summary> public static readonly DependencyProperty AreActionButtonPositionsInvertedProperty = DependencyProperty.Register( nameof(AreActionButtonPositionsInverted), typeof(bool), typeof(Banner), new PropertyMetadata(default(bool))); /// <summary> /// Gets or sets a value indicating if dismissing is active when clicking action buttons (defaults to true). /// </summary> public bool DismissOnActionButtonClick { get => (bool)GetValue(DismissOnActionButtonClickProperty); set => SetValue(DismissOnActionButtonClickProperty, value); } /// <summary> /// Registers <see cref="DismissOnActionButtonClick"/> as a dependency property. /// </summary> public static readonly DependencyProperty DismissOnActionButtonClickProperty = DependencyProperty.Register( nameof(DismissOnActionButtonClick), typeof(bool), typeof(Banner), new PropertyMetadata(true, DismissOnActionButtonClickChanged)); /// <summary> /// Called whenever the <see cref="DismissOnActionButtonClick"/> property changes. /// </summary> /// <param name="sender">The object whose property changed.</param> /// <param name="args">Information about the property change.</param> private static void DismissOnActionButtonClickChanged(DependencyObject sender, DependencyPropertyChangedEventArgs args) { if (!(sender is Banner casted)) return; if (args.NewValue as bool? == true) casted.RegisterDismissOnClickEvents(); else casted.UnregisterDismissOnClickEvents(); } /// <summary> /// Registers event handlers for message clicks management. /// </summary> private void RegisterDismissOnClickEvents() { AddHandler(InformationMessage.ActionClickEvent, new RoutedEventHandler(Close), true); AddHandler(InformationMessage.SecondaryActionClickEvent, new RoutedEventHandler(Close), true); } /// <summary> /// Clear event handlers for message clicks management. /// </summary> private void UnregisterDismissOnClickEvents() { RemoveHandler(InformationMessage.ActionClickEvent, new RoutedEventHandler(Close)); RemoveHandler(InformationMessage.SecondaryActionClickEvent, new RoutedEventHandler(Close)); } #endregion } }
45.191083
176
0.649049
[ "MIT" ]
davidlebourdais/MaterialDesignInXamlToolkitAddOns
MaterialDesignThemes.Wpf.AddOns/Banner.cs
7,097
C#
// Copyright (c) 2018-2020 Alexander Bogarsukov. // Licensed under the MIT license. See the LICENSE.md file in the project root for more information. using System; using System.Collections.Generic; namespace UnityFx.Async { /// <summary> /// Represents the producer side of an asynchronous operation unbound to a delegate, providing access to the consumer side through the <see cref="Operation"/> property. /// </summary> /// <seealso cref="IAsyncOperation"/> public interface IAsyncCompletionSource { /// <summary> /// Gets the operation being controller by the source. /// </summary> /// <value>The underlying operation instance.</value> IAsyncOperation Operation { get; } /// <summary> /// Attempts to set the operation progress value in range [0, 1]. /// </summary> /// <param name="progress">The operation progress in range [0, 1].</param> /// <exception cref="ArgumentOutOfRangeException">Thrown if <paramref name="progress"/> is not in range [0, 1].</exception> /// <exception cref="ObjectDisposedException">Thrown is the operation is disposed.</exception> /// <returns>Returns <see langword="true"/> if the attemp was successfull; <see langword="false"/> otherwise.</returns> /// <seealso cref="TrySetCompleted"/> bool TrySetProgress(float progress); /// <summary> /// Attempts to transition the underlying <see cref="IAsyncOperation"/> into the <see cref="AsyncOperationStatus.Canceled"/> state. /// </summary> /// <exception cref="ObjectDisposedException">Thrown is the operation is disposed.</exception> /// <returns>Returns <see langword="true"/> if the attemp was successfull; <see langword="false"/> otherwise.</returns> /// <seealso cref="TrySetException(Exception)"/> /// <seealso cref="TrySetCompleted"/> bool TrySetCanceled(); /// <summary> /// Attempts to transition the underlying <see cref="IAsyncOperation"/> into the <see cref="AsyncOperationStatus.Faulted"/> state. /// </summary> /// <param name="exception">An exception that caused the operation to end prematurely.</param> /// <exception cref="ArgumentNullException">Thrown if <paramref name="exception"/> is <see langword="null"/>.</exception> /// <exception cref="ObjectDisposedException">Thrown is the operation is disposed.</exception> /// <returns>Returns <see langword="true"/> if the attemp was successfull; <see langword="false"/> otherwise.</returns> /// <seealso cref="TrySetCanceled"/> /// <seealso cref="TrySetCompleted"/> bool TrySetException(Exception exception); /// <summary> /// Attempts to transition the underlying <see cref="IAsyncOperation"/> into the <see cref="AsyncOperationStatus.RanToCompletion"/> state. /// </summary> /// <exception cref="ObjectDisposedException">Thrown is the operation is disposed.</exception> /// <returns>Returns <see langword="true"/> if the attemp was successfull; <see langword="false"/> otherwise.</returns> /// <seealso cref="TrySetCanceled"/> /// <seealso cref="TrySetException(Exception)"/> /// <seealso cref="TrySetProgress(float)"/> bool TrySetCompleted(); } }
49.870968
169
0.713454
[ "MIT" ]
Arvtesh/UnityFx.Async
src/UnityFx.Async/Api/Interfaces/IAsyncCompletionSource.cs
3,094
C#
using UnityEngine; public class Shake : MonoBehaviour { private float shakeTimer; private const float shakeTimerRef = .2f; private const float shakeForceRef = 0.8f; private float shakeForce; private Vector3 basePos; private void Start() { shakeTimer = 0f; basePos = transform.position; } public void ShakeCamera() { shakeTimer = shakeTimerRef; shakeForce = shakeForceRef; } private void Update() { if (shakeTimer > 0f) { transform.localPosition = basePos + Random.insideUnitSphere * shakeForce * shakeTimer; shakeForce -= Time.deltaTime * .1f; shakeTimer -= Time.deltaTime; } else transform.position = basePos; } }
22.514286
98
0.598985
[ "Apache-2.0" ]
Xwilarg/Paint-Jam
Assets/Scripts/Shake.cs
790
C#
// Copyright (c) Dapplo and contributors. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace Dapplo.Config.Tests.ConverterTests { public enum TestEnum { Val1, Val2, Val3 } }
22.166667
101
0.74812
[ "MIT" ]
dapplo/Dapplo.Config
src/Dapplo.Config.Tests/ConverterTests/TestEnum.cs
268
C#
// Copyright (c) All contributors. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace Jmelosegui.DevOpsCLI.Commands { using McMaster.Extensions.CommandLineUtils; using Microsoft.Extensions.Logging; [Command("git", Description = "Commands for work with git repositories is Azure DevOps.")] [Subcommand(typeof(CommitCommand))] [Subcommand(typeof(RepositoryCommand))] public sealed class GitCommand : ProjectCommandBase { public GitCommand(ApplicationConfiguration settings, ILogger<GitCommand> logger) : base(settings, logger) { } } }
34.3
101
0.718659
[ "MIT" ]
jmelosegui/DevOps-CLI
DevOpsCLI/Commands/Git/GitCommand.cs
688
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.ComponentModel.DataAnnotations; namespace VipcoMachine.Models { public class Employee { [Key] public string EmpCode { get; set; } [StringLength(20)] public string Title { get; set; } [StringLength(100)] [Required] public string NameThai { get; set; } [StringLength(100)] public string NameEng { get; set; } [StringLength(100)] public string GroupCode { get; set; } [StringLength(100)] public string GroupName { get; set; } public TypeEmployee? TypeEmployee { get; set; } //FK public ICollection<User> Users { get; set; } public ICollection<MachineHasOperator> MachineHasOperators { get; set; } public ICollection<TaskMachine> TaskMachines { get; set; } public ICollection<TaskMachineHasOverTime> TaskMachineHasOverTimes { get; set; } public ICollection<OverTimeDetail> OverTimeDetails { get; set; } // GroupMIS [StringLength(100)] public string GroupMIS { get; set; } public EmployeeGroupMIS EmployeeGroupMIS { get; set; } } public enum TypeEmployee { พนักงานตามโครงการ = 1, พนักงานประจำรายชั่วโมง = 2, พนักงานประจำรายเดือน = 3, พนักงานทดลองงาน = 4, พนักงานพม่า = 5 } public enum TitleEmployee { นาย,นางสาว,นาง } }
26.508772
88
0.616148
[ "MIT" ]
nuttanon001/VipcoMachineAndVipcoOverTime
Models/Employee.cs
1,707
C#
// ReSharper disable ArrangeTrailingCommaInMultilineLists namespace Content.Server { public static class IgnoredComponents { public static string[] List => new [] { "ConstructionGhost", "IconSmooth", "LowWall", "ReinforcedWall", "InteractionOutline", "MeleeWeaponArcAnimation", "AnimationsTest", "ItemStatus", "Marker", "Clickable", "RadiatingLight", "Icon", "ClientEntitySpawner", "ToySingularity" }; } }
25.083333
57
0.518272
[ "MIT" ]
BingoJohnson/space-station-14
Content.Server/IgnoredComponents.cs
602
C#
#region License Header /* * QUANTLER.COM - Quant Fund Development Platform * Quantler Core Trading Engine. Copyright 2018 Quantler B.V. * * 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 License Header namespace Quantler.Messaging { public enum MessageResult { /// <summary> /// Message was processed with success /// </summary> Success, /// <summary> /// Message was processed with a failed result /// </summary> Failure, /// <summary> /// Message can be dead lettered (will not be resend any more) /// </summary> DeadLettered, /// <summary> /// Message should be resend to be picked up by another node/queue /// </summary> Resend } }
29.159091
84
0.657833
[ "Apache-2.0" ]
Quantler/Core
Quantler/Messaging/MessageResult.cs
1,285
C#
using System.Linq; namespace Orchard.Projections.Settings { public class SValue : ISItem { public object Value { get; set; } public SValue(object value) { Value = value; } #region ICloneable Members public object Clone() { return new SValue(Value); } public static SValue operator &(SValue o1, SValue o2) { return o2; } public static SArray operator &(SValue o1, SArray o2) { // concatenate the value with the array return new SArray(new[] { o1 }.Union(o2.Values).ToArray()); } public static SObject operator &(SValue o1, SObject o2) { return o2; } #endregion } }
23.625
71
0.546296
[ "BSD-3-Clause" ]
AzureWebApps/OrchardCMS
Modules/Orchard.Projections/Settings/SValue.cs
758
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.Xna.Framework; //using AnimationAux; using Anarian.DataStructures.Animation.Aux; namespace Anarian.DataStructures.Animation { /// <summary> /// Bones in this model are represented by this class, which /// allows a bone to have more detail associatd with it. /// /// This class allows you to manipulate the local coordinate system /// for objects by changing the scaling, translation, and rotation. /// These are indepenent of the bind transformation originally supplied /// for the model. So, the actual transformation for a bone is /// the product of the: /// /// Scaling /// Bind scaling (scaling removed from the bind transform) /// Rotation /// Translation /// Bind Transformation /// Parent Absolute Transformation /// /// </summary> public class Bone { #region Fields /// <summary> /// Any parent for this bone /// </summary> private Bone parent = null; /// <summary> /// The children of this bone /// </summary> private List<Bone> children = new List<Bone>(); /// <summary> /// The bind transform is the transform for this bone /// as loaded from the original model. It's the base pose. /// I do remove any scaling, though. /// </summary> private Matrix bindTransform = Matrix.Identity; /// <summary> /// The bind scaling component extracted from the bind transform /// </summary> private Vector3 bindScale = Vector3.One; /// <summary> /// Any translation applied to the bone /// </summary> private Vector3 translation = Vector3.Zero; /// <summary> /// Any rotation applied to the bone /// </summary> private Quaternion rotation = Quaternion.Identity; /// <summary> /// Any scaling applied to the bone /// </summary> private Vector3 scale = Vector3.One; #endregion #region Properties /// <summary> /// The bone name /// </summary> public string Name = ""; /// <summary> /// The bone bind transform /// </summary> public Matrix BindTransform { get {return bindTransform;} } /// <summary> /// Inverse of absolute bind transform for skinnning /// </summary> public Matrix SkinTransform { get; set; } /// <summary> /// Bone rotation /// </summary> public Quaternion Rotation {get {return rotation;} set {rotation = value;}} /// <summary> /// Any translations /// </summary> public Vector3 Translation {get {return translation;} set {translation = value;}} /// <summary> /// Any scaling /// </summary> public Vector3 Scale { get { return scale; } set { scale = value; } } /// <summary> /// The parent bone or null for the root bone /// </summary> public Bone Parent { get { return parent; } } /// <summary> /// The children of this bone /// </summary> public List<Bone> Children { get { return children; } } /// <summary> /// The bone absolute transform /// </summary> public Matrix AbsoluteTransform = Matrix.Identity; #endregion #region Operations /// <summary> /// Constructor for a bone object /// </summary> /// <param name="name">The name of the bone</param> /// <param name="bindTransform">The initial bind transform for the bone</param> /// <param name="parent">A parent for this bone</param> public Bone(string name, Matrix bindTransform, Bone parent) { this.Name = name; this.parent = parent; if (parent != null) parent.children.Add(this); // I am not supporting scaling in animation in this // example, so I extract the bind scaling from the // bind transform and save it. this.bindScale = new Vector3(bindTransform.Right.Length(), bindTransform.Up.Length(), bindTransform.Backward.Length()); bindTransform.Right = bindTransform.Right / bindScale.X; bindTransform.Up = bindTransform.Up / bindScale.Y; bindTransform.Backward = bindTransform.Backward / bindScale.Y; this.bindTransform = bindTransform; // Set the skinning bind transform // That is the inverse of the absolute transform in the bind pose ComputeAbsoluteTransform(); SkinTransform = Matrix.Invert(AbsoluteTransform); } public Bone(AnimationAux.Bone bone) { } /// <summary> /// Compute the absolute transformation for this bone. /// </summary> public void ComputeAbsoluteTransform() { Matrix transform = Matrix.CreateScale(Scale * bindScale) * Matrix.CreateFromQuaternion(Rotation) * Matrix.CreateTranslation(Translation) * BindTransform; if (Parent != null) { // This bone has a parent bone AbsoluteTransform = transform * Parent.AbsoluteTransform; } else { // The root bone AbsoluteTransform = transform; } } /// <summary> /// This sets the rotation and translation such that the /// rotation times the translation times the bind after set /// equals this matrix. This is used to set animation values. /// </summary> /// <param name="m">A matrix include translation and rotation</param> public void SetCompleteTransform(Matrix m) { Matrix setTo = m * Matrix.Invert(BindTransform); Translation = setTo.Translation; Rotation = Quaternion.CreateFromRotationMatrix(setTo); } #endregion } }
31.262626
87
0.571082
[ "MIT" ]
KillerrinStudios/Anarian-Game-Engine-MonoGame
Anarian Game Engine.Shared/DataStructures/Animation/Bone.cs
6,192
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 ModelBazy { using System; using System.Data.Entity; using System.Data.Entity.Infrastructure; using System.Data.Entity.Core.Objects; using System.Linq; public partial class WypozyczalniaEntities : DbContext { public WypozyczalniaEntities() : base("name=WypozyczalniaEntities") { } protected override void OnModelCreating(DbModelBuilder modelBuilder) { throw new UnintentionalCodeFirstException(); } public virtual DbSet<Kategorie> Kategorie { get; set; } public virtual DbSet<Klienci> Klienci { get; set; } public virtual DbSet<Pracownicy> Pracownicy { get; set; } public virtual DbSet<Produkty> Produkty { get; set; } public virtual DbSet<ProduktySz> ProduktySz { get; set; } public virtual DbSet<PunktyObslugi> PunktyObslugi { get; set; } public virtual DbSet<Rezerwacje> Rezerwacje { get; set; } public virtual DbSet<RezerwacjeSz> RezerwacjeSz { get; set; } public virtual DbSet<Wypozyczenie> Wypozyczenie { get; set; } public virtual DbSet<WypozyczenieSz> WypozyczenieSz { get; set; } public virtual DbSet<PelnyProdukt> PelnyProdukt { get; set; } public virtual DbSet<WypozyczenieView> WypozyczenieViews { get; set; } public virtual int sp_alterdiagram(string diagramname, Nullable<int> owner_id, Nullable<int> version, byte[] definition) { var diagramnameParameter = diagramname != null ? new ObjectParameter("diagramname", diagramname) : new ObjectParameter("diagramname", typeof(string)); var owner_idParameter = owner_id.HasValue ? new ObjectParameter("owner_id", owner_id) : new ObjectParameter("owner_id", typeof(int)); var versionParameter = version.HasValue ? new ObjectParameter("version", version) : new ObjectParameter("version", typeof(int)); var definitionParameter = definition != null ? new ObjectParameter("definition", definition) : new ObjectParameter("definition", typeof(byte[])); return ((IObjectContextAdapter)this).ObjectContext.ExecuteFunction("sp_alterdiagram", diagramnameParameter, owner_idParameter, versionParameter, definitionParameter); } public virtual int sp_creatediagram(string diagramname, Nullable<int> owner_id, Nullable<int> version, byte[] definition) { var diagramnameParameter = diagramname != null ? new ObjectParameter("diagramname", diagramname) : new ObjectParameter("diagramname", typeof(string)); var owner_idParameter = owner_id.HasValue ? new ObjectParameter("owner_id", owner_id) : new ObjectParameter("owner_id", typeof(int)); var versionParameter = version.HasValue ? new ObjectParameter("version", version) : new ObjectParameter("version", typeof(int)); var definitionParameter = definition != null ? new ObjectParameter("definition", definition) : new ObjectParameter("definition", typeof(byte[])); return ((IObjectContextAdapter)this).ObjectContext.ExecuteFunction("sp_creatediagram", diagramnameParameter, owner_idParameter, versionParameter, definitionParameter); } public virtual int sp_dropdiagram(string diagramname, Nullable<int> owner_id) { var diagramnameParameter = diagramname != null ? new ObjectParameter("diagramname", diagramname) : new ObjectParameter("diagramname", typeof(string)); var owner_idParameter = owner_id.HasValue ? new ObjectParameter("owner_id", owner_id) : new ObjectParameter("owner_id", typeof(int)); return ((IObjectContextAdapter)this).ObjectContext.ExecuteFunction("sp_dropdiagram", diagramnameParameter, owner_idParameter); } public virtual ObjectResult<sp_helpdiagramdefinition_Result> sp_helpdiagramdefinition(string diagramname, Nullable<int> owner_id) { var diagramnameParameter = diagramname != null ? new ObjectParameter("diagramname", diagramname) : new ObjectParameter("diagramname", typeof(string)); var owner_idParameter = owner_id.HasValue ? new ObjectParameter("owner_id", owner_id) : new ObjectParameter("owner_id", typeof(int)); return ((IObjectContextAdapter)this).ObjectContext.ExecuteFunction<sp_helpdiagramdefinition_Result>("sp_helpdiagramdefinition", diagramnameParameter, owner_idParameter); } public virtual ObjectResult<sp_helpdiagrams_Result> sp_helpdiagrams(string diagramname, Nullable<int> owner_id) { var diagramnameParameter = diagramname != null ? new ObjectParameter("diagramname", diagramname) : new ObjectParameter("diagramname", typeof(string)); var owner_idParameter = owner_id.HasValue ? new ObjectParameter("owner_id", owner_id) : new ObjectParameter("owner_id", typeof(int)); return ((IObjectContextAdapter)this).ObjectContext.ExecuteFunction<sp_helpdiagrams_Result>("sp_helpdiagrams", diagramnameParameter, owner_idParameter); } public virtual int sp_renamediagram(string diagramname, Nullable<int> owner_id, string new_diagramname) { var diagramnameParameter = diagramname != null ? new ObjectParameter("diagramname", diagramname) : new ObjectParameter("diagramname", typeof(string)); var owner_idParameter = owner_id.HasValue ? new ObjectParameter("owner_id", owner_id) : new ObjectParameter("owner_id", typeof(int)); var new_diagramnameParameter = new_diagramname != null ? new ObjectParameter("new_diagramname", new_diagramname) : new ObjectParameter("new_diagramname", typeof(string)); return ((IObjectContextAdapter)this).ObjectContext.ExecuteFunction("sp_renamediagram", diagramnameParameter, owner_idParameter, new_diagramnameParameter); } public virtual int sp_upgraddiagrams() { return ((IObjectContextAdapter)this).ObjectContext.ExecuteFunction("sp_upgraddiagrams"); } } }
48.217687
181
0.632901
[ "MIT" ]
amitrega01/WypozyczalniaElektronarzedzi
ModelBazy/ModelBazy.Context.cs
7,090
C#
using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Text; using System.Threading.Tasks; using BTCPayServer.Plugins.Shopify.ApiModels; using Newtonsoft.Json; using Newtonsoft.Json.Linq; namespace BTCPayServer.Plugins.Shopify { public class ShopifyApiClient { private readonly HttpClient _httpClient; private readonly ShopifyApiClientCredentials _credentials; public ShopifyApiClient(IHttpClientFactory httpClientFactory, ShopifyApiClientCredentials credentials) { if (httpClientFactory != null) { _httpClient = httpClientFactory.CreateClient(nameof(ShopifyApiClient)); } else // tests don't provide IHttpClientFactory { _httpClient = new HttpClient(); } _credentials = credentials; var bearer = $"{_credentials.ApiKey}:{_credentials.ApiPassword}"; bearer = NBitcoin.DataEncoders.Encoders.Base64.EncodeData(Encoding.UTF8.GetBytes(bearer)); _httpClient.DefaultRequestHeaders.Add("Authorization", "Basic " + bearer); } private HttpRequestMessage CreateRequest(string shopName, HttpMethod method, string action, string relativeUrl = null) { var url = $"https://{(shopName.Contains(".", StringComparison.InvariantCulture) ? shopName : $"{shopName}.myshopify.com")}/{relativeUrl ?? ("admin/api/2020-07/" + action)}"; var req = new HttpRequestMessage(method, url); return req; } private async Task<string> SendRequest(HttpRequestMessage req) { using var resp = await _httpClient.SendAsync(req); var strResp = await resp.Content.ReadAsStringAsync(); if (strResp?.StartsWith("{\"errors\":\"[API] Invalid API key or access token", StringComparison.OrdinalIgnoreCase) == true) throw new ShopifyApiException("Invalid API key or access token"); return strResp; } public async Task<CreateWebhookResponse> CreateWebhook(string topic, string address, string format = "json") { var req = CreateRequest(_credentials.ShopName, HttpMethod.Post, $"webhooks.json"); req.Content = new StringContent(JsonConvert.SerializeObject(new {topic, address, format}), Encoding.UTF8, "application/json"); var strResp = await SendRequest(req); return JsonConvert.DeserializeObject<CreateWebhookResponse>(strResp); } public async Task RemoveWebhook(string id) { var req = CreateRequest(_credentials.ShopName, HttpMethod.Delete, $"webhooks/{id}.json"); var strResp = await SendRequest(req); } public async Task<string[]> CheckScopes() { var req = CreateRequest(_credentials.ShopName, HttpMethod.Get, null, "admin/oauth/access_scopes.json"); return JObject.Parse(await SendRequest(req))["access_scopes"].Values<JToken>() .Select(token => token["handle"].Value<string>()).ToArray(); } public async Task<TransactionsListResp> TransactionsList(string orderId) { var req = CreateRequest(_credentials.ShopName, HttpMethod.Get, $"orders/{orderId}/transactions.json"); var strResp = await SendRequest(req); var parsed = JsonConvert.DeserializeObject<TransactionsListResp>(strResp); return parsed; } public async Task<TransactionsCreateResp> TransactionCreate(string orderId, TransactionsCreateReq txnCreate) { var postJson = JsonConvert.SerializeObject(txnCreate); var req = CreateRequest(_credentials.ShopName, HttpMethod.Post, $"orders/{orderId}/transactions.json"); req.Content = new StringContent(postJson, Encoding.UTF8, "application/json"); var strResp = await SendRequest(req); return JsonConvert.DeserializeObject<TransactionsCreateResp>(strResp); } public async Task<ShopifyOrder> GetOrder(string orderId) { var req = CreateRequest(_credentials.ShopName, HttpMethod.Get, $"orders/{orderId}.json?fields=id,total_price,currency,transactions,financial_status"); var strResp = await SendRequest(req); return JObject.Parse(strResp)["order"].ToObject<ShopifyOrder>(); } public async Task<long> OrdersCount() { var req = CreateRequest(_credentials.ShopName, HttpMethod.Get, $"orders/count.json"); var strResp = await SendRequest(req); var parsed = JsonConvert.DeserializeObject<CountResponse>(strResp); return parsed.Count; } public async Task<bool> OrderExists(string orderId) { var req = CreateRequest(_credentials.ShopName, HttpMethod.Get, $"orders/{orderId}.json?fields=id"); var strResp = await SendRequest(req); return strResp?.Contains(orderId, StringComparison.OrdinalIgnoreCase) == true; } } public class ShopifyApiClientCredentials { public string ShopName { get; set; } public string ApiKey { get; set; } public string ApiPassword { get; set; } } }
39.233577
179
0.643907
[ "MIT" ]
1nF0rmed/btcpayserver
BTCPayServer/Plugins/Shopify/ShopifyApiClient.cs
5,375
C#
using System; using JsonLD.Entities; using Nancy.Responses; using Newtonsoft.Json.Linq; namespace Nancy.Rdf.Contexts { /// <summary> /// Module, which serves JSON-LD contexts /// </summary> public class JsonLdContextModule : NancyModule { private readonly ContextResolver resolver; /// <summary> /// Initializes a new instance of the <see cref="JsonLdContextModule"/> class. /// </summary> /// <param name="pathProvider">@context path provider</param> /// <param name="provider">custom @context provider</param> public JsonLdContextModule(IContextPathMapper pathProvider, IContextProvider provider) : base(pathProvider.BasePath) { this.resolver = new ContextResolver(provider); foreach (var path in pathProvider.Contexts) { this.Get(path.Path, this.ServeContextOf(path.ModelType)); } } /// <summary> /// Initializes a new instance of the <see cref="JsonLdContextModule"/> class. /// </summary> public JsonLdContextModule() { } private Func<object, object> ServeContextOf(Type modelType) { return request => { var context = new JObject { { JsonLdKeywords.Context, this.resolver.GetContext(modelType) } }; var response = new TextResponse(context.ToString(), RdfSerialization.JsonLd.MediaType); return this.Negotiate.WithAllowedMediaRange(RdfSerialization.JsonLd.MediaType) .WithMediaRangeResponse(RdfSerialization.JsonLd.MediaType, response); }; } } }
33.358491
103
0.589367
[ "MIT" ]
wikibus/Nancy.Rdf
src/Nancy.Rdf/Contexts/JsonLdContextModule.cs
1,770
C#
using Microsoft.VisualStudio.TestTools.UnitTesting; using Moq; using Reverb.Data.Contracts; using Reverb.Data.Models; using System.Collections.Generic; using System.Linq; namespace Reverb.Services.UnitTests.CreationServiceTests { [TestClass] public class CreateAlbum_Should { [TestMethod] public void CallCreateArtist_IfArtistRepoDoesNotFindArtistWithGivenName() { // Arrange var songRepo = new Mock<IEfContextWrapper<Song>>(); var artistRepo = new Mock<IEfContextWrapper<Artist>>(); var albumRepo = new Mock<IEfContextWrapper<Album>>(); var genreRepo = new Mock<IEfContextWrapper<Genre>>(); var context = new Mock<ISaveContext>(); var title = "Title"; var artistName = "Artist Name"; var coverUrl = "CoverUrl"; var artistCollection = new List<Artist>() { new Artist() { Name = "Some Name" } }; artistRepo.Setup(x => x.All).Returns(() => artistCollection.AsQueryable()); artistRepo.Setup(x => x.Add(It.IsAny<Artist>())); var sut = new CreationService( songRepo.Object, artistRepo.Object, albumRepo.Object, genreRepo.Object, context.Object); // Act sut.CreateAlbum(title, artistName, coverUrl); // Assert artistRepo.Verify(x => x.Add(It.IsAny<Artist>()), Times.Once); } [TestMethod] public void CallArtistRepoPropertyAll_WhenInvoked() { // Arrange var songRepo = new Mock<IEfContextWrapper<Song>>(); var artistRepo = new Mock<IEfContextWrapper<Artist>>(); var albumRepo = new Mock<IEfContextWrapper<Album>>(); var genreRepo = new Mock<IEfContextWrapper<Genre>>(); var context = new Mock<ISaveContext>(); var title = "Title"; var artistName = "Artist Name"; var coverUrl = "CoverUrl"; var artistCollection = new List<Artist>() { new Artist() { Name = artistName } }; artistRepo.Setup(x => x.All).Returns(() => artistCollection.AsQueryable()); artistRepo.Setup(x => x.Add(It.IsAny<Artist>())); var sut = new CreationService( songRepo.Object, artistRepo.Object, albumRepo.Object, genreRepo.Object, context.Object); // Act sut.CreateAlbum(title, artistName, coverUrl); // Assert artistRepo.Verify(x => x.All, Times.Exactly(2)); } [TestMethod] public void CallAlbumsRepoMethodAddOnce_WhenInvoked() { // Arrange var songRepo = new Mock<IEfContextWrapper<Song>>(); var artistRepo = new Mock<IEfContextWrapper<Artist>>(); var albumRepo = new Mock<IEfContextWrapper<Album>>(); var genreRepo = new Mock<IEfContextWrapper<Genre>>(); var context = new Mock<ISaveContext>(); var title = "Title"; var artistName = "Artist Name"; var coverUrl = "CoverUrl"; var artistCollection = new List<Artist>() { new Artist() { Name = artistName } }; artistRepo.Setup(x => x.All).Returns(() => artistCollection.AsQueryable()); artistRepo.Setup(x => x.Add(It.IsAny<Artist>())); albumRepo.Setup(x => x.Add(It.IsAny<Album>())); var sut = new CreationService( songRepo.Object, artistRepo.Object, albumRepo.Object, genreRepo.Object, context.Object); // Act sut.CreateAlbum(title, artistName, coverUrl); // Assert albumRepo.Verify(x => x.Add(It.IsAny<Album>()), Times.Once); } [TestMethod] public void CallContextSaveChangesOnce_WhenInvoked() { // Arrange var songRepo = new Mock<IEfContextWrapper<Song>>(); var artistRepo = new Mock<IEfContextWrapper<Artist>>(); var albumRepo = new Mock<IEfContextWrapper<Album>>(); var genreRepo = new Mock<IEfContextWrapper<Genre>>(); var context = new Mock<ISaveContext>(); var title = "Title"; var artistName = "Artist Name"; var coverUrl = "CoverUrl"; var artistCollection = new List<Artist>() { new Artist() { Name = artistName } }; artistRepo.Setup(x => x.All).Returns(() => artistCollection.AsQueryable()); artistRepo.Setup(x => x.Add(It.IsAny<Artist>())); albumRepo.Setup(x => x.Add(It.IsAny<Album>())); context.Setup(x => x.SaveChanges()); var sut = new CreationService( songRepo.Object, artistRepo.Object, albumRepo.Object, genreRepo.Object, context.Object); // Act sut.CreateAlbum(title, artistName, coverUrl); // Assert context.Verify(x => x.SaveChanges(), Times.Once); } } }
32.387283
87
0.514724
[ "MIT" ]
Xenoleth/Reverb-MVC
Reverb/Reverb.Services.UnitTests/CreationServiceTests/CreateAlbum_Should.cs
5,605
C#
using System.Threading; using HotChocolate.Resolvers.CodeGeneration; namespace HotChocolate.Resolvers { public class CancellationTokenArgumentSourceCodeGeneratorTests : ArgumentSourceCodeGeneratorTestBase { public CancellationTokenArgumentSourceCodeGeneratorTests() : base(new CancellationTokenArgumentSourceCodeGenerator(), typeof(CancellationToken), ArgumentKind.CancellationToken, ArgumentKind.DirectiveArgument) { } } }
29.444444
70
0.701887
[ "MIT" ]
Dolfik1/hotchocolate
src/Core/Types.Tests/Resolvers/CodeGeneration/ArgumentGenerators/CancellationTokenArgumentSourceCodeGeneratorTests.cs
532
C#
using Codeco.CrossPlatform.Models.FileSystem; using Codeco.CrossPlatform.Services.DependencyInterfaces; using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Threading.Tasks; namespace Codeco.CrossPlatform.Services { public class FileService : IFileService { private readonly INativeFileServiceFacade _nativeFileService; public FileService(INativeFileServiceFacade nativeFileService) { _nativeFileService = nativeFileService; } public async Task<FileStream> OpenOrCreateFileAsync(string relativeFilePath) { var fileStream = await _nativeFileService.OpenOrCreateFileAsync(relativeFilePath); return fileStream; } public async Task<CreateFileResult> CreateFileAsync(string relativeFilePath) { var createdFile = await _nativeFileService.CreateFileAsync(relativeFilePath); if (createdFile == null || createdFile.Stream == null) { return null; } return createdFile; } public async Task WriteBytesAsync(string relativeFilePath, byte[] data) { using (var fileStream = await _nativeFileService.OpenOrCreateFileAsync(relativeFilePath)) { await fileStream.WriteAsync(data, 0, data.Length); } } /// <summary> /// /// </summary> /// <param name="relativeFolderPath"></param> /// <returns></returns> public DirectoryInfo CreateFolder(string relativeFolderPath) { try { DirectoryInfo createdDir = Directory.CreateDirectory(relativeFolderPath); return createdDir; } catch (Exception ex) { Debug.WriteLine($"Failed to create folder at {relativeFolderPath}. Reason: {ex.Message}"); return null; } } public async Task<string> RenameFileAsync(string relativeFilePath, string newName) { return await _nativeFileService.RenameFileAsync(relativeFilePath, newName); } public Task<string> MoveFileAsync(string sourceRelativeFilePath, string destinationRelativeFlePath) { return _nativeFileService.MoveFileAsync(sourceRelativeFilePath, destinationRelativeFlePath); } public Task DeleteFileAsync(string relativeFilePath) { return _nativeFileService.DeleteFileAsync(relativeFilePath); } /// <summary> /// /// </summary> /// <param name="relativeFolderPath"></param> /// <returns></returns> public Task<List<string>> GetFilesInFolder(string relativeFolderPath) { return _nativeFileService.GetFilesAsync(relativeFolderPath); } public Task<string> GetFileContentsAsync(string relativeFilePath) { return _nativeFileService.GetFileContentsAsync(relativeFilePath); } } }
32.652632
107
0.628304
[ "MIT" ]
pingzing/Codeco
Codeco.CrossPlatform/Services/FileService.cs
3,104
C#
// Copyright (c) Microsoft Open Technologies, Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Reflection.Metadata; using System.Reflection.Metadata.Ecma335; using Microsoft.Cci; namespace Microsoft.CodeAnalysis.Emit { public delegate ImmutableArray<string> LocalVariableNameProvider(uint methodIndex); /// <summary> /// Represents a module from a previous compilation. Used in Edit and Continue /// to emit the differences in a subsequent compilation. /// </summary> public sealed class EmitBaseline { private static readonly ImmutableArray<int> EmptyTableSizes = ImmutableArray.Create(new int[MetadataTokens.TableCount]); /// <summary> /// Creates an <see cref="EmitBaseline"/> from the metadata of the module before editing /// and from a function that maps from a method to an array of local names. Only the /// initial baseline is created using this method; subsequent baselines are created /// automatically when emitting the differences in subsequent compilations. /// </summary> /// <param name="module">The metadata of the module before editing.</param> /// <param name="localNames">A function that returns the array of local names given a method index from the module metadata.</param> /// <returns>An EmitBaseline for the module.</returns> public static EmitBaseline CreateInitialBaseline(ModuleMetadata module, LocalVariableNameProvider localNames) { if (module == null) { throw new ArgumentNullException("module"); } if (!module.Module.HasIL) { throw new ArgumentException(CodeAnalysisResources.PEImageNotAvailable, "module"); } if (localNames == null) { throw new ArgumentNullException("localNames"); } return CreateInitialBaselineWithoutChecks(module, localNames); } /// <summary> /// Entrypoint for the <see cref="T:Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator.CSharpExpressionCompiler"/>. /// </summary> internal static EmitBaseline CreateInitialBaselineWithoutChecks(ModuleMetadata module, LocalVariableNameProvider localNames) { var reader = module.MetadataReader; var moduleVersionId = module.GetModuleVersionId(); return new EmitBaseline( module, compilation: null, moduleBuilder: null, moduleVersionId: moduleVersionId, ordinal: 0, encId: default(Guid), typesAdded: new Dictionary<ITypeDefinition, uint>(), eventsAdded: new Dictionary<IEventDefinition, uint>(), fieldsAdded: new Dictionary<IFieldDefinition, uint>(), methodsAdded: new Dictionary<IMethodDefinition, uint>(), propertiesAdded: new Dictionary<IPropertyDefinition, uint>(), eventMapAdded: new Dictionary<uint, uint>(), propertyMapAdded: new Dictionary<uint, uint>(), tableEntriesAdded: EmptyTableSizes, blobStreamLengthAdded: 0, stringStreamLengthAdded: 0, userStringStreamLengthAdded: 0, guidStreamLengthAdded: 0, anonymousTypeMap: null, // Unset for initial metadata localsForMethodsAddedOrChanged: new Dictionary<uint, ImmutableArray<EncLocalInfo>>(), localNames: localNames, typeToEventMap: reader.CalculateTypeEventMap(), typeToPropertyMap: reader.CalculateTypePropertyMap()); } /// <summary> /// The original metadata of the module. /// </summary> public readonly ModuleMetadata OriginalMetadata; internal readonly Compilation Compilation; internal readonly CommonPEModuleBuilder PEModuleBuilder; internal readonly Guid ModuleVersionId; /// <summary> /// Metadata generation ordinal. Zero for /// full metadata and non-zero for delta. /// </summary> internal readonly int Ordinal; /// <summary> /// Unique Guid for this delta, or default(Guid) /// if full metadata. /// </summary> internal readonly Guid EncId; internal readonly IReadOnlyDictionary<ITypeDefinition, uint> TypesAdded; internal readonly IReadOnlyDictionary<IEventDefinition, uint> EventsAdded; internal readonly IReadOnlyDictionary<IFieldDefinition, uint> FieldsAdded; internal readonly IReadOnlyDictionary<IMethodDefinition, uint> MethodsAdded; internal readonly IReadOnlyDictionary<IPropertyDefinition, uint> PropertiesAdded; internal readonly IReadOnlyDictionary<uint, uint> EventMapAdded; internal readonly IReadOnlyDictionary<uint, uint> PropertyMapAdded; internal readonly ImmutableArray<int> TableEntriesAdded; internal readonly int BlobStreamLengthAdded; internal readonly int StringStreamLengthAdded; internal readonly int UserStringStreamLengthAdded; internal readonly int GuidStreamLengthAdded; /// <summary> /// Map from syntax to local variable for methods added or updated /// since the initial generation, indexed by method row. /// </summary> internal readonly IReadOnlyDictionary<uint, ImmutableArray<EncLocalInfo>> LocalsForMethodsAddedOrChanged; /// <summary> /// Local variable names for methods from metadata, /// indexed by method row. /// </summary> internal readonly LocalVariableNameProvider LocalNames; internal readonly ImmutableArray<int> TableSizes; internal readonly IReadOnlyDictionary<uint, uint> TypeToEventMap; internal readonly IReadOnlyDictionary<uint, uint> TypeToPropertyMap; internal readonly IReadOnlyDictionary<AnonymousTypeKey, AnonymousTypeValue> AnonymousTypeMap; private EmitBaseline( ModuleMetadata module, Compilation compilation, CommonPEModuleBuilder moduleBuilder, Guid moduleVersionId, int ordinal, Guid encId, IReadOnlyDictionary<ITypeDefinition, uint> typesAdded, IReadOnlyDictionary<IEventDefinition, uint> eventsAdded, IReadOnlyDictionary<IFieldDefinition, uint> fieldsAdded, IReadOnlyDictionary<IMethodDefinition, uint> methodsAdded, IReadOnlyDictionary<IPropertyDefinition, uint> propertiesAdded, IReadOnlyDictionary<uint, uint> eventMapAdded, IReadOnlyDictionary<uint, uint> propertyMapAdded, ImmutableArray<int> tableEntriesAdded, int blobStreamLengthAdded, int stringStreamLengthAdded, int userStringStreamLengthAdded, int guidStreamLengthAdded, IReadOnlyDictionary<AnonymousTypeKey, AnonymousTypeValue> anonymousTypeMap, IReadOnlyDictionary<uint, ImmutableArray<EncLocalInfo>> localsForMethodsAddedOrChanged, LocalVariableNameProvider localNames, IReadOnlyDictionary<uint, uint> typeToEventMap, IReadOnlyDictionary<uint, uint> typeToPropertyMap) { Debug.Assert(module != null); Debug.Assert((ordinal == 0) == (encId == default(Guid))); Debug.Assert(encId != module.GetModuleVersionId()); Debug.Assert(localNames != null); Debug.Assert(typeToEventMap != null); Debug.Assert(typeToPropertyMap != null); Debug.Assert(tableEntriesAdded.Length == MetadataTokens.TableCount); // The size of each table is the total number of entries added in all previous // generations after the initial generation. Depending on the table, some of the // entries may not be available in the current generation (say, a synthesized type // from a method that was not recompiled for instance) Debug.Assert(tableEntriesAdded[(int)TableIndex.TypeDef] >= typesAdded.Count); Debug.Assert(tableEntriesAdded[(int)TableIndex.Event] >= eventsAdded.Count); Debug.Assert(tableEntriesAdded[(int)TableIndex.Field] >= fieldsAdded.Count); Debug.Assert(tableEntriesAdded[(int)TableIndex.MethodDef] >= methodsAdded.Count); Debug.Assert(tableEntriesAdded[(int)TableIndex.Property] >= propertiesAdded.Count); Debug.Assert(tableEntriesAdded[(int)TableIndex.EventMap] >= eventMapAdded.Count); Debug.Assert(tableEntriesAdded[(int)TableIndex.PropertyMap] >= propertyMapAdded.Count); var reader = module.Module.MetadataReader; this.OriginalMetadata = module; this.Compilation = compilation; this.PEModuleBuilder = moduleBuilder; this.ModuleVersionId = moduleVersionId; this.Ordinal = ordinal; this.EncId = encId; this.TypesAdded = typesAdded; this.EventsAdded = eventsAdded; this.FieldsAdded = fieldsAdded; this.MethodsAdded = methodsAdded; this.PropertiesAdded = propertiesAdded; this.EventMapAdded = eventMapAdded; this.PropertyMapAdded = propertyMapAdded; this.TableEntriesAdded = tableEntriesAdded; this.BlobStreamLengthAdded = blobStreamLengthAdded; this.StringStreamLengthAdded = stringStreamLengthAdded; this.UserStringStreamLengthAdded = userStringStreamLengthAdded; this.GuidStreamLengthAdded = guidStreamLengthAdded; this.AnonymousTypeMap = anonymousTypeMap; this.LocalsForMethodsAddedOrChanged = localsForMethodsAddedOrChanged; this.LocalNames = localNames; this.TableSizes = CalculateTableSizes(reader, this.TableEntriesAdded); this.TypeToEventMap = typeToEventMap; this.TypeToPropertyMap = typeToPropertyMap; } internal EmitBaseline With( Compilation compilation, CommonPEModuleBuilder moduleBuilder, int ordinal, Guid encId, IReadOnlyDictionary<ITypeDefinition, uint> typesAdded, IReadOnlyDictionary<IEventDefinition, uint> eventsAdded, IReadOnlyDictionary<IFieldDefinition, uint> fieldsAdded, IReadOnlyDictionary<IMethodDefinition, uint> methodsAdded, IReadOnlyDictionary<IPropertyDefinition, uint> propertiesAdded, IReadOnlyDictionary<uint, uint> eventMapAdded, IReadOnlyDictionary<uint, uint> propertyMapAdded, ImmutableArray<int> tableEntriesAdded, int blobStreamLengthAdded, int stringStreamLengthAdded, int userStringStreamLengthAdded, int guidStreamLengthAdded, IReadOnlyDictionary<AnonymousTypeKey, AnonymousTypeValue> anonymousTypeMap, IReadOnlyDictionary<uint, ImmutableArray<EncLocalInfo>> localsForMethodsAddedOrChanged, LocalVariableNameProvider localNames) { Debug.Assert((this.AnonymousTypeMap == null) || (anonymousTypeMap != null)); Debug.Assert((this.AnonymousTypeMap == null) || (anonymousTypeMap.Count >= this.AnonymousTypeMap.Count)); return new EmitBaseline( this.OriginalMetadata, compilation, moduleBuilder, this.ModuleVersionId, ordinal, encId, typesAdded, eventsAdded, fieldsAdded, methodsAdded, propertiesAdded, eventMapAdded, propertyMapAdded, tableEntriesAdded, blobStreamLengthAdded: blobStreamLengthAdded, stringStreamLengthAdded: stringStreamLengthAdded, userStringStreamLengthAdded: userStringStreamLengthAdded, guidStreamLengthAdded: guidStreamLengthAdded, anonymousTypeMap: anonymousTypeMap, localsForMethodsAddedOrChanged: localsForMethodsAddedOrChanged, localNames: localNames, typeToEventMap: this.TypeToEventMap, typeToPropertyMap: this.TypeToPropertyMap); } internal MetadataReader MetadataReader { get { return this.OriginalMetadata.MetadataReader; } } internal int BlobStreamLength { get { return this.BlobStreamLengthAdded + this.MetadataReader.GetHeapSize(HeapIndex.Blob); } } internal int StringStreamLength { get { return this.StringStreamLengthAdded + this.MetadataReader.GetHeapSize(HeapIndex.String); } } internal int UserStringStreamLength { get { return this.UserStringStreamLengthAdded + this.MetadataReader.GetHeapSize(HeapIndex.UserString); } } internal int GuidStreamLength { get { return this.GuidStreamLengthAdded + this.MetadataReader.GetHeapSize(HeapIndex.Guid); } } private static ImmutableArray<int> CalculateTableSizes(MetadataReader reader, ImmutableArray<int> delta) { var sizes = new int[MetadataTokens.TableCount]; for (int i = 0; i < sizes.Length; i++) { sizes[i] = reader.GetTableRowCount((TableIndex)i) + delta[i]; } return ImmutableArray.Create(sizes); } internal int GetNextAnonymousTypeIndex(bool fromDelegates = false) { int nextIndex = 0; foreach (var pair in this.AnonymousTypeMap) { if (fromDelegates != pair.Key.IsDelegate) { continue; } int index = pair.Value.UniqueIndex; if (index >= nextIndex) { nextIndex = index + 1; } } return nextIndex; } } }
45.024922
184
0.644849
[ "ECL-2.0", "Apache-2.0" ]
binsys/roslyn_java
Src/Compilers/Core/Source/Emit/EmitBaseline.cs
14,455
C#
using System; using System.Collections.Generic; using System.IdentityModel.Tokens.Jwt; using System.Linq; using System.Security.Claims; using System.Threading.Tasks; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.IdentityModel.Tokens; using Senai.OpFlix.WebApi.Domains; using Senai.OpFlix.WebApi.Interfaces; using Senai.OpFlix.WebApi.Repositories; using Senai.OpFlix.WebApi.ViewModels; namespace Senai.OpFlix.WebApi.Controllers { [Route("api/[controller]")] [Produces("application/json")] [ApiController] public class UsuariosController : ControllerBase { private IUsuarioRepository UsuarioRepository { get; set; } public UsuariosController() { UsuarioRepository = new UsuarioRepository(); } [Authorize(Roles = "Administrador")] [HttpGet] public IActionResult ListarUsuarios() { return Ok(UsuarioRepository.Listar()); } [Authorize(Roles = "Administrador")] [HttpPost] public IActionResult CadastrarUsuario(Usuarios usuario) { try { UsuarioRepository.Cadastrar(usuario); return Ok(); } catch (Exception ex) { return BadRequest(new { mensagem = ex.Message }); } } [HttpPost("login")] public IActionResult Login(LoginViewModel login) { try { Usuarios usuarioBuscado = UsuarioRepository.BuscarPorEmailSenha(login); if (usuarioBuscado == null) return NotFound(new { mensagem = "Usuario não encontrado" }); var claims = new[] { new Claim(JwtRegisteredClaimNames.Email, usuarioBuscado.Email), new Claim(JwtRegisteredClaimNames.Jti, usuarioBuscado.IdUsuario.ToString()), new Claim(ClaimTypes.Role, usuarioBuscado.IdTipoUsuarioNavigation.Tipo), }; var key = new SymmetricSecurityKey(System.Text.Encoding.UTF8.GetBytes("opflix-chave-autenticacao")); var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256); var token = new JwtSecurityToken( issuer: "OpFlix.WebApi", audience: "OpFlix.WebApi", claims: claims, expires: DateTime.Now.AddMinutes(30), signingCredentials: creds); return Ok(new { token = new JwtSecurityTokenHandler().WriteToken(token) }); } catch (System.Exception ex) { return BadRequest(new { mensagem = "ferrou deu erro " + ex.Message }); } } } }
32.21978
116
0.577763
[ "MIT" ]
S0L4/2s2019-sprint-2-backend-OpFlix
Senai.OpFlix.WebApi/Senai.OpFlix.WebApi/Controllers/UsuariosController.cs
2,935
C#
// Licensed to the .NET Foundation under one or more agreements. The .NET Foundation licenses this file to you under the MIT license. See the LICENSE.md file in the project root for more information. using Xunit; namespace Microsoft.VisualStudio.ProjectSystem.Build { public class PublishableProjectConfigProviderTests { [Fact] public async Task IsPublishSupportedAsync_ReturnsFalse() { var provider = CreateInstance(); var result = await provider.IsPublishSupportedAsync(); Assert.False(result); } [Fact] public async Task PublishAsync_ThrowsInvalidOperation() { var provider = CreateInstance(); var writer = new StringWriter(); await Assert.ThrowsAsync<InvalidOperationException>(() => { return provider.PublishAsync(CancellationToken.None, writer); }); } [Fact] public async Task ShowPublishPromptAsync_ThrowsInvalidOperation() { var provider = CreateInstance(); await Assert.ThrowsAsync<InvalidOperationException>(() => { return provider.ShowPublishPromptAsync(); }); } private static PublishableProjectConfigProvider CreateInstance() { return new PublishableProjectConfigProvider(); } } }
30.645833
201
0.598912
[ "MIT" ]
brunom/project-system
tests/Microsoft.VisualStudio.ProjectSystem.Managed.UnitTests/ProjectSystem/Build/PublishableProjectConfigProviderTests.cs
1,426
C#
using System.Resources; 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("Xamarians.CropImage")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Xamarians.CropImage")] [assembly: AssemblyCopyright("Copyright © 2014")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: NeutralResourcesLanguage("en")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
35.258065
84
0.745654
[ "MIT" ]
Xamarians/Xamarians.CropImage
Xamarians.CropImage/Properties/AssemblyInfo.cs
1,096
C#
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Documents; using Amusoft.UI.WPF.Controls; namespace Amusoft.UI.WPF.Utility { public static class VisualStateManagerHelper { public static Dictionary<VisualStateGroup, IEnumerable<VisualState>> GetVisualStateMap(FrameworkElement element) { if (element == null) throw new ArgumentNullException(nameof(element)); var groups = VisualStateManager.GetVisualStateGroups(element); return groups.Cast<VisualStateGroup>().ToDictionary(d => d, group => group.States.Count > 0 ? group.States.Cast<VisualState>() : Enumerable.Empty<VisualState>()); } public static async Task GoToStateAsync(FrameworkElement control, string stateName, bool useTransition) { var tcs = new TaskCompletionSource<object>(); var root = GetRoot(control); var group = GetVisualStateMap(root).FirstOrDefault(d => d.Value.Any(state => string.Equals(state.Name, stateName, StringComparison.OrdinalIgnoreCase))); EventHandler<VisualStateChangedEventArgs> handler = null; handler = (sender, args) => { group.Key.CurrentStateChanged -= handler; tcs.TrySetResult(null); }; if (group.Key != null) { group.Key.CurrentStateChanged += handler; VisualStateManager.GoToState(control, stateName, true); await tcs.Task; } else { VisualStateManager.GoToState(control, stateName, true); } } private static FrameworkElement GetRoot(FrameworkElement control) { var property = typeof(FrameworkElement).GetProperty("StateGroupsRoot", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); var root = property.GetGetMethod(true).Invoke(control, null); return root as FrameworkElement; } } }
34.333333
165
0.751348
[ "MIT" ]
taori/Amusoft.UI.WPF
src/Amusoft.UI.WPF/Utility/VisualStateManagerHelper.cs
1,856
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("JustSnake")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("JustSnake")] [assembly: AssemblyCopyright("Copyright © 2016")] [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("6aefa362-1e74-4514-ac01-689c72360574")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
37.594595
84
0.744069
[ "MIT" ]
grandeto/TelerikAcademy
C# 1 Homeworks/ExamPreparation/JustSnake/Properties/AssemblyInfo.cs
1,394
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace BattaTech.ExcelExport.PL { public partial class example_dataset { /// <summary> /// btnExport control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.Button btnExport; } }
31.08
84
0.473616
[ "MIT" ]
battatech/battatech_ServerSideExcelExport
Code/PL/example_dataset.aspx.designer.cs
779
C#
// <auto-generated> // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/ads/googleads/v2/resources/operating_system_version_constant.proto // </auto-generated> #pragma warning disable 1591, 0612, 3021 #region Designer generated code using pb = global::Google.Protobuf; using pbc = global::Google.Protobuf.Collections; using pbr = global::Google.Protobuf.Reflection; using scg = global::System.Collections.Generic; namespace Google.Ads.GoogleAds.V2.Resources { /// <summary>Holder for reflection information generated from google/ads/googleads/v2/resources/operating_system_version_constant.proto</summary> public static partial class OperatingSystemVersionConstantReflection { #region Descriptor /// <summary>File descriptor for google/ads/googleads/v2/resources/operating_system_version_constant.proto</summary> public static pbr::FileDescriptor Descriptor { get { return descriptor; } } private static pbr::FileDescriptor descriptor; static OperatingSystemVersionConstantReflection() { byte[] descriptorData = global::System.Convert.FromBase64String( string.Concat( "Cklnb29nbGUvYWRzL2dvb2dsZWFkcy92Mi9yZXNvdXJjZXMvb3BlcmF0aW5n", "X3N5c3RlbV92ZXJzaW9uX2NvbnN0YW50LnByb3RvEiFnb29nbGUuYWRzLmdv", "b2dsZWFkcy52Mi5yZXNvdXJjZXMaSmdvb2dsZS9hZHMvZ29vZ2xlYWRzL3Yy", "L2VudW1zL29wZXJhdGluZ19zeXN0ZW1fdmVyc2lvbl9vcGVyYXRvcl90eXBl", "LnByb3RvGh5nb29nbGUvcHJvdG9idWYvd3JhcHBlcnMucHJvdG8aHGdvb2ds", "ZS9hcGkvYW5ub3RhdGlvbnMucHJvdG8i+wIKHk9wZXJhdGluZ1N5c3RlbVZl", "cnNpb25Db25zdGFudBIVCg1yZXNvdXJjZV9uYW1lGAEgASgJEicKAmlkGAIg", "ASgLMhsuZ29vZ2xlLnByb3RvYnVmLkludDY0VmFsdWUSKgoEbmFtZRgDIAEo", "CzIcLmdvb2dsZS5wcm90b2J1Zi5TdHJpbmdWYWx1ZRI1ChBvc19tYWpvcl92", "ZXJzaW9uGAQgASgLMhsuZ29vZ2xlLnByb3RvYnVmLkludDMyVmFsdWUSNQoQ", "b3NfbWlub3JfdmVyc2lvbhgFIAEoCzIbLmdvb2dsZS5wcm90b2J1Zi5JbnQz", "MlZhbHVlEn8KDW9wZXJhdG9yX3R5cGUYBiABKA4yaC5nb29nbGUuYWRzLmdv", "b2dsZWFkcy52Mi5lbnVtcy5PcGVyYXRpbmdTeXN0ZW1WZXJzaW9uT3BlcmF0", "b3JUeXBlRW51bS5PcGVyYXRpbmdTeXN0ZW1WZXJzaW9uT3BlcmF0b3JUeXBl", "QpACCiVjb20uZ29vZ2xlLmFkcy5nb29nbGVhZHMudjIucmVzb3VyY2VzQiNP", "cGVyYXRpbmdTeXN0ZW1WZXJzaW9uQ29uc3RhbnRQcm90b1ABWkpnb29nbGUu", "Z29sYW5nLm9yZy9nZW5wcm90by9nb29nbGVhcGlzL2Fkcy9nb29nbGVhZHMv", "djIvcmVzb3VyY2VzO3Jlc291cmNlc6ICA0dBQaoCIUdvb2dsZS5BZHMuR29v", "Z2xlQWRzLlYyLlJlc291cmNlc8oCIUdvb2dsZVxBZHNcR29vZ2xlQWRzXFYy", "XFJlc291cmNlc+oCJUdvb2dsZTo6QWRzOjpHb29nbGVBZHM6OlYyOjpSZXNv", "dXJjZXNiBnByb3RvMw==")); descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, new pbr::FileDescriptor[] { global::Google.Ads.GoogleAds.V2.Enums.OperatingSystemVersionOperatorTypeReflection.Descriptor, global::Google.Protobuf.WellKnownTypes.WrappersReflection.Descriptor, global::Google.Api.AnnotationsReflection.Descriptor, }, new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::Google.Ads.GoogleAds.V2.Resources.OperatingSystemVersionConstant), global::Google.Ads.GoogleAds.V2.Resources.OperatingSystemVersionConstant.Parser, new[]{ "ResourceName", "Id", "Name", "OsMajorVersion", "OsMinorVersion", "OperatorType" }, null, null, null) })); } #endregion } #region Messages /// <summary> /// A mobile operating system version or a range of versions, depending on /// `operator_type`. List of available mobile platforms at /// https://developers.google.com/adwords/api/docs/appendix/codes-formats#mobile-platforms /// </summary> public sealed partial class OperatingSystemVersionConstant : pb::IMessage<OperatingSystemVersionConstant> { private static readonly pb::MessageParser<OperatingSystemVersionConstant> _parser = new pb::MessageParser<OperatingSystemVersionConstant>(() => new OperatingSystemVersionConstant()); private pb::UnknownFieldSet _unknownFields; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<OperatingSystemVersionConstant> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Ads.GoogleAds.V2.Resources.OperatingSystemVersionConstantReflection.Descriptor.MessageTypes[0]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public OperatingSystemVersionConstant() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public OperatingSystemVersionConstant(OperatingSystemVersionConstant other) : this() { resourceName_ = other.resourceName_; Id = other.Id; Name = other.Name; OsMajorVersion = other.OsMajorVersion; OsMinorVersion = other.OsMinorVersion; operatorType_ = other.operatorType_; _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public OperatingSystemVersionConstant Clone() { return new OperatingSystemVersionConstant(this); } /// <summary>Field number for the "resource_name" field.</summary> public const int ResourceNameFieldNumber = 1; private string resourceName_ = ""; /// <summary> /// The resource name of the operating system version constant. /// Operating system version constant resource names have the form: /// /// `operatingSystemVersionConstants/{criterion_id}` /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string ResourceName { get { return resourceName_; } set { resourceName_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "id" field.</summary> public const int IdFieldNumber = 2; private static readonly pb::FieldCodec<long?> _single_id_codec = pb::FieldCodec.ForStructWrapper<long>(18); private long? id_; /// <summary> /// The ID of the operating system version. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public long? Id { get { return id_; } set { id_ = value; } } /// <summary>Field number for the "name" field.</summary> public const int NameFieldNumber = 3; private static readonly pb::FieldCodec<string> _single_name_codec = pb::FieldCodec.ForClassWrapper<string>(26); private string name_; /// <summary> /// Name of the operating system. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string Name { get { return name_; } set { name_ = value; } } /// <summary>Field number for the "os_major_version" field.</summary> public const int OsMajorVersionFieldNumber = 4; private static readonly pb::FieldCodec<int?> _single_osMajorVersion_codec = pb::FieldCodec.ForStructWrapper<int>(34); private int? osMajorVersion_; /// <summary> /// The OS Major Version number. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int? OsMajorVersion { get { return osMajorVersion_; } set { osMajorVersion_ = value; } } /// <summary>Field number for the "os_minor_version" field.</summary> public const int OsMinorVersionFieldNumber = 5; private static readonly pb::FieldCodec<int?> _single_osMinorVersion_codec = pb::FieldCodec.ForStructWrapper<int>(42); private int? osMinorVersion_; /// <summary> /// The OS Minor Version number. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int? OsMinorVersion { get { return osMinorVersion_; } set { osMinorVersion_ = value; } } /// <summary>Field number for the "operator_type" field.</summary> public const int OperatorTypeFieldNumber = 6; private global::Google.Ads.GoogleAds.V2.Enums.OperatingSystemVersionOperatorTypeEnum.Types.OperatingSystemVersionOperatorType operatorType_ = 0; /// <summary> /// Determines whether this constant represents a single version or a range of /// versions. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::Google.Ads.GoogleAds.V2.Enums.OperatingSystemVersionOperatorTypeEnum.Types.OperatingSystemVersionOperatorType OperatorType { get { return operatorType_; } set { operatorType_ = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as OperatingSystemVersionConstant); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(OperatingSystemVersionConstant other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (ResourceName != other.ResourceName) return false; if (Id != other.Id) return false; if (Name != other.Name) return false; if (OsMajorVersion != other.OsMajorVersion) return false; if (OsMinorVersion != other.OsMinorVersion) return false; if (OperatorType != other.OperatorType) return false; return Equals(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (ResourceName.Length != 0) hash ^= ResourceName.GetHashCode(); if (id_ != null) hash ^= Id.GetHashCode(); if (name_ != null) hash ^= Name.GetHashCode(); if (osMajorVersion_ != null) hash ^= OsMajorVersion.GetHashCode(); if (osMinorVersion_ != null) hash ^= OsMinorVersion.GetHashCode(); if (OperatorType != 0) hash ^= OperatorType.GetHashCode(); if (_unknownFields != null) { hash ^= _unknownFields.GetHashCode(); } return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (ResourceName.Length != 0) { output.WriteRawTag(10); output.WriteString(ResourceName); } if (id_ != null) { _single_id_codec.WriteTagAndValue(output, Id); } if (name_ != null) { _single_name_codec.WriteTagAndValue(output, Name); } if (osMajorVersion_ != null) { _single_osMajorVersion_codec.WriteTagAndValue(output, OsMajorVersion); } if (osMinorVersion_ != null) { _single_osMinorVersion_codec.WriteTagAndValue(output, OsMinorVersion); } if (OperatorType != 0) { output.WriteRawTag(48); output.WriteEnum((int) OperatorType); } if (_unknownFields != null) { _unknownFields.WriteTo(output); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (ResourceName.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(ResourceName); } if (id_ != null) { size += _single_id_codec.CalculateSizeWithTag(Id); } if (name_ != null) { size += _single_name_codec.CalculateSizeWithTag(Name); } if (osMajorVersion_ != null) { size += _single_osMajorVersion_codec.CalculateSizeWithTag(OsMajorVersion); } if (osMinorVersion_ != null) { size += _single_osMinorVersion_codec.CalculateSizeWithTag(OsMinorVersion); } if (OperatorType != 0) { size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) OperatorType); } if (_unknownFields != null) { size += _unknownFields.CalculateSize(); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(OperatingSystemVersionConstant other) { if (other == null) { return; } if (other.ResourceName.Length != 0) { ResourceName = other.ResourceName; } if (other.id_ != null) { if (id_ == null || other.Id != 0L) { Id = other.Id; } } if (other.name_ != null) { if (name_ == null || other.Name != "") { Name = other.Name; } } if (other.osMajorVersion_ != null) { if (osMajorVersion_ == null || other.OsMajorVersion != 0) { OsMajorVersion = other.OsMajorVersion; } } if (other.osMinorVersion_ != null) { if (osMinorVersion_ == null || other.OsMinorVersion != 0) { OsMinorVersion = other.OsMinorVersion; } } if (other.OperatorType != 0) { OperatorType = other.OperatorType; } _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); break; case 10: { ResourceName = input.ReadString(); break; } case 18: { long? value = _single_id_codec.Read(input); if (id_ == null || value != 0L) { Id = value; } break; } case 26: { string value = _single_name_codec.Read(input); if (name_ == null || value != "") { Name = value; } break; } case 34: { int? value = _single_osMajorVersion_codec.Read(input); if (osMajorVersion_ == null || value != 0) { OsMajorVersion = value; } break; } case 42: { int? value = _single_osMinorVersion_codec.Read(input); if (osMinorVersion_ == null || value != 0) { OsMinorVersion = value; } break; } case 48: { OperatorType = (global::Google.Ads.GoogleAds.V2.Enums.OperatingSystemVersionOperatorTypeEnum.Types.OperatingSystemVersionOperatorType) input.ReadEnum(); break; } } } } } #endregion } #endregion Designer generated code
39.086162
313
0.673547
[ "Apache-2.0" ]
chrisdunelm/google-ads-dotnet
src/V2/Stubs/OperatingSystemVersionConstant.cs
14,970
C#
namespace Inventory.Frm { partial class frmTakeStock { /// <summary> /// 必需的设计器变量。 /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// 清理所有正在使用的资源。 /// </summary> /// <param name="disposing">如果应释放托管资源,为 true;否则为 false。</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows 窗体设计器生成的代码 /// <summary> /// 设计器支持所需的方法 - 不要 /// 使用代码编辑器修改此方法的内容。 /// </summary> private void InitializeComponent() { this.menuItem1 = new System.Windows.Forms.MenuItem(); this.mainMenu1 = new System.Windows.Forms.MainMenu(); this.miBack = new System.Windows.Forms.MenuItem(); this.textBox1 = new System.Windows.Forms.TextBox(); this.tabOther = new System.Windows.Forms.TabPage(); this.label2 = new System.Windows.Forms.Label(); this.txtGdBaco = new System.Windows.Forms.TextBox(); this.lvGd = new System.Windows.Forms.ListView(); this.lblGdBaco = new System.Windows.Forms.Label(); this.tabControl = new System.Windows.Forms.TabControl(); this.tabPage1 = new System.Windows.Forms.TabPage(); this.listView1 = new System.Windows.Forms.ListView(); this.tabOther.SuspendLayout(); this.tabControl.SuspendLayout(); this.tabPage1.SuspendLayout(); this.SuspendLayout(); // // menuItem1 // this.menuItem1.Text = "确认"; // // mainMenu1 // this.mainMenu1.MenuItems.Add(this.menuItem1); this.mainMenu1.MenuItems.Add(this.miBack); // // miBack // this.miBack.Text = "返回"; // // textBox1 // this.textBox1.Anchor = System.Windows.Forms.AnchorStyles.Right; this.textBox1.Location = new System.Drawing.Point(69, 3); this.textBox1.Name = "textBox1"; this.textBox1.Size = new System.Drawing.Size(165, 21); this.textBox1.TabIndex = 58; // // tabOther // this.tabOther.BackColor = System.Drawing.SystemColors.ScrollBar; this.tabOther.Controls.Add(this.textBox1); this.tabOther.Controls.Add(this.label2); this.tabOther.Controls.Add(this.txtGdBaco); this.tabOther.Controls.Add(this.lvGd); this.tabOther.Controls.Add(this.lblGdBaco); this.tabOther.Location = new System.Drawing.Point(0, 0); this.tabOther.Name = "tabOther"; this.tabOther.Size = new System.Drawing.Size(240, 245); this.tabOther.Text = "物料"; // // label2 // this.label2.Anchor = System.Windows.Forms.AnchorStyles.Left; this.label2.Location = new System.Drawing.Point(4, 4); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(73, 20); this.label2.Text = "盘点代码"; // // txtGdBaco // this.txtGdBaco.Anchor = System.Windows.Forms.AnchorStyles.Right; this.txtGdBaco.Location = new System.Drawing.Point(69, 223); this.txtGdBaco.Name = "txtGdBaco"; this.txtGdBaco.Size = new System.Drawing.Size(165, 21); this.txtGdBaco.TabIndex = 52; // // lvGd // this.lvGd.Location = new System.Drawing.Point(0, 27); this.lvGd.Name = "lvGd"; this.lvGd.Size = new System.Drawing.Size(240, 194); this.lvGd.TabIndex = 27; // // lblGdBaco // this.lblGdBaco.Anchor = System.Windows.Forms.AnchorStyles.Left; this.lblGdBaco.Location = new System.Drawing.Point(4, 226); this.lblGdBaco.Name = "lblGdBaco"; this.lblGdBaco.Size = new System.Drawing.Size(73, 20); this.lblGdBaco.Text = "包装码"; // // tabControl // this.tabControl.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.tabControl.Controls.Add(this.tabOther); this.tabControl.Controls.Add(this.tabPage1); this.tabControl.Dock = System.Windows.Forms.DockStyle.None; this.tabControl.Location = new System.Drawing.Point(0, 0); this.tabControl.Name = "tabControl"; this.tabControl.SelectedIndex = 0; this.tabControl.Size = new System.Drawing.Size(240, 268); this.tabControl.TabIndex = 23; // // tabPage1 // this.tabPage1.BackColor = System.Drawing.SystemColors.ScrollBar; this.tabPage1.Controls.Add(this.listView1); this.tabPage1.Location = new System.Drawing.Point(0, 0); this.tabPage1.Name = "tabPage1"; this.tabPage1.Size = new System.Drawing.Size(240, 245); this.tabPage1.Text = "条码"; // // listView1 // this.listView1.Dock = System.Windows.Forms.DockStyle.Fill; this.listView1.Location = new System.Drawing.Point(0, 0); this.listView1.Name = "listView1"; this.listView1.Size = new System.Drawing.Size(240, 245); this.listView1.TabIndex = 28; // // frmTakeStock // this.AutoScaleDimensions = new System.Drawing.SizeF(96F, 96F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Dpi; this.AutoScroll = true; this.ClientSize = new System.Drawing.Size(240, 268); this.Controls.Add(this.tabControl); this.Menu = this.mainMenu1; this.Name = "frmTakeStock"; this.Text = "盘点"; this.tabOther.ResumeLayout(false); this.tabControl.ResumeLayout(false); this.tabPage1.ResumeLayout(false); this.ResumeLayout(false); } #endregion private System.Windows.Forms.MenuItem menuItem1; private System.Windows.Forms.MainMenu mainMenu1; private System.Windows.Forms.MenuItem miBack; private System.Windows.Forms.TextBox textBox1; private System.Windows.Forms.TabPage tabOther; private System.Windows.Forms.Label label2; private System.Windows.Forms.TextBox txtGdBaco; private System.Windows.Forms.ListView lvGd; private System.Windows.Forms.Label lblGdBaco; private System.Windows.Forms.TabControl tabControl; private System.Windows.Forms.TabPage tabPage1; private System.Windows.Forms.ListView listView1; } }
41.137931
161
0.562587
[ "Apache-2.0" ]
mikeleishen/bacosys
pda/Inventory/Frm/frmTakeStock.Designer.cs
7,344
C#
using System; using System.Threading.Tasks; using Windows.Data.Xml.Dom; using Windows.Storage; using Windows.UI.Notifications; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409 namespace LiveTilesAndNotifications { /// <summary> /// An empty page that can be used on its own or navigated to within a Frame. /// </summary> public sealed partial class MainPage : Page { public MainPage() { this.InitializeComponent(); } private async void Button_Click(object sender, RoutedEventArgs e) { var file = await this.GetPackagedFile("AdaptiveTiles", "UpdatePrimaryTileTemplate.xml"); var xmlDoc = await Windows.Data.Xml.Dom.XmlDocument.LoadFromFileAsync(file); var updater = TileUpdateManager.CreateTileUpdaterForApplication(); var tileNotification = new TileNotification(xmlDoc); updater.Update(tileNotification); } private void NavigateSecPageButton_Button_Click(object sender, RoutedEventArgs e) { this.Frame.Navigate(typeof(Views.SecondaryPage)); } private async void ToastButton_Button_Click(object sender, RoutedEventArgs e) { var file = await this.GetPackagedFile("AdaptiveTiles", "Toast.xml"); var xmlDoc = await Windows.Data.Xml.Dom.XmlDocument.LoadFromFileAsync(file); var toast = new ToastNotification(xmlDoc); var notifier = ToastNotificationManager.CreateToastNotifier(); notifier.Show(toast); } private async Task<StorageFile> GetPackagedFile(string folderName, string fileName) { StorageFolder installFolder = Windows.ApplicationModel.Package.Current.InstalledLocation; if (folderName != null) { StorageFolder subFolder = await installFolder.GetFolderAsync(folderName); return await subFolder.GetFileAsync(fileName); } else { return await installFolder.GetFileAsync(fileName); } } } }
34.369231
106
0.65085
[ "MIT" ]
nahuel-ianni/workshop-intro-to-uwp
src/08. Live tiles and notifications/LiveTilesAndNotifications/MainPage.xaml.cs
2,236
C#
// <auto-generated> // Code generated by https://github.com/kubernetes-client/csharp/tree/master/gen/KubernetesGenerator // Changes may cause incorrect behavior and will be lost if the code is // regenerated. // </auto-generated> namespace k8s.Models { using Microsoft.Rest; using Newtonsoft.Json; using System.Collections.Generic; using System.Collections; using System.Linq; /// <summary> /// ReplicationControllerStatus represents the current status of a replication /// controller. /// </summary> public partial class V1ReplicationControllerStatus { /// <summary> /// Initializes a new instance of the V1ReplicationControllerStatus class. /// </summary> public V1ReplicationControllerStatus() { CustomInit(); } /// <summary> /// Initializes a new instance of the V1ReplicationControllerStatus class. /// </summary> /// <param name="replicas"> /// Replicas is the most recently oberved number of replicas. More info: /// https://kubernetes.io/docs/concepts/workloads/controllers/replicationcontroller#what-is-a-replicationcontroller /// </param> /// <param name="availableReplicas"> /// The number of available replicas (ready for at least minReadySeconds) for this /// replication controller. /// </param> /// <param name="conditions"> /// Represents the latest available observations of a replication controller&apos;s /// current state. /// </param> /// <param name="fullyLabeledReplicas"> /// The number of pods that have labels matching the labels of the pod template of /// the replication controller. /// </param> /// <param name="observedGeneration"> /// ObservedGeneration reflects the generation of the most recently observed /// replication controller. /// </param> /// <param name="readyReplicas"> /// The number of ready replicas for this replication controller. /// </param> public V1ReplicationControllerStatus(int replicas, int? availableReplicas = null, IList<V1ReplicationControllerCondition> conditions = null, int? fullyLabeledReplicas = null, long? observedGeneration = null, int? readyReplicas = null) { AvailableReplicas = availableReplicas; Conditions = conditions; FullyLabeledReplicas = fullyLabeledReplicas; ObservedGeneration = observedGeneration; ReadyReplicas = readyReplicas; Replicas = replicas; CustomInit(); } /// <summary> /// An initialization method that performs custom operations like setting defaults /// </summary> partial void CustomInit(); /// <summary> /// The number of available replicas (ready for at least minReadySeconds) for this /// replication controller. /// </summary> [JsonProperty(PropertyName = "availableReplicas")] public int? AvailableReplicas { get; set; } /// <summary> /// Represents the latest available observations of a replication controller&apos;s /// current state. /// </summary> [JsonProperty(PropertyName = "conditions")] public IList<V1ReplicationControllerCondition> Conditions { get; set; } /// <summary> /// The number of pods that have labels matching the labels of the pod template of /// the replication controller. /// </summary> [JsonProperty(PropertyName = "fullyLabeledReplicas")] public int? FullyLabeledReplicas { get; set; } /// <summary> /// ObservedGeneration reflects the generation of the most recently observed /// replication controller. /// </summary> [JsonProperty(PropertyName = "observedGeneration")] public long? ObservedGeneration { get; set; } /// <summary> /// The number of ready replicas for this replication controller. /// </summary> [JsonProperty(PropertyName = "readyReplicas")] public int? ReadyReplicas { get; set; } /// <summary> /// Replicas is the most recently oberved number of replicas. More info: /// https://kubernetes.io/docs/concepts/workloads/controllers/replicationcontroller#what-is-a-replicationcontroller /// </summary> [JsonProperty(PropertyName = "replicas")] public int Replicas { get; set; } /// <summary> /// Validate the object. /// </summary> /// <exception cref="ValidationException"> /// Thrown if validation fails /// </exception> public virtual void Validate() { foreach(var obj in Conditions) { obj.Validate(); } } } }
38.834646
242
0.619424
[ "Apache-2.0" ]
anshulahuja98/csharp
src/KubernetesClient/generated/Models/V1ReplicationControllerStatus.cs
4,932
C#
using Orleans.Redis.Common; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; using Microsoft.Extensions.Options; using Orleans.Configuration; using Orleans.Hosting; using Orleans.Providers; using Orleans.Runtime; using Orleans.Serialization; using System; using System.Collections.Generic; using System.Text; using Orleans.Storage; namespace Orleans.Hosting { public static class RedisStorageBuilderExtensions { /// <summary> /// Configure silo to use redis storage as the default grain storage. /// </summary> public static ISiloHostBuilder AddRedisGrainStorageAsDefault(this ISiloHostBuilder builder, Action<RedisGrainStorageOptions> configureOptions) { return builder.AddRedisGrainStorage(ProviderConstants.DEFAULT_STORAGE_PROVIDER_NAME, configureOptions); } /// <summary> /// Configure silo to use redis table storage for grain storage. /// </summary> public static ISiloHostBuilder AddRedisGrainStorage(this ISiloHostBuilder builder, string name, Action<RedisGrainStorageOptions> configureOptions) { return builder.ConfigureServices(services => services.AddRedisGrainStorage(name, ob => ob.Configure(configureOptions))); } internal static IServiceCollection AddRedisGrainStorage(this IServiceCollection services, string name, Action<OptionsBuilder<RedisGrainStorageOptions>> configureOptions = null) { configureOptions?.Invoke(services.AddOptions<RedisGrainStorageOptions>(name)); services.TryAddSingleton(SilentLogger.Logger); services.TryAddSingleton(CachedConnectionMultiplexerFactory.Default); services.TryAddSingleton<ISerializationManager, OrleansSerializationManager>(); services.AddTransient<IConfigurationValidator>(sp => new RedisGrainStorageOptionsValidator(sp.GetService<IOptionsSnapshot<RedisGrainStorageOptions>>().Get(name), name)); services.ConfigureNamedOptionForLogging<RedisGrainStorageOptions>(name); services.TryAddSingleton(sp => sp.GetServiceByName<IGrainStorage>(ProviderConstants.DEFAULT_STORAGE_PROVIDER_NAME)); services.AddSingletonNamedService(name, RedisGrainStorageFactory.Create); services.AddSingletonNamedService(name, (s, n) => (ILifecycleParticipant<ISiloLifecycle>)s.GetRequiredServiceByName<IGrainStorage>(n)); return services; } } }
48.384615
184
0.752385
[ "MIT" ]
EvgenSk/Orleans.Providers.Redis
src/Orleans.Storage.Redis/Hosting/RedisStorageBuilderExtensions.cs
2,518
C#
using Microsoft.Data.Sqlite; using System.Threading.Tasks; namespace BotBase.Databases.MainDatabaseTables { public class DatabaseTable : ITable { private readonly SqliteConnection connection; public DatabaseTable(SqliteConnection connection) => this.connection = connection; public Task InitAsync() { using SqliteCommand cmd = new("CREATE TABLE IF NOT EXISTS Database (guild_id TEXT PRIMARY KEY, data TEXT NOT NULL);", connection); return cmd.ExecuteNonQueryAsync(); } } }
29.105263
142
0.688969
[ "MIT" ]
the-mighty-mo/BotBase
BotBase/Databases/MainDatabaseTables/DatabaseTable.cs
555
C#
using cabzcommerce.cshared.DTOs; using cabzcommerce.cshared.DTOs.User; using cabzcommerce.cshared.Models; namespace cabzcommerce.api.Repositories { public interface IUserRepo { Task<Profile> Register(Registration User); Task<UserAccessToken> GrantUserAccess(User User); Task<User> GetUser(Guid Id); Task<User> GetUserByEmail(string Email); Task<UserAccessToken> RefreshToken(Guid RefToken,string UserToken); Task<UserAccessToken> GetUserAccessByCurrentToken(string UserToken); } }
31.882353
76
0.738007
[ "BSD-2-Clause" ]
ecabigting/cabzcommerce
src/cabzcommerce.api/Repositories/User/IUserRepo.cs
542
C#
using ECM7.Migrator.Framework; using Framework.Migrator.Extensions; namespace Core.WebContent.Migrations { /// <summary> /// Adds ContentPages table. /// </summary> [Migration(6)] public class Migration_AddArticles : Migration { /// <summary> /// Executes migration. /// </summary> public override void Apply() { Database.AddTable("WebContent_Articles", t => { t.PrimaryKey(); t.DateTime("CreateDate").Null(); t.Long("UserId").Null(); t.Integer("Status"); t.String("Author").Null(); t.DateTime("StartPublishingDate").Null(); t.DateTime("FinishPublishingDate").Null(); t.DateTime("LastModifiedDate").Null(); t.String("Url"); t.Integer("UrlType"); t.ForeignKey("Category").Table("WebContent_Categories"); }); } /// <summary> /// Rollbacks migration. /// </summary> public override void Revert() { Database.ChangeTable("WebContent_Articles", t => t.RemoveForeignKey("Category").Table("WebContent_Categories")); Database.RemoveTable("WebContent_Articles"); } } }
30.72093
124
0.526117
[ "BSD-2-Clause" ]
coreframework/Core-Framework
Source/Core.WebContent.Migrations/Migration_AddArticles.cs
1,323
C#
// <auto-generated> // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. // </auto-generated> namespace Gov.Lclb.Cllb.Interfaces { using Microsoft.Rest; using Models; using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; /// <summary> /// Regionprocesssession operations. /// </summary> public partial class Regionprocesssession : IServiceOperations<DynamicsClient>, IRegionprocesssession { /// <summary> /// Initializes a new instance of the Regionprocesssession class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public Regionprocesssession(DynamicsClient client) { if (client == null) { throw new System.ArgumentNullException("client"); } Client = client; } /// <summary> /// Gets a reference to the DynamicsClient /// </summary> public DynamicsClient Client { get; private set; } /// <summary> /// Get adoxio_region_ProcessSession from adoxio_regions /// </summary> /// <param name='adoxioRegionid'> /// key: adoxio_regionid of adoxio_region /// </param> /// <param name='top'> /// </param> /// <param name='skip'> /// </param> /// <param name='search'> /// </param> /// <param name='filter'> /// </param> /// <param name='count'> /// </param> /// <param name='orderby'> /// Order items by property values /// </param> /// <param name='select'> /// Select properties to be returned /// </param> /// <param name='expand'> /// Expand related entities /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="HttpOperationException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<HttpOperationResponse<MicrosoftDynamicsCRMprocesssessionCollection>> GetWithHttpMessagesAsync(string adoxioRegionid, int? top = default(int?), int? skip = default(int?), string search = default(string), string filter = default(string), bool? count = default(bool?), IList<string> orderby = default(IList<string>), IList<string> select = default(IList<string>), IList<string> expand = default(IList<string>), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (adoxioRegionid == null) { throw new ValidationException(ValidationRules.CannotBeNull, "adoxioRegionid"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("adoxioRegionid", adoxioRegionid); tracingParameters.Add("top", top); tracingParameters.Add("skip", skip); tracingParameters.Add("search", search); tracingParameters.Add("filter", filter); tracingParameters.Add("count", count); tracingParameters.Add("orderby", orderby); tracingParameters.Add("select", select); tracingParameters.Add("expand", expand); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "adoxio_regions({adoxio_regionid})/adoxio_region_ProcessSession").ToString(); _url = _url.Replace("{adoxio_regionid}", System.Uri.EscapeDataString(adoxioRegionid)); List<string> _queryParameters = new List<string>(); if (top != null) { _queryParameters.Add(string.Format("$top={0}", System.Uri.EscapeDataString(Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(top, Client.SerializationSettings).Trim('"')))); } if (skip != null) { _queryParameters.Add(string.Format("$skip={0}", System.Uri.EscapeDataString(Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(skip, Client.SerializationSettings).Trim('"')))); } if (search != null) { _queryParameters.Add(string.Format("$search={0}", System.Uri.EscapeDataString(search))); } if (filter != null) { _queryParameters.Add(string.Format("$filter={0}", System.Uri.EscapeDataString(filter))); } if (count != null) { _queryParameters.Add(string.Format("$count={0}", System.Uri.EscapeDataString(Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(count, Client.SerializationSettings).Trim('"')))); } if (orderby != null) { _queryParameters.Add(string.Format("$orderby={0}", System.Uri.EscapeDataString(string.Join(",", orderby)))); } if (select != null) { _queryParameters.Add(string.Format("$select={0}", System.Uri.EscapeDataString(string.Join(",", select)))); } if (expand != null) { _queryParameters.Add(string.Format("$expand={0}", System.Uri.EscapeDataString(string.Join(",", expand)))); } if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); if (_httpResponse.Content != null) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); } else { _responseContent = string.Empty; } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new HttpOperationResponse<MicrosoftDynamicsCRMprocesssessionCollection>(); _result.Request = _httpRequest; _result.Response = _httpResponse; // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<MicrosoftDynamicsCRMprocesssessionCollection>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Get adoxio_region_ProcessSession from adoxio_regions /// </summary> /// <param name='adoxioRegionid'> /// key: adoxio_regionid of adoxio_region /// </param> /// <param name='processsessionid'> /// key: processsessionid of processsession /// </param> /// <param name='select'> /// Select properties to be returned /// </param> /// <param name='expand'> /// Expand related entities /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="HttpOperationException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<HttpOperationResponse<MicrosoftDynamicsCRMprocesssession>> ProcessSessionByKeyWithHttpMessagesAsync(string adoxioRegionid, string processsessionid, IList<string> select = default(IList<string>), IList<string> expand = default(IList<string>), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (adoxioRegionid == null) { throw new ValidationException(ValidationRules.CannotBeNull, "adoxioRegionid"); } if (processsessionid == null) { throw new ValidationException(ValidationRules.CannotBeNull, "processsessionid"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("adoxioRegionid", adoxioRegionid); tracingParameters.Add("processsessionid", processsessionid); tracingParameters.Add("select", select); tracingParameters.Add("expand", expand); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ProcessSessionByKey", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "adoxio_regions({adoxio_regionid})/adoxio_region_ProcessSession({processsessionid})").ToString(); _url = _url.Replace("{adoxio_regionid}", System.Uri.EscapeDataString(adoxioRegionid)); _url = _url.Replace("{processsessionid}", System.Uri.EscapeDataString(processsessionid)); List<string> _queryParameters = new List<string>(); if (select != null) { _queryParameters.Add(string.Format("$select={0}", System.Uri.EscapeDataString(string.Join(",", select)))); } if (expand != null) { _queryParameters.Add(string.Format("$expand={0}", System.Uri.EscapeDataString(string.Join(",", expand)))); } if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); if (_httpResponse.Content != null) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); } else { _responseContent = string.Empty; } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new HttpOperationResponse<MicrosoftDynamicsCRMprocesssession>(); _result.Request = _httpRequest; _result.Response = _httpResponse; // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<MicrosoftDynamicsCRMprocesssession>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } } }
44.716628
554
0.566618
[ "Apache-2.0" ]
BrendanBeachBC/jag-lcrb-carla-public
cllc-interfaces/Dynamics-Autorest/Regionprocesssession.cs
19,094
C#
#region BSD License /* * Use of this source code is governed by a BSD-style * license that can be found in the LICENSE.md file or at * https://github.com/Wagnerp/Krypton-Toolkit-Suite-Extended-NET-5.451/blob/master/LICENSE * */ #endregion using System.Diagnostics; using System.Drawing; namespace ExtendedControls.Base.Code.Colours { public sealed class RGBColour { #region Public static methods. // ------------------------------------------------------------------ /// <summary> /// Creates from a given color. /// </summary> /// <param name="colour">The color.</param> /// <returns></returns> public static RGBColour FromColour(Color colour) { return ColourConverting.ColourToRGB(colour); } /// <summary> /// Creates from a given color. /// </summary> /// <param name="colour">The color.</param> /// <returns></returns> public static RGBColour FromRgbColour(RGBColour colour) { return new RGBColour(colour.Red, colour.Green, colour.Blue); } /// <summary> /// Creates from a given color. /// </summary> /// <param name="colour">The color.</param> /// <returns></returns> public static RGBColour FromHSBColour(HSBColour colour) { return colour.ToRGBColour(); } /// <summary> /// Creates from a given color. /// </summary> /// <param name="colour">The color.</param> /// <returns></returns> public static RGBColour FromHSLColour(HSLColour colour) { return colour.ToRGBColour(); } // ------------------------------------------------------------------ #endregion #region Public methods. // ------------------------------------------------------------------ /// <summary> /// Initializes a new instance of the <see cref="RgbColor"/> class. /// </summary> /// <param name="red">The red.</param> /// <param name="green">The green.</param> /// <param name="blue">The blue.</param> public RGBColour(int red, int green, int blue) { Red = red; Green = green; Blue = blue; } /// <summary> /// Returns a <see cref="T:System.String"/> that represents the current /// <see cref="T:System.Object"/>. /// </summary> /// <returns> /// A <see cref="T:System.String"/> that represents the current /// <see cref="T:System.Object"/>. /// </returns> public override string ToString() { return string.Format( @"Red: {0}; green: {1}; blue: {2}", Red, Green, Blue); } /// <summary> /// Returns the underlying .NET color. /// </summary> /// <returns></returns> public Color ToColour() { return ColourConverting.RGBToColour(this); } /// <summary> /// Returns a RGB color. /// </summary> /// <returns></returns> public RGBColour ToRGBColour() { return this; } /// <summary> /// Returns a HSB color. /// </summary> /// <returns></returns> public HSBColour ToHSBColour() { return ColourConverting.RGBToHSB(this); } /// <summary> /// Returns a HSL color. /// </summary> /// <returns></returns> public HSLColour ToHSLColour() { return ColourConverting.RGBToHSL(this); } /// <summary> /// Determines whether the specified <see cref="T:System.Object"/> is /// equal to the current <see cref="T:System.Object"/>. /// </summary> /// <param name="obj">The <see cref="T:System.Object"/> to compare with /// the current <see cref="T:System.Object"/>.</param> /// <returns> /// true if the specified <see cref="T:System.Object"/> is equal to the /// current <see cref="T:System.Object"/>; otherwise, false. /// </returns> /// <exception cref="T:System.NullReferenceException">The /// <paramref name="obj"/> parameter is null.</exception> public override bool Equals( object obj) { var equal = false; if (obj is RGBColour) { var rgb = (RGBColour)obj; if (Red == rgb.Red && Blue == rgb.Blue && Green == rgb.Green) { equal = true; } } return equal; } /// <summary> /// Serves as a hash function for a particular type. /// </summary> /// <returns> /// A hash code for the current <see cref="T:System.Object"/>. /// </returns> public override int GetHashCode() { Debug.Assert(1 == 1); return base.GetHashCode(); } // ------------------------------------------------------------------ #endregion #region Public properties. // ------------------------------------------------------------------ /// <summary> /// Gets or sets the red component. Values from 0 to 255. /// </summary> /// <value>The red component.</value> public int Red { get; set; } /// <summary> /// Gets or sets the green component. Values from 0 to 255. /// </summary> /// <value>The green component.</value> public int Green { get; set; } /// <summary> /// Gets or sets the blue component. Values from 0 to 255. /// </summary> /// <value>The blue component.</value> public int Blue { get; set; } // ------------------------------------------------------------------ #endregion } }
29.333333
90
0.459578
[ "BSD-3-Clause" ]
Krypton-Suite-Legacy/Krypton-Toolkit-Suite-Extended-NET-5.451
Source/Krypton Toolkit Suite Extended/Full Toolkit/Extended Controls/Base/Code/Colours/RGBColour.cs
6,162
C#
using System.Linq; using Microsoft.EntityFrameworkCore; using Abp.Configuration; using Abp.Localization; using Abp.Net.Mail; namespace Exceed.EntityFrameworkCore.Seed.Host { public class DefaultSettingsCreator { private readonly ExceedDbContext _context; public DefaultSettingsCreator(ExceedDbContext context) { _context = context; } public void Create() { // Emailing AddSettingIfNotExists(EmailSettingNames.DefaultFromAddress, "admin@mydomain.com"); AddSettingIfNotExists(EmailSettingNames.DefaultFromDisplayName, "mydomain.com mailer"); // Languages AddSettingIfNotExists(LocalizationSettingNames.DefaultLanguage, "en"); } private void AddSettingIfNotExists(string name, string value, int? tenantId = null) { if (_context.Settings.IgnoreQueryFilters().Any(s => s.Name == name && s.TenantId == tenantId && s.UserId == null)) { return; } _context.Settings.Add(new Setting(tenantId, null, name, value)); _context.SaveChanges(); } } }
29.525
126
0.631668
[ "MIT" ]
yiershan/Excced
aspnet-core/src/Exceed.EntityFrameworkCore/EntityFrameworkCore/Seed/Host/DefaultSettingsCreator.cs
1,183
C#
using SampleArchitecture.Api.Controllers.Users.Requests; using SampleArchitecture.Commands; using SampleArchitecture.Models; using SampleArchitecture.Storage; namespace SampleArchitecture.Api.Controllers.Users.CommandHandlers { /// <summary> /// The get user by identifier request command handler. /// </summary> /// <seealso cref="ICommandHandler{TCommand, TResult}" /> internal sealed class GetUserByIdRequestCommandHandler : ICommandHandler<GetUserByIdRequest, User> { private readonly IUserRepository _userRepository; /// <summary> /// Initializes a new instance of <see cref="GetUserByIdRequestCommandHandler" />. /// </summary> /// <param name="userRepository">The <see cref="IUserRepository" />.</param> public GetUserByIdRequestCommandHandler(IUserRepository userRepository) { _userRepository = userRepository; } /// <inheritdoc /> public async ValueTask<User> HandleAsync(GetUserByIdRequest command, CancellationToken cancellationToken) { return await _userRepository.GetAsync(command.Id, cancellationToken); } } }
37.09375
102
0.693345
[ "MIT" ]
dotnet-enthusiast/SampleArchitecture
src/Ports/SampleArchitecture.Api/Controllers/Users/CommandHandlers/GetUserByIdRequestCommandHandler.cs
1,189
C#
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Windows; using System.Windows.Controls; using System.Windows.Navigation; using Microsoft.Phone.Controls; using Microsoft.Phone.Shell; namespace ActiveVB.News.WinPhone { public partial class MainPage : global::Xamarin.Forms.Platform.WinPhone.FormsApplicationPage { public MainPage() { InitializeComponent(); SupportedOrientations = SupportedPageOrientation.PortraitOrLandscape; global::Xamarin.Forms.Forms.Init(); LoadApplication(new ActiveVB.News.App()); } } }
24.28
94
0.75453
[ "Unlicense" ]
Henkoglobin/ActiveVB.News
ActiveVB.News/ActiveVB.News.WinPhone/MainPage.xaml.cs
609
C#
using System; using System.Collections.Generic; using System.Text; using Newtonsoft.Json; namespace Backlog4net.Internal.Json.CustomFields { public class DateValueSettingJsonImpl : DateValueSetting { internal class JsonConverter : InterfaceConverter<DateValueSetting, DateValueSettingJsonImpl> { } [JsonProperty("id")] public DateCustomFieldInitialValueType ValueType { get; private set; } [JsonProperty] public DateTime? Date { get; private set; } [JsonProperty] public int? Shift { get; private set; } } }
26.409091
105
0.702238
[ "MIT" ]
JTOne123/backlog4net
src/Backlog4net/Internal/Json/CustomFields/DateValueSettingJsonImpl.cs
583
C#
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; using ZYNet.CloudSystem.Frame; namespace ZYNet.CloudSystem.Client { public class ModuleDictionary : IModuleDictionary { public Dictionary<int, IAsyncMethodDef> ModuleDiy { get; private set; } public ModuleDictionary() { ModuleDiy = new Dictionary<int, IAsyncMethodDef>(); } public void Install(object o) { Type type = o.GetType(); var methos = type.GetMethods(); Type tasktype = typeof(Task); foreach (var method in methos) { var attr = method.GetCustomAttributes(typeof(TAG), true); foreach (var att in attr) { if (att is TAG attrcmdtype) { if ((method.ReturnType == tasktype || (Common.IsTypeOfBaseTypeIs(method.ReturnType, tasktype) && method.ReturnType.IsConstructedGenericType))) { if (method.GetParameters().Length > 0 && (method.GetParameters()[0].ParameterType == typeof(AsyncCalls)|| method.GetParameters()[0].ParameterType == typeof(IASync))) { if (!ModuleDiy.ContainsKey(attrcmdtype.CmdTag)) { AsyncMethodDef tmp = new AsyncMethodDef(method, o); ModuleDiy.Add(attrcmdtype.CmdTag, tmp); } else { AsyncMethodDef tmp = new AsyncMethodDef(method, o); ModuleDiy[attrcmdtype.CmdTag] = tmp; } } else if(method.GetParameters().Length==0|| (method.GetParameters()[0].ParameterType!= typeof(AsyncCalls) && method.GetParameters()[0].ParameterType != typeof(IASync))) { if (!ModuleDiy.ContainsKey(attrcmdtype.CmdTag)) { AsyncMethodDef tmp = new AsyncMethodDef(method, o) { IsNotRefAsyncArg = true }; ModuleDiy.Add(attrcmdtype.CmdTag, tmp); } else { AsyncMethodDef tmp = new AsyncMethodDef(method, o) { IsNotRefAsyncArg = true }; ModuleDiy[attrcmdtype.CmdTag] = tmp; } } } else if (method.GetParameters().Length > 0 && (method.GetParameters()[0].ParameterType == typeof(CloudClient) || method.GetParameters()[0].ParameterType == typeof(IASync))) { if (!ModuleDiy.ContainsKey(attrcmdtype.CmdTag)) { AsyncMethodDef tmp = new AsyncMethodDef(method, o); ModuleDiy.Add(attrcmdtype.CmdTag, tmp); } else { AsyncMethodDef tmp = new AsyncMethodDef(method, o); ModuleDiy[attrcmdtype.CmdTag] = tmp; } } else if (method.GetParameters().Length == 0 || (method.GetParameters()[0].ParameterType != typeof(CloudClient) || method.GetParameters()[0].ParameterType != typeof(IASync))) { if (!ModuleDiy.ContainsKey(attrcmdtype.CmdTag)) { AsyncMethodDef tmp = new AsyncMethodDef(method, o) { IsNotRefAsyncArg = true }; ModuleDiy.Add(attrcmdtype.CmdTag, tmp); } else { AsyncMethodDef tmp = new AsyncMethodDef(method, o) { IsNotRefAsyncArg = true }; ModuleDiy[attrcmdtype.CmdTag] = tmp; } } break; } } } } } public class AsyncMethodDef : IAsyncMethodDef { Type tasktype = typeof(Task); public object Obj { get; private set; } public bool IsAsync { get; set; } public bool IsRet { get; set; } public bool IsNotRefAsyncArg { get; set; } public MethodInfo MethodInfo { get; set; } public Type[] ArgsType { get; set; } public AsyncMethodDef(MethodInfo methodInfo, object token) { this.Obj = token; this.MethodInfo = methodInfo; var parameters = methodInfo.GetParameters(); ArgsType = new Type[parameters.Length]; for (int i = 0; i < parameters.Length; i++) { ArgsType[i] = parameters[i].ParameterType; } if (methodInfo.ReturnType == tasktype || methodInfo.ReturnType == null|| methodInfo.ReturnType == typeof(void)) { IsRet = false; } else IsRet = true; if (Common.IsTypeOfBaseTypeIs(methodInfo.ReturnType ,tasktype)) { IsAsync = true; } } } }
36.770588
197
0.412894
[ "Apache-2.0" ]
luyikk/ZYNet
src/ZYNetClient/Client/AsyncModuleDef.cs
6,253
C#
using System.Threading.Tasks; using MimeKit; namespace Vue.Splash_API.Services.Mail.Mailable; public interface IMailable { Task<MimeMessage> Build(); Task<string> GetHtmlBody(); Task<string> GetPlainTextBody(); }
20.545455
48
0.752212
[ "MIT" ]
Ola-jed/Vue.Splash-API
Vue.Splash-API/Services/Mail/Mailable/IMailable.cs
226
C#
// *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.Aws.DirectConnect { /// <summary> /// Provides a Direct Connect hosted public virtual interface resource. This resource represents the allocator's side of the hosted virtual interface. /// A hosted virtual interface is a virtual interface that is owned by another AWS account. /// /// ## Example Usage /// /// ```csharp /// using Pulumi; /// using Aws = Pulumi.Aws; /// /// class MyStack : Stack /// { /// public MyStack() /// { /// var foo = new Aws.DirectConnect.HostedPublicVirtualInterface("foo", new Aws.DirectConnect.HostedPublicVirtualInterfaceArgs /// { /// AddressFamily = "ipv4", /// AmazonAddress = "175.45.176.2/30", /// BgpAsn = 65352, /// ConnectionId = "dxcon-zzzzzzzz", /// CustomerAddress = "175.45.176.1/30", /// RouteFilterPrefixes = /// { /// "210.52.109.0/24", /// "175.45.176.0/22", /// }, /// Vlan = 4094, /// }); /// } /// /// } /// ``` /// /// ## Import /// /// Direct Connect hosted public virtual interfaces can be imported using the `vif id`, e.g. /// /// ```sh /// $ pulumi import aws:directconnect/hostedPublicVirtualInterface:HostedPublicVirtualInterface test dxvif-33cc44dd /// ``` /// </summary> [AwsResourceType("aws:directconnect/hostedPublicVirtualInterface:HostedPublicVirtualInterface")] public partial class HostedPublicVirtualInterface : Pulumi.CustomResource { /// <summary> /// The address family for the BGP peer. `ipv4 ` or `ipv6`. /// </summary> [Output("addressFamily")] public Output<string> AddressFamily { get; private set; } = null!; /// <summary> /// The IPv4 CIDR address to use to send traffic to Amazon. Required for IPv4 BGP peers. /// </summary> [Output("amazonAddress")] public Output<string> AmazonAddress { get; private set; } = null!; [Output("amazonSideAsn")] public Output<string> AmazonSideAsn { get; private set; } = null!; /// <summary> /// The ARN of the virtual interface. /// </summary> [Output("arn")] public Output<string> Arn { get; private set; } = null!; /// <summary> /// The Direct Connect endpoint on which the virtual interface terminates. /// </summary> [Output("awsDevice")] public Output<string> AwsDevice { get; private set; } = null!; /// <summary> /// The autonomous system (AS) number for Border Gateway Protocol (BGP) configuration. /// </summary> [Output("bgpAsn")] public Output<int> BgpAsn { get; private set; } = null!; /// <summary> /// The authentication key for BGP configuration. /// </summary> [Output("bgpAuthKey")] public Output<string> BgpAuthKey { get; private set; } = null!; /// <summary> /// The ID of the Direct Connect connection (or LAG) on which to create the virtual interface. /// </summary> [Output("connectionId")] public Output<string> ConnectionId { get; private set; } = null!; /// <summary> /// The IPv4 CIDR destination address to which Amazon should send traffic. Required for IPv4 BGP peers. /// </summary> [Output("customerAddress")] public Output<string> CustomerAddress { get; private set; } = null!; /// <summary> /// The name for the virtual interface. /// </summary> [Output("name")] public Output<string> Name { get; private set; } = null!; /// <summary> /// The AWS account that will own the new virtual interface. /// </summary> [Output("ownerAccountId")] public Output<string> OwnerAccountId { get; private set; } = null!; /// <summary> /// A list of routes to be advertised to the AWS network in this region. /// </summary> [Output("routeFilterPrefixes")] public Output<ImmutableArray<string>> RouteFilterPrefixes { get; private set; } = null!; /// <summary> /// The VLAN ID. /// </summary> [Output("vlan")] public Output<int> Vlan { get; private set; } = null!; /// <summary> /// Create a HostedPublicVirtualInterface 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 HostedPublicVirtualInterface(string name, HostedPublicVirtualInterfaceArgs args, CustomResourceOptions? options = null) : base("aws:directconnect/hostedPublicVirtualInterface:HostedPublicVirtualInterface", name, args ?? new HostedPublicVirtualInterfaceArgs(), MakeResourceOptions(options, "")) { } private HostedPublicVirtualInterface(string name, Input<string> id, HostedPublicVirtualInterfaceState? state = null, CustomResourceOptions? options = null) : base("aws:directconnect/hostedPublicVirtualInterface:HostedPublicVirtualInterface", name, state, MakeResourceOptions(options, id)) { } private static CustomResourceOptions MakeResourceOptions(CustomResourceOptions? options, Input<string>? id) { var defaultOptions = new CustomResourceOptions { Version = Utilities.Version, }; 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 HostedPublicVirtualInterface 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="state">Any extra arguments used during the lookup.</param> /// <param name="options">A bag of options that control this resource's behavior</param> public static HostedPublicVirtualInterface Get(string name, Input<string> id, HostedPublicVirtualInterfaceState? state = null, CustomResourceOptions? options = null) { return new HostedPublicVirtualInterface(name, id, state, options); } } public sealed class HostedPublicVirtualInterfaceArgs : Pulumi.ResourceArgs { /// <summary> /// The address family for the BGP peer. `ipv4 ` or `ipv6`. /// </summary> [Input("addressFamily", required: true)] public Input<string> AddressFamily { get; set; } = null!; /// <summary> /// The IPv4 CIDR address to use to send traffic to Amazon. Required for IPv4 BGP peers. /// </summary> [Input("amazonAddress")] public Input<string>? AmazonAddress { get; set; } /// <summary> /// The autonomous system (AS) number for Border Gateway Protocol (BGP) configuration. /// </summary> [Input("bgpAsn", required: true)] public Input<int> BgpAsn { get; set; } = null!; /// <summary> /// The authentication key for BGP configuration. /// </summary> [Input("bgpAuthKey")] public Input<string>? BgpAuthKey { get; set; } /// <summary> /// The ID of the Direct Connect connection (or LAG) on which to create the virtual interface. /// </summary> [Input("connectionId", required: true)] public Input<string> ConnectionId { get; set; } = null!; /// <summary> /// The IPv4 CIDR destination address to which Amazon should send traffic. Required for IPv4 BGP peers. /// </summary> [Input("customerAddress")] public Input<string>? CustomerAddress { get; set; } /// <summary> /// The name for the virtual interface. /// </summary> [Input("name")] public Input<string>? Name { get; set; } /// <summary> /// The AWS account that will own the new virtual interface. /// </summary> [Input("ownerAccountId", required: true)] public Input<string> OwnerAccountId { get; set; } = null!; [Input("routeFilterPrefixes", required: true)] private InputList<string>? _routeFilterPrefixes; /// <summary> /// A list of routes to be advertised to the AWS network in this region. /// </summary> public InputList<string> RouteFilterPrefixes { get => _routeFilterPrefixes ?? (_routeFilterPrefixes = new InputList<string>()); set => _routeFilterPrefixes = value; } /// <summary> /// The VLAN ID. /// </summary> [Input("vlan", required: true)] public Input<int> Vlan { get; set; } = null!; public HostedPublicVirtualInterfaceArgs() { } } public sealed class HostedPublicVirtualInterfaceState : Pulumi.ResourceArgs { /// <summary> /// The address family for the BGP peer. `ipv4 ` or `ipv6`. /// </summary> [Input("addressFamily")] public Input<string>? AddressFamily { get; set; } /// <summary> /// The IPv4 CIDR address to use to send traffic to Amazon. Required for IPv4 BGP peers. /// </summary> [Input("amazonAddress")] public Input<string>? AmazonAddress { get; set; } [Input("amazonSideAsn")] public Input<string>? AmazonSideAsn { get; set; } /// <summary> /// The ARN of the virtual interface. /// </summary> [Input("arn")] public Input<string>? Arn { get; set; } /// <summary> /// The Direct Connect endpoint on which the virtual interface terminates. /// </summary> [Input("awsDevice")] public Input<string>? AwsDevice { get; set; } /// <summary> /// The autonomous system (AS) number for Border Gateway Protocol (BGP) configuration. /// </summary> [Input("bgpAsn")] public Input<int>? BgpAsn { get; set; } /// <summary> /// The authentication key for BGP configuration. /// </summary> [Input("bgpAuthKey")] public Input<string>? BgpAuthKey { get; set; } /// <summary> /// The ID of the Direct Connect connection (or LAG) on which to create the virtual interface. /// </summary> [Input("connectionId")] public Input<string>? ConnectionId { get; set; } /// <summary> /// The IPv4 CIDR destination address to which Amazon should send traffic. Required for IPv4 BGP peers. /// </summary> [Input("customerAddress")] public Input<string>? CustomerAddress { get; set; } /// <summary> /// The name for the virtual interface. /// </summary> [Input("name")] public Input<string>? Name { get; set; } /// <summary> /// The AWS account that will own the new virtual interface. /// </summary> [Input("ownerAccountId")] public Input<string>? OwnerAccountId { get; set; } [Input("routeFilterPrefixes")] private InputList<string>? _routeFilterPrefixes; /// <summary> /// A list of routes to be advertised to the AWS network in this region. /// </summary> public InputList<string> RouteFilterPrefixes { get => _routeFilterPrefixes ?? (_routeFilterPrefixes = new InputList<string>()); set => _routeFilterPrefixes = value; } /// <summary> /// The VLAN ID. /// </summary> [Input("vlan")] public Input<int>? Vlan { get; set; } public HostedPublicVirtualInterfaceState() { } } }
38.011905
185
0.583151
[ "ECL-2.0", "Apache-2.0" ]
aamir-locus/pulumi-aws
sdk/dotnet/DirectConnect/HostedPublicVirtualInterface.cs
12,772
C#
using System; using System.Collections.Generic; using System.ComponentModel; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc.ModelBinding; namespace IdentityServerAspNet.Models.ManageViewModels { public class EnableAuthenticatorViewModel { [Required] [StringLength(7, ErrorMessage = "The {0} must be at least {2} and at max {1} characters long.", MinimumLength = 6)] [DataType(DataType.Text)] [Display(Name = "Verification Code")] public string Code { get; set; } [BindNever] public string SharedKey { get; set; } [BindNever] public string AuthenticatorUri { get; set; } } }
29.846154
127
0.657216
[ "MIT" ]
victorioferrario/hubx-identity
servers/IdentityServerAspNet/Models/ManageViewModels/EnableAuthenticatorViewModel.cs
778
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.Windows.Forms; namespace LockerAnnouncer { static class Program { /// <summary> /// 應用程式的主要進入點。 /// </summary> [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new LockerAnnouncer()); } } }
21.478261
65
0.611336
[ "BSD-3-Clause" ]
HarrisQs/Locker
LockerAnnouncer/Program.cs
518
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namespace SistemaAlugarCarro { class Program { static string[,] baseDeCarros; static void Main(string[] args) { CarregaBancoDeDados(); var opcaomenu = MenuPrincipal(); while (opcaomenu != 3) { if (opcaomenu == 1) MenuAlugarCarro(); if (opcaomenu == 2) MenuDevolverCarro(); opcaomenu = MenuPrincipal(); } } /// <summary> /// Metodo que mostra o bem vindo ao sistema. /// </summary> public static void BemVindo() { Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine(" ,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,"); Console.WriteLine(" | Bem vindo a DiCars™ |"); Console.ForegroundColor = ConsoleColor.White; Console.WriteLine(" *****************************************************"); Console.WriteLine(" | Carros importados |"); Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine(" | Nacionais |"); Console.WriteLine(" *****************************************************"); Console.ForegroundColor = ConsoleColor.White; } /// <summary> /// Metodo que mostra as opções do menu inicial. /// </summary> /// <returns>Retorna a opção desejada do cliente.</returns> public static int MenuPrincipal() { Console.Clear(); BemVindo(); Console.WriteLine("Como podemos ajuda-lo?"); Console.WriteLine("\r\n1 - Alugar carro"); Console.WriteLine("\r\n2 - Devolver carro"); Console.WriteLine("\r\n3 - Sair do sistema"); Console.WriteLine("\r\nDigite a opção desejada:"); Console.WriteLine("\r\n"); int.TryParse(Console.ReadKey().KeyChar.ToString(), out int opcao); return opcao; } /// <summary> /// Metodo que carrega o banco de dados. /// </summary> public static void CarregaBancoDeDados() { baseDeCarros = new string[5, 3] { {"Ferrari","2011","sim",}, {"Lamborguine", "2015", "sim"}, {"Porsche", "2018", "nâo"}, {"Golf", "2010","não"}, {"Fiat147","1980","sim"}, }; } /// <summary> /// Metodo que retorna se o carro pode ser alugado. /// </summary> /// <param name="nomeCarro">Nome do carro a ser alugado.</param> /// <returns>Retorna verdadeiro caso o carro esteja disponivel para alugar.</returns> public static bool? PesquisaCarroParaAlugar(string nomeCarro) { for (int i = 0; i < baseDeCarros.GetLength(0); i++) { if (CompararNomes(nomeCarro, baseDeCarros[i, 0])) { Console.WriteLine($"O Carro: {nomeCarro}" + $" pode ser alugado?: {baseDeCarros[i, 2]}"); return baseDeCarros[i, 2] == "sim"; } } Console.WriteLine("Nenhum carro encontrado. Deseja realizar a busca novamente ?"); Console.WriteLine("Digite o número da opção desejada: Sim - 1 Não - 2"); int.TryParse(Console.ReadKey().KeyChar.ToString(), out int opcao); if (opcao == 1) { Console.WriteLine("Digite o nome do carro a ser pesquisado:"); nomeCarro = Console.ReadLine(); return PesquisaCarroParaAlugar(nomeCarro); } return null; } /// <summary> /// Metodo para alterar a informação de alugar um carro. /// </summary> /// <param name="nomeDeCarro">Nome do carro.</param> /// <param name="alugar">Parametro que diz se o carro pode ou não ser alugado.</param> public static void AtualizarCarro(string nomeCarro, bool alugar) { for (int i = 0; i < baseDeCarros.GetLength(0); i++) { if (CompararNomes(nomeCarro, baseDeCarros[i, 0])) { baseDeCarros[i, 2] = alugar? "não" : "sim"; } } } /// <summary> /// Metodo que mostra o menu de alugar carro. /// </summary> public static void MenuAlugarCarro() { MostrarMenuInicialCarros("MenuAlugarCarro um carro"); var nomedoCarro = Console.ReadLine(); var resultadoPesquisa = PesquisaCarroParaAlugar(nomedoCarro); if (resultadoPesquisa != null && resultadoPesquisa == true) { Console.Clear(); BemVindo(); Console.WriteLine("\n\nVocê deseja alugar esse carro? para sim - 1 para não - 2"); AtualizarCarro(nomedoCarro, Console.ReadKey().KeyChar.ToString() == "1"); MostarListaDeCarros(); Console.ReadKey(); } if (resultadoPesquisa == null) { Console.WriteLine("Nenhum livro encontrado em nossa base de dados do sistema."); } } /// <summary> /// mostra o menu de devolver o carro. /// </summary> public static void MenuDevolverCarro() { MostrarMenuInicialCarros("Devolver um carro"); MostarListaDeCarros(); var nomeCarro = Console.ReadLine(); var resultadoPesquisa = PesquisaCarroParaAlugar(nomeCarro); if (resultadoPesquisa != null && resultadoPesquisa == false) { Console.Clear(); BemVindo(); Console.WriteLine("\n\nVocê deseja devolver esse carro? para sim - 1 para não - 2"); AtualizarCarro(nomeCarro, Console.ReadKey().KeyChar.ToString() == "0"); MostarListaDeCarros(); Console.ReadKey(); } if (resultadoPesquisa == null) { Console.WriteLine("Nenhum livro encontrado em nossa base de dados do sistema."); } } /// <summary> /// Mostra a lista de carros disponiveis ou não. /// </summary> public static void MostarListaDeCarros() { Console.WriteLine("Carros ainda disponiveis:"); for (int i = 0; i < baseDeCarros.GetLength(0); i++) { Console.WriteLine($"\nNome: {baseDeCarros[i, 0]} Ano: {baseDeCarros[i, 1]} Disponivel: {baseDeCarros[i, 2]}"); } } /// <summary> /// metodo usado para mostrar o menu inicial para alugar ou devolver carros. /// </summary> /// <param name="operacao">Nome do menu a ser exibido.</param> public static void MostrarMenuInicialCarros(string operacao) { Console.Clear(); BemVindo(); Console.WriteLine($"Menu - {operacao}"); Console.WriteLine("Digite o nome do carro para realizar a operação:"); } /// <summary> /// Metodo que compara duas string deixando em caixa alta e removendo espaços vazios dentro da mesma. /// </summary> /// <param name="primeiro">Primeira string.</param> /// <param name="segundo">Segunda string.</param> /// <returns></returns> public static bool CompararNomes(string primeiro, string segundo) { if (primeiro.ToUpper().Replace(" ","") == segundo.ToUpper().Replace(" ","")) return true; return false; } } }
34.697872
126
0.497179
[ "MIT" ]
vitorsousa95/GITvitor
Console/SistemaAlugarCarro/Program.cs
8,182
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. #nullable enable using System.Diagnostics; using System.Threading; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.Syntax { /// <summary> /// This is a SyntaxReference implementation that lazily translates the result (SyntaxNode) of the /// original syntax reference to another one. /// </summary> internal abstract class TranslationSyntaxReference : SyntaxReference { private readonly SyntaxReference _reference; protected TranslationSyntaxReference(SyntaxReference reference) { _reference = reference; } public sealed override TextSpan Span { get { return _reference.Span; } } public sealed override SyntaxTree SyntaxTree { get { return _reference.SyntaxTree; } } public sealed override SyntaxNode GetSyntax(CancellationToken cancellationToken = default(CancellationToken)) { var node = Translate(_reference, cancellationToken); Debug.Assert(node.SyntaxTree == _reference.SyntaxTree); return node; } protected abstract SyntaxNode Translate(SyntaxReference reference, CancellationToken cancellationToken); } }
31.630435
117
0.687285
[ "MIT" ]
06needhamt/roslyn
src/Compilers/Core/Portable/Syntax/TranslationSyntaxReference.cs
1,457
C#
using UnityEngine; public class LockAttribute : PropertyAttribute { public bool locked = true; }
19.8
48
0.777778
[ "MIT" ]
tomkail/UnityX
Assets/UnityX/Scripts/Property Drawers/Lock/LockAttribute.cs
101
C#
/* * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. * If a copy of the MPL was not distributed with this file, You can obtain one at * http://mozilla.org/MPL/2.0/. */ using System; using System.Collections.Generic; using System.Linq; using System.Text; using FSO.Files.HIT; using System.Runtime.InteropServices; using FSO.Files.XA; using Microsoft.Xna.Framework.Audio; using System.IO; namespace FSO.HIT { public class FSCPlayer { /// <summary> /// A Class to play FSC sequences. Bundled in with the HIT engine because it wouldn't really go anywhere else. :I /// </summary> /// public int CurrentPosition; public short LoopCount = -1; public float TimeDiff; private FSC fsc; private string BaseDir; private float BeatLength; private float Volume = 1; private List<SoundEffectInstance> SoundEffects; private Dictionary<string, SoundEffect> SoundCache; public FSCPlayer(FSC fsc, string basedir) { this.fsc = fsc; this.BaseDir = basedir; SoundCache = new Dictionary<string, SoundEffect>(); SoundEffects = new List<SoundEffectInstance>(); BeatLength = 60.0f / fsc.Tempo; RestartFSC(); } public void SetManualTempo(int tempo) { BeatLength = 60.0f / fsc.Tempo; } public void SetVolume(float volume) { Volume = volume; } public void RecalculateVolume() { } public void Tick(float time) { for (int i = 0; i < SoundEffects.Count; i++) //dispose and remove sound effect instances that are finished { if (SoundEffects[i].State != SoundState.Playing) { SoundEffects[i].Dispose(); SoundEffects.RemoveAt(i--); } } TimeDiff += time; while (TimeDiff > BeatLength) { TimeDiff -= BeatLength; NextNote(); } } private SoundEffect LoadSound(string filename) { if (SoundCache.ContainsKey(filename)) return SoundCache[filename]; try { byte[] data = new XAFile(BaseDir + filename).DecompressedData; var stream = new MemoryStream(data); var sfx = SoundEffect.FromStream(stream); stream.Close(); SoundCache.Add(filename, sfx); return sfx; } catch (Exception) { return null; } } private void RestartFSC() { if (fsc.RandomJumpPoints.Count == 0) CurrentPosition = 0; else { CurrentPosition = fsc.RandomJumpPoints[new Random().Next(fsc.RandomJumpPoints.Count)]; } } private void NextNote() { if (LoopCount == -1) { var note = fsc.Notes[CurrentPosition++]; if (note.Rand || CurrentPosition >= fsc.Notes.Count) { RestartFSC(); //current random segment ended. jump to another. note = fsc.Notes[CurrentPosition]; } if (note.Filename != "NONE") { bool play; if (note.Prob > 0) play = (new Random().Next(16) < note.Prob); else play = true; if (play) { float volume = (note.Volume / 1024.0f) * (fsc.MasterVolume / 1024.0f) * Volume * HITVM.Get().GetMasterVolume(Model.HITVolumeGroup.AMBIENCE); var sound = LoadSound(note.Filename); if (sound != null) { var instance = sound.CreateInstance(); instance.Volume = volume; instance.Pan = (note.LRPan / 512.0f) - 1; instance.Play(); SoundEffects.Add(instance); } } LoopCount = (short)(note.Loop - 1); } } else LoopCount--; } } }
30.465753
164
0.489883
[ "MPL-2.0", "MPL-2.0-no-copyleft-exception" ]
Blayer98/FreeSO
TSOClient/tso.sound/FSCPlayer.cs
4,450
C#
// Copyright (c) Peter Vrenken. All rights reserved. See the license on https://github.com/vrenken/EtAlii.Ubigia namespace EtAlii.Ubigia.Api.Transport.Grpc { using global::Grpc.Core.Interceptors; using global::EtAlii.xTechnology.Threading; using global::Grpc.Core; /// <summary> /// The task of the CorrelationCallInterceptor is to find all context correlation scopes and package and send them into /// Grpc metadata. This is needed to make the client correlation Id's cascade from the client to the server. /// </summary> public class CorrelationCallInterceptor : Interceptor { private readonly IContextCorrelator _contextCorrelator; public CorrelationCallInterceptor(IContextCorrelator contextCorrelator) { _contextCorrelator = contextCorrelator; } public override AsyncUnaryCall<TResponse> AsyncUnaryCall<TRequest, TResponse>( TRequest request, ClientInterceptorContext<TRequest, TResponse> context, AsyncUnaryCallContinuation<TRequest, TResponse> continuation) { AddHeadersWhenNeeded(context.Options.Headers); return base.AsyncUnaryCall(request, context, continuation); } public override TResponse BlockingUnaryCall<TRequest, TResponse>(TRequest request, ClientInterceptorContext<TRequest, TResponse> context, BlockingUnaryCallContinuation<TRequest, TResponse> continuation) { AddHeadersWhenNeeded(context.Options.Headers); return base.BlockingUnaryCall(request, context, continuation); } public override AsyncClientStreamingCall<TRequest, TResponse> AsyncClientStreamingCall<TRequest, TResponse>(ClientInterceptorContext<TRequest, TResponse> context, AsyncClientStreamingCallContinuation<TRequest, TResponse> continuation) { AddHeadersWhenNeeded(context.Options.Headers); return base.AsyncClientStreamingCall(context, continuation); } public override AsyncDuplexStreamingCall<TRequest, TResponse> AsyncDuplexStreamingCall<TRequest, TResponse>(ClientInterceptorContext<TRequest, TResponse> context, AsyncDuplexStreamingCallContinuation<TRequest, TResponse> continuation) { AddHeadersWhenNeeded(context.Options.Headers); return base.AsyncDuplexStreamingCall(context, continuation); } private void AddHeadersWhenNeeded(Metadata metadata) { foreach (var correlationId in Correlation.AllIds) { if (_contextCorrelator.TryGetValue(correlationId, out var correlationIdValue)) { metadata.Add(correlationId, correlationIdValue); } } } } }
43.369231
170
0.695991
[ "MIT" ]
vrenken/EtAlii.Ubigia
Source/Api/EtAlii.Ubigia.Api.Transport.Grpc/CorrelationCallInterceptor.cs
2,819
C#
using BlazorState; using System; using DataBrowser.Services; namespace DataBrowser.Features.AppState { public enum DataAction { VIEW, REMOVE, CLEAR, DELETE } public partial class AppState { public class SetE1ContextAction : IAction { public string Name { get; set; } } public class ResponseDataDownloadAction : IAction { public Guid DataId { get; set; } } public class ResponseDataAction : IAction { public DataAction Action { get; set; } public Guid DataId { get; set; } } public class DemoDataAction : IAction { public DataAction Action { get; set; } public Guid DataId { get; set; } } public class AddE1ContextAction : IAction { public string Name { get; set; } public string BaseUrl { get; set; } } public class SaveQueryRequestAction : IAction { public Guid Id { get; set; } public string Title { get; set; } public string Query { get; set; } } public class DeleteQueryRequestAction : IAction { public Guid Id { get; set; } } public class AddNewQueryRequestAction : IAction { public string Title { get; set; } public string Query { get; set; } } public class ToggleQueryRequestVisibilityAction : IAction { public Guid Id { get; set; } } public class ValidateRequestAction : IAction { public Guid Id { get; set; } } public class SubmitQueryAction : IAction { public Guid Id { get; set; } } public class RefreshCloudStorageAction : IAction { public StorageType StorageType { get; set; } } public class LoginAction : IAction { public E1Context E1Context { get; set; } } public class LogoutAction : IAction { } } }
27.571429
65
0.530853
[ "MIT" ]
Herdubreid/DataBrowser
Features/AppState/Actions.cs
2,125
C#
using System.Threading.Tasks; using Equinor.ProCoSys.Preservation.Command.RequirementTypeCommands.CreateRequirementType; using Equinor.ProCoSys.Preservation.Command.Validators.RequirementTypeValidators; using Equinor.ProCoSys.Preservation.Domain.AggregateModels.RequirementTypeAggregate; using Microsoft.VisualStudio.TestTools.UnitTesting; using Moq; namespace Equinor.ProCoSys.Preservation.Command.Tests.RequirementTypeCommands.CreateRequirementType { [TestClass] public class CreateRequirementTypeCommandValidatorTests { private CreateRequirementTypeCommandValidator _dut; private Mock<IRequirementTypeValidator> _requirementTypeValidatorMock; private CreateRequirementTypeCommand _command; private int _sortKey = 10; private string _title = "Title"; private string _code = "Code"; [TestInitialize] public void Setup_OkState() { _requirementTypeValidatorMock = new Mock<IRequirementTypeValidator>(); _command = new CreateRequirementTypeCommand(_sortKey, _code, _title, RequirementTypeIcon.Other); _dut = new CreateRequirementTypeCommandValidator(_requirementTypeValidatorMock.Object); } [TestMethod] public void Validate_ShouldBeValid_WhenOkState() { var result = _dut.Validate(_command); Assert.IsTrue(result.IsValid); } [TestMethod] public void Validate_ShouldFail_WhenRequirementTypeWithSameTitleAlreadyExists() { _requirementTypeValidatorMock.Setup(r => r.ExistsWithSameTitleAsync(_title, default)).Returns(Task.FromResult(true)); var result = _dut.Validate(_command); Assert.IsFalse(result.IsValid); Assert.AreEqual(1, result.Errors.Count); Assert.IsTrue(result.Errors[0].ErrorMessage.StartsWith("Requirement type with this title already exists!")); } [TestMethod] public void Validate_ShouldFail_WhenRequirementTypeWithSameCodeAlreadyExists() { _requirementTypeValidatorMock.Setup(r => r.ExistsWithSameCodeAsync(_code, default)).Returns(Task.FromResult(true)); var result = _dut.Validate(_command); Assert.IsFalse(result.IsValid); Assert.AreEqual(1, result.Errors.Count); Assert.IsTrue(result.Errors[0].ErrorMessage.StartsWith("Requirement type with this code already exists!")); } } }
39.967742
129
0.713479
[ "MIT" ]
equinor/pcs-preservation-api
src/tests/Equinor.ProCoSys.Preservation.Command.Tests/RequirementTypeCommands/CreateRequirementType/CreateRequirementTypeCommandValidatorTests.cs
2,480
C#
// // RedundantNullCoalescingExpressionTests.cs // // Author: // Luís Reis <luiscubal@gmail.com> // // Copyright (c) 2013 Luís Reis // // 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 ICSharpCode.NRefactory.CSharp.CodeActions; using ICSharpCode.NRefactory.CSharp.Refactoring; using NUnit.Framework; using ICSharpCode.NRefactory.CSharp.CodeCompletion; namespace ICSharpCode.NRefactory.CSharp.CodeIssues { [TestFixture] public class ConstantNullCoalescingConditionIssueTests : InspectionActionTestBase { [Test] public void TestNullRightSide() { Test<ConstantNullCoalescingConditionIssue>(@" class TestClass { void Foo() { object o = new object () ?? null; } }", @" class TestClass { void Foo() { object o = new object (); } }"); } [Test] public void TestNullLeftSide() { Test<ConstantNullCoalescingConditionIssue>(@" class TestClass { void Foo() { object o = null ?? new object (); } }", @" class TestClass { void Foo() { object o = new object (); } }"); } [Test] public void TestEqualExpressions() { Test<ConstantNullCoalescingConditionIssue>(@" class TestClass { void Foo() { object o = new object () ?? new object (); } }", @" class TestClass { void Foo() { object o = new object (); } }"); } [Test] public void TestSmartUsage() { //Previously, this was a "TestWrongContext". //However, since smart null coallescing was introduced, this can now be //detected as redundant Test<ConstantNullCoalescingConditionIssue>(@" class TestClass { void Foo() { object o = new object () ?? """"; } }", @" class TestClass { void Foo() { object o = new object (); } }"); } [Test] public void TestSmartUsageInParam() { TestWrongContext<ConstantNullCoalescingConditionIssue>(@" class TestClass { void Foo(object o) { object p = o ?? """"; } }"); } [Ignore("enable again")] [Test] public void TestDisable() { TestWrongContext<ConstantNullCoalescingConditionIssue>(@" class TestClass { void Foo() { // ReSharper disable once ConstantNullCoalescingCondition object o = new object () ?? null; } }"); } } }
21.391892
82
0.700569
[ "MIT" ]
Jenkin0603/myvim
bundle/omnisharp-vim/server/NRefactory/ICSharpCode.NRefactory.Tests/CSharp/CodeIssues/ConstantNullCoalescingConditionIssueTests.cs
3,170
C#
using System; using System.Collections.Generic; using System.Collections.ObjectModel; namespace SpeedTest.TestObjects { public class NullableTestObject { public int? RInt { get; set; } public decimal? RDecimal { get; set; } public double? RDouble { get; set; } public int? RInt2 { get; set; } public decimal? RDecimal2 { get; set; } public double? RDouble2 { get; set; } public TestEnum? REnum { get; set; } public ICollection<TestEnum?> REnumCollection { get; set; } public IList<TestEnum?> REnumList { get; set; } public Guid? RGuid { get; set; } public List<double?> RList { get; set; } public Collection<int?> RCollection { get; set; } public ICollection<bool?> RCollection2 { get; set; } public DateTime? RDateTime { get; set; } public IEnumerable<short?> LazyShorts { get; set; } public IEnumerable<List<Collection<bool?>>> CrazyBools { get; set; } public string GetOnly => "Test"; } }
37.214286
76
0.619002
[ "MIT" ]
Sobieck00/SpeedTest
SpeedTest/SpeedTest/TestObjects/NullableTestObject.cs
1,044
C#
using AutoFixture; using FluentAssertions; using FunctionalTest.Extensions; using FunctionalTest.Fixtures; using FunctionalTest.Fixtures.Resets; using OrderApp.Models.Customers; using System; using System.Net; using System.Threading.Tasks; using Xunit; namespace FunctionalTest.Scenarios.Customers { [Collection(TestConstants.TestCollection)] public class CreateCustomerScenario { private readonly TestHostFixture _host; private readonly string _url; private readonly Fixture _autofixture; public CreateCustomerScenario(TestHostFixture host) { this._host = host; this._url = $"/api/customers"; this._autofixture = new Fixture(); } [Fact] [ResetCustomersService] public async Task return_preconditionfailed_when_not_customers_exists() { var response = await _host.Server .CreateClient() .PostJsonAsync(_url, new { }); response.StatusCode.Should().Be(HttpStatusCode.PreconditionFailed); } [Fact] [ResetCustomersService] public async Task return_preconditionfailed_when_request_name_is_null() { var request = this._autofixture .Build<CreateCustomerRequest>() .Without(customer => customer.Name) .With(customer => customer.Age, new Random().Next(18, 80)) .With(customer => customer.Email, "email@email.com") .Create(); var response = await _host.Server .CreateClient() .PostJsonAsync(_url, request); response.StatusCode.Should().Be(HttpStatusCode.PreconditionFailed); } [Fact] [ResetCustomersService] public async Task return_preconditionfailed_when_request_surname_is_null() { var request = this._autofixture .Build<CreateCustomerRequest>() .Without(customer => customer.Surname) .With(customer => customer.Age, new Random().Next(18, 80)) .With(customer => customer.Email, "email@email.com") .Create(); var response = await _host.Server .CreateClient() .PostJsonAsync(_url, request); response.StatusCode.Should().Be(HttpStatusCode.PreconditionFailed); } [Fact] [ResetCustomersService] public async Task return_preconditionfailed_when_request_age_is_smaller_than_18() { var request = this._autofixture .Build<CreateCustomerRequest>() .With(customer => customer.Age, 5) .With(customer => customer.Email, "email@email.com") .Create(); var response = await _host.Server .CreateClient() .PostJsonAsync(_url, request); response.StatusCode.Should().Be(HttpStatusCode.PreconditionFailed); } [Fact] [ResetCustomersService] public async Task return_preconditionfailed_when_request_has_wrong_email() { var request = this._autofixture .Build<CreateCustomerRequest>() .With(customer => customer.Age, new Random().Next(18, 80)) .With(customer => customer.Email, "emailwitoutarroba") .Create(); var response = await _host.Server .CreateClient() .PostJsonAsync(_url, request); response.StatusCode.Should().Be(HttpStatusCode.PreconditionFailed); } [Fact] [ResetCustomersService] public async Task return_ok_when_customer_is_ok() { var request = this._autofixture .Build<CreateCustomerRequest>() .With(customer => customer.Age, new Random().Next(18, 80)) .With(customer => customer.Email, "email@email.com") .Create(); var response = await _host.Server .CreateClient() .PostJsonAsync(_url, request); response.EnsureSuccessStatusCode(); var result = await _host.Server .CreateClient() .GetJsonAsync<CustomerResponse>(response.Headers.Location.AbsoluteUri)!; result.Name.Should().Be(request.Name); result.Surname.Should().Be(request.Surname); result.Age.Should().Be(request.Age); result.Email.Should().Be(request.Email); } } }
33.867647
89
0.587495
[ "Apache-2.0" ]
acnagrellos/NetCoreDemo_3
6.asp_net_core_test/EjerciciosTestIntegracion/Solucion/OrderApp/test/FunctionalTest/FunctionalTest/Scenarios/Customers/CreateCustomerScenario.cs
4,608
C#
namespace AForge.Imaging.Filters { using AForge.Imaging; using System; using System.Collections.Generic; using System.Drawing; using System.Drawing.Imaging; public abstract class BaseFilter : IFilter, IFilterInformation { protected BaseFilter() { } public UnmanagedImage Apply(UnmanagedImage image) { this.CheckSourceFormat(image.PixelFormat); UnmanagedImage destinationData = UnmanagedImage.Create(image.Width, image.Height, this.FormatTranslations[image.PixelFormat]); this.ProcessFilter(image, destinationData); return destinationData; } public Bitmap Apply(Bitmap image) { BitmapData imageData = image.LockBits(new Rectangle(0, 0, image.Width, image.Height), ImageLockMode.ReadOnly, image.PixelFormat); Bitmap bitmap = null; try { bitmap = this.Apply(imageData); } finally { image.UnlockBits(imageData); } return bitmap; } public Bitmap Apply(BitmapData imageData) { this.CheckSourceFormat(imageData.PixelFormat); int width = imageData.Width; int height = imageData.Height; PixelFormat format = this.FormatTranslations[imageData.PixelFormat]; Bitmap bitmap = (format == PixelFormat.Format8bppIndexed) ? Image.CreateGrayscaleImage(width, height) : new Bitmap(width, height, format); BitmapData bitmapData = bitmap.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.ReadWrite, format); try { this.ProcessFilter(new UnmanagedImage(imageData), new UnmanagedImage(bitmapData)); } finally { bitmap.UnlockBits(bitmapData); } return bitmap; } public void Apply(UnmanagedImage sourceImage, UnmanagedImage destinationImage) { this.CheckSourceFormat(sourceImage.PixelFormat); if (destinationImage.PixelFormat != ((PixelFormat) this.FormatTranslations[sourceImage.PixelFormat])) { throw new InvalidImagePropertiesException("Destination pixel format is specified incorrectly."); } if ((destinationImage.Width != sourceImage.Width) || (destinationImage.Height != sourceImage.Height)) { throw new InvalidImagePropertiesException("Destination image must have the same width and height as source image."); } this.ProcessFilter(sourceImage, destinationImage); } private void CheckSourceFormat(PixelFormat pixelFormat) { if (!this.FormatTranslations.ContainsKey(pixelFormat)) { throw new UnsupportedImageFormatException("Source pixel format is not supported by the filter."); } } protected abstract void ProcessFilter(UnmanagedImage sourceData, UnmanagedImage destinationData); public abstract Dictionary<PixelFormat, PixelFormat> FormatTranslations { get; } } }
38.8
151
0.604306
[ "MIT" ]
siddhesh-vartak98/Fire-Detection-Using-Infrared-Images
AForge.Imaging/AForge/Imaging/Filters/BaseFilter.cs
3,300
C#
using UnityEngine; using System.Collections; using UnityEditor; public class GATBaseInspector : Editor { protected static GUILayoutOption[] __largeButtonOptions = new GUILayoutOption[]{ GUILayout.Width( 130f ), GUILayout.ExpandWidth( false ) }; protected static GUILayoutOption[] __buttonOptions = new GUILayoutOption[]{ GUILayout.Width( 70f ), GUILayout.ExpandWidth( false ) }; protected static GUILayoutOption[] __sliderOptions = new GUILayoutOption[]{ GUILayout.Width( 300f ), GUILayout.ExpandWidth( false ) }; protected static GUILayoutOption[] __closeTogglesOptions = new GUILayoutOption[]{ GUILayout.Width( 20f ), GUILayout.ExpandWidth( false ) }; protected static GUILayoutOption[] __closeButtonsOptions = new GUILayoutOption[]{ GUILayout.Width( 20f ), GUILayout.ExpandWidth( false ) }; protected static GUIStyle __boxStyle; protected static GUIStyle __xButtonStyle; protected static Color __blueColor = new Color( .7f, .7f, 1f ); protected static Color __purpleColor = new Color( .8f, .6f, 1f ); public override void OnInspectorGUI() { if( __boxStyle == null ) { __boxStyle = new GUIStyle( GUI.skin.box ); __boxStyle.fontSize = 15; __boxStyle.fontStyle = FontStyle.Bold; __xButtonStyle = new GUIStyle( GUI.skin.button ); __xButtonStyle.normal.textColor = Color.white; } } protected float ResettableSlider( string valString, float val, float min, float max, float resetValue ) { float ret; EditorGUILayout.BeginHorizontal(); valString = ( valString + val.ToString( "0.00" ) ); if( GUILayout.Button( valString, __buttonOptions ) ) { ret = resetValue; val = resetValue; } GUILayout.Space( 30f ); ret = GUILayout.HorizontalSlider( val , min, max, __sliderOptions ); EditorGUILayout.EndHorizontal(); return ret; } }
32.428571
142
0.731278
[ "MIT" ]
PowerOlive/G-Audio
Editor/Inspectors/GATBaseInspector.cs
1,818
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Collections; using System.Diagnostics; using System.Reflection; using System.Runtime.CompilerServices; using System.Threading; namespace System { public static partial class Environment { public static int ProcessorCount { get; } = GetProcessorCount(); /// <summary> /// Gets whether the current machine has only a single processor. /// </summary> internal static bool IsSingleProcessor => ProcessorCount == 1; // Unconditionally return false since .NET Core does not support object finalization during shutdown. public static bool HasShutdownStarted => false; public static string? GetEnvironmentVariable(string variable) { if (variable == null) throw new ArgumentNullException(nameof(variable)); return GetEnvironmentVariableCore(variable); } public static string? GetEnvironmentVariable(string variable, EnvironmentVariableTarget target) { if (target == EnvironmentVariableTarget.Process) return GetEnvironmentVariable(variable); if (variable == null) throw new ArgumentNullException(nameof(variable)); bool fromMachine = ValidateAndConvertRegistryTarget(target); return GetEnvironmentVariableFromRegistry(variable, fromMachine); } public static IDictionary GetEnvironmentVariables(EnvironmentVariableTarget target) { if (target == EnvironmentVariableTarget.Process) return GetEnvironmentVariables(); bool fromMachine = ValidateAndConvertRegistryTarget(target); return GetEnvironmentVariablesFromRegistry(fromMachine); } public static void SetEnvironmentVariable(string variable, string? value) { ValidateVariableAndValue(variable, ref value); SetEnvironmentVariableCore(variable, value); } public static void SetEnvironmentVariable(string variable, string? value, EnvironmentVariableTarget target) { if (target == EnvironmentVariableTarget.Process) { SetEnvironmentVariable(variable, value); return; } ValidateVariableAndValue(variable, ref value); bool fromMachine = ValidateAndConvertRegistryTarget(target); SetEnvironmentVariableFromRegistry(variable, value, fromMachine: fromMachine); } public static string CommandLine => PasteArguments.Paste(GetCommandLineArgs(), pasteFirstArgumentUsingArgV0Rules: true); public static string CurrentDirectory { get => CurrentDirectoryCore; set { if (value == null) throw new ArgumentNullException(nameof(value)); if (value.Length == 0) throw new ArgumentException(SR.Argument_PathEmpty, nameof(value)); CurrentDirectoryCore = value; } } public static string ExpandEnvironmentVariables(string name) { if (name == null) throw new ArgumentNullException(nameof(name)); if (name.Length == 0) return name; return ExpandEnvironmentVariablesCore(name); } private static string[]? s_commandLineArgs; internal static void SetCommandLineArgs(string[] cmdLineArgs) // invoked from VM { s_commandLineArgs = cmdLineArgs; } public static string GetFolderPath(SpecialFolder folder) => GetFolderPath(folder, SpecialFolderOption.None); public static string GetFolderPath(SpecialFolder folder, SpecialFolderOption option) { if (!Enum.IsDefined(typeof(SpecialFolder), folder)) throw new ArgumentOutOfRangeException(nameof(folder), folder, SR.Format(SR.Arg_EnumIllegalVal, folder)); if (option != SpecialFolderOption.None && !Enum.IsDefined(typeof(SpecialFolderOption), option)) throw new ArgumentOutOfRangeException(nameof(option), option, SR.Format(SR.Arg_EnumIllegalVal, option)); return GetFolderPathCore(folder, option); } private static volatile int s_processId; /// <summary>Gets the unique identifier for the current process.</summary> public static int ProcessId { get { int processId = s_processId; if (processId == 0) { s_processId = processId = GetProcessId(); // Assume that process Id zero is invalid for user processes. It holds for all mainstream operating systems. Debug.Assert(processId != 0); } return processId; } } private static volatile string? s_processPath; /// <summary> /// Returns the path of the executable that started the currently executing process. Returns null when the path is not available. /// </summary> /// <returns>Path of the executable that started the currently executing process</returns> /// <remarks> /// If the executable is renamed or deleted before this property is first accessed, the return value is undefined and depends on the operating system. /// </remarks> public static string? ProcessPath { get { string? processPath = s_processPath; if (processPath == null) { // The value is cached both as a performance optimization and to ensure that the API always returns // the same path in a given process. Interlocked.CompareExchange(ref s_processPath, GetProcessPath() ?? "", null); processPath = s_processPath; Debug.Assert(processPath != null); } return (processPath.Length != 0) ? processPath : null; } } public static bool Is64BitProcess => IntPtr.Size == 8; public static bool Is64BitOperatingSystem => Is64BitProcess || Is64BitOperatingSystemWhen32BitProcess; public static string NewLine => NewLineConst; private static volatile OperatingSystem? s_osVersion; public static OperatingSystem OSVersion { get { OperatingSystem? osVersion = s_osVersion; if (osVersion == null) { Interlocked.CompareExchange(ref s_osVersion, GetOSVersion(), null); osVersion = s_osVersion; Debug.Assert(osVersion != null); } return osVersion; } } public static Version Version { get { string? versionString = typeof(object).Assembly.GetCustomAttribute<AssemblyInformationalVersionAttribute>()?.InformationalVersion; ReadOnlySpan<char> versionSpan = versionString.AsSpan(); // Strip optional suffixes int separatorIndex = versionSpan.IndexOfAny('-', '+', ' '); if (separatorIndex != -1) versionSpan = versionSpan.Slice(0, separatorIndex); // Return zeros rather then failing if the version string fails to parse return Version.TryParse(versionSpan, out Version? version) ? version : new Version(); } } public static string StackTrace { [MethodImpl(MethodImplOptions.NoInlining)] // Prevent inlining from affecting where the stacktrace starts get => new StackTrace(true).ToString(System.Diagnostics.StackTrace.TraceFormat.Normal); } private static volatile int s_systemPageSize; public static int SystemPageSize { get { int systemPageSize = s_systemPageSize; if (systemPageSize == 0) { s_systemPageSize = systemPageSize = GetSystemPageSize(); } return systemPageSize; } } private static bool ValidateAndConvertRegistryTarget(EnvironmentVariableTarget target) { Debug.Assert(target != EnvironmentVariableTarget.Process); if (target == EnvironmentVariableTarget.Machine) return true; if (target == EnvironmentVariableTarget.User) return false; throw new ArgumentOutOfRangeException(nameof(target), target, SR.Format(SR.Arg_EnumIllegalVal, target)); } private static void ValidateVariableAndValue(string variable, ref string? value) { if (variable == null) throw new ArgumentNullException(nameof(variable)); if (variable.Length == 0) throw new ArgumentException(SR.Argument_StringZeroLength, nameof(variable)); if (variable[0] == '\0') throw new ArgumentException(SR.Argument_StringFirstCharIsZero, nameof(variable)); if (variable.Contains('=')) throw new ArgumentException(SR.Argument_IllegalEnvVarName, nameof(variable)); if (string.IsNullOrEmpty(value) || value[0] == '\0') { // Explicitly null out value if it's empty value = null; } } } }
37.255725
158
0.60127
[ "MIT" ]
3DCloud/runtime
src/libraries/System.Private.CoreLib/src/System/Environment.cs
9,761
C#
using System; namespace RBS.Messages.std_msgs { [System.Serializable] public class UInt32 : ExtendMessage { public uint data; public override string Type() { return "std_msgs/UInt32"; } public UInt32() { data = 0; } } }
19.2
67
0.5625
[ "MIT" ]
yuyaushiro/ARviz_unity
Assets/ROSBridgeSharp/Assets/RBSocket/Message/DefaultMsgs/std_msgs/UInt32.cs
288
C#
//---------------------------------------------- // ColaFramework // Copyright © 2018-2049 ColaFramework 马三小伙儿 //---------------------------------------------- using System; using System.Collections; using System.Collections.Generic; using UnityEngine; namespace ColaFramework { /// <summary> /// 对象池类(单独存储某一类物件的对象池) /// </summary> /// <typeparam name="T"></typeparam> public class ObjectPool<T> where T : class { private const int RESERVED_SIZE = 4; private const int CAPCITY_SIZE = 16; /// <summary> /// 存储堆栈 /// </summary> private readonly Stack<T> stack; /// <summary> /// 创建对象的方法(外部传入) /// </summary> private Func<T> createAction; /// <summary> /// 获取对象的方法(外部传入) /// </summary> private Action<T> getAction; /// <summary> /// 回收对象的方法(外部传入) /// </summary> private Action<T> releaseAction; private int capcity; public ObjectPool(Func<T> createAction, Action<T> getAction, Action<T> relaseAction, int reservedSize = RESERVED_SIZE, int capcity = CAPCITY_SIZE) { stack = new Stack<T>(); this.createAction = createAction; this.getAction = getAction; this.releaseAction = relaseAction; this.capcity = capcity; //可以提前申请出一些Object,提升之后的加载速度 if (null != createAction) { for (int i = 0; i < reservedSize && i < capcity; i++) { var element = createAction(); Release(element); } } } /// <summary> /// 取得一个对象池中的物件,如果没有就新创建一个 /// </summary> /// <returns></returns> public T Get() { T obj = null; if (stack.Count == 0) { //执行创建操作 if (null != createAction) { obj = createAction(); } else { Debug.LogWarning(string.Format("类型:{0}的创建方法不能为空!", typeof(T))); } } else { obj = stack.Pop(); } if (null == obj) { Debug.LogWarning(string.Format("获取类型:{0}的物体失败!请检查!", typeof(T))); } if (null != getAction) { getAction(obj); } return obj; } /// <summary> /// 回收/释放一个物体 /// </summary> /// <param name="obj"></param> public void Release(T obj) { if (null == obj) { Debug.LogWarning(string.Format("回收的{0}类型的物件为空!", typeof(T))); return; } if (null != releaseAction) { releaseAction(obj); } if (stack.Count < capcity) { stack.Push(obj); } } /// <summary> /// 清理当前的对象池 /// </summary> public void Clear() { stack.Clear(); } } /// <summary> /// 快速-轻量级的对象池 /// </summary> /// <typeparam name="T"></typeparam> public class QuickObjectPool<T> where T : new() { private readonly Stack<T> m_Stack = new Stack<T>(); private readonly Action<T> m_ActionOnGet; private readonly Action<T> m_ActionOnRelease; public int countAll { get; private set; } public int countActive { get { return countAll - countInactive; } } public int countInactive { get { return m_Stack.Count; } } public QuickObjectPool(Action<T> actionOnGet, Action<T> actionOnRelease) { m_ActionOnGet = actionOnGet; m_ActionOnRelease = actionOnRelease; } public T Get() { T element; if (m_Stack.Count == 0) { element = new T(); countAll++; } else { element = m_Stack.Pop(); } if (m_ActionOnGet != null) m_ActionOnGet(element); return element; } public void Release(T element) { if (m_Stack.Count > 0 && ReferenceEquals(m_Stack.Peek(), element)) Debug.LogError("release error. Trying to destroy object that is already released to pool."); if (m_ActionOnRelease != null) m_ActionOnRelease(element); m_Stack.Push(element); } } /// <summary> /// 极简的对象池 /// </summary> /// <typeparam name="T"></typeparam> public class MiniObjectPool<T> where T : class, new() { private readonly Stack<T> _pool = new Stack<T>(); public MiniObjectPool(int initCount) { for (var i = 0; i < initCount; i++) { _pool.Push(new T()); } } public T Get() { return _pool.Count == 0 ? new T() : _pool.Pop(); } public void Release(T obj) { _pool.Push(obj); } } }
26.20297
154
0.448139
[ "MIT" ]
Og-ChRoNiC/ColaFrameWork
Assets/Scripts/CommonHelper/ObjectPoolHelper.cs
5,642
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.Windows.Input; using Microsoft.Toolkit.Uwp.UI.Controls; using Microsoft.Toolkit.Uwp.UI.Extensions; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; namespace Microsoft.Toolkit.Uwp.SampleApp.SamplePages { public sealed partial class InAppNotificationPage : Page, IXamlRenderListener { private ControlTemplate _defaultInAppNotificationControlTemplate; private ControlTemplate _customInAppNotificationControlTemplate; private InAppNotification _exampleInAppNotification; private InAppNotification _exampleCustomInAppNotification; private InAppNotification _exampleVSCodeInAppNotification; private ResourceDictionary _resources; public bool IsRootGridActualWidthLargerThan700 { get; set; } public int NotificationDuration { get; set; } = 0; public InAppNotificationPage() { InitializeComponent(); Load(); } public void OnXamlRendered(FrameworkElement control) { NotificationDuration = 0; _exampleInAppNotification = control.FindChildByName("ExampleInAppNotification") as InAppNotification; _defaultInAppNotificationControlTemplate = _exampleInAppNotification?.Template; _exampleCustomInAppNotification = control.FindChildByName("ExampleCustomInAppNotification") as InAppNotification; _customInAppNotificationControlTemplate = _exampleCustomInAppNotification?.Template; _exampleVSCodeInAppNotification = control.FindChildByName("ExampleVSCodeInAppNotification") as InAppNotification; _resources = control.Resources; var notificationDurationTextBox = control.FindChildByName("NotificationDurationTextBox") as TextBox; if (notificationDurationTextBox != null) { notificationDurationTextBox.TextChanged += NotificationDurationTextBox_TextChanged; } } private void Load() { SampleController.Current.RegisterNewCommand("Show notification with random text", (sender, args) => { _exampleVSCodeInAppNotification?.Dismiss(); SetDefaultControlTemplate(); _exampleInAppNotification?.Show(GetRandomText(), NotificationDuration); }); SampleController.Current.RegisterNewCommand("Show notification with object", (sender, args) => { _exampleVSCodeInAppNotification?.Dismiss(); SetDefaultControlTemplate(); var random = new Random(); _exampleInAppNotification?.Show(new KeyValuePair<int, string>(random.Next(1, 10), GetRandomText()), NotificationDuration); }); SampleController.Current.RegisterNewCommand("Show notification with buttons (without DataTemplate)", (sender, args) => { _exampleVSCodeInAppNotification?.Dismiss(); SetDefaultControlTemplate(); var grid = new Grid() { Margin = new Thickness(0, 0, -38, 0) }; grid.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) }); grid.ColumnDefinitions.Add(new ColumnDefinition { Width = GridLength.Auto }); // Text part var textBlock = new TextBlock { Text = "Do you like it?", VerticalAlignment = VerticalAlignment.Center, Margin = new Thickness(0, 0, 24, 0), FontSize = 16 }; grid.Children.Add(textBlock); // Buttons part var stackPanel = new StackPanel { Orientation = Orientation.Horizontal, VerticalAlignment = VerticalAlignment.Center }; var yesButton = new Button { Content = "Yes", Width = 120, Height = 40, FontSize = 16 }; yesButton.Click += YesButton_Click; stackPanel.Children.Add(yesButton); var noButton = new Button { Content = "No", Width = 120, Height = 40, FontSize = 16, Margin = new Thickness(4, 0, 0, 0) }; noButton.Click += NoButton_Click; stackPanel.Children.Add(noButton); Grid.SetColumn(stackPanel, 1); grid.Children.Add(stackPanel); _exampleInAppNotification?.Show(grid, NotificationDuration); }); SampleController.Current.RegisterNewCommand("Show notification with buttons (with DataTemplate)", (sender, args) => { _exampleVSCodeInAppNotification?.Dismiss(); SetCustomControlTemplate(); // Use the custom template without the Dismiss button. The DataTemplate will handle re-adding it. object inAppNotificationWithButtonsTemplate = null; bool? isTemplatePresent = _resources?.TryGetValue("InAppNotificationWithButtonsTemplate", out inAppNotificationWithButtonsTemplate); if (isTemplatePresent == true && inAppNotificationWithButtonsTemplate is DataTemplate template) { _exampleInAppNotification.Show(template, NotificationDuration); } }); SampleController.Current.RegisterNewCommand("Show notification with Drop Shadow (based on default template)", (sender, args) => { _exampleVSCodeInAppNotification.Dismiss(); SetDefaultControlTemplate(); // Update control template object inAppNotificationDropShadowControlTemplate = null; bool? isTemplatePresent = _resources?.TryGetValue("InAppNotificationDropShadowControlTemplate", out inAppNotificationDropShadowControlTemplate); if (isTemplatePresent == true && inAppNotificationDropShadowControlTemplate is ControlTemplate template) { _exampleInAppNotification.Template = template; } _exampleInAppNotification.Show(GetRandomText(), NotificationDuration); }); SampleController.Current.RegisterNewCommand("Show notification with Visual Studio Code template (info notification)", (sender, args) => { _exampleInAppNotification.Dismiss(); _exampleVSCodeInAppNotification.Show(NotificationDuration); }); SampleController.Current.RegisterNewCommand("Dismiss", (sender, args) => { // Dismiss all notifications (should not be replicated in production) _exampleInAppNotification.Dismiss(); _exampleVSCodeInAppNotification.Dismiss(); }); } private string GetRandomText() { var random = new Random(); int result = random.Next(1, 4); switch (result) { case 1: return "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec sollicitudin bibendum enim at tincidunt. Praesent egestas ipsum ligula, nec tincidunt lacus semper non."; case 2: return "Pellentesque in risus eget leo rhoncus ultricies nec id ante."; case 3: default: return "Sed quis nisi quis nunc condimentum varius id consectetur metus. Duis mauris sapien, commodo eget erat ac, efficitur iaculis magna. Morbi eu velit nec massa pharetra cursus. Fusce non quam egestas leo finibus interdum eu ac massa. Quisque nec justo leo. Aenean scelerisque placerat ultrices. Sed accumsan lorem at arcu commodo tristique."; } } private void SetDefaultControlTemplate() { // Update control template _exampleInAppNotification.Template = _defaultInAppNotificationControlTemplate; } private void SetCustomControlTemplate() { // Update control template _exampleInAppNotification.Template = _customInAppNotificationControlTemplate; } private void NotificationDurationTextBox_TextChanged(object sender, TextChangedEventArgs e) { int newDuration; if (int.TryParse((sender as TextBox)?.Text, out newDuration)) { NotificationDuration = newDuration; } } private void YesButton_Click(object sender, RoutedEventArgs e) { _exampleInAppNotification?.Dismiss(); } private void NoButton_Click(object sender, RoutedEventArgs e) { _exampleInAppNotification?.Dismiss(); } } #pragma warning disable SA1402 // File may only contain a single class internal class DismissCommand : ICommand #pragma warning restore SA1402 // File may only contain a single class { event EventHandler ICommand.CanExecuteChanged { add { } remove { } } public bool CanExecute(object parameter) { return true; } public void Execute(object parameter) { (parameter as InAppNotification)?.Dismiss(); } } }
40.743802
380
0.611866
[ "MIT" ]
Difegue/WindowsCommunityToolkit
Microsoft.Toolkit.Uwp.SampleApp/SamplePages/InAppNotification/InAppNotificationPage.xaml.cs
9,860
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("Backup")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Backup")] [assembly: AssemblyCopyright("Copyright © 2017")] [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("aac4f593-e162-40a9-8cc3-3517d16724b2")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
37.432432
84
0.74296
[ "MIT" ]
pkudrel/Sabot
src/Backup/Properties/AssemblyInfo.cs
1,388
C#
using Demo.Domain.Handlers.Users; using Xunit; namespace Demo.Domain.Tests.Handlers.Users { public class UpdateMyTestGenderHandlerTests { [Fact(Skip="Change this to a real test")] public void Sample() { // Arrange // Act // Assert } } }
16.894737
49
0.551402
[ "MIT" ]
TomMalow/atc
sample/Demo.Domain.Tests/Handlers/Users/UpdateMyTestGenderHandlerTests.cs
323
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("AppEmail")] [assembly: System.Reflection.AssemblyConfigurationAttribute("Debug")] [assembly: System.Reflection.AssemblyFileVersionAttribute("1.0.0.0")] [assembly: System.Reflection.AssemblyInformationalVersionAttribute("1.0.0")] [assembly: System.Reflection.AssemblyProductAttribute("AppEmail")] [assembly: System.Reflection.AssemblyTitleAttribute("AppEmail")] [assembly: System.Reflection.AssemblyVersionAttribute("1.0.0.0")] // Generated by the MSBuild WriteCodeFragment class.
40.583333
80
0.644764
[ "MIT" ]
dfilitto/ProjetosXamarinForms
AppEmail/AppEmail/AppEmail/obj/Debug/netstandard2.0/AppEmail.AssemblyInfo.cs
974
C#
using Abp.Application.Services; using Abp.Application.Services.Dto; using EventCloud.Lims.Dtos; using System; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; namespace EventCloud.Lims { public interface ILimsAppService: IApplicationService { Task<ListResultDto<PackageListDTO>> GetPackageListAsync(); } }
22.625
66
0.779006
[ "MIT" ]
HealthPro-Alborg-Demo/alborg_project
aspnet-core/src/EventCloud.Application/Lims/ILimsAppService.cs
364
C#
using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; namespace Lophtware.Testing.Utilities.NonDeterminism.PrimitiveGeneration { [SuppressMessage("ReSharper", "UnusedMember.Global", Justification = CodeAnalysisJustification.PublishedApi)] public static class EnumGenerator { public static T Any<T>() where T : struct, Enum { return EnumFrom<T>(IntegerGenerator.Any()); } private static T EnumFrom<T>(int value) { return (T) Enum.ToObject(typeof(T), value); } public static T AnyUndefined<T>() where T : struct, Enum { return AnyExcept(EnumValues<T>().ToArray()); } [SuppressMessage("ReSharper", "MemberCanBePrivate.Global", Justification = CodeAnalysisJustification.PublishedApi)] public static T AnyExcept<T>(params T[] except) where T : struct, Enum { return EnumFrom<T>(IntegerGenerator.AnyExcept(ValuesAsIntegers(except).ToArray())); } private static IEnumerable<int> ValuesAsIntegers<T>(IEnumerable<T> except) where T : struct, Enum { return except.Select(x => Convert.ToInt32(x)); } private static IEnumerable<T> EnumValues<T>() where T : struct, Enum { return Enum.GetValues(typeof(T)).Cast<T>(); } public static T AnyDefinedExcept<T>(params T[] except) where T : struct, Enum { var value = AnyDefined<T>(); return !except.Contains(value) ? value : AnyDefinedExcept(except); } [SuppressMessage("ReSharper", "MemberCanBePrivate.Global", Justification = CodeAnalysisJustification.PublishedApi)] public static T AnyDefined<T>() where T : struct, Enum { return EnumValues<T>().AnyItem(); } } }
29.836364
117
0.723949
[ "MIT" ]
lophtware/Testing.Utilities
src/Testing.Utilities/NonDeterminism/PrimitiveGeneration/EnumGenerator.cs
1,643
C#
using FactoryMethodPattern.Contracts; namespace FactoryMethodPattern { public class Bear : ICarnivore { public Bear() { } public string AnimalsThatIEat { get; set; } } }
18.181818
51
0.655
[ "MIT" ]
IPMihnev/SoftUni
Object-orientedProgramming/DesignPatterns/CreationalPatterns/FactoryMethodPattern/Bear.cs
202
C#
using System; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Diagnostics.HealthChecks; using Mercan.HealthChecks.Common; using Moq; namespace Mercan.HealthChecks.Common.Tests.WriteResponse { public class WriteResponsesShould { public void CreateAWriteListResponse() { var moqContext = new Mock<HttpContext>(); var httpContext = moqContext.Object; HealthReport result = new HealthReport(null, TimeSpan.FromMinutes(5)); WriteResponses.WriteListResponse(httpContext, result); } } }
27.52381
82
0.700692
[ "MIT" ]
mmercan/sentinel
HealthChecks/Mercan.HealthChecks.Common.Tests/WriteResponses/WriteResponsesShould.cs
578
C#
// ReSharper disable once CheckNamespace namespace Telegram.Bot.Types { /// <summary> /// A marker for input media types that can be used in sendMediaGroup method. /// </summary> public interface IAlbumInputMedia : IInputMedia { } }
21.583333
81
0.675676
[ "MIT" ]
4vz/jovice
Athena/Library/Telegram.Bot/Types/InputFiles/IAlbumInputMedia.cs
261
C#
namespace ThisNetWorks.OrchardCore.OpenApi.Models { public class ContentFieldDto : ContentElementDto { } }
17.142857
52
0.733333
[ "BSD-3-Clause" ]
ThisNetWorks/ThisNetWorks.OrchardCore.OpenApi
src/ThisNetWorks.OrchardCore.OpenApi.Abstractions/Models/ContentFieldDto.cs
122
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("CustomIcon.UWP")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("CustomIcon.UWP")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: ComVisible(false)]
36.034483
84
0.74067
[ "MIT" ]
wilsonvargas/CustomIconNavigationPage
src/CustomIcon/CustomIcon.UWP/Properties/AssemblyInfo.cs
1,048
C#
using ProjectRimFactory.Common; using RimWorld; using System; using System.Collections.Generic; using System.Linq; using System.Text; using UnityEngine; using Verse; using Verse.AI; using ProjectRimFactory.AutoMachineTool; namespace ProjectRimFactory.Drones { //This is basicly a clone of Area_Allowed it was created since the former one is limited to 10 in vanilla RimWorld public class DroneArea : Area { private string labelInt; public DroneArea() { } public DroneArea(AreaManager areaManager, string label = null) : base(areaManager) { base.areaManager = areaManager; if (!label.NullOrEmpty()) { labelInt = label; } else { int num = 1; while (true) { labelInt = "AreaDefaultLabel".Translate(num); if (areaManager.GetLabeled(labelInt) == null) { break; } num++; } } colorInt = new Color(Rand.Value, Rand.Value, Rand.Value); colorInt = Color.Lerp(colorInt, Color.gray, 0.5f); } private Color colorInt = Color.red; private string LabelText = "DroneZone"; public override string Label => LabelText; public override Color Color => colorInt; public override int ListPriority => 3000; public override bool Mutable => true; public override string GetUniqueLoadID() { return "Area_" + ID + "_DroneArea"; } public override void ExposeData() { //IL_0025: Unknown result type (might be due to invalid IL or missing references) //IL_002b: Unknown result type (might be due to invalid IL or missing references) base.ExposeData(); Scribe_Values.Look(ref labelInt, "label"); Scribe_Values.Look(ref colorInt, "color"); } } //This Class is used for the Area Selection for Drones where the range is unlimeted (0) public class DroneAreaSelector : Designator { //Content is mostly a copy of Designator_AreaAllowedExpand private static Area selectedArea; public Action<Area> selectAction; public static Area SelectedArea => selectedArea; public override AcceptanceReport CanDesignateCell(IntVec3 loc) { return loc.InBounds(base.Map) && Designator_AreaAllowed.SelectedArea != null && !Designator_AreaAllowed.SelectedArea[loc]; //throw new NotImplementedException(); } public override void SelectedUpdate() { // Log.Message("SelectedUpdate"); } public override void ProcessInput(Event ev) { if (CheckCanInteract()) { if (selectedArea != null) { //base.ProcessInput(ev); } AreaUtility.MakeAllowedAreaListFloatMenu(delegate (Area a) { selectedArea = a; // base.ProcessInput(ev); /* selectedArea == null --> Unrestricted selectedArea != null --> User Area */ selectAction(selectedArea); }, addNullAreaOption: true, addManageOption: false, base.Map); } } //public static void ClearSelectedArea() //{ // selectedArea = null; //} //protected override void FinalizeDesignationSucceeded() //{ // base.FinalizeDesignationSucceeded(); // PlayerKnowledgeDatabase.KnowledgeDemonstrated(ConceptDefOf.AllowedAreas, KnowledgeAmount.SpecificInteraction); //} } [StaticConstructorOnStartup] public abstract class Building_DroneStation : Building , IPowerSupplyMachineHolder , IDroneSeetingsITab, IPRF_SettingsContentLink { //Sleep Time List (Loaded on Spawn) public string[] cachedSleepTimeList; private const int defaultSkillLevel = 20; public int GetdefaultSkillLevel { get { return defaultSkillLevel; } } protected CompRefuelable refuelableComp; private List<SkillRecord> droneSkillsRecord = new List<SkillRecord>(); public List<SkillRecord> GetDroneSkillsRecord { get { return droneSkillsRecord; } set { droneSkillsRecord = value; } } //Return the Range depending on the Active Defenition public int DroneRange { get { if (compPowerWorkSetting != null) { return (int)Math.Ceiling(compPowerWorkSetting.GetRange()); } else { return def.GetModExtension<DefModExtension_DroneStation>().SquareJobRadius; } } } private CompPowerWorkSetting compPowerWorkSetting; public IEnumerable<IntVec3> StationRangecells { get { if (compPowerWorkSetting != null && compPowerWorkSetting.RangeSetting) { return compPowerWorkSetting.GetRangeCells(); } else { return GenAdj.OccupiedRect(this).ExpandedBy(DroneRange).Cells; } } } private IEnumerable<IntVec3> StationRangecells_old; public List<IntVec3> cashed_GetCoverageCells = null; //droneAllowedArea Loaded on Spawn | this is ithe zone where the DronePawns are allowed to move in //This needs to be "Area" as one can cast "DroneArea" to "Area" but not the other way around //That feature is needed to assign vanilla Allowed Areas //Please note that for Area Null is a valid Value. it stands for unrestricted public Area droneAllowedArea = null; public DroneArea GetDroneAllowedArea { get { DroneArea droneArea = null; if (DroneRange > 0) { droneArea = new DroneArea(this.Map.areaManager); //Need to set the Area to a size foreach (IntVec3 cell in StationRangecells) { droneArea[cell] = true; } //Not shure if i need that but just to be shure droneArea[Position] = true; this.Map.areaManager.AllAreas.Add(droneArea); } return droneArea; } } //This function can be used to Update the Allowed area for all Drones (Active and future) //Just need to auto call tha on Change from CompPowerWorkSetting public void Update_droneAllowedArea_forDrones(Area dr) { //Refresh area if current is null droneAllowedArea = dr ?? (Area)GetDroneAllowedArea; if (!StationRangecells_old.SequenceEqual(StationRangecells)) { droneAllowedArea.Delete(); droneAllowedArea = (Area)GetDroneAllowedArea; StationRangecells_old = StationRangecells; } for (int i = 0; i < spawnedDrones.Count; i++) { spawnedDrones[i].playerSettings.AreaRestriction = droneAllowedArea; } } public static readonly Texture2D Cancel = ContentFinder<Texture2D>.Get("UI/Designators/Cancel", true); protected bool lockdown; private string droneAreaSelectorLable = "Unrestricted\nSelect Area"; protected DefModExtension_DroneStation extension; protected List<Pawn_Drone> spawnedDrones = new List<Pawn_Drone>(); public abstract int DronesLeft { get; } public IPowerSupplyMachine RangePowerSupplyMachine => this.GetComp<CompPowerWorkSetting>(); public Dictionary<WorkTypeDef, bool> WorkSettings = new Dictionary<WorkTypeDef, bool>(); public Dictionary<WorkTypeDef, bool> GetWorkSettings { get { return WorkSettings; } set { WorkSettings = value; } } public List<SkillRecord> DroneSeetings_skillDefs => droneSkillsRecord; public string[] GetSleepTimeList => cachedSleepTimeList; public CompRefuelable compRefuelable => GetComp<CompRefuelable>(); public void UpdateDronePrioritys() { if (spawnedDrones.Count > 0) { foreach (Pawn pawn in spawnedDrones) { foreach (WorkTypeDef def in WorkSettings.Keys) { if (WorkSettings[def]) { pawn.workSettings.SetPriority(def, 3); } else { pawn.workSettings.SetPriority(def, 0); } } } } } // Used for destroyed pawns public abstract void Notify_DroneLost(); // Used to negate imaginary pawns despawned in WorkGiverDroneStations and JobDriver_ReturnToStation public abstract void Notify_DroneGained(); public override void PostMake() { base.PostMake(); extension = def.GetModExtension<DefModExtension_DroneStation>(); refuelableComp = GetComp<CompRefuelable>(); compPowerTrader = GetComp<CompPowerTrader>(); compPowerWorkSetting = GetComp<CompPowerWorkSetting>(); } private MapTickManager mapManager; protected MapTickManager MapManager => this.mapManager; IPRF_SettingsContent IPRF_SettingsContentLink.PRF_SettingsContentOb => new ITab_DroneStation_Def(this); public override void SpawnSetup(Map map, bool respawningAfterLoad) { base.SpawnSetup(map, respawningAfterLoad); this.mapManager = map.GetComponent<MapTickManager>(); refuelableComp = GetComp<CompRefuelable>(); compPowerTrader = GetComp<CompPowerTrader>(); extension = def.GetModExtension<DefModExtension_DroneStation>(); compPowerWorkSetting = GetComp<CompPowerWorkSetting>(); StationRangecells_old = StationRangecells; //Setup Allowd Area //Enssuring that Update_droneAllowedArea_forDrones() is run resolves #224 (May need to add a diffrent check) if (droneAllowedArea == null) { //Log.Message("droneAllowedArea was null"); Update_droneAllowedArea_forDrones(droneAllowedArea); } //Load the SleepTimes from XML cachedSleepTimeList = extension.Sleeptimes.Split(','); cashed_GetCoverageCells = StationRangecells.ToList(); //Check for missing WorkTypeDef foreach (WorkTypeDef def in extension.workTypes.Except(WorkSettings.Keys).ToList()) { WorkSettings.Add(def, true); } //Remove stuff thats nolonger valid (can only happen after updates) foreach (WorkTypeDef def in WorkSettings.Keys.Except(extension.workTypes).ToList()) { WorkSettings.Remove(def); } //need to take action to init droneSkillsRecord if (droneSkillsRecord.Count == 0) { Pawn_Drone drone = MakeDrone(); GenSpawn.Spawn(drone, Position, Map); drone.Destroy(); GetComp<CompRefuelable>()?.Refuel(1); } //Init the Designator default Label update_droneAreaSelectorLable(droneAllowedArea); //Need this type of call to set the Powerconsumption on load //A normal call will not work var rangePowerSupplyMachine = this.RangePowerSupplyMachine; if (rangePowerSupplyMachine != null) { this.MapManager.NextAction(rangePowerSupplyMachine.RefreshPowerStatus); this.MapManager.AfterAction(5, rangePowerSupplyMachine.RefreshPowerStatus); } } private void update_droneAreaSelectorLable(Area a) { if (a == null) { droneAreaSelectorLable = "PRFDroneStationSelectArea".Translate("Unrestricted".Translate()); } else { droneAreaSelectorLable = "PRFDroneStationSelectArea".Translate(a.Label); } } public override void Draw() { base.Draw(); if (extension.displayDormantDrones) { DrawDormantDrones(); } } public override void DeSpawn(DestroyMode mode = DestroyMode.Vanish) { base.DeSpawn(); List<Pawn_Drone> drones = spawnedDrones.ToList(); for (int i = 0; i < drones.Count; i++) { drones[i].Destroy(); } if (droneAllowedArea != null) { //Deleate the old Zone droneAllowedArea.Delete(); } droneAllowedArea = null; } public virtual void DrawDormantDrones() { foreach (IntVec3 cell in GenAdj.CellsOccupiedBy(this).Take(DronesLeft)) { PRFDefOf.PRFDrone.graphic.DrawFromDef(cell.ToVector3ShiftedWithAltitude(AltitudeLayer.LayingPawn), default(Rot4), PRFDefOf.PRFDrone); } } public override void DrawGUIOverlay() { base.DrawGUIOverlay(); if (lockdown) { Map.overlayDrawer.DrawOverlay(this, OverlayTypes.ForbiddenBig); } } public abstract Job TryGiveJob(); protected CompPowerTrader compPowerTrader; protected int additionJobSearchTickDelay = 0; public override void Tick() { //Base Tick base.Tick(); //Return if not Spawnd if (!this.Spawned) return; //Should not draw much performence... //To enhance performence we could add "this.IsHashIntervalTick(60)" if (spawnedDrones.Count > 0 && compPowerTrader?.PowerOn == false) { for (int i = spawnedDrones.Count - 1; i >= 0; i--) { spawnedDrones[i].jobs.StartJob(new Job(PRFDefOf.PRFDrone_ReturnToStation, this), JobCondition.InterruptForced); } //return as there is nothing to do if its off.... return; } //Update the Allowed Area Range on Power Change if (this.IsHashIntervalTick(60)) { //Update the Range Update_droneAllowedArea_forDrones(droneAllowedArea); //TODO add cell calc cashed_GetCoverageCells = StationRangecells.ToList(); } //Search for Job if (this.IsHashIntervalTick(60 + additionJobSearchTickDelay) && DronesLeft > 0 && !lockdown && compPowerTrader?.PowerOn != false) { //The issue appears to be 100% with TryGiveJob Job job = TryGiveJob(); if (job != null) { additionJobSearchTickDelay = 0; //Reset to 0 - found a job -> may find more job.playerForced = true; job.expiryInterval = -1; //MakeDrone takes about 1ms Pawn_Drone drone = MakeDrone(); GenSpawn.Spawn(drone, Position, Map); drone.jobs.StartJob(job); } else { //Experimental Delay //Add delay (limit to 300) i am well aware that this can be higher that 300 with the current code if (additionJobSearchTickDelay < 300) { //Exponential delay additionJobSearchTickDelay = (additionJobSearchTickDelay + 1) * 2; } } } } //It appers as if TickLong & TickRare are not getting called here public void Notify_DroneMayBeLost(Pawn_Drone drone) { if (spawnedDrones.Contains(drone)) { spawnedDrones.Remove(drone); Notify_DroneLost(); } } //Handel the Range UI public override void DrawExtraSelectionOverlays() { base.DrawExtraSelectionOverlays(); //Dont Draw if infinite if (def.GetModExtension<DefModExtension_DroneStation>().SquareJobRadius > 0) { GenDraw.DrawFieldEdges(cashed_GetCoverageCells); } } public override string GetInspectString() { StringBuilder builder = new StringBuilder(); string str = base.GetInspectString(); if (!string.IsNullOrEmpty(str)) { builder.AppendLine(str); } builder.Append("PRFDroneStation_NumberOfDrones".Translate(DronesLeft)); return builder.ToString(); } public virtual Pawn_Drone MakeDrone() { Pawn_Drone drone = (Pawn_Drone)PawnGenerator.GeneratePawn(PRFDefOf.PRFDroneKind, Faction); drone.station = this; spawnedDrones.Add(drone); return drone; } public override void ExposeData() { base.ExposeData(); Scribe_Collections.Look(ref spawnedDrones, "spawnedDrones", LookMode.Reference); Scribe_Values.Look(ref lockdown, "lockdown"); Scribe_References.Look(ref droneAllowedArea, "droneAllowedArea"); //WorkSettings Scribe_Collections.Look(ref WorkSettings, "WorkSettings"); if (WorkSettings == null) //Need for Compatibility with older saves { WorkSettings = new Dictionary<WorkTypeDef, bool>(); } //init refuelableComp after a Load if (refuelableComp == null) { refuelableComp = this.GetComp<CompRefuelable>(); } if (StationRangecells_old == null) { StationRangecells_old = StationRangecells; } } public override IEnumerable<Gizmo> GetGizmos() { foreach (Gizmo g in base.GetGizmos()) yield return g; yield return new Command_Toggle() { defaultLabel = "PRFDroneStationLockdown".Translate(), defaultDesc = "PRFDroneStationLockdownDesc".Translate(), toggleAction = () => { lockdown = !lockdown; if (lockdown) { foreach (Pawn_Drone drone in spawnedDrones.ToList()) { drone.jobs.StartJob(new Job(PRFDefOf.PRFDrone_ReturnToStation, this), JobCondition.InterruptForced); } } }, isActive = () => lockdown, icon = Cancel }; yield return new Command_Action() { defaultLabel = "PRFDroneStationLockdownAll".Translate(), defaultDesc = "PRFDroneStationLockdownAllDesc".Translate(), action = () => { List<Building_DroneStation> buildings = Map.listerThings.AllThings.OfType<Building_DroneStation>().ToList(); for (int i = 0; i< buildings.Count;i++) { buildings[i].lockdown = true; foreach (Pawn_Drone drone in buildings[i].spawnedDrones.ToList()) { drone.jobs.StartJob(new Job(PRFDefOf.PRFDrone_ReturnToStation, buildings[i]), JobCondition.InterruptForced); } } }, icon = ContentFinder<Texture2D>.Get("PRFUi/deactivate", true) }; yield return new Command_Action() { defaultLabel = "PRFDroneStationLiftLockdownAll".Translate(), defaultDesc = "PRFDroneStationLiftLockdownAllDesc".Translate(), action = () => { List<Building_DroneStation> buildings = Map.listerThings.AllThings.OfType<Building_DroneStation>().ToList(); for (int i = 0; i < buildings.Count; i++) { buildings[i].lockdown = false; } }, icon = ContentFinder<Texture2D>.Get("PRFUi/activate", true) }; if (DroneRange == 0) { /* "Verse.Designator" Holds example of how i want this Gizmo Implemented */ yield return new DroneAreaSelector() { icon = ContentFinder<Texture2D>.Get("UI/Designators/AreaAllowedExpand"), defaultLabel = droneAreaSelectorLable, selectAction = (a) => { Update_droneAllowedArea_forDrones(a); update_droneAreaSelectorLable(a); } }; } if (Prefs.DevMode) { yield return new Command_Action() { defaultLabel = "DEV: Respawn drones", defaultDesc = "Respawns all Drones", action = () => { for (int i = spawnedDrones.Count - 1; i >= 0; i--) { spawnedDrones[i].Destroy(); Notify_DroneGained(); } }, }; } } } }
34.4
150
0.512689
[ "MIT" ]
gabrielbunselmeyer/Project-RimFactory-Revived
Source/ProjectRimFactory/Drones/Building_DroneStation.cs
23,566
C#
using Microsoft.Extensions.Hosting; using Microsoft.AspNetCore.Hosting; using System; using Microsoft.AspNetCore.Builder; using System.Threading.Tasks; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.DependencyInjection; namespace App { public class Program { public static void Main() { Host.CreateDefaultBuilder() .ConfigureWebHostDefaults(builder => builder.Configure(app => app .UseExceptionHandler(app2 => app2.Run(HandleAsync)) .Run(context => Task.FromException(new InvalidOperationException("Manually thrown exception..."))))) .Build() .Run(); static Task HandleAsync(HttpContext context) => context.Response.WriteAsync("Unhandled exception occurred!"); } } }
32.538462
120
0.643026
[ "MIT" ]
hyperpc/AspNetCoreFxAdv
inside-asp-net-core-3/ch_16/S1603/App/Program.cs
848
C#
using System; using System.Collections.Generic; using System.Text; namespace StackOperations.BasicOperations { public class OperationDif : IStackItem, IStackOperation { public string Print => throw new NotImplementedException(); public Stack<IStackItem> Eval(Stack<IStackItem> stack) { // not enought parameters if (stack.Count < 2) { stack.Push(new Message() { Value = "Error, required at least 2 items" }); return stack; } var value1 = stack.Pop(); var value2 = stack.Pop(); // happy path if ((value1 is IStackNumber parsedValue1) && (value2 is IStackNumber parsedValue2)) { var result = parsedValue2.Value - parsedValue1.Value; stack.Push(new IntegerNumber() { Value = result }); return stack; } // error stack.Push(value2); stack.Push(value1); stack.Push(new Message() { Value = "First and second value must be a number" }); return stack; } public IStackItem Parse(string raw) { if (raw == "-") { return this; } return null; } } }
27.55102
92
0.507407
[ "MIT" ]
cpsaez-Lendsum/stackcalculator
stackCalculator/StackOperations/BasicOperations/OperationDif.cs
1,352
C#
using System; using System.Collections.Generic; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using essentialMix.Patterns.Direction; using essentialMix.Threading.Helpers; using JetBrains.Annotations; // ReSharper disable once CheckNamespace namespace essentialMix.Extensions; public static class ListBoxExtension { public static void SelectAll([NotNull] this ListBox thisValue) { if (thisValue.Items.Count == 0) return; for (int i = 0; i < thisValue.Items.Count; i++) { if (thisValue.SelectedIndices.Contains(i)) continue; thisValue.SelectedIndices.Add(i); } } public static void SelectNone([NotNull] this ListBox thisValue) { thisValue.SelectedIndices.Clear(); } public static void SelectInvert([NotNull] this ListBox thisValue) { if (thisValue.Items.Count == 0) return; if (thisValue.SelectedIndices.Count == 0) SelectAll(thisValue); else if (thisValue.SelectedIndices.Count == thisValue.Items.Count) SelectNone(thisValue); else { HashSet<int> selected = new HashSet<int>(thisValue.SelectedIndices.Cast<int>()); thisValue.SelectedIndices.Clear(); for (int i = 0; i < thisValue.Items.Count; i++) { if (selected.Contains(i)) continue; thisValue.SelectedIndices.Add(i); } } } public static void Copy<T>([NotNull] this ListBox thisValue, Action<StringBuilder, T> onAppend = null) { if (thisValue.Items.Count == 0) return; StringBuilder sb = new StringBuilder(); onAppend ??= (builder, item) => { string t = Convert.ToString(item); if (string.IsNullOrEmpty(t)) return; builder.AppendLine(t); }; if (thisValue.SelectedIndices.Count == 0) { foreach (T item in thisValue.Items) onAppend(sb, item); } else { foreach (T item in thisValue.SelectedItems) onAppend(sb, item); } Clipboard.SetText(sb.ToString()); } public static void OpenOnActivate([NotNull] this ListBox thisValue, Point location) { int index = thisValue.IndexFromPoint(location); if (index == ListBox.NoMatches) return; string value = Convert.ToString(thisValue.Items[index]); if (string.IsNullOrEmpty(value)) return; ProcessHelper.ShellExec(value); } public static void MoveSelectedItems([NotNull] this ListBox thisValue, VerticalDirection moveDirection) { ListBox.SelectedIndexCollection selectedIndices = thisValue.SelectedIndices; if (selectedIndices.Count == 0) return; ListBox.ObjectCollection items = thisValue.Items; switch (moveDirection) { case VerticalDirection.Up when selectedIndices[0] <= 0: return; case VerticalDirection.Down when selectedIndices[selectedIndices.Count - 1] >= items.Count - 1: return; } IEnumerable<int> itemsToBeMoved = selectedIndices.Cast<int>(); if (moveDirection == VerticalDirection.Down) itemsToBeMoved = itemsToBeMoved.Reverse(); thisValue.BeginUpdate(); int direction = (int)moveDirection; foreach (int indices in itemsToBeMoved) { int index = indices + direction; object item = items[index]; items.RemoveAt(indices); items.Insert(index, item); } thisValue.EndUpdate(); } }
25.793388
104
0.723806
[ "MIT" ]
asm2025/essentialMix
Framework/essentialMix.Windows/Extensions/ListBoxExtension.cs
3,121
C#
using UnityEngine; namespace GameScripts { public class ShoulderLight : MonoBehaviour { private void Update() { if (Input.GetButtonDown("ToggleLight")) { GetComponent<Light>().enabled = !GetComponent<Light>().enabled; } } } }
19.75
79
0.53481
[ "MIT" ]
AnnaGoanna/spacelabyrinth3d
src/SpaceLabyrinth3D/Assets/Scripts/GameScripts/ShoulderLight.cs
318
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.IO; using System.Text.RegularExpressions; using Microsoft.Tye.Serialization; using Tye.Serialization; namespace Microsoft.Tye.ConfigModel { public static class ConfigFactory { public static ConfigApplication FromFile(FileInfo file) { var extension = file.Extension.ToLowerInvariant(); switch (extension) { case ".yaml": case ".yml": return FromYaml(file); case ".csproj": case ".fsproj": return FromProject(file); case ".sln": return FromSolution(file); default: throw new CommandException($"File '{file.FullName}' is not a supported format."); } } private static ConfigApplication FromProject(FileInfo file) { var application = new ConfigApplication() { Source = file, Name = NameInferer.InferApplicationName(file) }; var service = new ConfigService() { Name = NormalizeServiceName(Path.GetFileNameWithoutExtension(file.Name)), Project = file.FullName.Replace('\\', '/'), }; application.Services.Add(service); return application; } private static ConfigApplication FromSolution(FileInfo file) { var application = new ConfigApplication() { Source = file, Name = NameInferer.InferApplicationName(file) }; // BE CAREFUL modifying this code. Avoid proliferating MSBuild types // throughout the code, because we load them dynamically. foreach (var projectFile in ProjectReader.EnumerateProjects(file)) { // Check for the existance of a launchSettings.json as an indication that the project is // runnable. This will only apply in the case where tye is being used against a solution // like `tye init` or `tye run` without a `tye.yaml`. // // We want a *fast* heuristic that excludes unit test projects and class libraries without // having to load all of the projects. var launchSettings = Path.Combine(projectFile.DirectoryName, "Properties", "launchSettings.json"); if (File.Exists(launchSettings) || ContainsOutputTypeExe(projectFile)) { var service = new ConfigService() { Name = NormalizeServiceName(Path.GetFileNameWithoutExtension(projectFile.Name)), Project = projectFile.FullName.Replace('\\', '/'), }; application.Services.Add(service); } } return application; } private static bool ContainsOutputTypeExe(FileInfo projectFile) { // Note, this will not work if OutputType is on separate lines. // TODO consider a more thorough check with xml reading, but at that point, it may be better just to read the project itself. var content = File.ReadAllText(projectFile.FullName); return content.Contains("<OutputType>exe</OutputType>", StringComparison.OrdinalIgnoreCase); } private static ConfigApplication FromYaml(FileInfo file) { using var parser = new YamlParser(file); return parser.ParseConfigApplication(); } private static string NormalizeServiceName(string name) => Regex.Replace(name.ToLowerInvariant(), "[^0-9A-Za-z-]+", "-"); } }
37.592593
137
0.575123
[ "MIT" ]
NileshGule/tye
src/Microsoft.Tye.Core/ConfigModel/ConfigFactory.cs
4,062
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("09.StudentGroups")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("09.StudentGroups")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("befa20e5-7065-4930-891a-cbd9cc9da245")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
37.972973
84
0.745196
[ "MIT" ]
Gecata-/OOP-Telerik
03.ExtensionMethodsDelegatesLambdaLINQ/09.StudentGroups/Properties/AssemblyInfo.cs
1,408
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using Com.H.IO; using Com.H.Linq; using Com.H.Text; namespace Com.H.Threading.Scheduler { public class HTaskScheduler : IDisposable { #region properties /// <summary> /// The time interval in miliseconds of how often the schedular checks on tasks eligibility to run. /// Default value is 1000 miliseconds /// </summary> public int TickInterval { get; set; } private string XmlConfigPath { get; set; } private IHTaskTimeLogger TimeLog { get; set; } public IHTaskCollection Tasks { get; private set; } private CancellationTokenSource Cts { get; set; } private AtomicGate RunSwitch { get; set; } private TrafficController ThreadTraffic { get; set; } #endregion #region constructor /// <summary> /// Default constructor that uses a local xml config file to load tasks configuration. /// For custom configuration from Database, Json files, etc.. implement /// IHTaskCollection and IHTaskTimeLog interfaces and make use of the overloaded constructor /// that accepts those interfaces to integrate your custom config / logging workflow with the schedular /// framework. /// </summary> /// <param name="xmlConfigPath"></param> public HTaskScheduler(string xmlConfigPath) { if (string.IsNullOrWhiteSpace(xmlConfigPath)) throw new ArgumentNullException(nameof(xmlConfigPath)); this.XmlConfigPath = xmlConfigPath; this.ThreadTraffic = new TrafficController(); this.TickInterval = 1000; // this.Load(); this.RunSwitch = new AtomicGate(); this.Load(); } /// <summary> /// You can make use of this constructor to provide your implemnetation of the IEnumerable<IHTaskItem> /// and IHTaskTimeLog if you wish to incorporate your config / loggin workflow into this schedular /// framework. /// Leaving timeLog empty defaults the schedular to do logging in memory only. The disadvantage is /// after a restart from a shutdown to the app, the schedular won't have information on what /// task it already ran prior the shutdown which would result in running the again. /// </summary> /// <param name="tasks"></param> /// <param name="timeLog"></param> public HTaskScheduler(IHTaskCollection tasks, IHTaskTimeLogger timeLog = null) { this.Tasks = tasks ?? throw new ArgumentNullException(nameof(tasks)); this.TimeLog = timeLog ?? new XmlFileHTaskTimeLogger(); this.ThreadTraffic = new TrafficController(); this.TickInterval = 1000; this.RunSwitch = new AtomicGate(); } #endregion #region load private void Load() { if (string.IsNullOrWhiteSpace(this.XmlConfigPath) && (this.Tasks?.Any() == false) ) throw new ArgumentNullException( "no file path or tasks defined"); if (string.IsNullOrWhiteSpace(this.XmlConfigPath) == false && !File.Exists(this.XmlConfigPath) && !Directory.Exists(this.XmlConfigPath)) { if (this.Tasks?.Any() == false) throw new FileNotFoundException(this.XmlConfigPath); return; } this.Tasks = new XmlFileHTaskCollection(this.XmlConfigPath); this.TimeLog = new XmlFileHTaskTimeLogger( Path.Combine( Directory.GetParent(this.XmlConfigPath).FullName, new FileInfo(this.XmlConfigPath).Name + ".log")); foreach (var task in this.Tasks.Where(x => x.Schedule.IgnoreLogOnRestart && this.TimeLog[x.UniqueKey] != null )) { this.TimeLog[task.UniqueKey].LastExecuted = null; this.TimeLog[task.UniqueKey].ErrorCount = 0; this.TimeLog[task.UniqueKey].LastError = null; } } #endregion #region start / stop /// <summary> /// Start monitoring scheduled tasks in order to trigger IsTaskDue event when tasks are ready for execution. /// </summary> /// <param name="cancellationToken">If provided, the monitoring force stops all running tasks</param> /// <returns>a running monitoring task</returns> public Task Start(CancellationToken? cancellationToken = null) { if (!this.RunSwitch.TryOpen()) return Task.CompletedTask; //this.Load(); this.Cts = cancellationToken == null ? new CancellationTokenSource() : CancellationTokenSource.CreateLinkedTokenSource( (CancellationToken)cancellationToken); return Cancellable.CancellableRunAsync(MonitorTasks, this.Cts.Token); } /// <summary> /// Stops monitoring tasks schedule, and terminates running tasks. /// </summary> public void Stop() { if (!this.RunSwitch.TryClose()) return; if (this.Cts?.IsCancellationRequested == true) return; try { this.Cts?.Cancel(); } catch { } } #endregion #region monitor private void MonitorTasks() { while (!this.Cts.IsCancellationRequested) { foreach (var task in this.Tasks) { Cancellable.CancellableRunAsync(() => { this.ThreadTraffic.QueueCall(() => { Process(task); }, 0, task.UniqueKey); }, this.Cts.Token); } Task.Delay(this.TickInterval, this.Cts.Token).GetAwaiter().GetResult(); } } private void Process(IHTaskItem task) { HTaskSchedulerEventArgs evArgs = null; try { // check if task is eligible to run including retry on error status (if failed to run in an earlier attempt and the schedule // for when to retry and retry max attempts). if (!this.IsDue(task)) return; void RunTask() { if (this.Cts.IsCancellationRequested) return; // todo: threaded having continuewith to check // run status evArgs = new HTaskSchedulerEventArgs( this, task, this.Cts.Token ); // if eligible to run (and has no previous error logged), trigger synchronous event this.OnTaskIsDueAsync(evArgs) .GetAwaiter().GetResult(); } if (task.Schedule?.Repeat != null) { AtomicGate delaySwitch = new AtomicGate(); foreach (var repeatDataModel in task.Schedule?.Repeat.EnsureEnumerable()) { if (task.Schedule?.RepeatDelayInterval > 0 && !delaySwitch.TryOpen()) { if (this.Cts?.Token != null) Task.Delay((int)task.Schedule.RepeatDelayInterval, (CancellationToken)this.Cts.Token) .GetAwaiter().GetResult(); else Task.Delay((int)task.Schedule.RepeatDelayInterval) .GetAwaiter().GetResult(); } if (this.Cts.IsCancellationRequested) return; IEnumerable<IHTaskItem> AllChildren(IHTaskItem item) { return (item.Children?.SelectMany(x => AllChildren(x)) ?? Enumerable.Empty<IHTaskItem>()).Append(item); } foreach (var child in AllChildren(task) //.Where(x => x.Vars?.Custom == null) ) child.Vars.Custom = repeatDataModel; RunTask(); } } else RunTask(); // log successful run, and reset retry on error logic in case it was previously set. this.TimeLog[task.UniqueKey].LastExecuted = DateTime.Now; this.TimeLog[task.UniqueKey].ErrorCount = 0; this.TimeLog[task.UniqueKey].LastError = null; this.TimeLog.Save(); } catch (Exception ex) { // catch errors within the thread, and check if retry on error is enabled // if enabled, don't throw exception, trigger OnErrorEvent async, then log error retry attempts and last error this.OnErrorAsync(new HTaskSchedularErrorEventArgs(this, ex, evArgs)); if (task.Schedule.RetryAttemptsAfterError == null) throw; this.TimeLog[task.UniqueKey].ErrorCount++; this.TimeLog[task.UniqueKey].LastError = DateTime.Now; this.TimeLog.Save(); } } #region is due private bool IsDue(IHTaskItem item) { if (item?.Schedule == null) return false; DateTime timeNow = DateTime.Now; var log = this.TimeLog?[item.UniqueKey]; #region error retry check if (item.Schedule.RetryAttemptsAfterError > 0 && log?.LastError != null && ( log.ErrorCount > item.Schedule.RetryAttemptsAfterError || ( item.Schedule.RetryInMilisecAfterError != null && timeNow < ((DateTime)log.LastError).AddMilliseconds( (int)item.Schedule.RetryInMilisecAfterError) ) ) ) return false; #endregion #region not before if (item.Schedule.NotBefore != null && timeNow < item.Schedule.NotBefore) return false; #endregion #region not after if (item.Schedule.NotAfter != null && timeNow > item.Schedule.NotAfter) return false; #endregion #region dates if (item.Schedule.Dates != null && !item.Schedule.Dates.Any(x=> timeNow >= x && timeNow < x.Date.AddDays(1))) return false; #endregion #region days of the year if (item.Schedule.DaysOfYear != null && !item.Schedule.DaysOfYear.Any(x => x == timeNow.DayOfYear)) return false; #endregion #region end of the month if (item.Schedule.LastDayOfMonth == true && timeNow.AddDays(1).Day != 1) return false; #endregion #region days of the month if (item.Schedule.DaysOfMonth != null && !item.Schedule.DaysOfMonth.Any(x => x == timeNow.Day)) return false; #endregion #region days of the week if (item.Schedule.DaysOfWeek != null && !item.Schedule.DaysOfWeek .Any(x => x.EqualsIgnoreCase(timeNow.DayOfWeek.ToString()))) return false; #endregion #region time if (item.Schedule.Time != null && timeNow < (timeNow.Date + item.Schedule.Time)) return false; #endregion #region until time if (item.Schedule.UntilTime != null && timeNow > (timeNow.Date + item.Schedule.UntilTime)) return false; #endregion #region interval & last executed logic if (item.Schedule.Interval != null) { if (log?.LastExecuted != null && item.Schedule.Interval > ((TimeSpan)(timeNow - log.LastExecuted)).TotalMilliseconds) return false; } else { if (log.LastExecuted?.Date == timeNow.Date) return false; } #endregion #region is enabled if (!item.Schedule.Enabled) return false; #endregion return true; } #endregion #endregion #region events #region OnTaskIsDue public delegate void TaskIsDueEventHandler(object sender, HTaskSchedulerEventArgs e); /// <summary> /// Gets triggered whenever a task is due for execution /// </summary> public event TaskIsDueEventHandler TaskIsDue; protected virtual Task OnTaskIsDueAsync(HTaskSchedulerEventArgs e) { if (e == null) return Task.CompletedTask; return Cancellable.CancellableRunAsync( () => TaskIsDue?.Invoke(e.Sender, e) , this.Cts.Token); } #endregion #region OnError public delegate void ErrorEventHandler(object sender, HTaskSchedularErrorEventArgs e); /// <summary> /// Gets triggered whenever there is an error that might get supressed if retry on error is enabled /// </summary> public event ErrorEventHandler Error; protected virtual Task OnErrorAsync(HTaskSchedularErrorEventArgs e) { if (e == null) return Task.CompletedTask; return Cancellable.CancellableRunAsync( () => Error?.Invoke(e.Sender, e) , this.Cts.Token); } #endregion #endregion #region disposable private bool disposedValue; protected virtual void Dispose(bool disposing) { if (!disposedValue) { if (disposing) { try { this.Cts.Cancel(); } catch { } try { this.RunSwitch.TryClose(); } catch { } } // TODO: free unmanaged resources (unmanaged objects) and override finalizer // TODO: set large fields to null disposedValue = true; } } // // TODO: override finalizer only if 'Dispose(bool disposing)' has code to free unmanaged resources // ~HTaskScheduler() // { // // Do not change this code. Put cleanup code in 'Dispose(bool disposing)' method // Dispose(disposing: false); // } public void Dispose() { // Do not change this code. Put cleanup code in 'Dispose(bool disposing)' method Dispose(disposing: true); GC.SuppressFinalize(this); } #endregion } }
36.197248
140
0.516348
[ "MIT" ]
H7O/Com.H.Threading.Scheduler
Com.H.Threading.Scheduler/HTaskScheduler.cs
15,784
C#
using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; using Rye.Enums; using Rye.Module; using System; namespace Rye.EntityFrameworkCore.MySql { /// <summary> /// MySql 数据库EF Core模块 /// </summary> //[DependsOnModules(typeof(EFCoreModule))] public class MySqlEFCoreModule : EFCoreModule { //public ModuleLevel Level => ModuleLevel.FrameWork; //public uint Order => 4; public MySqlEFCoreModule(Action<RyeDbContextOptionsBuilder> action) : base(action) { } public override void ConfigueServices(IServiceCollection services) { base.ConfigueServices(services); services.AddMySqlEFCore(); } } }
22.545455
90
0.662634
[ "MIT" ]
JolyneStone/Monica
src/Domain/Rye.EntityFrameworkCore.MySql/MySqlEFCoreModule.cs
756
C#
using System; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Linq; using System.Threading.Tasks; using System.Windows; using System.Windows.Threading; using Microsoft.WebMatrix.Core; using Microsoft.WebMatrix.Core.SQM; using Microsoft.WebMatrix.Extensibility; using Microsoft.WebMatrix.Utility; using NuGet; namespace NuGet.WebMatrix { internal class NuGetModel { private static HashSet<string> _tempFilesToDelete = new HashSet<string>(StringComparer.OrdinalIgnoreCase); private static bool _cleanupAdded = false; private static object _lock = new object(); private readonly static Dictionary<Tuple<string, FeedSource, bool>, NuGetModel> _cache = new Dictionary<Tuple<string, FeedSource, bool>, NuGetModel>(); private readonly IWebMatrixHost _webMatrixHost; private readonly string _packageKind; private readonly int _galleryId; internal static void ClearCache() { lock (_cache) { _cache.Clear(); } } public static NuGetModel GetModel(INuGetGalleryDescriptor descriptor, IWebMatrixHost webMatrixHost, FeedSource remoteSource, bool includePrerelease = false) { return GetModel(descriptor, webMatrixHost, remoteSource, null, null, TaskScheduler.Default); } public static NuGetModel GetModel(INuGetGalleryDescriptor descriptor, IWebMatrixHost webMatrixHost, FeedSource remoteSource, string destination, Func<Uri, string, INuGetPackageManager> packageManagerCreator, TaskScheduler scheduler, bool includePrerelease = false) { if (destination == null) { var siteRoot = webMatrixHost.WebSite == null ? null : webMatrixHost.WebSite.Path; if (String.IsNullOrWhiteSpace(siteRoot)) { Debug.Fail("The NuGetModel needs a site with a physical path"); return null; } destination = siteRoot; } NuGetModel model; lock (_cache) { var key = new Tuple<string, FeedSource, bool>(destination, remoteSource, includePrerelease); if (_cache.TryGetValue(key, out model)) { model.FromCache = true; } else { INuGetPackageManager packageManager; if (packageManagerCreator == null) { packageManager = new NuGetPackageManager(remoteSource.SourceUrl, destination, webMatrixHost); } else { packageManager = packageManagerCreator(remoteSource.SourceUrl, destination); } model = new NuGetModel(descriptor, webMatrixHost, remoteSource, destination, packageManager, scheduler); packageManager.IncludePrerelease = includePrerelease; _cache[key] = model; } } Debug.Assert(model != null, "model should be created"); return model; } /// <summary> /// Initializes a new instance of the <see cref="T:NuGetModel"/> class. /// <remarks>This is internal for tests. Callers inside of the NuGet module should used NuGetDataCache::GetModel to /// take advantage of cachein</remarks> /// </summary> internal NuGetModel(INuGetGalleryDescriptor descriptor, IWebMatrixHost host, FeedSource remoteSource, string destination, INuGetPackageManager packageManager, TaskScheduler scheduler) { Debug.Assert(host != null, "webMatrixHost must not be null"); Debug.Assert(remoteSource != null, "remoteSource must not be null"); Debug.Assert(remoteSource.SourceUrl != null, "remoteSource.SourceUrl must not be null"); this.Descriptor = descriptor; this.Scheduler = scheduler; FeedSource = remoteSource; _webMatrixHost = host; _packageKind = descriptor.PackageKind; _galleryId = descriptor.GalleryId; this.PackageManager = packageManager; this.FilterManager = new FilterManager(this, this.Scheduler, descriptor); } internal INuGetGalleryDescriptor Descriptor { get; private set; } internal FilterManager FilterManager { get; private set; } internal bool FromCache { get; private set; } internal INuGetPackageManager PackageManager { get; private set; } internal TaskScheduler Scheduler { get; private set; } public IEnumerable<string> UninstallPackage(IPackage package, bool inDetails) { Exception exception = null; IEnumerable<string> result = null; try { result = this.PackageManager.UninstallPackage(package); } catch (Exception ex) { exception = ex; throw; } finally { // Log the result of the uninstall var telemetry = WebMatrixTelemetryServiceProvider.GetTelemetryService(); if (telemetry != null) { string appId = _webMatrixHost.WebSite.ApplicationIdentifier; telemetry.LogPackageUninstall(_galleryId, package.Id, appId, exception, inDetails, isFeatured: false, isCustomFeed: !FeedSource.IsBuiltIn); } } if (_webMatrixHost != null) { _webMatrixHost.ShowNotification(string.Format(Resources.Notification_Uninstalled, _packageKind, package.Id)); } return result; } public IEnumerable<string> InstallPackage(IPackage package, bool inDetails) { Exception exception = null; IEnumerable<string> result = null; try { result = this.PackageManager.InstallPackage(package); } catch (Exception ex) { exception = ex; throw; } finally { // Log the result of the install var telemetry = WebMatrixTelemetryServiceProvider.GetTelemetryService(); if (telemetry != null) { string appId = _webMatrixHost.WebSite.ApplicationIdentifier; telemetry.LogPackageInstall(_galleryId, package.Id, appId, exception, inDetails, isFeatured: false, isCustomFeed: !FeedSource.IsBuiltIn); } } if (_webMatrixHost != null) { string message = string.Format(Resources.Notification_Installed, _packageKind, package.Id); ShowMessageAndReadme(package, message); } return result; } [SuppressMessage("Microsoft.Usage", "CA2202:Do not dispose objects multiple times", Justification = "It's safe to dispose the stream twice")] private void ShowMessageAndReadme(IPackage package, string message) { var files = package.GetContentFiles(); string filePath = null; if (files != null) { var readme = files.FirstOrDefault( (file) => file.Path.Equals("ReadMe.txt", StringComparison.OrdinalIgnoreCase)); if (readme == null) { readme = files.FirstOrDefault( (file) => file.Path.IndexOf("ReadMe.txt", StringComparison.OrdinalIgnoreCase) >= 0); } string text = null; if (readme != null) { try { using (var stream = readme.GetStream()) { using (var reader = new StreamReader(stream)) { text = reader.ReadToEnd(); } } if (!string.IsNullOrWhiteSpace(text)) { var tempFilePath = Path.GetTempFileName(); lock (_lock) { if (!_cleanupAdded) { var dispatcher = TryGetDispatcher(); if (dispatcher != null) { dispatcher.BeginInvoke(DispatcherPriority.Normal, (Action)AddExitCleanUp); } } } File.WriteAllText(tempFilePath, text); filePath = tempFilePath; lock (_lock) { _tempFilesToDelete.Add(filePath); } } } catch (Exception ex) { Debug.Fail(ex.ToString()); } } } if (filePath != null) { _webMatrixHost.ShowNotification(message, Resources.ClickForReadme, () => ShowReadMe(filePath, true)); } else { _webMatrixHost.ShowNotification(message); } } private void AddExitCleanUp() { lock (_lock) { if (!_cleanupAdded) { var current = Application.Current; if (current != null) { current.Exit += ApplicationExitCleanupHandler; _cleanupAdded = true; } } } } private void ApplicationExitCleanupHandler(object sender, ExitEventArgs e) { string[] list = null; lock (_lock) { if (_tempFilesToDelete != null) { list = _tempFilesToDelete.ToArray(); _tempFilesToDelete = null; } } if (list != null) { foreach (var file in list) { if (File.Exists(file)) { try { File.Delete(file); } catch { } } } } } private Dispatcher TryGetDispatcher() { var current = Application.Current; if (current != null) { var dispatcher = current.Dispatcher; if (dispatcher != null && !dispatcher.HasShutdownStarted) { return dispatcher; } } return null; } private void ShowReadMe(string filePath, bool deleteAfterReading) { Debug.Assert(File.Exists(filePath), "Where is the file"); if (File.Exists(filePath)) { var host = _webMatrixHost as IWebMatrixHostInternal; var editorService = host.ServiceProvider.GetService<EditorService>(); editorService.FileEditorModule.OpenFile(filePath, OpenMode.OpenInEditor); if (deleteAfterReading) { var dispatcher = TryGetDispatcher(); if (dispatcher != null) { dispatcher.BeginInvoke(DispatcherPriority.SystemIdle, (Action)(() => TryDeleteFile(filePath))); } } } } private void TryDeleteFile(string filePath) { try { lock (_lock) { File.Delete(filePath); _tempFilesToDelete.Remove(filePath); } } catch { } } public IEnumerable<string> UpdatePackage(IPackage package, bool inDetails) { Exception exception = null; IEnumerable<string> result; try { result = this.PackageManager.UpdatePackage(package); } catch (Exception ex) { exception = ex; throw; } finally { // Log the result of the update var telemetry = WebMatrixTelemetryServiceProvider.GetTelemetryService(); if (telemetry != null) { string appId = _webMatrixHost.WebSite.ApplicationIdentifier; telemetry.LogPackageUpdate(_galleryId, package.Id, appId, exception, inDetails, isFeatured: false, isCustomFeed: !FeedSource.IsBuiltIn); } } if (_webMatrixHost != null) { var message = string.Format(Resources.Notification_Updated, _packageKind, package.Id); ShowMessageAndReadme(package, message); } return result; } public IEnumerable<string> UpdateAllPackages(bool inDetails) { Exception exception = null; IEnumerable<string> result; try { result = this.PackageManager.UpdateAllPackages(); } catch (Exception ex) { exception = ex; throw; } finally { // Log the result of the update var telemetry = WebMatrixTelemetryServiceProvider.GetTelemetryService(); if (telemetry != null) { string appId = _webMatrixHost.WebSite.ApplicationIdentifier; //telemetry.LogPackageUpdate(_galleryId, package.Id, appId, exception, inDetails, isFeatured: false, isCustomFeed: !FeedSource.IsBuiltIn); } } if (_webMatrixHost != null) { var message = string.Format(Resources.Notification_UpdatedAll); _webMatrixHost.ShowNotification(message); } return result; } public bool IsPackageInstalled(IPackage package) { return this.PackageManager.IsPackageInstalled(package); } public IQueryable<IPackage> GetInstalledPackages() { return this.PackageManager.GetInstalledPackages(); } public IEnumerable<IPackage> GetPackagesWithUpdates() { return this.PackageManager.GetPackagesWithUpdates(); } public FeedSource FeedSource { get; private set; } public IEnumerable<IPackage> FindPackages(IEnumerable<string> packageIds) { return this.PackageManager.FindPackages(packageIds); } public IEnumerable<IPackage> FindDependenciesToBeInstalled(IPackage package) { return this.PackageManager.FindDependenciesToBeInstalled(package); } } }
32.507071
272
0.498167
[ "ECL-2.0", "Apache-2.0" ]
Barsonax/NuGet2
WebMatrixExtension/NuGetExtension/WPF/Model/NuGetModel.cs
16,093
C#
/********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ using System; using System.Management.Automation; using Microsoft.Management.Infrastructure; using Dbg = System.Management.Automation.Diagnostics; namespace Microsoft.PowerShell.Cmdletization.Cim { /// <summary> /// Job wrapping invocation of a ModifyInstance intrinsic CIM method /// </summary> internal class ModifyInstanceJob : PropertySettingJob<CimInstance> { private CimInstance _resultFromModifyInstance; private bool _resultFromModifyInstanceHasBeenPassedThru; private readonly CimInstance _originalInstance; private CimInstance _temporaryInstance; internal ModifyInstanceJob(CimJobContext jobContext, bool passThru, CimInstance managementObject, MethodInvocationInfo methodInvocationInfo) : base(jobContext, passThru, managementObject, methodInvocationInfo) { Dbg.Assert(this.MethodSubject != null, "Caller should verify managementObject != null"); _originalInstance = managementObject; } internal override IObservable<CimInstance> GetCimOperation() { if (!this.ShouldProcess()) { return null; } _temporaryInstance = new CimInstance(_originalInstance); ModifyLocalCimInstance(_temporaryInstance); IObservable<CimInstance> observable = this.JobContext.Session.ModifyInstanceAsync( this.JobContext.Namespace, _temporaryInstance, this.CreateOperationOptions()); return observable; } public override void OnNext(CimInstance item) { Dbg.Assert(item != null, "ModifyInstance and GetInstance should not return a null instance"); _resultFromModifyInstance = item; } public override void OnCompleted() { Dbg.Assert(_resultFromModifyInstance != null, "ModifyInstance should return an instance over DCOM and WSMan"); ModifyLocalCimInstance(_originalInstance); /* modify input CimInstance only upon success (fix for bug WinBlue #) */ base.OnCompleted(); } internal override object PassThruObject { get { Dbg.Assert(_resultFromModifyInstance != null, "ModifyInstance should return an instance over DCOM and WSMan"); if (IsShowComputerNameMarkerPresent(_originalInstance)) { PSObject pso = PSObject.AsPSObject(_resultFromModifyInstance); AddShowComputerNameMarker(pso); } _resultFromModifyInstanceHasBeenPassedThru = true; return _resultFromModifyInstance; } } internal override CimCustomOptionsDictionary CalculateJobSpecificCustomOptions() { return CimCustomOptionsDictionary.MergeOptions( base.CalculateJobSpecificCustomOptions(), _originalInstance); } protected override void Dispose(bool disposing) { if (!_resultFromModifyInstanceHasBeenPassedThru && _resultFromModifyInstance != null) { _resultFromModifyInstance.Dispose(); _resultFromModifyInstance = null; } if (_temporaryInstance != null) { _temporaryInstance.Dispose(); _temporaryInstance = null; } base.Dispose(disposing); } } }
37.757576
148
0.608882
[ "Apache-2.0", "MIT-0" ]
KevinMarquette/Powershell
src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/ModifyInstanceJob.cs
3,740
C#
using System; using System.Threading.Tasks; using Microsoft.Extensions.Logging; using SharpBrick.PoweredUp; namespace Example { public class ExampleMarioBarcode : BaseExample { public override async Task ExecuteAsync() { using (var mario = Host.FindByType<MarioHub>()) { await mario.VerifyDeploymentModelAsync(modelBuilder => modelBuilder .AddHub<MarioHub>(hubBuilder => { }) ); // for a normal scenario, a combined mode would not be needed. The tag sensor is able to detect brick colors AND the barcode on its own. The RGB scanner is neither very accurate and is scaled strangely. var tagSensor = mario.TagSensor; await tagSensor.SetupNotificationAsync(tagSensor.ModeIndexTag, true); var d1 = tagSensor.BarcodeObservable.Subscribe(x => Log.LogWarning($"Barcode: {x}")); var d2 = tagSensor.ColorNoObservable.Subscribe(x => Log.LogWarning($"Color No: {x}")); await Task.Delay(20_000); d1.Dispose(); d2.Dispose(); await mario.SwitchOffAsync(); } } } }
35.970588
218
0.600164
[ "MIT" ]
KeyDecoder/powered-up
examples/SharpBrick.PoweredUp.Examples/ExampleMarioBarcode.cs
1,223
C#
// Copyright (c) Dolittle. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Collections.Generic; using Dolittle.Assemblies; using Dolittle.DependencyInversion; using Dolittle.Types; namespace Dolittle.Booting { /// <summary> /// Represents the result of the <see cref="Bootloader"/> start. /// </summary> public class BootloaderResult { /// <summary> /// Initializes a new instance of the <see cref="BootloaderResult"/> class. /// </summary> /// <param name="container"><see cref="IContainer"/> configured.</param> /// <param name="typeFinder"><see cref="ITypeFinder"/> configured.</param> /// <param name="assemblies"><see cref="IAssemblies"/> configured.</param> /// <param name="bindings"><see cref="IBindingCollection"/> configured.</param> /// <param name="bootStageResults"><see cref="BootStageResults">Results from each boot stage</see>.</param> public BootloaderResult( IContainer container, ITypeFinder typeFinder, IAssemblies assemblies, IBindingCollection bindings, IEnumerable<BootStageResult> bootStageResults) { Container = container; TypeFinder = typeFinder; Assemblies = assemblies; Bindings = bindings; BootStageResults = bootStageResults; } /// <summary> /// Gets the <see cref="IContainer"/> configured. /// </summary> public IContainer Container { get; } /// <summary> /// Gets the <see cref="ITypeFinder"/> configured. /// </summary> public ITypeFinder TypeFinder { get; } /// <summary> /// Gets the <see cref="IAssemblies"/> configured. /// </summary> public IAssemblies Assemblies { get; } /// <summary> /// Gets the <see cref="IBindingCollection">bindings</see> configured. /// </summary> public IBindingCollection Bindings { get; } /// <summary> /// Gets the <see cref="BootStageResults">results from each boot stage</see>. /// </summary> public IEnumerable<BootStageResult> BootStageResults { get; } } }
36.746032
115
0.606911
[ "MIT" ]
dolittle-fundamentals/DotNET.Fundamentals
Source/Booting/BootloaderResult.cs
2,315
C#
using System; namespace NetCore31WebApp { public class WeatherForecast { public DateTime Date { get; set; } public int TemperatureC { get; set; } public int TemperatureF => 32 + (int)(TemperatureC / 0.5556); public string Summary { get; set; } } }
16.4375
63
0.684411
[ "MIT" ]
christophwille/pscore-playground
ExchangeOnlinePsSpike/NetCore31WebApp/WeatherForecast.cs
263
C#
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.VisualStudio.IntegrationTest.Utilities; using Xunit; namespace Roslyn.VisualStudio.IntegrationTests.CSharp { [Collection(nameof(SharedIntegrationHostFixture))] public class CSharpOrganizing : AbstractEditorTest { protected override string LanguageName => LanguageNames.CSharp; public CSharpOrganizing(VisualStudioInstanceFactory instanceFactory) : base(instanceFactory, nameof(CSharpOrganizing)) { } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public void RemoveAndSort() { SetUpEditor(@"$$ using C; using B; using A; class Test { CA a = null; CC c = null; } namespace A { public class CA { } } namespace B { public class CB { } } namespace C { public class CC { } }"); VisualStudio.ExecuteCommand("Edit.RemoveAndSort"); VisualStudio.Editor.Verify.TextContains(@" using A; using C; class Test { CA a = null; CC c = null; } namespace A { public class CA { } } namespace B { public class CB { } } namespace C { public class CC { } }"); } } }
25.622642
161
0.67673
[ "Apache-2.0" ]
liuyl1992/roslyn
src/VisualStudio/IntegrationTest/IntegrationTests/CSharp/CSharpOrganizing.cs
1,360
C#
using IntegrationController.Interface; using System; using System.Collections.Generic; using System.IO; using System.Linq; namespace IntegrationController.Model { public abstract class FileIntegration : IFileIntegration { private readonly FileInfo _file; private readonly DateTime _dateTime; public virtual FileInfo File => _file; public virtual DateTime AsOfDate => _dateTime; public virtual Dictionary<string, string> UserVariables { get; set; } public FileIntegration(DirectoryInfo directory, DateTime dateTime) { _file = directory.GetFiles(string.Format("{0}_{1:ddMMyyyy}.CSV", FileIntegrationType, dateTime), SearchOption.TopDirectoryOnly).FirstOrDefault(); _dateTime = dateTime; Init(); } private void Init() { if (IsValid) { UserVariables = new Dictionary<string, string> { { string.Format("{0}FilePath", FileIntegrationType), File.FullName } }; } } public abstract FileIntegrationType FileIntegrationType { get; } public virtual bool IsValid => File != null && File.Exists; } }
24.090909
148
0.733962
[ "MIT" ]
iAvinashVarma/Runner
Reflector/IntegrationController/Model/FileIntegration.cs
1,062
C#
/* ======================================================================= Copyright 2017 Technische Universitaet Darmstadt, Fachgebiet fuer Stroemungsdynamik (chair of fluid dynamics) 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 BoSSS.Foundation.Grid; using BoSSS.Foundation.IO; using BoSSS.Foundation.XDG; using BoSSS.Platform; using ilPSP; using BoSSS.Foundation.Grid.Classic; namespace CutCellQuadrature.TestCases { /// <summary> /// Grid solution /// </summary> public enum GridSizes { /// <summary> /// Coarsest resolution /// </summary> Tiny, /// <summary> /// Second coarsest resolution /// </summary> Small, /// <summary> /// Medium resolution /// </summary> Normal, /// <summary> /// Second finest resolution /// </summary> Large, /// <summary> /// Finest resolution /// </summary> Huge } /// <summary> /// The type of the grid that the test case should be performed on /// </summary> public enum GridTypes { /// <summary> /// A fully structure grid (consisting of either squares or /// hexahedrals) /// </summary> Structured, /// <summary> /// An unstructured triangle/tetra grid that is obtained by subdividing /// a structured grid) /// </summary> PseudoStructured, /// <summary> /// A fully unstructured grid provided by a grid generator (consisting /// of either triangles or tetras) /// </summary> Unstructured } /// <summary> /// A generic test case /// </summary> public interface ITestCase { /// <summary> /// Loads the next shift of the level set function- /// </summary> /// <returns> /// True, if there is another shift to be considered; false /// otherwise /// </returns> bool ProceedToNextShift(); /// <summary> /// Returns to the first shift. /// </summary> void ResetShifts(); /// <summary> /// Scales all shifts, see <see cref="Shift.Scale"/> /// </summary> /// <param name="scaling"></param> void ScaleShifts(double scaling); /// <summary> /// The total number of shifts that are defined /// </summary> int NumberOfShifts { get; } /// <summary> /// Returns the computational mesh for the current test. /// </summary> /// <param name="db"> /// The database where the grid is stored (optionally) /// </param> /// <returns> /// The grid on which the test should be performed /// </returns> IGrid GetGrid(IDatabaseInfo db); /// <summary> /// The type of the grid. /// </summary> GridTypes GridType { get; } /// <summary> /// The size of the grid. /// </summary> GridSizes GridSize { get; } /// <summary> /// A measure for the size of the cells <b>on the coarsest</b> grid /// </summary> double GridSpacing { get; } /// <summary> /// The true solution of the test case /// </summary> double Solution { get; } /// <summary> /// The degree of the integrand that is considered in this test case /// </summary> int IntegrandDegree { get; } /// <summary> /// Retrieves the level set function that is associated with this test. /// </summary> /// <param name="gridData"> /// Information about the grid. /// </param> /// <returns> /// The level set function associated with this test. /// </returns> ILevelSet GetLevelSet(GridData gridData); /// <summary> /// Updates the given level set according to the current shift. /// </summary> /// <param name="levelSet"> /// The level set to be modified /// </param> void UpdateLevelSet(ILevelSet levelSet); /// <summary> /// Initial value of a continuous integrand. Required for the testing /// of surface integrals /// </summary> /// <param name="input">positions in space at which the function should be evaluated; /// - 1st index: point index; /// - 2nd index: spatial coordinate vector (from 0 to D-1); /// </param> /// <param name="output">result of function evaluation; /// - 1st index: point index, corresponds with 1st index of <paramref name="input"/> /// </param> void ContinuousFieldInitialValue(MultidimensionalArray input, MultidimensionalArray output); /// <summary> /// Initial value of a discontinuous integrand in regions with negative /// level set values. Required for the testing of volume integrals /// </summary> /// <param name="input">positions in space at which the function should be evaluated; /// - 1st index: point index; /// - 2nd index: spatial coordinate vector (from 0 to D-1); /// </param> /// <param name="output">result of function evaluation; /// - 1st index: point index, corresponds with 1st index of <paramref name="input"/> /// </param> void JumpingFieldSpeciesAInitialValue(MultidimensionalArray input, MultidimensionalArray output); /// <summary> /// Initial value of a discontinuous integrand in regions with positive /// level set values. Required for the testing of volume integrals /// </summary> /// <param name="input">positions in space at which the function should be evaluated; /// - 1st index: point index; /// - 2nd index: spatial coordinate vector (from 0 to D-1); /// </param> /// <param name="output">result of function evaluation; /// - 1st index: point index, corresponds with 1st index of <paramref name="input"/> /// </param> void JumpingFieldSpeciesBInitialValue(MultidimensionalArray input, MultidimensionalArray output); } /// <summary> /// Extension methods <see cref="ITestCase"/> /// </summary> public static class ITestCaseExtensions { /// <summary> /// Retrieves the appropriate regularization polynomial. /// </summary> /// <param name="testCase"> /// The test case under consideration. /// </param> /// <param name="numberOfVanishingMoments"> /// The requested number of vanishing moments /// </param> /// <param name="numberOfContinuousDerivatives"> /// The requested number of continuous derivatives. /// </param> /// <returns></returns> public static RegularizationPolynomoial GetPolynomial(this ITestCase testCase, int numberOfVanishingMoments, int numberOfContinuousDerivatives) { if (testCase is IVolumeTestCase) { return HeavisidePolynomial.GetPolynomial(numberOfVanishingMoments, numberOfContinuousDerivatives); } else if (testCase is ISurfaceTestCase) { return DeltaPolynomial.GetPolynomial(numberOfVanishingMoments, numberOfContinuousDerivatives); } else { throw new NotImplementedException(); } } } /// <summary> /// Tags test cases for surface integrals /// </summary> interface ISurfaceTestCase { } /// <summary> /// Tags test cases for volume integrals /// </summary> interface IVolumeTestCase { } }
33.223938
154
0.556188
[ "Apache-2.0" ]
FDYdarmstadt/BoSSS
src/L4-application/CutCellQuadrature/TestCases/ITestCase.cs
8,349
C#
// ---------------------------------------------------------------------------------- // // Copyright Microsoft Corporation // 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.Collections; using System.Collections.Generic; using System.IO; using System.Linq; using Commands.Storage.ScenarioTest.Common; using Commands.Storage.ScenarioTest.Util; using Microsoft.VisualStudio.TestTools.UnitTesting; using MS.Test.Common.MsTestLib; using StorageTestLib; using StorageBlob = Microsoft.WindowsAzure.Storage.Blob; namespace Commands.Storage.ScenarioTest.Functional.Blob { /// <summary> /// functional tests for Set-ContainerAcl /// </summary> [TestClass] class SetBlobContent : TestBase { private static string uploadDirRoot; private static List<string> files = new List<string>(); //TODO upload a already opened read/write file [ClassInitialize()] public static void ClassInit(TestContext testContext) { TestBase.TestClassInitialize(testContext); uploadDirRoot = Test.Data.Get("UploadDir"); SetupUploadDir(); } [ClassCleanup()] public static void SetBlobContentClassCleanup() { TestBase.TestClassCleanup(); } /// <summary> /// create upload dir and temp files /// </summary> private static void SetupUploadDir() { Test.Verbose("Create Upload dir {0}", uploadDirRoot); if (!Directory.Exists(uploadDirRoot)) { Directory.CreateDirectory(uploadDirRoot); } FileUtil.CleanDirectory(uploadDirRoot); int minDirDepth = 1, maxDirDepth = 3; int dirDepth = random.Next(minDirDepth, maxDirDepth); Test.Info("Generate Temp files for Set-AzureStorageBlobContent"); files = FileUtil.GenerateTempFiles(uploadDirRoot, dirDepth); files.Sort(); } /// <summary> /// set azure blob content by mutilple files /// 8.14 Set-AzureStorageBlobContent /// 3. Upload a list of new blob files /// </summary> [TestMethod()] [TestCategory(Tag.Function)] [TestCategory(PsTag.Blob)] [TestCategory(PsTag.SetBlobContent)] public void SetBlobContentByMultipleFiles() { string containerName = Utility.GenNameString("container"); StorageBlob.CloudBlobContainer container = blobUtil.CreateContainer(containerName); try { List<StorageBlob.IListBlobItem> blobLists = container.ListBlobs(string.Empty, true, StorageBlob.BlobListingDetails.All).ToList(); Test.Assert(blobLists.Count == 0, string.Format("container {0} should contain {1} blobs, and actually it contain {2} blobs", containerName, 0, blobLists.Count)); DirectoryInfo rootDir = new DirectoryInfo(uploadDirRoot); FileInfo[] rootFiles = rootDir.GetFiles(); ((PowerShellAgent)agent).AddPipelineScript(string.Format("ls -File -Path {0}", uploadDirRoot)); Test.Info("Upload files..."); Test.Assert(agent.SetAzureStorageBlobContent(string.Empty, containerName, StorageBlob.BlobType.BlockBlob), "upload multiple files should be successsed"); Test.Info("Upload finished..."); blobLists = container.ListBlobs(string.Empty, true, StorageBlob.BlobListingDetails.All).ToList(); Test.Assert(blobLists.Count == rootFiles.Count(), string.Format("set-azurestorageblobcontent should upload {0} files, and actually it's {1}", rootFiles.Count(), blobLists.Count)); StorageBlob.ICloudBlob blob = null; for (int i = 0, count = rootFiles.Count(); i < count; i++) { blob = blobLists[i] as StorageBlob.ICloudBlob; if (blob == null) { Test.AssertFail("blob can't be null"); } Test.Assert(rootFiles[i].Name == blob.Name, string.Format("blob name should be {0}, and actully it's {1}", rootFiles[i].Name, blob.Name)); string localMd5 = Helper.GetFileContentMD5(Path.Combine(uploadDirRoot, rootFiles[i].Name)); Test.Assert(blob.BlobType == Microsoft.WindowsAzure.Storage.Blob.BlobType.BlockBlob, "blob type should be block blob"); Test.Assert(localMd5 == blob.Properties.ContentMD5, string.Format("blob content md5 should be {0}, and actualy it's {1}", localMd5, blob.Properties.ContentMD5)); } } finally { blobUtil.RemoveContainer(containerName); } } /// <summary> /// upload files in subdirectory /// 8.14 Set-AzureStorageBlobContent positive functional cases. /// 4. Upload a block blob file and a page blob file with a subdirectory /// </summary> [TestMethod()] [TestCategory(Tag.Function)] [TestCategory(PsTag.Blob)] [TestCategory(PsTag.SetBlobContent)] public void SetBlobContentWithSubDirectory() { DirectoryInfo rootDir = new DirectoryInfo(uploadDirRoot); DirectoryInfo[] dirs = rootDir.GetDirectories(); foreach (DirectoryInfo dir in dirs) { string containerName = Utility.GenNameString("container"); StorageBlob.CloudBlobContainer container = blobUtil.CreateContainer(containerName); try { List<StorageBlob.IListBlobItem> blobLists = container.ListBlobs(string.Empty, true, StorageBlob.BlobListingDetails.All).ToList(); Test.Assert(blobLists.Count == 0, string.Format("container {0} should contain {1} blobs, and actually it contain {2} blobs", containerName, 0, blobLists.Count)); StorageBlob.BlobType blobType = StorageBlob.BlobType.BlockBlob; if (dir.Name.StartsWith("dirpage")) { blobType = Microsoft.WindowsAzure.Storage.Blob.BlobType.PageBlob; } ((PowerShellAgent)agent).AddPipelineScript(string.Format("ls -File -Recurse -Path {0}", dir.FullName)); Test.Info("Upload files..."); Test.Assert(agent.SetAzureStorageBlobContent(string.Empty, containerName, blobType), "upload multiple files should be successsed"); Test.Info("Upload finished..."); blobLists = container.ListBlobs(string.Empty, true, StorageBlob.BlobListingDetails.All).ToList(); List<string> dirFiles = files.FindAll(item => item.StartsWith(dir.Name)); Test.Assert(blobLists.Count == dirFiles.Count(), string.Format("set-azurestorageblobcontent should upload {0} files, and actually it's {1}", dirFiles.Count(), blobLists.Count)); StorageBlob.ICloudBlob blob = null; for (int i = 0, count = dirFiles.Count(); i < count; i++) { blob = blobLists[i] as StorageBlob.ICloudBlob; if (blob == null) { Test.AssertFail("blob can't be null"); } string convertedName = blobUtil.ConvertBlobNameToFileName(blob.Name, dir.Name); Test.Assert(dirFiles[i] == convertedName, string.Format("blob name should be {0}, and actully it's {1}", dirFiles[i], convertedName)); string localMd5 = Helper.GetFileContentMD5(Path.Combine(uploadDirRoot, dirFiles[i])); Test.Assert(blob.BlobType == blobType, "blob type should be block blob"); Test.Assert(localMd5 == blob.Properties.ContentMD5, string.Format("blob content md5 should be {0}, and actualy it's {1}", localMd5, blob.Properties.ContentMD5)); } } finally { blobUtil.RemoveContainer(containerName); } } } /// <summary> /// set blob content with invalid bob name /// 8.14 Set-AzureStorageBlobContent negative functional cases /// 1. Upload a block blob file and a page blob file with a subdirectory /// </summary> [TestMethod()] [TestCategory(Tag.Function)] [TestCategory(PsTag.Blob)] [TestCategory(PsTag.SetBlobContent)] public void SetBlobContentWithInvalidBlobName() { string containerName = Utility.GenNameString("container"); StorageBlob.CloudBlobContainer container = blobUtil.CreateContainer(containerName); try { int MaxBlobNameLength = 1024; string blobName = new string('a', MaxBlobNameLength + 1); List<StorageBlob.IListBlobItem> blobLists = container.ListBlobs(string.Empty, true, StorageBlob.BlobListingDetails.All).ToList(); Test.Assert(blobLists.Count == 0, string.Format("container {0} should contain {1} blobs, and actually it contain {2} blobs", containerName, 0, blobLists.Count)); Test.Assert(!agent.SetAzureStorageBlobContent(Path.Combine(uploadDirRoot, files[0]), containerName, StorageBlob.BlobType.BlockBlob, blobName), "upload blob with invalid blob name should be failed"); string expectedErrorMessage = string.Format("Blob name '{0}' is invalid.", blobName); ExpectedStartsWithErrorMessage(expectedErrorMessage); } finally { blobUtil.RemoveContainer(containerName); } } /// <summary> /// set blob content with invalid blob type /// 8.14 Set-AzureStorageBlobContent negative functional cases /// 6. Upload a blob file with the same name but with different BlobType /// </summary> [TestMethod()] [TestCategory(Tag.Function)] [TestCategory(PsTag.Blob)] [TestCategory(PsTag.SetBlobContent)] public void SetBlobContentWithInvalidBlobType() { string containerName = Utility.GenNameString("container"); StorageBlob.CloudBlobContainer container = blobUtil.CreateContainer(containerName); try { string blobName = files[0]; List<StorageBlob.IListBlobItem> blobLists = container.ListBlobs(string.Empty, true, StorageBlob.BlobListingDetails.All).ToList(); Test.Assert(blobLists.Count == 0, string.Format("container {0} should contain {1} blobs, and actually it contain {2} blobs", containerName, 0, blobLists.Count)); Test.Assert(agent.SetAzureStorageBlobContent(Path.Combine(uploadDirRoot, files[0]), containerName, StorageBlob.BlobType.BlockBlob, blobName), "upload blob should be successful."); blobLists = container.ListBlobs(string.Empty, true, StorageBlob.BlobListingDetails.All).ToList(); Test.Assert(blobLists.Count == 1, string.Format("container {0} should contain {1} blobs, and actually it contain {2} blobs", containerName, 1, blobLists.Count)); string convertBlobName = blobUtil.ConvertFileNameToBlobName(blobName); Test.Assert(((StorageBlob.ICloudBlob)blobLists[0]).Name == convertBlobName, string.Format("blob name should be {0}, actually it's {1}", convertBlobName, ((StorageBlob.ICloudBlob)blobLists[0]).Name)); Test.Assert(!agent.SetAzureStorageBlobContent(Path.Combine(uploadDirRoot, files[0]), containerName, StorageBlob.BlobType.PageBlob, blobName), "upload blob should be with invalid blob should be failed."); string expectedErrorMessage = string.Format("Blob type mismatched, the current blob type of '{0}' is BlockBlob.", ((StorageBlob.ICloudBlob)blobLists[0]).Name); Test.Assert(agent.ErrorMessages[0] == expectedErrorMessage, string.Format("Expect error message: {0} != {1}", expectedErrorMessage, agent.ErrorMessages[0])); } finally { blobUtil.RemoveContainer(containerName); } } /// <summary> /// upload page blob with invalid file size /// 8.14 Set-AzureStorageBlobContent negative functional cases /// 8. Upload a page blob the size of which is not 512*n /// </summary> [TestMethod()] [TestCategory(Tag.Function)] [TestCategory(PsTag.Blob)] [TestCategory(PsTag.SetBlobContent)] public void SetPageBlobWithInvalidFileSize() { string fileName = Utility.GenNameString("tinypageblob"); string filePath = Path.Combine(uploadDirRoot, fileName); int fileSize = 480; Helper.GenerateTinyFile(filePath, fileSize); string containerName = Utility.GenNameString("container"); StorageBlob.CloudBlobContainer container = blobUtil.CreateContainer(containerName); try { List<StorageBlob.IListBlobItem> blobLists = container.ListBlobs(string.Empty, true, StorageBlob.BlobListingDetails.All).ToList(); Test.Assert(blobLists.Count == 0, string.Format("container {0} should contain {1} blobs, and actually it contain {2} blobs", containerName, 0, blobLists.Count)); Test.Assert(!agent.SetAzureStorageBlobContent(filePath, containerName, StorageBlob.BlobType.PageBlob), "upload page blob with invalid file size should be failed."); string expectedErrorMessage = "The page blob size must be a multiple of 512 bytes."; Test.Assert(agent.ErrorMessages[0].StartsWith(expectedErrorMessage), expectedErrorMessage); blobLists = container.ListBlobs(string.Empty, true, StorageBlob.BlobListingDetails.All).ToList(); Test.Assert(blobLists.Count == 0, string.Format("container {0} should contain {1} blobs, and actually it contain {2} blobs", containerName, 0, blobLists.Count)); } finally { blobUtil.RemoveContainer(containerName); FileUtil.RemoveFile(filePath); } } /// <summary> /// Set blob content with blob properties /// </summary> [TestMethod()] [TestCategory(Tag.Function)] [TestCategory(PsTag.Blob)] [TestCategory(PsTag.SetBlobContent)] public void SetBlobContentWithProperties() { SetBlobContentWithProperties(StorageBlob.BlobType.BlockBlob); SetBlobContentWithProperties(StorageBlob.BlobType.PageBlob); } /// <summary> /// set blob content with blob meta data /// </summary> [TestMethod()] [TestCategory(Tag.Function)] [TestCategory(PsTag.Blob)] [TestCategory(PsTag.SetBlobContent)] public void SetBlobContentWithMetadata() { SetBlobContentWithMetadata(StorageBlob.BlobType.BlockBlob); SetBlobContentWithMetadata(StorageBlob.BlobType.PageBlob); } /// <summary> /// set blob content with blob meta data /// </summary> [TestMethod()] [TestCategory(Tag.Function)] [TestCategory(PsTag.Blob)] [TestCategory(PsTag.SetBlobContent)] public void SetBlobContentForEixstsBlobWithoutForce() { string filePath = FileUtil.GenerateOneTempTestFile(); StorageBlob.CloudBlobContainer container = blobUtil.CreateContainer(); string blobName = Utility.GenNameString("blob"); StorageBlob.ICloudBlob blob = blobUtil.CreateRandomBlob(container, blobName); try { string previousMd5 = blob.Properties.ContentMD5; Test.Assert(!agent.SetAzureStorageBlobContent(filePath, container.Name, blob.BlobType, blob.Name, false), "set blob content without force parameter should fail"); ExpectedContainErrorMessage(ConfirmExceptionMessage); blob.FetchAttributes(); ExpectEqual(previousMd5, blob.Properties.ContentMD5, "content md5"); } finally { blobUtil.RemoveContainer(container.Name); FileUtil.RemoveFile(filePath); } } public void SetBlobContentWithProperties(StorageBlob.BlobType blobType) { string filePath = FileUtil.GenerateOneTempTestFile(); StorageBlob.CloudBlobContainer container = blobUtil.CreateContainer(); Hashtable properties = new Hashtable(); properties.Add("CacheControl", Utility.GenNameString(string.Empty)); properties.Add("ContentEncoding", Utility.GenNameString(string.Empty)); properties.Add("ContentLanguage", Utility.GenNameString(string.Empty)); properties.Add("ContentMD5", Utility.GenNameString(string.Empty)); properties.Add("ContentType", Utility.GenNameString(string.Empty)); try { Test.Assert(agent.SetAzureStorageBlobContent(filePath, container.Name, blobType, string.Empty, true, -1, properties), "set blob content with property should succeed"); StorageBlob.ICloudBlob blob = container.GetBlobReferenceFromServer(Path.GetFileName(filePath)); blob.FetchAttributes(); ExpectEqual(properties["CacheControl"].ToString(), blob.Properties.CacheControl, "Cache control"); ExpectEqual(properties["ContentEncoding"].ToString(), blob.Properties.ContentEncoding, "Content Encoding"); ExpectEqual(properties["ContentLanguage"].ToString(), blob.Properties.ContentLanguage, "Content Language"); ExpectEqual(properties["ContentMD5"].ToString(), blob.Properties.ContentMD5, "Content MD5"); ExpectEqual(properties["ContentType"].ToString(), blob.Properties.ContentType, "Content Type"); } finally { blobUtil.RemoveContainer(container.Name); FileUtil.RemoveFile(filePath); } } public void SetBlobContentWithMetadata(StorageBlob.BlobType blobType) { string filePath = FileUtil.GenerateOneTempTestFile(); StorageBlob.CloudBlobContainer container = blobUtil.CreateContainer(); Hashtable metadata = new Hashtable(); int metaCount = GetRandomTestCount(); for (int i = 0; i < metaCount; i++) { string key = Utility.GenRandomAlphabetString(); string value = Utility.GenNameString(string.Empty); if (!metadata.ContainsKey(key)) { Test.Info(string.Format("Add meta key: {0} value : {1}", key, value)); metadata.Add(key, value); } } try { Test.Assert(agent.SetAzureStorageBlobContent(filePath, container.Name, blobType, string.Empty, true, -1, null, metadata), "set blob content with meta should succeed"); StorageBlob.ICloudBlob blob = container.GetBlobReferenceFromServer(Path.GetFileName(filePath)); blob.FetchAttributes(); ExpectEqual(metadata.Count, blob.Metadata.Count, "meta data count"); foreach (string key in metadata.Keys) { ExpectEqual(metadata[key].ToString(), blob.Metadata[key], "Meta data key " + key); } } finally { blobUtil.RemoveContainer(container.Name); FileUtil.RemoveFile(filePath); } } } }
50.553957
220
0.599355
[ "MIT" ]
Andrean/azure-powershell
src/StackAdmin/Storage/Commands.Storage.ScenarioTest/Functional/Blob/SetBlobContent.cs
20,665
C#
// Author: Daniele Giardini - http://www.demigiant.com // Created: 2018/07/13 using System; using UnityEngine; using DG.Tweening.Core; using DG.Tweening.Plugins.Options; #if UNITY_2018_1_OR_NEWER && (NET_4_6 || NET_STANDARD_2_0) using System.Threading.Tasks; #endif #pragma warning disable 1591 namespace DG.Tweening { /// <summary> /// Shortcuts/functions that are not strictly related to specific Modules /// but are available only on some Unity versions /// </summary> public static class DOTweenModuleUnityVersion { #if UNITY_4_3 || UNITY_4_4 || UNITY_4_5 || UNITY_4_6 || UNITY_5 || UNITY_2017_1_OR_NEWER #region Unity 4.3 or Newer #region Material /// <summary>Tweens a Material's color using the given gradient /// (NOTE 1: only uses the colors of the gradient, not the alphas - NOTE 2: creates a Sequence, not a Tweener). /// Also stores the image as the tween's target so it can be used for filtered operations</summary> /// <param name="gradient">The gradient to use</param><param name="duration">The duration of the tween</param> public static Sequence DOGradientColor(this Material target, Gradient gradient, float duration) { Sequence s = DOTween.Sequence(); GradientColorKey[] colors = gradient.colorKeys; int len = colors.Length; for (int i = 0; i < len; ++i) { GradientColorKey c = colors[i]; if (i == 0 && c.time <= 0) { target.color = c.color; continue; } float colorDuration = i == len - 1 ? duration - s.Duration(false) // Verifies that total duration is correct : duration * (i == 0 ? c.time : c.time - colors[i - 1].time); s.Append(target.DOColor(c.color, colorDuration).SetEase(Ease.Linear)); } s.SetTarget(target); return s; } /// <summary>Tweens a Material's named color property using the given gradient /// (NOTE 1: only uses the colors of the gradient, not the alphas - NOTE 2: creates a Sequence, not a Tweener). /// Also stores the image as the tween's target so it can be used for filtered operations</summary> /// <param name="gradient">The gradient to use</param> /// <param name="property">The name of the material property to tween (like _Tint or _SpecColor)</param> /// <param name="duration">The duration of the tween</param> public static Sequence DOGradientColor(this Material target, Gradient gradient, string property, float duration) { Sequence s = DOTween.Sequence(); GradientColorKey[] colors = gradient.colorKeys; int len = colors.Length; for (int i = 0; i < len; ++i) { GradientColorKey c = colors[i]; if (i == 0 && c.time <= 0) { target.SetColor(property, c.color); continue; } float colorDuration = i == len - 1 ? duration - s.Duration(false) // Verifies that total duration is correct : duration * (i == 0 ? c.time : c.time - colors[i - 1].time); s.Append(target.DOColor(c.color, property, colorDuration).SetEase(Ease.Linear)); } s.SetTarget(target); return s; } #endregion #endregion #endif #if UNITY_5_3_OR_NEWER || UNITY_2017_1_OR_NEWER #region Unity 5.3 or Newer #region CustomYieldInstructions /// <summary> /// Returns a <see cref="CustomYieldInstruction"/> that waits until the tween is killed or complete. /// It can be used inside a coroutine as a yield. /// <para>Example usage:</para><code>yield return myTween.WaitForCompletion(true);</code> /// </summary> public static CustomYieldInstruction WaitForCompletion(this Tween t, bool returnCustomYieldInstruction) { if (!t.active) { if (Debugger.logPriority > 0) Debugger.LogInvalidTween(t); return null; } return new DOTweenCYInstruction.WaitForCompletion(t); } /// <summary> /// Returns a <see cref="CustomYieldInstruction"/> that waits until the tween is killed or rewinded. /// It can be used inside a coroutine as a yield. /// <para>Example usage:</para><code>yield return myTween.WaitForRewind();</code> /// </summary> public static CustomYieldInstruction WaitForRewind(this Tween t, bool returnCustomYieldInstruction) { if (!t.active) { if (Debugger.logPriority > 0) Debugger.LogInvalidTween(t); return null; } return new DOTweenCYInstruction.WaitForRewind(t); } /// <summary> /// Returns a <see cref="CustomYieldInstruction"/> that waits until the tween is killed. /// It can be used inside a coroutine as a yield. /// <para>Example usage:</para><code>yield return myTween.WaitForKill();</code> /// </summary> public static CustomYieldInstruction WaitForKill(this Tween t, bool returnCustomYieldInstruction) { if (!t.active) { if (Debugger.logPriority > 0) Debugger.LogInvalidTween(t); return null; } return new DOTweenCYInstruction.WaitForKill(t); } /// <summary> /// Returns a <see cref="CustomYieldInstruction"/> that waits until the tween is killed or has gone through the given amount of loops. /// It can be used inside a coroutine as a yield. /// <para>Example usage:</para><code>yield return myTween.WaitForElapsedLoops(2);</code> /// </summary> /// <param name="elapsedLoops">Elapsed loops to wait for</param> public static CustomYieldInstruction WaitForElapsedLoops(this Tween t, int elapsedLoops, bool returnCustomYieldInstruction) { if (!t.active) { if (Debugger.logPriority > 0) Debugger.LogInvalidTween(t); return null; } return new DOTweenCYInstruction.WaitForElapsedLoops(t, elapsedLoops); } /// <summary> /// Returns a <see cref="CustomYieldInstruction"/> that waits until the tween is killed /// or has reached the given time position (loops included, delays excluded). /// It can be used inside a coroutine as a yield. /// <para>Example usage:</para><code>yield return myTween.WaitForPosition(2.5f);</code> /// </summary> /// <param name="position">Position (loops included, delays excluded) to wait for</param> public static CustomYieldInstruction WaitForPosition(this Tween t, float position, bool returnCustomYieldInstruction) { if (!t.active) { if (Debugger.logPriority > 0) Debugger.LogInvalidTween(t); return null; } return new DOTweenCYInstruction.WaitForPosition(t, position); } /// <summary> /// Returns a <see cref="CustomYieldInstruction"/> that waits until the tween is killed or started /// (meaning when the tween is set in a playing state the first time, after any eventual delay). /// It can be used inside a coroutine as a yield. /// <para>Example usage:</para><code>yield return myTween.WaitForStart();</code> /// </summary> public static CustomYieldInstruction WaitForStart(this Tween t, bool returnCustomYieldInstruction) { if (!t.active) { if (Debugger.logPriority > 0) Debugger.LogInvalidTween(t); return null; } return new DOTweenCYInstruction.WaitForStart(t); } #endregion #endregion #endif #if UNITY_2018_1_OR_NEWER #region Unity 2018.1 or Newer #region Material /// <summary>Tweens a Material's named texture offset property with the given ID to the given value. /// Also stores the material as the tween's target so it can be used for filtered operations</summary> /// <param name="endValue">The end value to reach</param> /// <param name="propertyID">The ID of the material property to tween (also called nameID in Unity's manual)</param> /// <param name="duration">The duration of the tween</param> public static TweenerCore<Vector2, Vector2, VectorOptions> DOOffset(this Material target, Vector2 endValue, int propertyID, float duration) { if (!target.HasProperty(propertyID)) { if (Debugger.logPriority > 0) Debugger.LogMissingMaterialProperty(propertyID); return null; } TweenerCore<Vector2, Vector2, VectorOptions> t = DOTween.To(() => target.GetTextureOffset(propertyID), x => target.SetTextureOffset(propertyID, x), endValue, duration); t.SetTarget(target); return t; } /// <summary>Tweens a Material's named texture scale property with the given ID to the given value. /// Also stores the material as the tween's target so it can be used for filtered operations</summary> /// <param name="endValue">The end value to reach</param> /// <param name="propertyID">The ID of the material property to tween (also called nameID in Unity's manual)</param> /// <param name="duration">The duration of the tween</param> public static TweenerCore<Vector2, Vector2, VectorOptions> DOTiling(this Material target, Vector2 endValue, int propertyID, float duration) { if (!target.HasProperty(propertyID)) { if (Debugger.logPriority > 0) Debugger.LogMissingMaterialProperty(propertyID); return null; } TweenerCore<Vector2, Vector2, VectorOptions> t = DOTween.To(() => target.GetTextureScale(propertyID), x => target.SetTextureScale(propertyID, x), endValue, duration); t.SetTarget(target); return t; } #endregion #region .NET 4.6 or Newer #if (NET_4_6 || NET_STANDARD_2_0) #region Async Instructions /// <summary> /// Returns an async <see cref="Task"/> that waits until the tween is killed or complete. /// It can be used inside an async operation. /// <para>Example usage:</para><code>await myTween.WaitForCompletion();</code> /// </summary> public static async Task AsyncWaitForCompletion(this Tween t) { if (!t.active) { if (Debugger.logPriority > 0) Debugger.LogInvalidTween(t); return; } while (t.active && !t.IsComplete()) await Task.Yield(); } /// <summary> /// Returns an async <see cref="Task"/> that waits until the tween is killed or rewinded. /// It can be used inside an async operation. /// <para>Example usage:</para><code>await myTween.AsyncWaitForRewind();</code> /// </summary> public static async Task AsyncWaitForRewind(this Tween t) { if (!t.active) { if (Debugger.logPriority > 0) Debugger.LogInvalidTween(t); return; } while (t.active && (!t.playedOnce || t.position * (t.CompletedLoops() + 1) > 0)) await Task.Yield(); } /// <summary> /// Returns an async <see cref="Task"/> that waits until the tween is killed. /// It can be used inside an async operation. /// <para>Example usage:</para><code>await myTween.AsyncWaitForKill();</code> /// </summary> public static async Task AsyncWaitForKill(this Tween t) { if (!t.active) { if (Debugger.logPriority > 0) Debugger.LogInvalidTween(t); return; } while (t.active) await Task.Yield(); } /// <summary> /// Returns an async <see cref="Task"/> that waits until the tween is killed or has gone through the given amount of loops. /// It can be used inside an async operation. /// <para>Example usage:</para><code>await myTween.AsyncWaitForElapsedLoops();</code> /// </summary> /// <param name="elapsedLoops">Elapsed loops to wait for</param> public static async Task AsyncWaitForElapsedLoops(this Tween t, int elapsedLoops) { if (!t.active) { if (Debugger.logPriority > 0) Debugger.LogInvalidTween(t); return; } while (t.active && t.CompletedLoops() < elapsedLoops) await Task.Yield(); } /// <summary> /// Returns an async <see cref="Task"/> that waits until the tween is killed or started /// (meaning when the tween is set in a playing state the first time, after any eventual delay). /// It can be used inside an async operation. /// <para>Example usage:</para><code>await myTween.AsyncWaitForPosition();</code> /// </summary> /// <param name="position">Position (loops included, delays excluded) to wait for</param> public static async Task AsyncWaitForPosition(this Tween t, float position) { if (!t.active) { if (Debugger.logPriority > 0) Debugger.LogInvalidTween(t); return; } while (t.active && t.position * (t.CompletedLoops() + 1) < position) await Task.Yield(); } /// <summary> /// Returns an async <see cref="Task"/> that waits until the tween is killed. /// It can be used inside an async operation. /// <para>Example usage:</para><code>await myTween.AsyncWaitForKill();</code> /// </summary> public static async Task AsyncWaitForStart(this Tween t) { if (!t.active) { if (Debugger.logPriority > 0) Debugger.LogInvalidTween(t); return; } while (t.active && !t.playedOnce) await Task.Yield(); } #endregion #endif #endregion #endregion #endif } // █████████████████████████████████████████████████████████████████████████████████████████████████████████████████████ // ███ CLASSES █████████████████████████████████████████████████████████████████████████████████████████████████████████ // █████████████████████████████████████████████████████████████████████████████████████████████████████████████████████ #if UNITY_5_3_OR_NEWER || UNITY_2017_1_OR_NEWER public static class DOTweenCYInstruction { public class WaitForCompletion : CustomYieldInstruction { public override bool keepWaiting { get { return t.active && !t.IsComplete(); }} readonly Tween t; public WaitForCompletion(Tween tween) { t = tween; } } public class WaitForRewind : CustomYieldInstruction { public override bool keepWaiting { get { return t.active && (!t.playedOnce || t.position * (t.CompletedLoops() + 1) > 0); }} readonly Tween t; public WaitForRewind(Tween tween) { t = tween; } } public class WaitForKill : CustomYieldInstruction { public override bool keepWaiting { get { return t.active; }} readonly Tween t; public WaitForKill(Tween tween) { t = tween; } } public class WaitForElapsedLoops : CustomYieldInstruction { public override bool keepWaiting { get { return t.active && t.CompletedLoops() < elapsedLoops; }} readonly Tween t; readonly int elapsedLoops; public WaitForElapsedLoops(Tween tween, int elapsedLoops) { t = tween; this.elapsedLoops = elapsedLoops; } } public class WaitForPosition : CustomYieldInstruction { public override bool keepWaiting { get { return t.active && t.position * (t.CompletedLoops() + 1) < position; }} readonly Tween t; readonly float position; public WaitForPosition(Tween tween, float position) { t = tween; this.position = position; } } public class WaitForStart : CustomYieldInstruction { public override bool keepWaiting { get { return t.active && !t.playedOnce; }} readonly Tween t; public WaitForStart(Tween tween) { t = tween; } } } #endif }
42.344059
180
0.570176
[ "MIT" ]
0007berd/MergeTest
Assets/Plugins/Demigiant/DOTween/Modules/DOTweenModuleUnityVersion.cs
17,793
C#
namespace model.timing { public interface IStepObserver { void NotifyStep(string structure, int phase, int step); } }
19.714286
63
0.666667
[ "Unlicense" ]
JeffSkyrunner/data-hunt
Assets/Scripts/Model/Timing/IStepObserver.cs
140
C#
using Abp.Domain.Uow; using Abp.EntityFrameworkCore; using Abp.MultiTenancy; using Abp.Zero.EntityFrameworkCore; namespace blogger.EntityFrameworkCore { public class AbpZeroDbMigrator : AbpZeroDbMigrator<bloggerDbContext> { public AbpZeroDbMigrator( IUnitOfWorkManager unitOfWorkManager, IDbPerTenantConnectionStringResolver connectionStringResolver, IDbContextResolver dbContextResolver) : base( unitOfWorkManager, connectionStringResolver, dbContextResolver) { } } }
27.409091
74
0.6733
[ "MIT" ]
Drex3l/aspboilerplate
aspnet-core/src/blogger.EntityFrameworkCore/EntityFrameworkCore/AbpZeroDbMigrator.cs
605
C#
// Copyright 2009 Auxilium B.V. - http://www.auxilium.nl/ // // 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 JelloScrum.Model.Tests.Model { using Creations; using Entities; using Enumerations; using NUnit.Framework; [TestFixture] public class TaakTest : TestBase { private Task taak; public override void SetUp() { taak = new Task(); base.SetUp(); } [Test] public void TestSaveTaakAlsDone() { taak.Close(); Assert.IsTrue(taak.State == State.Closed); } [Test] public void TestTaakOppakkenGeeftEenBehandelaarDeTaak() { Task task = Creation.Task(); SprintUser sprintGebruiker = Creation.SprintGebruiker(Creation.Gebruiker()); sprintGebruiker.TakeTask(task); Assert.IsTrue(sprintGebruiker.Tasks.Contains(task)); } [Test] public void TestTaakAlsNietOpgepaktZettenZorgtDatBehandelaarTaakNietMeerHeeft() { Task task = Creation.Task(); SprintUser sprintGebruiker = Creation.SprintGebruiker(Creation.Gebruiker()); sprintGebruiker.TakeTask(task); sprintGebruiker.UnAssignTask(task); Assert.IsTrue(sprintGebruiker.Tasks.Contains(task) == false); } [Test] public void TestTaakOvernemenPaktTaakAfVanBehandelaar() { Task task = Creation.Task(); SprintUser sprintGebruiker1 = Creation.SprintGebruiker(Creation.Gebruiker()); SprintUser sprintGebruiker2 = Creation.SprintGebruiker(Creation.Gebruiker()); sprintGebruiker1.TakeTask(task); sprintGebruiker2.TakeOverTask(task); Assert.IsTrue(sprintGebruiker1.Tasks.Contains(task) == false && sprintGebruiker2.Tasks.Contains(task)); } } }
32.77027
115
0.641237
[ "Apache-2.0" ]
auxilium/JelloScrum
JelloScrum/JelloScrum.Model.Tests/Model/TaakTest.cs
2,425
C#
using FluentAssertions; using Microsoft.Extensions.Options; using Wellcome.Dds.Common; using Wellcome.Dds.IIIFBuilding; using Xunit; namespace Wellcome.Dds.Tests.IIIFBuilding { public class UriPatternsTests { private readonly UriPatterns sut; public UriPatternsTests() { var ddsOptions = new DdsOptions { LinkedDataDomain = "https://test.linkeddata", WellcomeCollectionApi = "https://test.wellcomeapi", ApiWorkTemplate = "https://api.wellcomecollection.org/catalogue/v2/works" }; sut = new UriPatterns(Options.Create(ddsOptions)); } [Fact] public void GetCacheInvalidationPaths_IIIF_Correct() { // Arrange const string identifier = "b1231231"; var expected = new[] { "/thumb/b1231231*", "/search/v0/b1231231*", "/search/v1/b1231231*", "/search/v2/b1231231*", "/search/autocomplete/v1/b1231231*", "/search/autocomplete/v2/b1231231*", "/annotations/v2/b1231231*", "/annotations/v3/b1231231*", "/presentation/b1231231*", "/presentation/v2/b1231231*", "/presentation/v3/b1231231*", }; // Act var actual = sut.GetCacheInvalidationPaths(identifier, InvalidationPathType.IIIF); // Assert actual.Should().BeEquivalentTo(expected); } [Fact] public void GetCacheInvalidationPaths_Text_Correct() { // Arrange const string identifier = "b1231231"; var expected = new[] { "/text/v1/b1231231*", "/text/alto/b1231231*", }; // Act var actual = sut.GetCacheInvalidationPaths(identifier, InvalidationPathType.Text); // Assert actual.Should().BeEquivalentTo(expected); } } }
31.114286
95
0.511478
[ "MIT" ]
wellcomecollection/iiif-builder
src/Wellcome.Dds/Wellcome.Dds.Tests/IIIFBuilding/UriPatternsTests.cs
2,180
C#
namespace JokesOnYou.Web.Api.DTOs { public class LikedTagsReplyDto { } }
12.285714
34
0.662791
[ "Unlicense" ]
Palisar/JokesOnYou
Server/JokesOnYou.Web.Api/DTOs/LikedTagsReplyDto.cs
88
C#
using EOLib.Net.Handlers; using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; namespace EOBot { sealed class BotFramework : IDisposable { public const int NUM_BOTS_MAX = 25; private readonly CancellationTokenSource _cancellationTokenSource; private readonly List<IBot> _botsList; private readonly string _host; private readonly ushort _port; private Semaphore _doneSignal; private bool _initialized; private int _numBots; private bool _terminating; public BotFramework(ArgumentsParser parsedArgs) { if (parsedArgs == null) throw new ArgumentNullException(nameof(parsedArgs)); _cancellationTokenSource = new CancellationTokenSource(); var numberOfBots = parsedArgs.NumBots; var simultaneousBots = parsedArgs.SimultaneousBots; var host = parsedArgs.Host; var port = parsedArgs.Port; if (numberOfBots > NUM_BOTS_MAX || simultaneousBots > NUM_BOTS_MAX || simultaneousBots > numberOfBots) throw new ArgumentException("Too many bots requested"); if (numberOfBots <= 0 || simultaneousBots <= 0) throw new ArgumentException("Not enough bots requested"); _numBots = numberOfBots; _host = host; _port = port; _botsList = new List<IBot>(numberOfBots); _doneSignal = new Semaphore(simultaneousBots, simultaneousBots); } public async Task InitializeAsync(IBotFactory botFactory, int delayBetweenInitsMS = 1100) { if (_initialized) throw new InvalidOperationException("Unable to initialize bot framework a second time."); int numFailed = 0; for (int i = 0; i < _numBots; ++i) { if (_terminating) throw new BotException("Received termination signal; initialization has been cancelled"); try { var bot = botFactory.CreateBot(i); bot.WorkCompleted += () => _doneSignal.Release(); await bot.InitializeAsync(_host, _port); _botsList.Add(bot); } catch(Exception ex) { ConsoleHelper.WriteMessage(ConsoleHelper.Type.Error, ex.Message, ConsoleColor.DarkRed); numFailed++; continue; } ConsoleHelper.WriteMessage(ConsoleHelper.Type.None, $"Bot {i} initialized."); await Task.Delay(delayBetweenInitsMS); //minimum for this is 1sec server-side } if (numFailed > 0) { ConsoleHelper.WriteMessage(ConsoleHelper.Type.Warning, "Some bot instances failed to initialize. These bot instances will not be run.", ConsoleColor.DarkYellow); _numBots -= numFailed; } else if (numFailed == _numBots) { throw new BotException("All bots failed to initialize. No bots will run."); } _initialized = true; } public async Task RunAsync() { if(!_initialized) throw new InvalidOperationException("Must call Initialize() before running!"); var botTasks = new List<Task>(); ConsoleHelper.WriteMessage(ConsoleHelper.Type.None, "Bot framework run has started.\n"); for (int i = 0; i < _numBots; ++i) { _doneSignal.WaitOne(); //acquire mutex for bot //semaphore limits number of concurrently running bots based on cmd-line param botTasks.Add(_botsList[i].RunAsync(_cancellationTokenSource.Token)); } // this is done to force handling of exceptions as an Aggregate exception so errors from multiple bots are shown properly // otherwise, only the first exception from the first faulting task will be thrown var continuation = Task.WhenAll(botTasks); try { await continuation; } catch { } if (continuation.Status != TaskStatus.RanToCompletion && continuation.Exception != null) { throw continuation.Exception; } } public void TerminateBots() { _terminating = true; if (!_initialized) return; _cancellationTokenSource.Cancel(); } ~BotFramework() { Dispose(false); GC.SuppressFinalize(this); } public void Dispose() { Dispose(true); } private void Dispose(bool disposing) { if (disposing) { _doneSignal?.Dispose(); _cancellationTokenSource?.Dispose(); } } } }
33.398693
177
0.562035
[ "MIT" ]
Septharoth/EndlessClient
EOBot/BotFramework.cs
5,112
C#
using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using AutoMapper; using Microsoft.Azure.Management.Monitor.Fluent.Models; using Microsoft.Extensions.Logging.Abstractions; using Promitor.Core.Scraping.Configuration.Model.Metrics.ResourceTypes; using Promitor.Core.Scraping.Configuration.Serialization; using Promitor.Core.Scraping.Configuration.Serialization.v1.Core; using Promitor.Core.Scraping.Configuration.Serialization.v1.Mapping; using Promitor.Core.Scraping.Configuration.Serialization.v1.Model; using Promitor.Core.Scraping.Configuration.Serialization.v1.Model.ResourceTypes; using Xunit; using ResourceType = Promitor.Core.Scraping.Configuration.Model.ResourceType; namespace Promitor.Tests.Unit.Serialization.v1 { /// <summary> /// This class contains tests that run the full end-to-end serialization and deserialization /// process to try to catch anything that the individual unit tests for the deserializers haven't /// caught. /// </summary> [Category("Unit")] public class V1SerializationTests { private readonly V1Deserializer _v1Deserializer; private readonly ConfigurationSerializer _configurationSerializer; private readonly MetricsDeclarationV1 _metricsDeclaration; private readonly IErrorReporter _errorReporter = new ErrorReporter(); public V1SerializationTests() { var mapperConfiguration = new MapperConfiguration(c => c.AddProfile<V1MappingProfile>()); var mapper = mapperConfiguration.CreateMapper(); _v1Deserializer = V1DeserializerFactory.CreateDeserializer(); _configurationSerializer = new ConfigurationSerializer(NullLogger<ConfigurationSerializer>.Instance, mapper, _v1Deserializer); _metricsDeclaration = new MetricsDeclarationV1 { AzureMetadata = new AzureMetadataV1 { TenantId = "tenant", SubscriptionId = "subscription", ResourceGroupName = "promitor-group" }, MetricDefaults = new MetricDefaultsV1 { Aggregation = new AggregationV1 { Interval = TimeSpan.FromMinutes(7) }, Scraping = new ScrapingV1 { Schedule = "1 2 3 4 5" } }, Metrics = new List<MetricDefinitionV1> { new MetricDefinitionV1 { Name = "promitor_demo_generic_queue_size", Description = "Amount of active messages of the 'orders' queue (determined with Generic provider)", ResourceType = ResourceType.Generic, Labels = new Dictionary<string, string> { {"app", "promitor"} }, AzureMetricConfiguration = new AzureMetricConfigurationV1 { MetricName = "ActiveMessages", Aggregation = new MetricAggregationV1 { Type = AggregationType.Average } }, Resources = new List<AzureResourceDefinitionV1> { new GenericResourceV1 { ResourceUri = "Microsoft.ServiceBus/namespaces/promitor-messaging", Filter = "EntityName eq 'orders'" }, new GenericResourceV1 { ResourceUri = "Microsoft.ServiceBus/namespaces/promitor-messaging", Filter = "EntityName eq 'accounts'" } } }, new MetricDefinitionV1 { Name = "promitor_demo_servicebusqueue_queue_size", Description = "Amount of active messages of the 'orders' queue (determined with ServiceBusQueue provider)", ResourceType = ResourceType.ServiceBusQueue, AzureMetricConfiguration = new AzureMetricConfigurationV1 { MetricName = "ActiveMessages", Aggregation = new MetricAggregationV1 { Type = AggregationType.Average, Interval = TimeSpan.FromMinutes(15) } }, Scraping = new ScrapingV1 { Schedule = "5 4 3 2 1" }, Resources = new List<AzureResourceDefinitionV1> { new ServiceBusQueueResourceV1 { Namespace = "promitor-messaging", QueueName = "orders", ResourceGroupName = "promitor-demo-group" } } } } }; } [Fact] public void Deserialize_SerializedModel_CanDeserialize() { // This test creates a v1 model, serializes it to yaml, and then verifies that // the V1Deserializer can deserialize it. // Arrange var yaml = _configurationSerializer.Serialize(_metricsDeclaration); // Act var deserializedModel = _v1Deserializer.Deserialize(YamlUtils.CreateYamlNode(yaml), _errorReporter); // Assert Assert.NotNull(deserializedModel); Assert.Equal("tenant", deserializedModel.AzureMetadata.TenantId); Assert.Equal("subscription", deserializedModel.AzureMetadata.SubscriptionId); Assert.Equal("promitor-group", deserializedModel.AzureMetadata.ResourceGroupName); Assert.Equal(TimeSpan.FromMinutes(7), deserializedModel.MetricDefaults.Aggregation.Interval); Assert.Equal("1 2 3 4 5", deserializedModel.MetricDefaults.Scraping.Schedule); // Check first metric Assert.Equal("promitor_demo_generic_queue_size", deserializedModel.Metrics.ElementAt(0).Name); Assert.Equal("Amount of active messages of the 'orders' queue (determined with Generic provider)", deserializedModel.Metrics.ElementAt(0).Description); Assert.Equal(ResourceType.Generic, deserializedModel.Metrics.ElementAt(0).ResourceType); Assert.Equal(new Dictionary<string, string> { { "app", "promitor" } }, deserializedModel.Metrics.ElementAt(0).Labels); Assert.Equal("ActiveMessages", deserializedModel.Metrics.ElementAt(0).AzureMetricConfiguration.MetricName); Assert.Equal(AggregationType.Average, deserializedModel.Metrics.ElementAt(0).AzureMetricConfiguration.Aggregation.Type); Assert.Equal(2, deserializedModel.Metrics.ElementAt(0).Resources.Count); var genericResource1 = Assert.IsType<GenericResourceV1>(deserializedModel.Metrics.ElementAt(0).Resources.ElementAt(0)); Assert.Equal("Microsoft.ServiceBus/namespaces/promitor-messaging", genericResource1.ResourceUri); Assert.Equal("EntityName eq 'orders'", genericResource1.Filter); var genericResource2 = Assert.IsType<GenericResourceV1>(deserializedModel.Metrics.ElementAt(0).Resources.ElementAt(1)); Assert.Equal("Microsoft.ServiceBus/namespaces/promitor-messaging", genericResource2.ResourceUri); Assert.Equal("EntityName eq 'accounts'", genericResource2.Filter); // Check second metric Assert.Equal("promitor_demo_servicebusqueue_queue_size", deserializedModel.Metrics.ElementAt(1).Name); Assert.Equal("Amount of active messages of the 'orders' queue (determined with ServiceBusQueue provider)", deserializedModel.Metrics.ElementAt(1).Description); Assert.Equal(ResourceType.ServiceBusQueue, deserializedModel.Metrics.ElementAt(1).ResourceType); Assert.Null(deserializedModel.Metrics.ElementAt(1).Labels); Assert.Equal(TimeSpan.FromMinutes(15), deserializedModel.Metrics.ElementAt(1).AzureMetricConfiguration.Aggregation.Interval); Assert.Equal("5 4 3 2 1", deserializedModel.Metrics.ElementAt(1).Scraping.Schedule); Assert.Single(deserializedModel.Metrics.ElementAt(1).Resources); var serviceBusQueueResource = Assert.IsType<ServiceBusQueueResourceV1>(deserializedModel.Metrics.ElementAt(1).Resources.ElementAt(0)); Assert.Equal("promitor-messaging", serviceBusQueueResource.Namespace); Assert.Equal("orders", serviceBusQueueResource.QueueName); Assert.Equal("promitor-demo-group", serviceBusQueueResource.ResourceGroupName); } [Fact] public void Deserialize_SerializedYaml_CanDeserializeToRuntimeModel() { // Arrange var yaml = _configurationSerializer.Serialize(_metricsDeclaration); // Act var runtimeModel = _configurationSerializer.Deserialize(yaml, _errorReporter); // Assert Assert.NotNull(runtimeModel); var firstMetric = runtimeModel.Metrics.ElementAt(0); Assert.Equal(ResourceType.Generic, firstMetric.ResourceType); Assert.Equal("promitor_demo_generic_queue_size", firstMetric.PrometheusMetricDefinition.Name); Assert.Equal("Amount of active messages of the 'orders' queue (determined with Generic provider)", firstMetric.PrometheusMetricDefinition.Description); Assert.Collection(firstMetric.Resources, r => { var definition = Assert.IsType<GenericAzureResourceDefinition>(r); Assert.Equal("EntityName eq 'orders'", definition.Filter); Assert.Equal("Microsoft.ServiceBus/namespaces/promitor-messaging", definition.ResourceUri); }, r => { var definition = Assert.IsType<GenericAzureResourceDefinition>(r); Assert.Equal("EntityName eq 'accounts'", definition.Filter); Assert.Equal("Microsoft.ServiceBus/namespaces/promitor-messaging", definition.ResourceUri); }); var secondMetric = runtimeModel.Metrics.ElementAt(1); Assert.Equal(ResourceType.ServiceBusQueue, secondMetric.ResourceType); Assert.Equal("promitor_demo_servicebusqueue_queue_size", secondMetric.PrometheusMetricDefinition.Name); Assert.Equal("Amount of active messages of the 'orders' queue (determined with ServiceBusQueue provider)", secondMetric.PrometheusMetricDefinition.Description); Assert.Collection(secondMetric.Resources, r => { var definition = Assert.IsType<ServiceBusQueueResourceDefinition>(r); Assert.Equal("promitor-messaging", definition.Namespace); Assert.Equal("orders", definition.QueueName); Assert.Equal("promitor-demo-group", definition.ResourceGroupName); }); } } }
53.104072
172
0.59816
[ "MIT" ]
ChristianEder/promitor
src/Promitor.Tests.Unit/Serialization/v1/V1SerializationTests.cs
11,738
C#
// <auto-generated> // Auto-generated by StoneAPI, do not modify. // </auto-generated> namespace Dropbox.Api.TeamLog { using sys = System; using col = System.Collections.Generic; using re = System.Text.RegularExpressions; using enc = Dropbox.Api.Stone; /// <summary> /// <para>Changed the allow remove or change expiration policy for the links shared outside /// of the team.</para> /// </summary> public class SharingChangeLinkEnforcePasswordPolicyDetails { #pragma warning disable 108 /// <summary> /// <para>The encoder instance.</para> /// </summary> internal static enc.StructEncoder<SharingChangeLinkEnforcePasswordPolicyDetails> Encoder = new SharingChangeLinkEnforcePasswordPolicyDetailsEncoder(); /// <summary> /// <para>The decoder instance.</para> /// </summary> internal static enc.StructDecoder<SharingChangeLinkEnforcePasswordPolicyDetails> Decoder = new SharingChangeLinkEnforcePasswordPolicyDetailsDecoder(); /// <summary> /// <para>Initializes a new instance of the <see /// cref="SharingChangeLinkEnforcePasswordPolicyDetails" /> class.</para> /// </summary> /// <param name="newValue">To.</param> /// <param name="previousValue">From.</param> public SharingChangeLinkEnforcePasswordPolicyDetails(ChangeLinkExpirationPolicy newValue, ChangeLinkExpirationPolicy previousValue = null) { if (newValue == null) { throw new sys.ArgumentNullException("newValue"); } this.NewValue = newValue; this.PreviousValue = previousValue; } /// <summary> /// <para>Initializes a new instance of the <see /// cref="SharingChangeLinkEnforcePasswordPolicyDetails" /> class.</para> /// </summary> /// <remarks>This is to construct an instance of the object when /// deserializing.</remarks> [sys.ComponentModel.EditorBrowsable(sys.ComponentModel.EditorBrowsableState.Never)] public SharingChangeLinkEnforcePasswordPolicyDetails() { } /// <summary> /// <para>To.</para> /// </summary> public ChangeLinkExpirationPolicy NewValue { get; protected set; } /// <summary> /// <para>From.</para> /// </summary> public ChangeLinkExpirationPolicy PreviousValue { get; protected set; } #region Encoder class /// <summary> /// <para>Encoder for <see cref="SharingChangeLinkEnforcePasswordPolicyDetails" /// />.</para> /// </summary> private class SharingChangeLinkEnforcePasswordPolicyDetailsEncoder : enc.StructEncoder<SharingChangeLinkEnforcePasswordPolicyDetails> { /// <summary> /// <para>Encode fields of given value.</para> /// </summary> /// <param name="value">The value.</param> /// <param name="writer">The writer.</param> public override void EncodeFields(SharingChangeLinkEnforcePasswordPolicyDetails value, enc.IJsonWriter writer) { WriteProperty("new_value", value.NewValue, writer, global::Dropbox.Api.TeamLog.ChangeLinkExpirationPolicy.Encoder); if (value.PreviousValue != null) { WriteProperty("previous_value", value.PreviousValue, writer, global::Dropbox.Api.TeamLog.ChangeLinkExpirationPolicy.Encoder); } } } #endregion #region Decoder class /// <summary> /// <para>Decoder for <see cref="SharingChangeLinkEnforcePasswordPolicyDetails" /// />.</para> /// </summary> private class SharingChangeLinkEnforcePasswordPolicyDetailsDecoder : enc.StructDecoder<SharingChangeLinkEnforcePasswordPolicyDetails> { /// <summary> /// <para>Create a new instance of type <see /// cref="SharingChangeLinkEnforcePasswordPolicyDetails" />.</para> /// </summary> /// <returns>The struct instance.</returns> protected override SharingChangeLinkEnforcePasswordPolicyDetails Create() { return new SharingChangeLinkEnforcePasswordPolicyDetails(); } /// <summary> /// <para>Set given field.</para> /// </summary> /// <param name="value">The field value.</param> /// <param name="fieldName">The field name.</param> /// <param name="reader">The json reader.</param> protected override void SetField(SharingChangeLinkEnforcePasswordPolicyDetails value, string fieldName, enc.IJsonReader reader) { switch (fieldName) { case "new_value": value.NewValue = global::Dropbox.Api.TeamLog.ChangeLinkExpirationPolicy.Decoder.Decode(reader); break; case "previous_value": value.PreviousValue = global::Dropbox.Api.TeamLog.ChangeLinkExpirationPolicy.Decoder.Decode(reader); break; default: reader.Skip(); break; } } } #endregion } }
39.178571
158
0.588879
[ "MIT" ]
MarkMichaelis/dropbox-sdk-dotnet
dropbox-sdk-dotnet/Dropbox.Api/Generated/TeamLog/SharingChangeLinkEnforcePasswordPolicyDetails.cs
5,485
C#
using System.Windows; using Stylet; namespace RyaUploader.ViewModels { public class TitleBarViewModel : Screen { private readonly IWindowManagerConfig _window; private readonly TrayIconViewModel _trayIconViewModel; public TitleBarViewModel(IWindowManagerConfig windowManager, TrayIconViewModel trayIconViewModel) { _window = windowManager; _trayIconViewModel = trayIconViewModel; } /// <summary> /// Method invoked when the user is holding leftmouse button over the whole UserControl to be able to drag the window. /// </summary> public void MoveWindow() { var window = _window.GetActiveWindow(); window.DragMove(); } /// <summary> /// Method invoked when the user clicks the close button on the window. /// This hides the window from the user but keeps it running in the background. /// </summary> public void CloseWindow() { _trayIconViewModel.IsShellVisible = Visibility.Hidden; } } }
30
126
0.632432
[ "MIT" ]
RyadaProductions/RyaUploader
RyaUploader/ViewModels/TitleBarViewModel.cs
1,112
C#