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.Collections.Generic; using UnityEngine; public class Test : MonoBehaviour { [FancyList] public List<string> testVariable; }
19.25
41
0.714286
[ "CC0-1.0" ]
sarisman84/Doing-the-thing
Assets/Editor/Test.cs
156
C#
// Copyright(c) 2007 Andreas Gullberg Larsen // https://github.com/anjdreas/UnitsNet // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System; using Xunit; namespace UnitsNet.Tests.CustomCode { public class RotationalSpeedTests : RotationalSpeedTestsBase { protected override double RadiansPerSecondInOneRadianPerSecond => 1; protected override double DeciradiansPerSecondInOneRadianPerSecond => 1E1; protected override double CentiradiansPerSecondInOneRadianPerSecond => 1E2; protected override double MilliradiansPerSecondInOneRadianPerSecond => 1E3; protected override double MicroradiansPerSecondInOneRadianPerSecond => 1E6; protected override double NanoradiansPerSecondInOneRadianPerSecond => 1E9; protected override double RevolutionsPerMinuteInOneRadianPerSecond => 9.54929659; protected override double RevolutionsPerSecondInOneRadianPerSecond => 0.15915494; protected override double DegreesPerSecondInOneRadianPerSecond => 57.29577951308; protected override double MillidegreesPerSecondInOneRadianPerSecond => 57295.77951308; protected override double MicrodegreesPerSecondInOneRadianPerSecond => 57295779.51308232; protected override double NanodegreesPerSecondInOneRadianPerSecond => 57295779513.08232087; protected override double DegreesPerMinuteInOneRadianPerSecond => 3437.74677; [Fact] public void DurationTimesRotationalSpeedEqualsAngle() { Angle angle = Duration.FromSeconds(9.0)*RotationalSpeed.FromRadiansPerSecond(10.0); Assert.Equal(angle, Angle.FromRadians(90.0)); } [Fact] public void RotationalSpeedTimesDurationEqualsAngle() { Angle angle = RotationalSpeed.FromRadiansPerSecond(10.0)*Duration.FromSeconds(9.0); Assert.Equal(angle, Angle.FromRadians(90.0)); } [Fact] public void RotationalSpeedTimesTimeSpanEqualsAngle() { Angle angle = RotationalSpeed.FromRadiansPerSecond(10.0)*TimeSpan.FromSeconds(9.0); Assert.Equal(angle, Angle.FromRadians(90.0)); } [Fact] public void TimeSpanTimesRotationalSpeedEqualsAngle() { Angle angle = TimeSpan.FromSeconds(9.0)*RotationalSpeed.FromRadiansPerSecond(10.0); Assert.Equal(angle, Angle.FromRadians(90.0)); } } }
41.843373
99
0.73222
[ "MIT" ]
Egor92/UnitsNet
UnitsNet.Tests/CustomCode/RotationalSpeedTests.cs
3,475
C#
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the textract-2018-06-27.normal.json service model. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Net; using System.Text; using System.Xml.Serialization; using Amazon.Textract.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; using ThirdParty.Json.LitJson; namespace Amazon.Textract.Model.Internal.MarshallTransformations { /// <summary> /// Response Unmarshaller for BoundingBox Object /// </summary> public class BoundingBoxUnmarshaller : IUnmarshaller<BoundingBox, XmlUnmarshallerContext>, IUnmarshaller<BoundingBox, JsonUnmarshallerContext> { /// <summary> /// Unmarshaller the response from the service to the response class. /// </summary> /// <param name="context"></param> /// <returns></returns> BoundingBox IUnmarshaller<BoundingBox, XmlUnmarshallerContext>.Unmarshall(XmlUnmarshallerContext context) { throw new NotImplementedException(); } /// <summary> /// Unmarshaller the response from the service to the response class. /// </summary> /// <param name="context"></param> /// <returns></returns> public BoundingBox Unmarshall(JsonUnmarshallerContext context) { context.Read(); if (context.CurrentTokenType == JsonToken.Null) return null; BoundingBox unmarshalledObject = new BoundingBox(); int targetDepth = context.CurrentDepth; while (context.ReadAtDepth(targetDepth)) { if (context.TestExpression("Height", targetDepth)) { var unmarshaller = FloatUnmarshaller.Instance; unmarshalledObject.Height = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("Left", targetDepth)) { var unmarshaller = FloatUnmarshaller.Instance; unmarshalledObject.Left = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("Top", targetDepth)) { var unmarshaller = FloatUnmarshaller.Instance; unmarshalledObject.Top = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("Width", targetDepth)) { var unmarshaller = FloatUnmarshaller.Instance; unmarshalledObject.Width = unmarshaller.Unmarshall(context); continue; } } return unmarshalledObject; } private static BoundingBoxUnmarshaller _instance = new BoundingBoxUnmarshaller(); /// <summary> /// Gets the singleton. /// </summary> public static BoundingBoxUnmarshaller Instance { get { return _instance; } } } }
35.136364
146
0.60414
[ "Apache-2.0" ]
ChristopherButtars/aws-sdk-net
sdk/src/Services/Textract/Generated/Model/Internal/MarshallTransformations/BoundingBoxUnmarshaller.cs
3,865
C#
using System; using UnityEngine; using RealtimeCSG; using RealtimeCSG.Components; using GeometryUtility = RealtimeCSG.GeometryUtility; namespace InternalRealtimeCSG { [Serializable] internal enum HandleConstraints { Straight, // Tangents are ignored (used for straight lines) Broken, // Both tangents are assumed to go in different directions Mirrored // Both tangents are aligned and mirror each other } [Serializable] internal struct TangentCurve2D { public Vector3 Tangent; public HandleConstraints Constraint; } [Serializable] internal class Curve2D { public Vector3[] Points; public TangentCurve2D[] Tangents; } #if !EVALUATION public #else internal #endif static class BrushUtility { public static void SetPivotToLocalCenter(CSGBrush brush) { if (!brush) return; var localCenter = BoundsUtilities.GetLocalCenter(brush); var worldCenter = brush.transform.localToWorldMatrix.MultiplyPoint(localCenter); SetPivot(brush, worldCenter); } public static void SetPivot(CSGBrush brush, Vector3 newCenter) { if (!brush) return; var transform = brush.transform; var realCenter = transform.position; var difference = newCenter - realCenter; if (difference.sqrMagnitude < MathConstants.ConsideredZero) return; transform.position += difference; GeometryUtility.MoveControlMeshVertices(brush, -difference); SurfaceUtility.TranslateSurfacesInWorldSpace(brush, -difference); ControlMeshUtility.RebuildShape(brush); } public static void TranslatePivot(CSGBrush[] brushes, Vector3 offset) { if (brushes == null || brushes.Length == 0 || offset.sqrMagnitude < MathConstants.ConsideredZero) return; for (int i = 0; i < brushes.Length; i++) brushes[i].transform.position += offset; GeometryUtility.MoveControlMeshVertices(brushes, -offset); SurfaceUtility.TranslateSurfacesInWorldSpace(brushes, -offset); ControlMeshUtility.RebuildShapes(brushes); } } }
23.939759
83
0.747358
[ "MIT" ]
Cheebang/high-stakes
Assets/Plugins/RealtimeCSG/Editor/Scripts/Control/BrushUtility.cs
1,989
C#
using System; using System.ComponentModel.DataAnnotations; namespace OnlineWallet.Infrastructure.Commands.Transactions { public class Withdraw : IAuthenticatedCommand { public Guid UserId { get; set; } [Required] [RegularExpression(@"[0-9]+(\.[0-9][0-9]?)?", ErrorMessage = "invalid value")] [Range(1.00,10000000.00)] public string Amount { get; set; } } }
25.75
86
0.643204
[ "MIT" ]
webprasanth/online-wallet
OnlineWallet.Infrastructure/Commands/Transactions/Withdraw.cs
414
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by \generate-code.bat. // // Changes to this file will be lost when the code is regenerated. // The build server regenerates the code before each build and a pre-build // step will regenerate the code on each local build. // // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. // Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // </auto-generated> //------------------------------------------------------------------------------ // Licensed under MIT No Attribution, see LICENSE file at the root. // Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. using System; using System.Globalization; using System.Linq; using JetBrains.Annotations; using UnitsNet.Units; using UnitsNet.InternalHelpers; // ReSharper disable once CheckNamespace namespace UnitsNet { /// <summary> /// Fuel efficiency is a form of thermal efficiency, meaning the ratio from effort to result of a process that converts chemical potential energy contained in a carrier (fuel) into kinetic energy or work. Fuel economy is stated as "fuel consumption" in liters per 100 kilometers (L/100 km). In countries using non-metric system, fuel economy is expressed in miles per gallon (mpg) (imperial galon or US galon). /// </summary> /// <remarks> /// https://en.wikipedia.org/wiki/Fuel_efficiency /// </remarks> // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components // Public structures can't have any members other than public fields, and those fields must be value types or strings. // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. public sealed partial class FuelEfficiency : IQuantity { /// <summary> /// The numeric value this quantity was constructed with. /// </summary> private readonly double _value; /// <summary> /// The unit this quantity was constructed with. /// </summary> private readonly FuelEfficiencyUnit? _unit; static FuelEfficiency() { BaseDimensions = BaseDimensions.Dimensionless; BaseUnit = FuelEfficiencyUnit.LiterPer100Kilometers; MaxValue = new FuelEfficiency(double.MaxValue, BaseUnit); MinValue = new FuelEfficiency(double.MinValue, BaseUnit); QuantityType = QuantityType.FuelEfficiency; Units = Enum.GetValues(typeof(FuelEfficiencyUnit)).Cast<FuelEfficiencyUnit>().Except(new FuelEfficiencyUnit[]{ FuelEfficiencyUnit.Undefined }).ToArray(); Zero = new FuelEfficiency(0, BaseUnit); Info = new QuantityInfo(QuantityType.FuelEfficiency, Units.Cast<Enum>().ToArray(), BaseUnit, Zero, BaseDimensions); } /// <summary> /// Creates the quantity with a value of 0 in the base unit LiterPer100Kilometers. /// </summary> /// <remarks> /// Windows Runtime Component requires a default constructor. /// </remarks> public FuelEfficiency() { _value = 0; _unit = BaseUnit; } /// <summary> /// Creates the quantity with the given numeric value and unit. /// </summary> /// <param name="value">The numeric value to construct this quantity with.</param> /// <param name="unit">The unit representation to construct this quantity with.</param> /// <remarks>Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component.</remarks> /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> private FuelEfficiency(double value, FuelEfficiencyUnit unit) { if (unit == FuelEfficiencyUnit.Undefined) throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); _value = Guard.EnsureValidNumber(value, nameof(value)); _unit = unit; } #region Static Properties /// <summary> /// Information about the quantity type, such as unit values and names. /// </summary> internal static QuantityInfo Info { get; } /// <summary> /// The <see cref="BaseDimensions" /> of this quantity. /// </summary> public static BaseDimensions BaseDimensions { get; } /// <summary> /// The base unit of FuelEfficiency, which is LiterPer100Kilometers. All conversions go via this value. /// </summary> public static FuelEfficiencyUnit BaseUnit { get; } /// <summary> /// Represents the largest possible value of FuelEfficiency /// </summary> public static FuelEfficiency MaxValue { get; } /// <summary> /// Represents the smallest possible value of FuelEfficiency /// </summary> public static FuelEfficiency MinValue { get; } /// <summary> /// The <see cref="QuantityType" /> of this quantity. /// </summary> [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] public static QuantityType QuantityType { get; } /// <summary> /// All units of measurement for the FuelEfficiency quantity. /// </summary> public static FuelEfficiencyUnit[] Units { get; } /// <summary> /// Gets an instance of this quantity with a value of 0 in the base unit LiterPer100Kilometers. /// </summary> public static FuelEfficiency Zero { get; } #endregion #region Properties /// <summary> /// The numeric value this quantity was constructed with. /// </summary> public double Value => Convert.ToDouble(_value); /// <inheritdoc cref="IQuantity.Unit"/> object IQuantity.Unit => Unit; /// <summary> /// The unit this quantity was constructed with -or- <see cref="BaseUnit" /> if default ctor was used. /// </summary> public FuelEfficiencyUnit Unit => _unit.GetValueOrDefault(BaseUnit); internal QuantityInfo QuantityInfo => Info; /// <summary> /// The <see cref="QuantityType" /> of this quantity. /// </summary> [Obsolete("QuantityType will be removed in the future. Use the Info property instead.")] public QuantityType Type => FuelEfficiency.QuantityType; /// <summary> /// The <see cref="BaseDimensions" /> of this quantity. /// </summary> public BaseDimensions Dimensions => FuelEfficiency.BaseDimensions; #endregion #region Conversion Properties /// <summary> /// Gets a <see cref="double"/> value of this quantity converted into <see cref="FuelEfficiencyUnit.KilometerPerLiter"/> /// </summary> public double KilometersPerLiters => As(FuelEfficiencyUnit.KilometerPerLiter); /// <summary> /// Gets a <see cref="double"/> value of this quantity converted into <see cref="FuelEfficiencyUnit.LiterPer100Kilometers"/> /// </summary> public double LitersPer100Kilometers => As(FuelEfficiencyUnit.LiterPer100Kilometers); /// <summary> /// Gets a <see cref="double"/> value of this quantity converted into <see cref="FuelEfficiencyUnit.MilePerUkGallon"/> /// </summary> public double MilesPerUkGallon => As(FuelEfficiencyUnit.MilePerUkGallon); /// <summary> /// Gets a <see cref="double"/> value of this quantity converted into <see cref="FuelEfficiencyUnit.MilePerUsGallon"/> /// </summary> public double MilesPerUsGallon => As(FuelEfficiencyUnit.MilePerUsGallon); #endregion #region Static Methods internal static void MapGeneratedLocalizations(UnitAbbreviationsCache unitAbbreviationsCache) { unitAbbreviationsCache.PerformAbbreviationMapping(FuelEfficiencyUnit.KilometerPerLiter, new CultureInfo("en-US"), false, true, new string[]{"km/L"}); unitAbbreviationsCache.PerformAbbreviationMapping(FuelEfficiencyUnit.LiterPer100Kilometers, new CultureInfo("en-US"), false, true, new string[]{"L/100km"}); unitAbbreviationsCache.PerformAbbreviationMapping(FuelEfficiencyUnit.MilePerUkGallon, new CultureInfo("en-US"), false, true, new string[]{"mpg (imp.)"}); unitAbbreviationsCache.PerformAbbreviationMapping(FuelEfficiencyUnit.MilePerUsGallon, new CultureInfo("en-US"), false, true, new string[]{"mpg (U.S.)"}); } /// <summary> /// Get unit abbreviation string. /// </summary> /// <param name="unit">Unit to get abbreviation for.</param> /// <returns>Unit abbreviation string.</returns> public static string GetAbbreviation(FuelEfficiencyUnit unit) { return GetAbbreviation(unit, null); } /// <summary> /// Get unit abbreviation string. /// </summary> /// <param name="unit">Unit to get abbreviation for.</param> /// <returns>Unit abbreviation string.</returns> /// <param name="cultureName">Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to <see cref="GlobalConfiguration.DefaultCulture" /> if null.</param> public static string GetAbbreviation(FuelEfficiencyUnit unit, [CanBeNull] string cultureName) { IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); } #endregion #region Static Factory Methods /// <summary> /// Creates a <see cref="FuelEfficiency"/> from <see cref="FuelEfficiencyUnit.KilometerPerLiter"/>. /// </summary> /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> [Windows.Foundation.Metadata.DefaultOverload] public static FuelEfficiency FromKilometersPerLiters(double kilometersperliters) { double value = (double) kilometersperliters; return new FuelEfficiency(value, FuelEfficiencyUnit.KilometerPerLiter); } /// <summary> /// Creates a <see cref="FuelEfficiency"/> from <see cref="FuelEfficiencyUnit.LiterPer100Kilometers"/>. /// </summary> /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> [Windows.Foundation.Metadata.DefaultOverload] public static FuelEfficiency FromLitersPer100Kilometers(double litersper100kilometers) { double value = (double) litersper100kilometers; return new FuelEfficiency(value, FuelEfficiencyUnit.LiterPer100Kilometers); } /// <summary> /// Creates a <see cref="FuelEfficiency"/> from <see cref="FuelEfficiencyUnit.MilePerUkGallon"/>. /// </summary> /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> [Windows.Foundation.Metadata.DefaultOverload] public static FuelEfficiency FromMilesPerUkGallon(double milesperukgallon) { double value = (double) milesperukgallon; return new FuelEfficiency(value, FuelEfficiencyUnit.MilePerUkGallon); } /// <summary> /// Creates a <see cref="FuelEfficiency"/> from <see cref="FuelEfficiencyUnit.MilePerUsGallon"/>. /// </summary> /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> [Windows.Foundation.Metadata.DefaultOverload] public static FuelEfficiency FromMilesPerUsGallon(double milesperusgallon) { double value = (double) milesperusgallon; return new FuelEfficiency(value, FuelEfficiencyUnit.MilePerUsGallon); } /// <summary> /// Dynamically convert from value and unit enum <see cref="FuelEfficiencyUnit" /> to <see cref="FuelEfficiency" />. /// </summary> /// <param name="value">Value to convert from.</param> /// <param name="fromUnit">Unit to convert from.</param> /// <returns>FuelEfficiency unit value.</returns> // Fix name conflict with parameter "value" [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] public static FuelEfficiency From(double value, FuelEfficiencyUnit fromUnit) { return new FuelEfficiency((double)value, fromUnit); } #endregion #region Static Parse Methods /// <summary> /// Parse a string with one or two quantities of the format "&lt;quantity&gt; &lt;unit&gt;". /// </summary> /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> /// <example> /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// </example> /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> /// <exception cref="ArgumentException"> /// Expected string to have one or two pairs of quantity and unit in the format /// "&lt;quantity&gt; &lt;unit&gt;". Eg. "5.5 m" or "1ft 2in" /// </exception> /// <exception cref="AmbiguousUnitParseException"> /// More than one unit is represented by the specified unit abbreviation. /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. /// </exception> /// <exception cref="UnitsNetException"> /// If anything else goes wrong, typically due to a bug or unhandled case. /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish /// Units.NET exceptions from other exceptions. /// </exception> public static FuelEfficiency Parse(string str) { return Parse(str, null); } /// <summary> /// Parse a string with one or two quantities of the format "&lt;quantity&gt; &lt;unit&gt;". /// </summary> /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> /// <example> /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// </example> /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> /// <exception cref="ArgumentException"> /// Expected string to have one or two pairs of quantity and unit in the format /// "&lt;quantity&gt; &lt;unit&gt;". Eg. "5.5 m" or "1ft 2in" /// </exception> /// <exception cref="AmbiguousUnitParseException"> /// More than one unit is represented by the specified unit abbreviation. /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. /// </exception> /// <exception cref="UnitsNetException"> /// If anything else goes wrong, typically due to a bug or unhandled case. /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish /// Units.NET exceptions from other exceptions. /// </exception> /// <param name="cultureName">Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to <see cref="GlobalConfiguration.DefaultCulture" /> if null.</param> public static FuelEfficiency Parse(string str, [CanBeNull] string cultureName) { IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); return QuantityParser.Default.Parse<FuelEfficiency, FuelEfficiencyUnit>( str, provider, From); } /// <summary> /// Try to parse a string with one or two quantities of the format "&lt;quantity&gt; &lt;unit&gt;". /// </summary> /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> /// <param name="result">Resulting unit quantity if successful.</param> /// <example> /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// </example> public static bool TryParse([CanBeNull] string str, out FuelEfficiency result) { return TryParse(str, null, out result); } /// <summary> /// Try to parse a string with one or two quantities of the format "&lt;quantity&gt; &lt;unit&gt;". /// </summary> /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> /// <param name="result">Resulting unit quantity if successful.</param> /// <returns>True if successful, otherwise false.</returns> /// <example> /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// </example> /// <param name="cultureName">Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to <see cref="GlobalConfiguration.DefaultCulture" /> if null.</param> public static bool TryParse([CanBeNull] string str, [CanBeNull] string cultureName, out FuelEfficiency result) { IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); return QuantityParser.Default.TryParse<FuelEfficiency, FuelEfficiencyUnit>( str, provider, From, out result); } /// <summary> /// Parse a unit string. /// </summary> /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> /// <example> /// Length.ParseUnit("m", new CultureInfo("en-US")); /// </example> /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> /// <exception cref="UnitsNetException">Error parsing string.</exception> public static FuelEfficiencyUnit ParseUnit(string str) { return ParseUnit(str, null); } /// <summary> /// Parse a unit string. /// </summary> /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> /// <example> /// Length.ParseUnit("m", new CultureInfo("en-US")); /// </example> /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> /// <exception cref="UnitsNetException">Error parsing string.</exception> /// <param name="cultureName">Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to <see cref="GlobalConfiguration.DefaultCulture" /> if null.</param> public static FuelEfficiencyUnit ParseUnit(string str, [CanBeNull] string cultureName) { IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); return UnitParser.Default.Parse<FuelEfficiencyUnit>(str, provider); } public static bool TryParseUnit(string str, out FuelEfficiencyUnit unit) { return TryParseUnit(str, null, out unit); } /// <summary> /// Parse a unit string. /// </summary> /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> /// <param name="unit">The parsed unit if successful.</param> /// <returns>True if successful, otherwise false.</returns> /// <example> /// Length.TryParseUnit("m", new CultureInfo("en-US")); /// </example> /// <param name="cultureName">Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to <see cref="GlobalConfiguration.DefaultCulture" /> if null.</param> public static bool TryParseUnit(string str, [CanBeNull] string cultureName, out FuelEfficiencyUnit unit) { IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); return UnitParser.Default.TryParse<FuelEfficiencyUnit>(str, provider, out unit); } #endregion #region Equality / IComparable public int CompareTo(object obj) { if (obj is null) throw new ArgumentNullException(nameof(obj)); if (!(obj is FuelEfficiency objFuelEfficiency)) throw new ArgumentException("Expected type FuelEfficiency.", nameof(obj)); return CompareTo(objFuelEfficiency); } // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods internal int CompareTo(FuelEfficiency other) { return _value.CompareTo(other.AsBaseNumericType(this.Unit)); } [Windows.Foundation.Metadata.DefaultOverload] public override bool Equals(object obj) { if (obj is null || !(obj is FuelEfficiency objFuelEfficiency)) return false; return Equals(objFuelEfficiency); } public bool Equals(FuelEfficiency other) { return _value.Equals(other.AsBaseNumericType(this.Unit)); } /// <summary> /// <para> /// Compare equality to another FuelEfficiency within the given absolute or relative tolerance. /// </para> /// <para> /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and /// <paramref name="other"/> as a percentage of this quantity's value. <paramref name="other"/> will be converted into /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of /// this quantity's value to be considered equal. /// <example> /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). /// <code> /// var a = Length.FromMeters(2.0); /// var b = Length.FromInches(50.0); /// a.Equals(b, 0.01, ComparisonType.Relative); /// </code> /// </example> /// </para> /// <para> /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and /// <paramref name="other"/> as a fixed number in this quantity's unit. <paramref name="other"/> will be converted into /// this quantity's unit for comparison. /// <example> /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). /// <code> /// var a = Length.FromMeters(2.0); /// var b = Length.FromInches(50.0); /// a.Equals(b, 0.01, ComparisonType.Absolute); /// </code> /// </example> /// </para> /// <para> /// Note that it is advised against specifying zero difference, due to the nature /// of floating point operations and using System.Double internally. /// </para> /// </summary> /// <param name="other">The other quantity to compare to.</param> /// <param name="tolerance">The absolute or relative tolerance value. Must be greater than or equal to 0.</param> /// <param name="comparisonType">The comparison type: either relative or absolute.</param> /// <returns>True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance.</returns> public bool Equals(FuelEfficiency other, double tolerance, ComparisonType comparisonType) { if (tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); double thisValue = (double)this.Value; double otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); } /// <summary> /// Returns the hash code for this instance. /// </summary> /// <returns>A hash code for the current FuelEfficiency.</returns> public override int GetHashCode() { return new { Info.Name, Value, Unit }.GetHashCode(); } #endregion #region Conversion Methods double IQuantity.As(object unit) => As((FuelEfficiencyUnit)unit); /// <summary> /// Convert to the unit representation <paramref name="unit" />. /// </summary> /// <returns>Value converted to the specified unit.</returns> public double As(FuelEfficiencyUnit unit) { if (Unit == unit) return Convert.ToDouble(Value); var converted = AsBaseNumericType(unit); return Convert.ToDouble(converted); } /// <summary> /// Converts this FuelEfficiency to another FuelEfficiency with the unit representation <paramref name="unit" />. /// </summary> /// <returns>A FuelEfficiency with the specified unit.</returns> public FuelEfficiency ToUnit(FuelEfficiencyUnit unit) { var convertedValue = AsBaseNumericType(unit); return new FuelEfficiency(convertedValue, unit); } /// <summary> /// Converts the current value + unit to the base unit. /// This is typically the first step in converting from one unit to another. /// </summary> /// <returns>The value in the base unit representation.</returns> private double AsBaseUnit() { switch(Unit) { case FuelEfficiencyUnit.KilometerPerLiter: return 100 / _value; case FuelEfficiencyUnit.LiterPer100Kilometers: return _value; case FuelEfficiencyUnit.MilePerUkGallon: return (100 * 4.54609188) / (1.609344 * _value); case FuelEfficiencyUnit.MilePerUsGallon: return (100 * 3.785411784) / (1.609344 * _value); default: throw new NotImplementedException($"Can not convert {Unit} to base units."); } } private double AsBaseNumericType(FuelEfficiencyUnit unit) { if (Unit == unit) return _value; var baseUnitValue = AsBaseUnit(); switch(unit) { case FuelEfficiencyUnit.KilometerPerLiter: return 100 / baseUnitValue; case FuelEfficiencyUnit.LiterPer100Kilometers: return baseUnitValue; case FuelEfficiencyUnit.MilePerUkGallon: return (100 * 4.54609188) / (1.609344 * baseUnitValue); case FuelEfficiencyUnit.MilePerUsGallon: return (100 * 3.785411784) / (1.609344 * baseUnitValue); default: throw new NotImplementedException($"Can not convert {Unit} to {unit}."); } } #endregion #region ToString Methods /// <summary> /// Get default string representation of value and unit. /// </summary> /// <returns>String representation.</returns> public override string ToString() { return ToString(null); } /// <summary> /// Get string representation of value and unit. Using two significant digits after radix. /// </summary> /// <returns>String representation.</returns> /// <param name="cultureName">Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to <see cref="GlobalConfiguration.DefaultCulture" /> if null.</param> public string ToString([CanBeNull] string cultureName) { var provider = cultureName; return ToString(provider, 2); } /// <summary> /// Get string representation of value and unit. /// </summary> /// <param name="significantDigitsAfterRadix">The number of significant digits after the radix point.</param> /// <returns>String representation.</returns> /// <param name="cultureName">Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to <see cref="GlobalConfiguration.DefaultCulture" /> if null.</param> public string ToString(string cultureName, int significantDigitsAfterRadix) { var provider = cultureName; var value = Convert.ToDouble(Value); var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); return ToString(provider, format); } /// <summary> /// Get string representation of value and unit. /// </summary> /// <param name="format">String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively."</param> /// <param name="args">Arguments for string format. Value and unit are implicitly included as arguments 0 and 1.</param> /// <returns>String representation.</returns> /// <param name="cultureName">Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to <see cref="GlobalConfiguration.DefaultCulture" /> if null.</param> public string ToString([CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) { var provider = GetFormatProviderFromCultureName(cultureName); if (format == null) throw new ArgumentNullException(nameof(format)); if (args == null) throw new ArgumentNullException(nameof(args)); provider = provider ?? GlobalConfiguration.DefaultCulture; var value = Convert.ToDouble(Value); var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); return string.Format(provider, format, formatArgs); } #endregion private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) { return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; } } }
47.868502
418
0.61937
[ "MIT-feh" ]
AIKICo/UnitsNet
UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/FuelEfficiency.g.cs
31,306
C#
namespace IndustryLP.Utils.Enums { public enum CellNeighbour { UP, DOWN, LEFT, RIGHT } }
13.75
33
0.609091
[ "MIT" ]
NEKERAFA/CS-IndustryLP
IndustryLP/Utils/Enums/CellNeighbour.cs
112
C#
using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Linq; using Dapper; using Repository.Interface; using Repository.Schema; namespace Repository.Implementation { public class GameTypeRepository : IGameTypeRepository { public GameTypeRepository() { new DapperHelper(); } public int Insert(GameTypeModel obj) { using (IDbConnection connection = new SqlConnection(ConnectionStrings.Core)) { return connection .Query<int>( "sp_insert_game_type", new { obj.Name, obj.Description }, commandType: CommandType.StoredProcedure) .Single(); } } public List<GameTypeModel> SelectList() { using (IDbConnection connection = new SqlConnection(ConnectionStrings.Core)) { return connection .Query<GameTypeModel>( "sp_select_list_game_type", commandType: CommandType.StoredProcedure) .ToList(); } } } }
28.022727
88
0.538524
[ "MIT" ]
charleyza/DunkMe
Repository/Implementation/GameTypeRepository.cs
1,235
C#
#region License // Copyright (c) 2007 James Newton-King // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. #endregion using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; #if NET20 using Newtonsoft.Json.Utilities.LinqBridge; #else using System.Linq; #endif using Newtonsoft.Json.Linq; #if DNXCORE50 using Xunit; using Test = Xunit.FactAttribute; using Assert = Newtonsoft.Json.Tests.XUnitAssert; #else using NUnit.Framework; #endif using System.IO; namespace Newtonsoft.Json.Tests.Linq { [TestFixture] public class JPropertyTests : TestFixtureBase { [Test] public void NullValue() { JProperty p = new JProperty("TestProperty", null); Assert.IsNotNull(p.Value); Assert.AreEqual(JTokenType.Null, p.Value.Type); Assert.AreEqual(p, p.Value.Parent); p.Value = null; Assert.IsNotNull(p.Value); Assert.AreEqual(JTokenType.Null, p.Value.Type); Assert.AreEqual(p, p.Value.Parent); } #if !(PORTABLE || DNXCORE50 || PORTABLE40) [Test] public void ListChanged() { JProperty p = new JProperty("TestProperty", null); IBindingList l = p; ListChangedType? listChangedType = null; int? index = null; l.ListChanged += (sender, args) => { listChangedType = args.ListChangedType; index = args.NewIndex; }; p.Value = 1; Assert.AreEqual(ListChangedType.ItemChanged, listChangedType.Value); Assert.AreEqual(0, index.Value); } #endif [Test] public void IListCount() { JProperty p = new JProperty("TestProperty", null); IList l = p; Assert.AreEqual(1, l.Count); } [Test] public void IListClear() { JProperty p = new JProperty("TestProperty", null); IList l = p; ExceptionAssert.Throws<JsonException>(() => { l.Clear(); }, "Cannot add or remove items from Newtonsoft.Json.Linq.JProperty."); } [Test] public void IListAdd() { JProperty p = new JProperty("TestProperty", null); IList l = p; ExceptionAssert.Throws<JsonException>(() => { l.Add(null); }, "Newtonsoft.Json.Linq.JProperty cannot have multiple values."); } [Test] public void IListRemove() { JProperty p = new JProperty("TestProperty", null); IList l = p; ExceptionAssert.Throws<JsonException>(() => { l.Remove(p.Value); }, "Cannot add or remove items from Newtonsoft.Json.Linq.JProperty."); } [Test] public void IListRemoveAt() { JProperty p = new JProperty("TestProperty", null); IList l = p; ExceptionAssert.Throws<JsonException>(() => { l.RemoveAt(0); }, "Cannot add or remove items from Newtonsoft.Json.Linq.JProperty."); } [Test] public void JPropertyLinq() { JProperty p = new JProperty("TestProperty", null); IList l = p; List<JToken> result = l.Cast<JToken>().ToList(); Assert.AreEqual(1, result.Count); } [Test] public void JPropertyDeepEquals() { JProperty p1 = new JProperty("TestProperty", null); JProperty p2 = new JProperty("TestProperty", null); Assert.AreEqual(true, JToken.DeepEquals(p1, p2)); } [Test] public void JPropertyIndexOf() { JValue v = new JValue(1); JProperty p1 = new JProperty("TestProperty", v); IList l1 = p1; Assert.AreEqual(0, l1.IndexOf(v)); IList<JToken> l2 = p1; Assert.AreEqual(0, l2.IndexOf(v)); } [Test] public void JPropertyContains() { JValue v = new JValue(1); JProperty p = new JProperty("TestProperty", v); Assert.AreEqual(true, p.Contains(v)); Assert.AreEqual(false, p.Contains(new JValue(1))); } [Test] public void Load() { JsonReader reader = new JsonTextReader(new StringReader("{'propertyname':['value1']}")); reader.Read(); Assert.AreEqual(JsonToken.StartObject, reader.TokenType); reader.Read(); JProperty property = JProperty.Load(reader); Assert.AreEqual("propertyname", property.Name); Assert.IsTrue(JToken.DeepEquals(JArray.Parse("['value1']"), property.Value)); Assert.AreEqual(JsonToken.EndObject, reader.TokenType); reader = new JsonTextReader(new StringReader("{'propertyname':null}")); reader.Read(); Assert.AreEqual(JsonToken.StartObject, reader.TokenType); reader.Read(); property = JProperty.Load(reader); Assert.AreEqual("propertyname", property.Name); Assert.IsTrue(JToken.DeepEquals(JValue.CreateNull(), property.Value)); Assert.AreEqual(JsonToken.EndObject, reader.TokenType); } [Test] public void MultiContentConstructor() { JProperty p = new JProperty("error", new List<string> { "one", "two" }); JArray a = (JArray)p.Value; Assert.AreEqual(a.Count, 2); Assert.AreEqual("one", (string)a[0]); Assert.AreEqual("two", (string)a[1]); } [Test] public void IListGenericAdd() { IList<JToken> t = new JProperty("error", new List<string> { "one", "two" }); ExceptionAssert.Throws<JsonException>(() => { t.Add(1); }, "Newtonsoft.Json.Linq.JProperty cannot have multiple values."); } [Test] public void NullParent() { var json = @"{ ""prop1"": { ""foo"": ""bar"" }, }"; var obj = JsonConvert.DeserializeObject<JObject>(json); var property = obj.Property("prop1"); var value = property.Value; // remove value so it has no parent property.Value = null; property.Remove(); obj.Add(new JProperty("prop2", value)); Assert.AreEqual(((JProperty)value.Parent).Name, "prop2"); } } }
31.036885
147
0.580747
[ "MIT" ]
0xced/Newtonsoft.Json
Src/Newtonsoft.Json.Tests/Linq/JPropertyTests.cs
7,575
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.ML.Core.Data; using Microsoft.ML.Runtime.Data; using Microsoft.ML.Runtime.KMeans; using Microsoft.ML.Runtime.Learners; using Microsoft.ML.Runtime.PCA; using Microsoft.ML.Runtime.RunTests; using Xunit; using Xunit.Abstractions; namespace Microsoft.ML.Tests.TrainerEstimators { public partial class TrainerEstimators : TestDataPipeBase { public TrainerEstimators(ITestOutputHelper helper) : base(helper) { } /// <summary> /// FastTreeBinaryClassification TrainerEstimator test /// </summary> [Fact] public void PCATrainerEstimator() { string featureColumn = "NumericFeatures"; var reader = new TextLoader(Env, new TextLoader.Arguments() { HasHeader = true, Separator = "\t", Column = new[] { new TextLoader.Column(featureColumn, DataKind.R4, new [] { new TextLoader.Range(1, 784) }) } }); var data = reader.Read(new MultiFileSource(GetDataPath(TestDatasets.mnistOneClass.trainFilename))); // Pipeline. var pipeline = new RandomizedPcaTrainer(Env, featureColumn, rank:10); TestEstimatorCore(pipeline, data); Done(); } /// <summary> /// KMeans TrainerEstimator test /// </summary> [Fact] public void KMeansEstimator() { string featureColumn = "NumericFeatures"; string weights = "Weights"; var reader = new TextLoader(Env, new TextLoader.Arguments { HasHeader = true, Separator = "\t", Column = new[] { new TextLoader.Column(featureColumn, DataKind.R4, new [] { new TextLoader.Range(1, 784) }), new TextLoader.Column(weights, DataKind.R4, 0) } }); var data = reader.Read(new MultiFileSource(GetDataPath(TestDatasets.mnistTiny28.trainFilename))); // Pipeline. var pipeline = new KMeansPlusPlusTrainer(Env, featureColumn, weightColumn: weights, advancedSettings: s => { s.InitAlgorithm = KMeansPlusPlusTrainer.InitAlgorithm.KMeansParallel; }); TestEstimatorCore(pipeline, data); Done(); } private (IEstimator<ITransformer>, IDataView) GetBinaryClassificationPipeline() { var data = new TextLoader(Env, new TextLoader.Arguments() { Separator = "\t", HasHeader = true, Column = new[] { new TextLoader.Column("Label", DataKind.BL, 0), new TextLoader.Column("SentimentText", DataKind.Text, 1) } }).Read(new MultiFileSource(GetDataPath(TestDatasets.Sentiment.trainFilename))); // Pipeline. var pipeline = new TextTransform(Env, "SentimentText", "Features"); return (pipeline, data); } private (IEstimator<ITransformer>, IDataView) GetRankingPipeline() { var data = new TextLoader(Env, new TextLoader.Arguments { HasHeader = true, Separator = "\t", Column = new[] { new TextLoader.Column("Label", DataKind.R4, 0), new TextLoader.Column("Workclass", DataKind.Text, 1), new TextLoader.Column("NumericFeatures", DataKind.R4, new [] { new TextLoader.Range(9, 14) }) } }).Read(new MultiFileSource(GetDataPath(TestDatasets.adultRanking.trainFilename))); // Pipeline. var pipeline = new TermEstimator(Env, new[]{ new TermTransform.ColumnInfo("Workclass", "Group"), new TermTransform.ColumnInfo("Label", "Label0") }); return (pipeline, data); } private IDataView GetRegressionPipeline() { return new TextLoader(Env, new TextLoader.Arguments() { Separator = ";", HasHeader = true, Column = new[] { new TextLoader.Column("Label", DataKind.R4, 11), new TextLoader.Column("Features", DataKind.R4, new [] { new TextLoader.Range(0, 10) } ) } }).Read(new MultiFileSource(GetDataPath(TestDatasets.generatedRegressionDatasetmacro.trainFilename))); } private TextLoader.Arguments GetIrisLoaderArgs() { return new TextLoader.Arguments() { Separator = "comma", HasHeader = true, Column = new[] { new TextLoader.Column("Features", DataKind.R4, new [] { new TextLoader.Range(0, 3) }), new TextLoader.Column("Label", DataKind.Text, 4) } }; } private (IEstimator<ITransformer>, IDataView) GetMultiClassPipeline() { var data = new TextLoader(Env, new TextLoader.Arguments() { Separator = "comma", HasHeader = true, Column = new[] { new TextLoader.Column("Features", DataKind.R4, new [] { new TextLoader.Range(0, 3) }), new TextLoader.Column("Label", DataKind.Text, 4) } }) .Read(new MultiFileSource(GetDataPath(IrisDataPath))); var pipeline = new TermEstimator(Env, "Label"); return (pipeline, data); } } }
36.526012
126
0.510999
[ "MIT" ]
DAXaholic/machinelearning
test/Microsoft.ML.Tests/TrainerEstimators/TrainerEstimators.cs
6,321
C#
namespace AnnoSavegameViewer.Structures.Savegame.Generated { public class RecommendedPosition { } }
17.5
60
0.8
[ "MIT" ]
Veraatversus/AnnoSavegameViewer
src/AnnoSavegameViewer/GeneratedA7s/Structures/Savegame2/Generated/Empty/RecommendedPosition.cs
105
C#
using UnityEngine; using System.Collections; using thelab.core; public class TweenExample01 : MonoBehaviour { public Transform target; public Transform position; // Use this for initialization void Start () { } void Update() { if(Input.GetKeyDown(KeyCode.Space)) { DoTween(); } float r = 2.5f; float w0 = Mathf.Sin(Time.time * 360f * Mathf.Deg2Rad * 0.5f) * r * 0.25f; float w1 = Mathf.Cos(Time.time * 360f * Mathf.Deg2Rad * 0.3f) * r * 1f; float w2 = Mathf.Sin(Time.time * 360f * Mathf.Deg2Rad * 0.2f) * r * 2f; Vector3 pos = new Vector3(w0 + w1, w1 + w2, w0 + w2); position.position = pos; } public void DoTween() { Tween.Add<Vector3>(target,"position",position.position,0.5f,Elastic.OutBig); } }
22.923077
85
0.54698
[ "Apache-2.0" ]
xiaogangliu/shangduli
shangduli/Assets/thelab/core/examples/tween/TweenExample01.cs
896
C#
/* Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. * Use of this file is governed by the BSD 3-clause license that * can be found in the LICENSE.txt file in the project root. */ using System.Collections.Generic; using Antlr4.Runtime.Sharpen; using Antlr4.Runtime.Tree; using Antlr4.Runtime.Tree.Xpath; namespace Antlr4.Runtime.Tree.Xpath { public class XPathWildcardAnywhereElement : XPathElement { public XPathWildcardAnywhereElement() : base(XPath.Wildcard) { } public override ICollection<IParseTree> Evaluate(IParseTree t) { if (invert) { return new List<IParseTree>(); } // !* is weird but valid (empty) return Trees.Descendants(t); } } }
27.1
70
0.624846
[ "BSD-3-Clause" ]
charwliu/antlr4
runtime/CSharp/runtime/CSharp/Antlr4.Runtime/Tree/Xpath/XPathWildcardAnywhereElement.cs
813
C#
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Text.RegularExpressions; using System.Threading.Tasks; using System.Windows.Forms; namespace Alarm_Clock_App { public class WorldClockClass { public string Place { get; set; } public string ID { get; set; } public async static void GetTimeOfPlace(string place, Label exitbox, bool isRecent = false) { using (HttpClient client = new HttpClient()) { string URL = string.Format("https://www.google.com/search?q=time+in+{0}", place.Replace(" ", "+")); HttpResponseMessage response = await client.GetAsync(URL); string content = await response.Content.ReadAsStringAsync(); Regex rx = new Regex(@"\d+:\d+\s..", RegexOptions.Compiled); // \d+:\d+\s.. Match m = rx.Match(content); if (m.Length == 0) { exitbox.Text = "No Result Found"; } else { exitbox.Text = string.Format("Time in {0}: {1}", place, m.ToString()); if (!isRecent) { WorldClockClass toSave = new WorldClockClass(); toSave.Place = place; DatabaseConnection.SaveWorldClockItem(toSave); Tabs.WorldClock.loadRecents(); } } } } } }
31
115
0.501861
[ "MIT" ]
RefinedDev/Alarm-Clock-App
Classes/WorldClock.cs
1,614
C#
using System; using System.Collections.Generic; using System.ComponentModel; using System.Windows.Forms; using System.Diagnostics; using Kitware.VTK; namespace ActiViz.Examples { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void renderWindowControl1_Load(object sender, EventArgs e) { try { Pyramid(); } catch(Exception ex) { MessageBox.Show(ex.Message, "Exception", MessageBoxButtons.OK); } } private void Pyramid() { vtkPoints points = vtkPoints.New(); double[,] p = new double[,] { { 1.0, 1.0, 1.0 }, {-1.0, 1.0, 1.0 }, {-1.0, -1.0, 1.0 }, { 1.0, -1.0, 1.0 }, { 0.0, 0.0, 0.0 }}; for(int i = 0; i < 5; i++) points.InsertNextPoint(p[i, 0], p[i, 1], p[i, 2]); vtkPyramid pyramid = vtkPyramid.New(); for(int i = 0; i < 5; i++) pyramid.GetPointIds().SetId(i, i); vtkCellArray cells = vtkCellArray.New(); cells.InsertNextCell(pyramid); vtkUnstructuredGrid ug = vtkUnstructuredGrid.New(); ug.SetPoints(points); ug.InsertNextCell(pyramid.GetCellType(), pyramid.GetPointIds()); //Create an actor and mapper vtkDataSetMapper mapper = vtkDataSetMapper.New(); mapper.SetInput(ug); vtkActor actor = vtkActor.New(); actor.RotateX(105.0); actor.RotateZ(-36.0); actor.SetMapper(mapper); vtkRenderWindow renderWindow = renderWindowControl1.RenderWindow; vtkRenderer renderer = renderWindow.GetRenderers().GetFirstRenderer(); renderer.SetBackground(0.2, 0.3, 0.4); renderer.AddActor(actor); renderer.ResetCamera(); } } }
28.984375
79
0.56496
[ "Apache-2.0" ]
FlorianFritz/VTKExamples
src/CSharp/GeometricObjects/Pyramid.cs
1,855
C#
// <auto-generated /> using System; using IdentityServer4.EntityFramework.DbContexts; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Migrations; using Microsoft.EntityFrameworkCore.Storage.ValueConversion; namespace Identity.Server.Migrations.PersistedGrantDb { [DbContext(typeof(PersistedGrantDbContext))] [Migration("20180705071639_InitialSetup")] partial class InitialSetup { protected override void BuildTargetModel(ModelBuilder modelBuilder) { #pragma warning disable 612, 618 modelBuilder .HasAnnotation("ProductVersion", "2.1.1-rtm-30846") .HasAnnotation("Relational:MaxIdentifierLength", 128) .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.PersistedGrant", b => { b.Property<string>("Key") .HasMaxLength(200); b.Property<string>("ClientId") .IsRequired() .HasMaxLength(200); b.Property<DateTime>("CreationTime"); b.Property<string>("Data") .IsRequired() .HasMaxLength(50000); b.Property<DateTime?>("Expiration"); b.Property<string>("SubjectId") .HasMaxLength(200); b.Property<string>("Type") .IsRequired() .HasMaxLength(50); b.HasKey("Key"); b.HasIndex("SubjectId", "ClientId", "Type"); b.ToTable("PersistedGrants"); }); #pragma warning restore 612, 618 } } }
34.793103
118
0.561447
[ "MIT" ]
hdnebat/Microservices
Identity/Identity.Server/Migrations/PersistedGrantDb/20180705071639_InitialSetup.Designer.cs
2,020
C#
/*============================================================================== Copyright (c) 2016-2018 PTC Inc. All Rights Reserved. Copyright (c) 2015 Qualcomm Connected Experiences, Inc. All Rights Reserved. Vuforia is a trademark of PTC Inc., registered in the United States and other countries. * ==============================================================================*/ using UnityEngine; using System.Collections.Generic; using System.Linq; using Vuforia; public class UDTEventHandler : MonoBehaviour, IUserDefinedTargetEventHandler { #region PUBLIC_MEMBERS /// <summary> /// Can be set in the Unity inspector to reference an ImageTargetBehaviour /// that is instantiated for augmentations of new User-Defined Targets. /// </summary> public ImageTargetBehaviour ImageTargetTemplate; public int LastTargetIndex { get { return (m_TargetCounter - 1) % MAX_TARGETS; } } #endregion PUBLIC_MEMBERS #region PRIVATE_MEMBERS const int MAX_TARGETS = 5; UserDefinedTargetBuildingBehaviour m_TargetBuildingBehaviour; ObjectTracker m_ObjectTracker; FrameQualityMeter m_FrameQualityMeter; // DataSet that newly defined targets are added to DataSet m_UDT_DataSet; // Currently observed frame quality ImageTargetBuilder.FrameQuality m_FrameQuality = ImageTargetBuilder.FrameQuality.FRAME_QUALITY_NONE; // Counter used to name newly created targets int m_TargetCounter; #endregion //PRIVATE_MEMBERS #region MONOBEHAVIOUR_METHODS void Start() { m_TargetBuildingBehaviour = GetComponent<UserDefinedTargetBuildingBehaviour>(); if (m_TargetBuildingBehaviour) { m_TargetBuildingBehaviour.RegisterEventHandler(this); Debug.Log("Registering User Defined Target event handler."); } m_FrameQualityMeter = FindObjectOfType<FrameQualityMeter>(); } #endregion //MONOBEHAVIOUR_METHODS #region IUserDefinedTargetEventHandler Implementation /// <summary> /// Called when UserDefinedTargetBuildingBehaviour has been initialized successfully /// </summary> public void OnInitialized() { m_ObjectTracker = TrackerManager.Instance.GetTracker<ObjectTracker>(); if (m_ObjectTracker != null) { // Create a new dataset m_UDT_DataSet = m_ObjectTracker.CreateDataSet(); m_ObjectTracker.ActivateDataSet(m_UDT_DataSet); } } /// <summary> /// Updates the current frame quality /// </summary> public void OnFrameQualityChanged(ImageTargetBuilder.FrameQuality frameQuality) { Debug.Log("Frame quality changed: " + frameQuality.ToString()); m_FrameQuality = frameQuality; if (m_FrameQuality == ImageTargetBuilder.FrameQuality.FRAME_QUALITY_LOW) { Debug.Log("Low camera image quality"); } m_FrameQualityMeter.SetQuality(frameQuality); } /// <summary> /// Takes a new trackable source and adds it to the dataset /// This gets called automatically as soon as you 'BuildNewTarget with UserDefinedTargetBuildingBehaviour /// </summary> public void OnNewTrackableSource(TrackableSource trackableSource) { m_TargetCounter++; // Deactivates the dataset first m_ObjectTracker.DeactivateDataSet(m_UDT_DataSet); // Destroy the oldest target if the dataset is full or the dataset // already contains five user-defined targets. if (m_UDT_DataSet.HasReachedTrackableLimit() || m_UDT_DataSet.GetTrackables().Count() >= MAX_TARGETS) { IEnumerable<Trackable> trackables = m_UDT_DataSet.GetTrackables(); Trackable oldest = null; foreach (Trackable trackable in trackables) { if (oldest == null || trackable.ID < oldest.ID) oldest = trackable; } if (oldest != null) { Debug.Log("Destroying oldest trackable in UDT dataset: " + oldest.Name); m_UDT_DataSet.Destroy(oldest, true); } } // Get predefined trackable and instantiate it ImageTargetBehaviour imageTargetCopy = Instantiate(ImageTargetTemplate); imageTargetCopy.gameObject.name = "UserDefinedTarget-" + m_TargetCounter; // Add the duplicated trackable to the data set and activate it m_UDT_DataSet.CreateTrackable(trackableSource, imageTargetCopy.gameObject); // Activate the dataset again m_ObjectTracker.ActivateDataSet(m_UDT_DataSet); // Make sure TargetBuildingBehaviour keeps scanning... m_TargetBuildingBehaviour.StartScanning(); } #endregion IUserDefinedTargetEventHandler implementation #region PUBLIC_METHODS /// <summary> /// Instantiates a new user-defined target and is also responsible for dispatching callback to /// IUserDefinedTargetEventHandler::OnNewTrackableSource /// </summary> public void BuildNewTarget() { if (m_FrameQuality == ImageTargetBuilder.FrameQuality.FRAME_QUALITY_MEDIUM || m_FrameQuality == ImageTargetBuilder.FrameQuality.FRAME_QUALITY_HIGH) { // create the name of the next target. // the TrackableName of the original, linked ImageTargetBehaviour is extended with a continuous number to ensure unique names string targetName = string.Format("{0}-{1}", ImageTargetTemplate.TrackableName, m_TargetCounter); // generate a new target: m_TargetBuildingBehaviour.BuildNewTarget(targetName, ImageTargetTemplate.GetSize().x); } else { Debug.Log("Cannot build new target, due to poor camera image quality"); StatusMessage.Instance.Display("Low camera image quality", true); } } #endregion //PUBLIC_METHODS }
36.231707
137
0.664759
[ "MIT" ]
ACT-ZUT/OrbitVue
Unity/ArSatelite/Assets/SamplesResources/SceneAssets/UserDefinedTargets/Scripts/UDTEventHandler.cs
5,942
C#
using System.IO; namespace Plethora.Context.Help.Streaming { public interface IDataStreamCapture<TData> { TData CaptureDataFromStream(Stream stream); } }
17.6
51
0.715909
[ "MIT", "BSD-3-Clause" ]
mikebarker/Plethora.NET
src/Plethora.Context/Help/Streaming/IDataStreamCapture.cs
178
C#
using MnistDigits.Models; using Models.MnistDigits; using OxyPlot; using OxyPlot.Series; using System; using System.Collections.Generic; using Vec = MathNet.Numerics.LinearAlgebra.Vector<double>; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace MnistDigits { public partial class LogisticRegressionForm : Form { private MnistDataset _dataset; private LogisticRegressionModel _model; private GradientDescentSeries _gradientDescentSeries; public LogisticRegressionForm(MnistDataset dataset) { InitializeComponent(); _dataset = dataset; _model = new LogisticRegressionModel(_dataset, 1); _gradientDescentSeries = new GradientDescentSeries(_model.CostsVector().Average()); // var myModel = new PlotModel { Title = "Cost" }; LineSeries s = new LineSeries(); s.ItemsSource = _gradientDescentSeries.Points; myModel.Series.Add(s); gradientDescentPlotView.Model = myModel; ReevaluatePredictions(); } private void MainForm_Load(object sender, EventArgs e) { } private void groupBox1_Enter(object sender, EventArgs e) { } private void groupBox1_Enter_1(object sender, EventArgs e) { } private void stepButton_Click(object sender, EventArgs e) { _model.GradientDescentStep(); EvaluateCostAndPlot(); ReevaluatePredictions(); } private void alphaTextBox_TextChanged(object sender, EventArgs e) { } private void predictButton_Click(object sender, EventArgs e) { ReevaluatePredictions(); } private void resetButton_Click(object sender, EventArgs e) { _model.ResetHypothesis(); EvaluateCostAndPlot(); ReevaluatePredictions(); } private void ReevaluatePredictions() { Vec actual = _dataset.IntTarget; Vec predicted = _model.Predict(_dataset.FeaturesWithBias); List<Tuple<int, int>> actualVsPredicted = new List<Tuple<int, int>>(); for (int i = 0; i < actual.Count; i++) { actualVsPredicted.Add(new Tuple<int, int>((int)actual[i], (int)predicted[i])); } predictionResultsListBox.DataSource = actualVsPredicted; int matches = actualVsPredicted.Where(t => (t.Item1 == t.Item2)).Count(); predictionsOutcomelabel.Text = string.Format("{0} matches out of {1} samples", matches, actual.Count); } private void EvaluateCostAndPlot() { _gradientDescentSeries.Add(_model.CostsVector().Average()); gradientDescentPlotView.InvalidatePlot(true); } } }
27.888889
114
0.620186
[ "MIT" ]
MartonBot/mnist-demo
LogisticRegressionForm.cs
3,014
C#
namespace AMSExplorer { partial class EncodingZenium { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(EncodingZenium)); this.label = new System.Windows.Forms.Label(); this.textBoxJobName = new System.Windows.Forms.TextBox(); this.label2 = new System.Windows.Forms.Label(); this.listbox = new System.Windows.Forms.ListBox(); this.buttonCancel = new System.Windows.Forms.Button(); this.label1 = new System.Windows.Forms.Label(); this.moreinfoprofilelink = new System.Windows.Forms.LinkLabel(); this.processorlabel = new System.Windows.Forms.Label(); this.label3 = new System.Windows.Forms.Label(); this.textboxoutputassetname = new System.Windows.Forms.TextBox(); this.radioButtonMultipleJob = new System.Windows.Forms.RadioButton(); this.radioButtonSingleJob = new System.Windows.Forms.RadioButton(); this.labelsummaryjob = new System.Windows.Forms.Label(); this.label5 = new System.Windows.Forms.Label(); this.numericUpDownPriority = new System.Windows.Forms.NumericUpDown(); this.buttonOk = new System.Windows.Forms.Button(); this.pictureBoxXenio = new System.Windows.Forms.PictureBox(); this.pictureBoxJob = new System.Windows.Forms.PictureBox(); ((System.ComponentModel.ISupportInitialize)(this.numericUpDownPriority)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.pictureBoxXenio)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.pictureBoxJob)).BeginInit(); this.SuspendLayout(); // // label // this.label.AutoSize = true; this.label.Location = new System.Drawing.Point(32, 23); this.label.Name = "label"; this.label.Size = new System.Drawing.Size(35, 13); this.label.TabIndex = 0; this.label.Text = "label1"; // // textBoxJobName // this.textBoxJobName.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.textBoxJobName.Location = new System.Drawing.Point(32, 268); this.textBoxJobName.Name = "textBoxJobName"; this.textBoxJobName.Size = new System.Drawing.Size(440, 20); this.textBoxJobName.TabIndex = 1; // // label2 // this.label2.AutoSize = true; this.label2.Location = new System.Drawing.Point(29, 54); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(338, 26); this.label2.TabIndex = 2; this.label2.Text = "Please select one or several blueprints.\r\nFor each blueprint selected, one parall" + "el task will be created in the job."; // // listbox // this.listbox.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.listbox.FormattingEnabled = true; this.listbox.Location = new System.Drawing.Point(32, 83); this.listbox.Name = "listbox"; this.listbox.SelectionMode = System.Windows.Forms.SelectionMode.MultiExtended; this.listbox.Size = new System.Drawing.Size(529, 147); this.listbox.TabIndex = 3; this.listbox.SelectedIndexChanged += new System.EventHandler(this.listbox_SelectedIndexChanged); // // buttonCancel // this.buttonCancel.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left))); this.buttonCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel; this.buttonCancel.Location = new System.Drawing.Point(336, 510); this.buttonCancel.Name = "buttonCancel"; this.buttonCancel.Size = new System.Drawing.Size(113, 32); this.buttonCancel.TabIndex = 4; this.buttonCancel.Text = "Cancel"; this.buttonCancel.UseVisualStyleBackColor = true; this.buttonCancel.Click += new System.EventHandler(this.buttonCancel_Click); // // label1 // this.label1.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left))); this.label1.AutoSize = true; this.label1.Location = new System.Drawing.Point(29, 252); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(70, 13); this.label1.TabIndex = 6; this.label1.Text = "Job(s) name :"; this.label1.Click += new System.EventHandler(this.label1_Click); // // moreinfoprofilelink // this.moreinfoprofilelink.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.moreinfoprofilelink.AutoSize = true; this.moreinfoprofilelink.Location = new System.Drawing.Point(567, 139); this.moreinfoprofilelink.Name = "moreinfoprofilelink"; this.moreinfoprofilelink.Size = new System.Drawing.Size(107, 13); this.moreinfoprofilelink.TabIndex = 7; this.moreinfoprofilelink.TabStop = true; this.moreinfoprofilelink.Text = "More info on features"; this.moreinfoprofilelink.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.moreinfoprofilelink_LinkClicked); // // processorlabel // this.processorlabel.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left))); this.processorlabel.Location = new System.Drawing.Point(32, 485); this.processorlabel.Name = "processorlabel"; this.processorlabel.Size = new System.Drawing.Size(365, 22); this.processorlabel.TabIndex = 8; this.processorlabel.Text = "processor name"; // // label3 // this.label3.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left))); this.label3.AutoSize = true; this.label3.Location = new System.Drawing.Point(32, 430); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(113, 13); this.label3.TabIndex = 11; this.label3.Text = "Output asset(s) name :"; this.label3.Click += new System.EventHandler(this.label3_Click); // // textboxoutputassetname // this.textboxoutputassetname.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.textboxoutputassetname.Location = new System.Drawing.Point(35, 449); this.textboxoutputassetname.Name = "textboxoutputassetname"; this.textboxoutputassetname.Size = new System.Drawing.Size(437, 20); this.textboxoutputassetname.TabIndex = 9; this.textboxoutputassetname.TextChanged += new System.EventHandler(this.outputassetname_TextChanged); // // radioButtonMultipleJob // this.radioButtonMultipleJob.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left))); this.radioButtonMultipleJob.AutoSize = true; this.radioButtonMultipleJob.Checked = true; this.radioButtonMultipleJob.Location = new System.Drawing.Point(32, 352); this.radioButtonMultipleJob.Name = "radioButtonMultipleJob"; this.radioButtonMultipleJob.Size = new System.Drawing.Size(211, 17); this.radioButtonMultipleJob.TabIndex = 12; this.radioButtonMultipleJob.TabStop = true; this.radioButtonMultipleJob.Text = "Multiple jobs (a job for each input asset)"; this.radioButtonMultipleJob.UseVisualStyleBackColor = true; this.radioButtonMultipleJob.CheckedChanged += new System.EventHandler(this.radioButtonMultipleJob_CheckedChanged); // // radioButtonSingleJob // this.radioButtonSingleJob.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left))); this.radioButtonSingleJob.AutoSize = true; this.radioButtonSingleJob.Location = new System.Drawing.Point(32, 375); this.radioButtonSingleJob.Name = "radioButtonSingleJob"; this.radioButtonSingleJob.Size = new System.Drawing.Size(400, 17); this.radioButtonSingleJob.TabIndex = 13; this.radioButtonSingleJob.Text = "Single job (Not supported today - one job and pass all selected assets as inputs)" + ""; this.radioButtonSingleJob.UseVisualStyleBackColor = true; // // labelsummaryjob // this.labelsummaryjob.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.labelsummaryjob.Location = new System.Drawing.Point(530, 271); this.labelsummaryjob.Name = "labelsummaryjob"; this.labelsummaryjob.Size = new System.Drawing.Size(228, 22); this.labelsummaryjob.TabIndex = 14; this.labelsummaryjob.Text = "You will submit n jobs with n tasks"; // // label5 // this.label5.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left))); this.label5.AutoSize = true; this.label5.Location = new System.Drawing.Point(32, 296); this.label5.Name = "label5"; this.label5.Size = new System.Drawing.Size(44, 13); this.label5.TabIndex = 36; this.label5.Text = "Priority :"; // // numericUpDownPriority // this.numericUpDownPriority.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left))); this.numericUpDownPriority.Location = new System.Drawing.Point(32, 312); this.numericUpDownPriority.Name = "numericUpDownPriority"; this.numericUpDownPriority.Size = new System.Drawing.Size(58, 20); this.numericUpDownPriority.TabIndex = 35; // // buttonOk // this.buttonOk.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left))); this.buttonOk.DialogResult = System.Windows.Forms.DialogResult.OK; this.buttonOk.Image = global::AMSExplorer.Bitmaps.encoding; this.buttonOk.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft; this.buttonOk.Location = new System.Drawing.Point(189, 510); this.buttonOk.Name = "buttonOk"; this.buttonOk.Size = new System.Drawing.Size(141, 32); this.buttonOk.TabIndex = 5; this.buttonOk.Text = "Launch encoding"; this.buttonOk.UseVisualStyleBackColor = true; // // pictureBoxXenio // this.pictureBoxXenio.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.pictureBoxXenio.Image = global::AMSExplorer.Bitmaps.xenio; this.pictureBoxXenio.Location = new System.Drawing.Point(570, 12); this.pictureBoxXenio.Name = "pictureBoxXenio"; this.pictureBoxXenio.Size = new System.Drawing.Size(188, 124); this.pictureBoxXenio.SizeMode = System.Windows.Forms.PictureBoxSizeMode.AutoSize; this.pictureBoxXenio.TabIndex = 42; this.pictureBoxXenio.TabStop = false; // // pictureBoxJob // this.pictureBoxJob.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.pictureBoxJob.Image = global::AMSExplorer.Bitmaps.modeltaskxenio2; this.pictureBoxJob.Location = new System.Drawing.Point(478, 296); this.pictureBoxJob.Name = "pictureBoxJob"; this.pictureBoxJob.Size = new System.Drawing.Size(280, 211); this.pictureBoxJob.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage; this.pictureBoxJob.TabIndex = 41; this.pictureBoxJob.TabStop = false; // // EncodingZenium // this.AcceptButton = this.buttonOk; this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.BackColor = System.Drawing.SystemColors.Window; this.CancelButton = this.buttonCancel; this.ClientSize = new System.Drawing.Size(784, 561); this.Controls.Add(this.pictureBoxXenio); this.Controls.Add(this.pictureBoxJob); this.Controls.Add(this.label5); this.Controls.Add(this.numericUpDownPriority); this.Controls.Add(this.labelsummaryjob); this.Controls.Add(this.radioButtonSingleJob); this.Controls.Add(this.radioButtonMultipleJob); this.Controls.Add(this.label3); this.Controls.Add(this.textboxoutputassetname); this.Controls.Add(this.processorlabel); this.Controls.Add(this.moreinfoprofilelink); this.Controls.Add(this.label1); this.Controls.Add(this.buttonOk); this.Controls.Add(this.buttonCancel); this.Controls.Add(this.listbox); this.Controls.Add(this.label2); this.Controls.Add(this.textBoxJobName); this.Controls.Add(this.label); this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); this.Name = "EncodingZenium"; this.Text = "Encoding with Zenium"; this.Load += new System.EventHandler(this.EncodingXenio_Load); ((System.ComponentModel.ISupportInitialize)(this.numericUpDownPriority)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.pictureBoxXenio)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.pictureBoxJob)).EndInit(); this.ResumeLayout(false); this.PerformLayout(); } #endregion public System.Windows.Forms.Label label; public System.Windows.Forms.TextBox textBoxJobName; public System.Windows.Forms.Label label2; public System.Windows.Forms.ListBox listbox; public System.Windows.Forms.Button buttonCancel; public System.Windows.Forms.Button buttonOk; public System.Windows.Forms.Label label1; private System.Windows.Forms.LinkLabel moreinfoprofilelink; private System.Windows.Forms.Label processorlabel; public System.Windows.Forms.Label label3; public System.Windows.Forms.TextBox textboxoutputassetname; private System.Windows.Forms.RadioButton radioButtonMultipleJob; private System.Windows.Forms.RadioButton radioButtonSingleJob; private System.Windows.Forms.Label labelsummaryjob; public System.Windows.Forms.Label label5; private System.Windows.Forms.NumericUpDown numericUpDownPriority; private System.Windows.Forms.PictureBox pictureBoxJob; private System.Windows.Forms.PictureBox pictureBoxXenio; } }
56.517799
172
0.637712
[ "Apache-2.0" ]
asolanki/Azure-Media-Services-Explorer
AMSExplorer/EncodingZenium.Designer.cs
17,466
C#
using AzR.Core.Config; using Microsoft.AspNet.Identity.EntityFramework; using System.ComponentModel.DataAnnotations.Schema; namespace AzR.Core.IdentityConfig { public class ApplicationUserRole : IdentityUserRole<int>, IBaseEntity { [ForeignKey("UserId")] public virtual ApplicationUser User { get; set; } [ForeignKey("RoleId")] public virtual ApplicationRole Role { get; set; } } }
26.75
73
0.712617
[ "MIT" ]
ashiquzzaman/azr-admin
Development/AzRAdmin/Libraries/AzR.Core/IdentityConfig/ApplicationUserRole.cs
428
C#
namespace MassTransit.Configuration { using ConsumePipeSpecifications; using Topology; using Topology.Observers; public class ConsumePipeConfiguration : IConsumePipeConfiguration { readonly ConsumePipeSpecification _specification; public ConsumePipeConfiguration(IConsumeTopology consumeTopology) { _specification = new ConsumePipeSpecification(); _specification.ConnectConsumePipeSpecificationObserver(new TopologyConsumePipeSpecificationObserver(consumeTopology)); } public ConsumePipeConfiguration(IConsumePipeSpecification parentSpecification) { _specification = new ConsumePipeSpecification(); _specification.ConnectConsumePipeSpecificationObserver(new ParentConsumePipeSpecificationObserver(parentSpecification)); } public IConsumePipeSpecification Specification => _specification; public IConsumePipeConfigurator Configurator => _specification; } }
34.965517
132
0.748521
[ "ECL-2.0", "Apache-2.0" ]
Aerodynamite/MassTrans
src/MassTransit/Configuration/Configuration/ConsumePipeConfiguration.cs
1,016
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // As informações gerais sobre um assembly são controladas por // conjunto de atributos. Altere estes valores de atributo para modificar as informações // associadas a um assembly. [assembly: AssemblyTitle("AgendaBasica")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("AgendaBasica")] [assembly: AssemblyCopyright("Copyright © 2019")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Definir ComVisible como false torna os tipos neste assembly invisíveis // para componentes COM. Caso precise acessar um tipo neste assembly de // COM, defina o atributo ComVisible como true nesse tipo. [assembly: ComVisible(false)] // O GUID a seguir será destinado à ID de typelib se este projeto for exposto para COM [assembly: Guid("f4e269ae-a6e7-44ad-a43f-f976e04bdd36")] // As informações da versão de um assembly consistem nos quatro valores a seguir: // // Versão Principal // Versão Secundária // Número da Versão // Revisão // // É possível especificar todos os valores ou usar como padrão os Números de Build e da Revisão // usando o "*" como mostrado abaixo: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
38.189189
95
0.753008
[ "MIT" ]
WalissonRodrigo/Agenda-B-sica
AgendaBasica/Properties/AssemblyInfo.cs
1,438
C#
using System; using System.Drawing; using System.IO; using System.Xml; using System.Text; using System.Windows.Forms; namespace SmartOCR { /// <summary> /// Application configuration /// </summary> public class Configuration { public Point mainWindowLocation = new Point(100, 50); public Size mainWindowSize = new Size(800, 600); public bool histogramVisible = false; public bool statisticsVisible = false; public bool resultsVisible = false; public bool splitFileVisible = false; public bool almodwanaVisible = false; public bool documentEditorVisible = false; public bool showPart = true; public bool openInNewDoc = false; public bool rememberOnChange = false; public int PageSize = 100100; public int OverlapLenght = 1000; // Constructor public Configuration( ) { } // Save configureation to file public void Save( string fileName ) { try { // open file FileStream fs = new FileStream(fileName, FileMode.Create); // create XML writer XmlTextWriter xmlOut = new XmlTextWriter(fs, Encoding.Unicode); // use indenting for readability xmlOut.Formatting = Formatting.Indented; // start document xmlOut.WriteStartDocument(); xmlOut.WriteComment("SmartOCR configuration file"); // main node xmlOut.WriteStartElement("SmartOCR"); // position node xmlOut.WriteStartElement("Position"); xmlOut.WriteAttributeString("x", mainWindowLocation.X.ToString()); xmlOut.WriteAttributeString("y", mainWindowLocation.Y.ToString()); xmlOut.WriteAttributeString("width", mainWindowSize.Width.ToString()); xmlOut.WriteAttributeString("height", mainWindowSize.Height.ToString()); xmlOut.WriteEndElement(); // settings node xmlOut.WriteStartElement("Settings"); xmlOut.WriteAttributeString("histogram", histogramVisible.ToString()); xmlOut.WriteAttributeString("statistics", statisticsVisible.ToString()); xmlOut.WriteAttributeString("results", resultsVisible.ToString()); xmlOut.WriteAttributeString("splitFile", splitFileVisible.ToString()); xmlOut.WriteAttributeString("documentEditor", documentEditorVisible.ToString()); xmlOut.WriteAttributeString("newOnChange", openInNewDoc.ToString()); xmlOut.WriteAttributeString("rememberOnChange", rememberOnChange.ToString()); xmlOut.WriteAttributeString("showPart", showPart.ToString()); xmlOut.WriteEndElement(); xmlOut.WriteEndElement(); // close file xmlOut.Close(); } catch (System.Exception ex) { } } // Load configureation from file public bool Load( string fileName ) { bool ret = false; // check file existance if ( File.Exists( fileName ) ) { FileStream fs = null; XmlTextReader xmlIn = null; try { // open file fs = new FileStream( fileName, FileMode.Open ); // create XML reader xmlIn = new XmlTextReader( fs ); xmlIn.WhitespaceHandling = WhitespaceHandling.None; xmlIn.MoveToContent( ); // check for main node if ( xmlIn.Name != "SmartOCR" ) throw new ApplicationException( "" ); // move to next node xmlIn.Read( ); if ( xmlIn.NodeType == XmlNodeType.EndElement ) xmlIn.Read( ); // check for position node if ( xmlIn.Name != "Position" ) throw new ApplicationException( "" ); // read main window position int x = Convert.ToInt32( xmlIn.GetAttribute( "x" ) ); int y = Convert.ToInt32( xmlIn.GetAttribute( "y" ) ); int width = Convert.ToInt32( xmlIn.GetAttribute( "width" ) ); int height = Convert.ToInt32( xmlIn.GetAttribute( "height" ) ); mainWindowLocation = new Point( x, y ); mainWindowSize = new Size( width, height ); // move to next node xmlIn.Read( ); if ( xmlIn.NodeType == XmlNodeType.EndElement ) xmlIn.Read( ); // check for position node if ( xmlIn.Name != "Settings" ) throw new ApplicationException( "" ); histogramVisible = Convert.ToBoolean( xmlIn.GetAttribute( "histogram" ) ); statisticsVisible = Convert.ToBoolean( xmlIn.GetAttribute( "statistics" ) ); splitFileVisible = Convert.ToBoolean(xmlIn.GetAttribute("splitFile")); documentEditorVisible = Convert.ToBoolean(xmlIn.GetAttribute("documentEditor")); resultsVisible = Convert.ToBoolean(xmlIn.GetAttribute("results")); openInNewDoc = Convert.ToBoolean( xmlIn.GetAttribute( "newOnChange" ) ); rememberOnChange = Convert.ToBoolean( xmlIn.GetAttribute( "rememberOnChange" ) ); showPart = Convert.ToBoolean(xmlIn.GetAttribute("showPart")); ret = true; } catch(System.Exception ex) { } finally { if ( xmlIn != null ) xmlIn.Close( ); } } return ret; } } }
37.53012
101
0.521669
[ "Apache-2.0" ]
alatabbi/TexE
TexEditor/Code/Configuration.cs
6,230
C#
//------------------------------------------------------------------------------ // <auto-generated> // Dieser Code wurde von einem Tool generiert. // Laufzeitversion:4.0.30319.42000 // // Änderungen an dieser Datei können falsches Verhalten verursachen und gehen verloren, wenn // der Code erneut generiert wird. // </auto-generated> //------------------------------------------------------------------------------ namespace XamlGeneratedNamespace { /// <summary> /// GeneratedInternalTypeHelper /// </summary> [System.Diagnostics.DebuggerNonUserCodeAttribute()] [System.CodeDom.Compiler.GeneratedCodeAttribute("PresentationBuildTasks", "5.0.4.0")] [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public sealed class GeneratedInternalTypeHelper : System.Windows.Markup.InternalTypeHelper { /// <summary> /// CreateInstance /// </summary> protected override object CreateInstance(System.Type type, System.Globalization.CultureInfo culture) { return System.Activator.CreateInstance(type, ((System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic) | (System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.CreateInstance)), null, null, culture); } /// <summary> /// GetPropertyValue /// </summary> protected override object GetPropertyValue(System.Reflection.PropertyInfo propertyInfo, object target, System.Globalization.CultureInfo culture) { return propertyInfo.GetValue(target, System.Reflection.BindingFlags.Default, null, null, culture); } /// <summary> /// SetPropertyValue /// </summary> protected override void SetPropertyValue(System.Reflection.PropertyInfo propertyInfo, object target, object value, System.Globalization.CultureInfo culture) { propertyInfo.SetValue(target, value, System.Reflection.BindingFlags.Default, null, null, culture); } /// <summary> /// CreateDelegate /// </summary> protected override System.Delegate CreateDelegate(System.Type delegateType, object target, string handler) { return ((System.Delegate)(target.GetType().InvokeMember("_CreateDelegate", (System.Reflection.BindingFlags.InvokeMethod | (System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance)), null, target, new object[] { delegateType, handler}, null))); } /// <summary> /// AddEventHandler /// </summary> protected override void AddEventHandler(System.Reflection.EventInfo eventInfo, object target, System.Delegate handler) { eventInfo.AddEventHandler(target, handler); } } }
47.142857
166
0.625926
[ "MIT" ]
fj-gruenewald/repo.history
WPF Applications/autoStarter/autoStarter/obj/Debug/netcoreapp3.1/GeneratedInternalTypeHelper.g.cs
2,974
C#
using System; namespace Aula35 { //Parecido com private, um membro protegido (protectec) é acessível dentro de sua classe e também por instâncias da classe derivada, esta é a diferença dentre protected e private. class Veiculo{ public int velAtual; private int velMax; protected bool ligado; public Veiculo(int velMax){ velAtual = 0; this.velMax = velMax; ligado = false; } public bool getLigado(){ return ligado; } public int getVelMax(){ return velMax; } } class Carro:Veiculo{ //Derivada de Veiculo public string nome; public Carro(string nome, int velMax):base(velMax){ this.nome=nome; ligado = true; } } class Program { static void Main(string[] args) { Carro carro = new Carro("Bontião", 120); Console.WriteLine($"Nome:.......{carro.nome}"); Console.WriteLine($"Vel.Máxima:.{carro.getVelMax()}"); Console.WriteLine($"Ligado:.....{carro.getLigado()}"); } } }
27.5
183
0.548918
[ "MIT" ]
Drlazinho/Linguagem-C-Sharp---CFBCursos
Aula36/Program.cs
1,165
C#
/* * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the datapipeline-2012-10-29.normal.json service model. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Text; using System.Xml.Serialization; using Amazon.DataPipeline.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; using ThirdParty.Json.LitJson; namespace Amazon.DataPipeline.Model.Internal.MarshallTransformations { /// <summary> /// CreatePipeline Request Marshaller /// </summary> public class CreatePipelineRequestMarshaller : IMarshaller<IRequest, CreatePipelineRequest> , IMarshaller<IRequest,AmazonWebServiceRequest> { /// <summary> /// Marshaller the request object to the HTTP request. /// </summary> /// <param name="input"></param> /// <returns></returns> public IRequest Marshall(AmazonWebServiceRequest input) { return this.Marshall((CreatePipelineRequest)input); } /// <summary> /// Marshaller the request object to the HTTP request. /// </summary> /// <param name="publicRequest"></param> /// <returns></returns> public IRequest Marshall(CreatePipelineRequest publicRequest) { IRequest request = new DefaultRequest(publicRequest, "Amazon.DataPipeline"); string target = "DataPipeline.CreatePipeline"; request.Headers["X-Amz-Target"] = target; request.Headers["Content-Type"] = "application/x-amz-json-1.1"; request.Headers[Amazon.Util.HeaderKeys.XAmzApiVersion] = "2012-10-29"; request.HttpMethod = "POST"; string uriResourcePath = "/"; request.ResourcePath = uriResourcePath; using (StringWriter stringWriter = new StringWriter(CultureInfo.InvariantCulture)) { JsonWriter writer = new JsonWriter(stringWriter); writer.WriteObjectStart(); var context = new JsonMarshallerContext(request, writer); if(publicRequest.IsSetDescription()) { context.Writer.WritePropertyName("description"); context.Writer.Write(publicRequest.Description); } if(publicRequest.IsSetName()) { context.Writer.WritePropertyName("name"); context.Writer.Write(publicRequest.Name); } if(publicRequest.IsSetTags()) { context.Writer.WritePropertyName("tags"); context.Writer.WriteArrayStart(); foreach(var publicRequestTagsListValue in publicRequest.Tags) { context.Writer.WriteObjectStart(); var marshaller = TagMarshaller.Instance; marshaller.Marshall(publicRequestTagsListValue, context); context.Writer.WriteObjectEnd(); } context.Writer.WriteArrayEnd(); } if(publicRequest.IsSetUniqueId()) { context.Writer.WritePropertyName("uniqueId"); context.Writer.Write(publicRequest.UniqueId); } writer.WriteObjectEnd(); string snippet = stringWriter.ToString(); request.Content = System.Text.Encoding.UTF8.GetBytes(snippet); } return request; } private static CreatePipelineRequestMarshaller _instance = new CreatePipelineRequestMarshaller(); internal static CreatePipelineRequestMarshaller GetInstance() { return _instance; } /// <summary> /// Gets the singleton. /// </summary> public static CreatePipelineRequestMarshaller Instance { get { return _instance; } } } }
35.932331
143
0.596359
[ "Apache-2.0" ]
Bio2hazard/aws-sdk-net
sdk/src/Services/DataPipeline/Generated/Model/Internal/MarshallTransformations/CreatePipelineRequestMarshaller.cs
4,779
C#
// <auto-generated /> using System; using IdentityExtension.Data; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Migrations; using Microsoft.EntityFrameworkCore.Storage.ValueConversion; namespace IdentityExtension.Data.Migrations { [DbContext(typeof(ApplicationDbContext))] [Migration("00000000000000_CreateIdentitySchema")] partial class CreateIdentitySchema { protected override void BuildTargetModel(ModelBuilder modelBuilder) { #pragma warning disable 612, 618 modelBuilder .HasAnnotation("ProductVersion", "2.1.0") .HasAnnotation("Relational:MaxIdentifierLength", 128) .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole", b => { b.Property<string>("Id") .ValueGeneratedOnAdd(); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken(); b.Property<string>("Name") .HasMaxLength(256); b.Property<string>("NormalizedName") .HasMaxLength(256); b.HasKey("Id"); b.HasIndex("NormalizedName") .IsUnique() .HasName("RoleNameIndex") .HasFilter("[NormalizedName] IS NOT NULL"); b.ToTable("AspNetRoles"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<string>", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("ClaimType"); b.Property<string>("ClaimValue"); b.Property<string>("RoleId") .IsRequired(); b.HasKey("Id"); b.HasIndex("RoleId"); b.ToTable("AspNetRoleClaims"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUser", b => { b.Property<string>("Id") .ValueGeneratedOnAdd(); b.Property<int>("AccessFailedCount"); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken(); b.Property<string>("Email") .HasMaxLength(256); b.Property<bool>("EmailConfirmed"); b.Property<bool>("LockoutEnabled"); b.Property<DateTimeOffset?>("LockoutEnd"); b.Property<string>("NormalizedEmail") .HasMaxLength(256); b.Property<string>("NormalizedUserName") .HasMaxLength(256); b.Property<string>("PasswordHash"); b.Property<string>("PhoneNumber"); b.Property<bool>("PhoneNumberConfirmed"); b.Property<string>("SecurityStamp"); b.Property<bool>("TwoFactorEnabled"); b.Property<string>("UserName") .HasMaxLength(256); b.HasKey("Id"); b.HasIndex("NormalizedEmail") .HasName("EmailIndex"); b.HasIndex("NormalizedUserName") .IsUnique() .HasName("UserNameIndex") .HasFilter("[NormalizedUserName] IS NOT NULL"); b.ToTable("AspNetUsers"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<string>", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("ClaimType"); b.Property<string>("ClaimValue"); b.Property<string>("UserId") .IsRequired(); b.HasKey("Id"); b.HasIndex("UserId"); b.ToTable("AspNetUserClaims"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<string>", b => { b.Property<string>("LoginProvider") .HasMaxLength(128); b.Property<string>("ProviderKey") .HasMaxLength(128); b.Property<string>("ProviderDisplayName"); b.Property<string>("UserId") .IsRequired(); b.HasKey("LoginProvider", "ProviderKey"); b.HasIndex("UserId"); b.ToTable("AspNetUserLogins"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<string>", b => { b.Property<string>("UserId"); b.Property<string>("RoleId"); b.HasKey("UserId", "RoleId"); b.HasIndex("RoleId"); b.ToTable("AspNetUserRoles"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<string>", b => { b.Property<string>("UserId"); b.Property<string>("LoginProvider") .HasMaxLength(128); b.Property<string>("Name") .HasMaxLength(128); b.Property<string>("Value"); b.HasKey("UserId", "LoginProvider", "Name"); b.ToTable("AspNetUserTokens"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<string>", b => { b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole") .WithMany() .HasForeignKey("RoleId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<string>", b => { b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser") .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<string>", b => { b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser") .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<string>", b => { b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole") .WithMany() .HasForeignKey("RoleId") .OnDelete(DeleteBehavior.Cascade); b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser") .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<string>", b => { b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser") .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade); }); #pragma warning restore 612, 618 } } }
35.075949
125
0.488993
[ "Unlicense" ]
kokyiphyocho/ASP.NET-Core-2.1-Customize-Login-Form
IdentityExtension/Data/Migrations/00000000000000_CreateIdentitySchema.Designer.cs
8,313
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by Codezu. // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ using System; using System.Collections.Generic; namespace Mozu.Api.Contracts.ProductAdmin { /// /// Describes the scope of the product publishing update, which can include individual product codes or all pending changes. /// public class PublishingScope { public bool? AllPending { get; set; } public List<string> ProductCodes { get; set; } /// ///The unique identifier of the product publish set.You can use this field to perform operations on all the pending product changes assigned to a publish set. For example, when you perform the PublishDrafts operation, you can specify the publish set that the pending product changes are assigned to in order to publish all of the pending changes. If you specify a publishSetCode, the respecting operation is performed on all pending product changes assigned to the publish set, even if you specify individual productCodes. /// public string PublishSetCode { get; set; } } }
39.939394
525
0.649469
[ "MIT" ]
GaryWayneSmith/mozu-dotnet
Mozu.Api/Contracts/ProductAdmin/PublishingScope.cs
1,318
C#
using Nethereum.JsonRpc.Client; using Nethereum.RPC.Infrastructure; using Newtonsoft.Json.Linq; namespace Nethereum.Parity.RPC.Network { /// <Summary> /// parity_netPeers /// Returns number of peers. /// Parameters /// None /// Returns /// Object - Number of peers /// active: Quantity - Number of active peers. /// connected: Quantity - Number of connected peers. /// max: Quantity - Maximum number of connected peers. /// peers: Array - List of all peers with details. /// Example /// Request /// curl --data '{"method":"parity_netPeers","params":[],"id":1,"jsonrpc":"2.0"}' -H "Content-Type: application/json" /// -X POST localhost:8545 /// Response /// { /// "id": 1, /// "jsonrpc": "2.0", /// "result": { /// "active": 0, /// "connected": 25, /// "max": 25, /// "peers": [{ ... }, { ... }, { ... }, ...] /// } /// } /// </Summary> public class ParityNetPeers : GenericRpcRequestResponseHandlerNoParam<JObject>, IParityNetPeers { public ParityNetPeers(IClient client) : base(client, ApiMethods.parity_netPeers.ToString()) { } } public interface IParityNetPeers : IGenericRpcRequestResponseHandlerNoParam<JObject> { } }
30.043478
125
0.542692
[ "MIT" ]
6ara6aka/Nethereum
src/Nethereum.Parity/RPC/Network/ParityNetPeers.cs
1,382
C#
using System; using System.Collections.Generic; using System.Net.Http.Headers; using KeyPayV2.Sg.Models.Common; using KeyPayV2.Sg.Enums; namespace KeyPayV2.Sg.Models.PayRateTemplate { public class PayRateTemplateExportModel { public int Id { get; set; } public string Name { get; set; } public int PrimaryPayCategoryId { get; set; } public List<PayRateTemplatePayCategoryExportModel> PayCategories { get; set; } public string ExternalId { get; set; } public string Source { get; set; } public bool ReapplyToLinkedEmployees { get; set; } } }
31.45
87
0.669316
[ "MIT" ]
KeyPay/keypay-dotnet-v2
src/keypay-dotnet/Sg/Models/PayRateTemplate/PayRateTemplateExportModel.cs
629
C#
using System.Linq; using UnityEditor.IMGUI.Controls; using UnityEngine; using UnityEngine.Timeline; namespace UnityEditor.Timeline { abstract class TimelineTrackBaseGUI : TreeViewItem, IBounds { static class Styles { public static readonly GUIContent s_LockedAndMuted = EditorGUIUtility.TrTextContent("Locked / Muted"); public static readonly GUIContent s_LockedAndPartiallyMuted = EditorGUIUtility.TrTextContent("Locked / Partially Muted"); public static readonly GUIContent s_Locked = EditorGUIUtility.TrTextContent("Locked"); public static readonly GUIContent s_Muted = EditorGUIUtility.TrTextContent("Muted"); public static readonly GUIContent s_PartiallyMuted = EditorGUIUtility.TrTextContent("Partially Muted"); } protected bool m_IsRoot = false; protected const float k_ButtonSize = 16.0f; readonly TimelineTreeViewGUI m_TreeViewGUI; readonly TrackDrawer m_Drawer; public Vector2 treeViewToWindowTransformation { get; set; } public bool isExpanded { get; set; } public bool isDropTarget { protected get; set; } public TrackAsset track { get; } TreeViewController treeView { get; } public TimelineWindow TimelineWindow { get { if (m_TreeViewGUI == null) return null; return m_TreeViewGUI.TimelineWindow; } } public TrackDrawer drawer { get { return m_Drawer; } } public virtual float GetVerticalSpacingBetweenTracks() { return 3.0f; } public bool visibleRow { get; set; } // is the header row visible public bool visibleExpanded { get; set; } // is the expanded area (group) visible public bool drawInsertionMarkerBefore { get; set; } public bool drawInsertionMarkerAfter { get; set; } public abstract Rect boundingRect { get; } public abstract bool expandable { get; } public abstract void Draw(Rect headerRect, Rect contentRect, WindowState state); public abstract void OnGraphRebuilt(); // callback when the corresponding graph is rebuilt. This can happen, but not have the GUI rebuilt. protected TimelineTrackBaseGUI(int id, int depth, TreeViewItem parent, string displayName, TrackAsset trackAsset, TreeViewController tv, TimelineTreeViewGUI tvgui) : base(id, depth, parent, displayName) { m_Drawer = TrackDrawer.CreateInstance(trackAsset); m_Drawer.sequencerState = tvgui.TimelineWindow.state; isExpanded = false; isDropTarget = false; track = trackAsset; treeView = tv; m_TreeViewGUI = tvgui; } public static TimelineTrackBaseGUI FindGUITrack(TrackAsset track) { var allTracks = TimelineWindow.instance.allTracks; return allTracks.Find(x => x.track == track); } protected void DrawTrackState(Rect trackRect, Rect expandedRect, TrackAsset track) { if (Event.current.type == EventType.Layout) { bool needStateBox = false; //Mute if (track.muted && !TimelineUtility.IsParentMuted(track)) { Rect bgRect = expandedRect; TimelineWindow.instance.OverlayDrawData.Add(TimelineWindow.OverlayData.CreateColorOverlay(GUIClip.Unclip(bgRect), DirectorStyles.Instance.customSkin.colorTrackDarken)); needStateBox = true; } //Lock if (!needStateBox && track.locked && !TimelineUtility.IsLockedFromGroup(track)) { Rect bgRect = expandedRect; TimelineWindow.instance.OverlayDrawData.Add(TimelineWindow.OverlayData.CreateTextureOverlay(GUIClip.Unclip(bgRect), DirectorStyles.Instance.lockedBG.normal.background)); needStateBox = true; } if (needStateBox) { DrawTrackStateBox(trackRect, track); } } } void DrawTrackStateBox(Rect trackRect, TrackAsset track) { const float k_LockTextPadding = 40f; var styles = DirectorStyles.Instance; bool locked = track.locked && !TimelineUtility.IsLockedFromGroup(track); bool muted = track.muted && !TimelineUtility.IsParentMuted(track); bool allSubTrackMuted = TimelineUtility.IsAllSubTrackMuted(track); GUIContent content = null; if (locked && muted) { content = Styles.s_LockedAndMuted; if (!allSubTrackMuted) content = Styles.s_LockedAndPartiallyMuted; } else if (locked) content = Styles.s_Locked; else if (muted) { content = Styles.s_Muted; if (!allSubTrackMuted) content = Styles.s_PartiallyMuted; } // the track could be locked, but we only show the 'locked portion' on the upper most track // that is causing the lock if (content == null) return; var textRect = trackRect; textRect.width = styles.fontClip.CalcSize(content).x + k_LockTextPadding; textRect.x += (trackRect.width - textRect.width) / 2f; textRect.height -= 4f; textRect.y += 2f; TimelineWindow.instance.OverlayDrawData.Add(TimelineWindow.OverlayData.CreateTextBoxOverlay(GUIClip.Unclip(textRect), content.text, styles.fontClip, Color.white, styles.customSkin.colorLockTextBG, styles.displayBackground)); } protected float DrawMuteButton(Rect rect, WindowState state) { if (track.mutedInHierarchy) { using (new EditorGUI.DisabledScope(TimelineUtility.IsParentMuted(track))) { if (GUI.Button(rect, GUIContent.none, TimelineWindow.styles.mute)) { MuteTrack.Mute(state, new[] { track }, false); } } return WindowConstants.trackHeaderButtonSize; } return 0.0f; } protected float DrawLockButton(Rect rect, WindowState state) { if (track.lockedInHierarchy) { // if the parent is locked, show it the lock disabled using (new EditorGUI.DisabledScope(TimelineUtility.IsLockedFromGroup(track))) { if (GUI.Button(rect, GUIContent.none, TimelineWindow.styles.locked)) { LockTrack.SetLockState(new[] { track }, !track.locked, state); } } return WindowConstants.trackHeaderButtonSize; } return 0.0f; } public void DrawInsertionMarkers(Rect rowRectWithIndent) { const float insertionHeight = WindowConstants.trackInsertionMarkerHeight; if (Event.current.type == EventType.Repaint && (drawInsertionMarkerAfter || drawInsertionMarkerBefore)) { if (drawInsertionMarkerBefore) { var rect = new Rect(rowRectWithIndent.x, rowRectWithIndent.y - insertionHeight * 0.5f - 2.0f, rowRectWithIndent.width, insertionHeight); EditorGUI.DrawRect(rect, Color.white); } if (drawInsertionMarkerAfter) { var rect = new Rect(rowRectWithIndent.x, rowRectWithIndent.y + rowRectWithIndent.height - insertionHeight * 0.5f + 1.0f, rowRectWithIndent.width, insertionHeight); EditorGUI.DrawRect(rect, Color.white); } } } public void ClearDrawFlags() { if (Event.current.type == EventType.Repaint) { isDropTarget = false; drawInsertionMarkerAfter = false; drawInsertionMarkerBefore = false; } } } }
38.700461
236
0.583591
[ "MIT" ]
AJ213/8-Bit-Battles
8-Bit Battles/Library/PackageCache/com.unity.timeline@1.1.0/Editor/treeview/TimelineTrackBaseGUI.cs
8,398
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // <auto-generated/> #nullable disable using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using Azure; using Azure.Core; using Azure.Core.Pipeline; using Azure.ResourceManager; using Azure.ResourceManager.Core; using Azure.ResourceManager.Resources; namespace Azure.ResourceManager.AppService { /// <summary> A class representing collection of TopLevelDomain and their operations over its parent. </summary> public partial class TopLevelDomainCollection : ArmCollection, IEnumerable<TopLevelDomain>, IAsyncEnumerable<TopLevelDomain> { private readonly ClientDiagnostics _clientDiagnostics; private readonly TopLevelDomainsRestOperations _topLevelDomainsRestClient; /// <summary> Initializes a new instance of the <see cref="TopLevelDomainCollection"/> class for mocking. </summary> protected TopLevelDomainCollection() { } /// <summary> Initializes a new instance of TopLevelDomainCollection class. </summary> /// <param name="parent"> The resource representing the parent resource. </param> internal TopLevelDomainCollection(ArmResource parent) : base(parent) { _clientDiagnostics = new ClientDiagnostics(ClientOptions); _topLevelDomainsRestClient = new TopLevelDomainsRestOperations(_clientDiagnostics, Pipeline, ClientOptions, BaseUri); } /// <summary> Gets the valid resource type for this object. </summary> protected override ResourceType ValidResourceType => Subscription.ResourceType; // Collection level operations. /// RequestPath: /subscriptions/{subscriptionId}/providers/Microsoft.DomainRegistration/topLevelDomains/{name} /// ContextualPath: /subscriptions/{subscriptionId} /// OperationId: TopLevelDomains_Get /// <summary> Description for Get details of a top-level domain. </summary> /// <param name="name"> Name of the top-level domain. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="name"/> is null. </exception> public virtual Response<TopLevelDomain> Get(string name, CancellationToken cancellationToken = default) { if (name == null) { throw new ArgumentNullException(nameof(name)); } using var scope = _clientDiagnostics.CreateScope("TopLevelDomainCollection.Get"); scope.Start(); try { var response = _topLevelDomainsRestClient.Get(Id.SubscriptionId, name, cancellationToken); if (response.Value == null) throw _clientDiagnostics.CreateRequestFailedException(response.GetRawResponse()); return Response.FromValue(new TopLevelDomain(Parent, response.Value), response.GetRawResponse()); } catch (Exception e) { scope.Failed(e); throw; } } /// RequestPath: /subscriptions/{subscriptionId}/providers/Microsoft.DomainRegistration/topLevelDomains/{name} /// ContextualPath: /subscriptions/{subscriptionId} /// OperationId: TopLevelDomains_Get /// <summary> Description for Get details of a top-level domain. </summary> /// <param name="name"> Name of the top-level domain. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="name"/> is null. </exception> public async virtual Task<Response<TopLevelDomain>> GetAsync(string name, CancellationToken cancellationToken = default) { if (name == null) { throw new ArgumentNullException(nameof(name)); } using var scope = _clientDiagnostics.CreateScope("TopLevelDomainCollection.Get"); scope.Start(); try { var response = await _topLevelDomainsRestClient.GetAsync(Id.SubscriptionId, name, cancellationToken).ConfigureAwait(false); if (response.Value == null) throw await _clientDiagnostics.CreateRequestFailedExceptionAsync(response.GetRawResponse()).ConfigureAwait(false); return Response.FromValue(new TopLevelDomain(Parent, response.Value), response.GetRawResponse()); } catch (Exception e) { scope.Failed(e); throw; } } /// <summary> Tries to get details for this resource from the service. </summary> /// <param name="name"> Name of the top-level domain. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="name"/> is null. </exception> public virtual Response<TopLevelDomain> GetIfExists(string name, CancellationToken cancellationToken = default) { if (name == null) { throw new ArgumentNullException(nameof(name)); } using var scope = _clientDiagnostics.CreateScope("TopLevelDomainCollection.GetIfExists"); scope.Start(); try { var response = _topLevelDomainsRestClient.Get(Id.SubscriptionId, name, cancellationToken: cancellationToken); return response.Value == null ? Response.FromValue<TopLevelDomain>(null, response.GetRawResponse()) : Response.FromValue(new TopLevelDomain(this, response.Value), response.GetRawResponse()); } catch (Exception e) { scope.Failed(e); throw; } } /// <summary> Tries to get details for this resource from the service. </summary> /// <param name="name"> Name of the top-level domain. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="name"/> is null. </exception> public async virtual Task<Response<TopLevelDomain>> GetIfExistsAsync(string name, CancellationToken cancellationToken = default) { if (name == null) { throw new ArgumentNullException(nameof(name)); } using var scope = _clientDiagnostics.CreateScope("TopLevelDomainCollection.GetIfExistsAsync"); scope.Start(); try { var response = await _topLevelDomainsRestClient.GetAsync(Id.SubscriptionId, name, cancellationToken: cancellationToken).ConfigureAwait(false); return response.Value == null ? Response.FromValue<TopLevelDomain>(null, response.GetRawResponse()) : Response.FromValue(new TopLevelDomain(this, response.Value), response.GetRawResponse()); } catch (Exception e) { scope.Failed(e); throw; } } /// <summary> Tries to get details for this resource from the service. </summary> /// <param name="name"> Name of the top-level domain. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="name"/> is null. </exception> public virtual Response<bool> Exists(string name, CancellationToken cancellationToken = default) { if (name == null) { throw new ArgumentNullException(nameof(name)); } using var scope = _clientDiagnostics.CreateScope("TopLevelDomainCollection.Exists"); scope.Start(); try { var response = GetIfExists(name, cancellationToken: cancellationToken); return Response.FromValue(response.Value != null, response.GetRawResponse()); } catch (Exception e) { scope.Failed(e); throw; } } /// <summary> Tries to get details for this resource from the service. </summary> /// <param name="name"> Name of the top-level domain. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="name"/> is null. </exception> public async virtual Task<Response<bool>> ExistsAsync(string name, CancellationToken cancellationToken = default) { if (name == null) { throw new ArgumentNullException(nameof(name)); } using var scope = _clientDiagnostics.CreateScope("TopLevelDomainCollection.ExistsAsync"); scope.Start(); try { var response = await GetIfExistsAsync(name, cancellationToken: cancellationToken).ConfigureAwait(false); return Response.FromValue(response.Value != null, response.GetRawResponse()); } catch (Exception e) { scope.Failed(e); throw; } } /// RequestPath: /subscriptions/{subscriptionId}/providers/Microsoft.DomainRegistration/topLevelDomains /// ContextualPath: /subscriptions/{subscriptionId} /// OperationId: TopLevelDomains_List /// <summary> Description for Get all top-level domains supported for registration. </summary> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <returns> A collection of <see cref="TopLevelDomain" /> that may take multiple service requests to iterate over. </returns> public virtual Pageable<TopLevelDomain> GetAll(CancellationToken cancellationToken = default) { Page<TopLevelDomain> FirstPageFunc(int? pageSizeHint) { using var scope = _clientDiagnostics.CreateScope("TopLevelDomainCollection.GetAll"); scope.Start(); try { var response = _topLevelDomainsRestClient.List(Id.SubscriptionId, cancellationToken: cancellationToken); return Page.FromValues(response.Value.Value.Select(value => new TopLevelDomain(Parent, value)), response.Value.NextLink, response.GetRawResponse()); } catch (Exception e) { scope.Failed(e); throw; } } Page<TopLevelDomain> NextPageFunc(string nextLink, int? pageSizeHint) { using var scope = _clientDiagnostics.CreateScope("TopLevelDomainCollection.GetAll"); scope.Start(); try { var response = _topLevelDomainsRestClient.ListNextPage(nextLink, Id.SubscriptionId, cancellationToken: cancellationToken); return Page.FromValues(response.Value.Value.Select(value => new TopLevelDomain(Parent, value)), response.Value.NextLink, response.GetRawResponse()); } catch (Exception e) { scope.Failed(e); throw; } } return PageableHelpers.CreateEnumerable(FirstPageFunc, NextPageFunc); } /// RequestPath: /subscriptions/{subscriptionId}/providers/Microsoft.DomainRegistration/topLevelDomains /// ContextualPath: /subscriptions/{subscriptionId} /// OperationId: TopLevelDomains_List /// <summary> Description for Get all top-level domains supported for registration. </summary> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <returns> An async collection of <see cref="TopLevelDomain" /> that may take multiple service requests to iterate over. </returns> public virtual AsyncPageable<TopLevelDomain> GetAllAsync(CancellationToken cancellationToken = default) { async Task<Page<TopLevelDomain>> FirstPageFunc(int? pageSizeHint) { using var scope = _clientDiagnostics.CreateScope("TopLevelDomainCollection.GetAll"); scope.Start(); try { var response = await _topLevelDomainsRestClient.ListAsync(Id.SubscriptionId, cancellationToken: cancellationToken).ConfigureAwait(false); return Page.FromValues(response.Value.Value.Select(value => new TopLevelDomain(Parent, value)), response.Value.NextLink, response.GetRawResponse()); } catch (Exception e) { scope.Failed(e); throw; } } async Task<Page<TopLevelDomain>> NextPageFunc(string nextLink, int? pageSizeHint) { using var scope = _clientDiagnostics.CreateScope("TopLevelDomainCollection.GetAll"); scope.Start(); try { var response = await _topLevelDomainsRestClient.ListNextPageAsync(nextLink, Id.SubscriptionId, cancellationToken: cancellationToken).ConfigureAwait(false); return Page.FromValues(response.Value.Value.Select(value => new TopLevelDomain(Parent, value)), response.Value.NextLink, response.GetRawResponse()); } catch (Exception e) { scope.Failed(e); throw; } } return PageableHelpers.CreateAsyncEnumerable(FirstPageFunc, NextPageFunc); } /// <summary> Filters the list of <see cref="TopLevelDomain" /> for this subscription represented as generic resources. </summary> /// <param name="nameFilter"> The filter used in this operation. </param> /// <param name="expand"> Comma-separated list of additional properties to be included in the response. Valid values include `createdTime`, `changedTime` and `provisioningState`. </param> /// <param name="top"> The number of results to return. </param> /// <param name="cancellationToken"> A token to allow the caller to cancel the call to the service. The default value is <see cref="CancellationToken.None" />. </param> /// <returns> A collection of resource that may take multiple service requests to iterate over. </returns> public virtual Pageable<GenericResource> GetAllAsGenericResources(string nameFilter, string expand = null, int? top = null, CancellationToken cancellationToken = default) { using var scope = _clientDiagnostics.CreateScope("TopLevelDomainCollection.GetAllAsGenericResources"); scope.Start(); try { var filters = new ResourceFilterCollection(TopLevelDomain.ResourceType); filters.SubstringFilter = nameFilter; return ResourceListOperations.GetAtContext(Parent as Subscription, filters, expand, top, cancellationToken); } catch (Exception e) { scope.Failed(e); throw; } } /// <summary> Filters the list of <see cref="TopLevelDomain" /> for this subscription represented as generic resources. </summary> /// <param name="nameFilter"> The filter used in this operation. </param> /// <param name="expand"> Comma-separated list of additional properties to be included in the response. Valid values include `createdTime`, `changedTime` and `provisioningState`. </param> /// <param name="top"> The number of results to return. </param> /// <param name="cancellationToken"> A token to allow the caller to cancel the call to the service. The default value is <see cref="CancellationToken.None" />. </param> /// <returns> An async collection of resource that may take multiple service requests to iterate over. </returns> public virtual AsyncPageable<GenericResource> GetAllAsGenericResourcesAsync(string nameFilter, string expand = null, int? top = null, CancellationToken cancellationToken = default) { using var scope = _clientDiagnostics.CreateScope("TopLevelDomainCollection.GetAllAsGenericResources"); scope.Start(); try { var filters = new ResourceFilterCollection(TopLevelDomain.ResourceType); filters.SubstringFilter = nameFilter; return ResourceListOperations.GetAtContextAsync(Parent as Subscription, filters, expand, top, cancellationToken); } catch (Exception e) { scope.Failed(e); throw; } } IEnumerator<TopLevelDomain> IEnumerable<TopLevelDomain>.GetEnumerator() { return GetAll().GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetAll().GetEnumerator(); } IAsyncEnumerator<TopLevelDomain> IAsyncEnumerable<TopLevelDomain>.GetAsyncEnumerator(CancellationToken cancellationToken) { return GetAllAsync(cancellationToken: cancellationToken).GetAsyncEnumerator(cancellationToken); } // Builders. // public ArmBuilder<Azure.Core.ResourceIdentifier, TopLevelDomain, TopLevelDomainData> Construct() { } } }
49.766017
195
0.62174
[ "MIT" ]
Manny27nyc/azure-sdk-for-net
sdk/websites/Azure.ResourceManager.AppService/src/Generated/TopLevelDomainCollection.cs
17,866
C#
using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Reflection; using System.Runtime.CompilerServices; using System.Security.Claims; using System.Threading.Tasks; using EntityGraphQL.Authorization; using EntityGraphQL.Compiler; using EntityGraphQL.Compiler.Util; using EntityGraphQL.Directives; using EntityGraphQL.Extensions; using EntityGraphQL.LinqQuery; namespace EntityGraphQL.Schema { /// <summary> /// Builder interface to build a schema definition. The built schema definition maps an external view of your data model to you internal model. /// This allows your internal model to change over time while not break your external API. You can create new versions when needed. /// </summary> /// <typeparam name="TContextType">Base object graph. Ex. DbContext</typeparam> public class SchemaProvider<TContextType> : ISchemaProvider { protected Dictionary<string, ISchemaType> types = new Dictionary<string, ISchemaType>(); protected Dictionary<string, MutationType> mutations = new Dictionary<string, MutationType>(); protected Dictionary<string, IDirectiveProcessor> directives = new Dictionary<string, IDirectiveProcessor> { // the 2 inbuilt directives defined by gql {"include", new IncludeDirectiveProcessor()}, {"skip", new SkipDirectiveProcessor()}, }; private readonly string queryContextName; // map some types to scalar types protected Dictionary<Type, GqlTypeInfo> customTypeMappings; public SchemaProvider() { // default GQL scalar types types.Add("Int", new SchemaType<int>(this, "Int", "Int scalar", false, false, true)); types.Add("Float", new SchemaType<double>(this, "Float", "Float scalar", false, false, true)); types.Add("Boolean", new SchemaType<bool>(this, "Boolean", "Boolean scalar", false, false, true)); types.Add("String", new SchemaType<string>(this, "String", "String scalar", false, false, true)); types.Add("ID", new SchemaType<Guid>(this, "ID", "ID scalar", false, false, true)); // default custom scalar for DateTime types.Add("Date", new SchemaType<DateTime>(this, "Date", "Date with time scalar", false, false, true)); customTypeMappings = new Dictionary<Type, GqlTypeInfo> { {typeof(short), new GqlTypeInfo(() => Type("Int"), typeof(short))}, {typeof(ushort), new GqlTypeInfo(() => Type("Int"), typeof(ushort))}, {typeof(uint), new GqlTypeInfo(() => Type("Int"), typeof(uint))}, {typeof(ulong), new GqlTypeInfo(() => Type("Int"), typeof(ulong))}, {typeof(long), new GqlTypeInfo(() => Type("Int"), typeof(long))}, {typeof(float), new GqlTypeInfo(() => Type("Float"), typeof(float))}, {typeof(decimal), new GqlTypeInfo(() => Type("Float"), typeof(decimal))}, {typeof(byte[]), new GqlTypeInfo(() => Type("String"), typeof(byte[]))}, {typeof(bool), new GqlTypeInfo(() => Type("Boolean"), typeof(bool))}, }; var queryContext = new SchemaType<TContextType>(this, typeof(TContextType).Name, "Query schema"); queryContextName = queryContext.Name; types.Add(queryContext.Name, queryContext); // add types first as fields from the other types may refer to these types AddType<Models.TypeElement>("__Type", "Information about types"); AddType<Models.EnumValue>("__EnumValue", "Information about enums"); AddType<Models.InputValue>("__InputValue", "Arguments provided to Fields or Directives and the input fields of an InputObject are represented as Input Values which describe their type and optionally a default value."); AddType<Models.Directive>("__Directive", "Information about directives"); AddType<Models.Field>("__Field", "Information about fields"); AddType<Models.SubscriptionType>("Information about subscriptions"); AddType<Models.Schema>("__Schema", "A GraphQL Schema defines the capabilities of a GraphQL server. It exposes all available types and directives on the server, as well as the entry points for query, mutation, and subscription operations."); // add the fields Type<Models.TypeElement>().AddAllFields(); Type<Models.EnumValue>().AddAllFields(); Type<Models.InputValue>().AddAllFields(); Type<Models.Directive>().AddAllFields(); Type<Models.Field>().AddAllFields(); Type<Models.SubscriptionType>().AddAllFields(); Type<Models.Schema>().AddAllFields(); Type<Models.TypeElement>("__Type").ReplaceField("enumValues", new { includeDeprecated = false }, (t, p) => t.EnumValues.Where(f => p.includeDeprecated ? f.IsDeprecated || !f.IsDeprecated : !f.IsDeprecated).ToList(), "Enum values available on type"); SetupIntrospectionTypesAndField(); } public QueryResult ExecuteQuery(QueryRequest gql, TContextType context, IServiceProvider serviceProvider, ClaimsIdentity claims, IMethodProvider methodProvider = null) { return ExecuteQueryAsync(gql, context, serviceProvider, claims, methodProvider).Result; } /// <summary> /// Execute a query using this schema. /// </summary> /// <param name="gql">The query</param> /// <param name="context">The context object. An instance of the context the schema was build from</param> /// <param name="serviceProvider">A service provider used for looking up dependencies of field selections and mutations</param> /// <param name="claims">Optional claims to check access for queries</param> /// <param name="methodProvider"></param> /// <param name="includeDebugInfo"></param> /// <typeparam name="TContextType"></typeparam> /// <returns></returns> public async Task<QueryResult> ExecuteQueryAsync(QueryRequest gql, TContextType context, IServiceProvider serviceProvider, ClaimsIdentity claims, IMethodProvider methodProvider = null) { if (methodProvider == null) methodProvider = new DefaultMethodProvider(); QueryResult result; try { var graphQLCompiler = new GraphQLCompiler(this, methodProvider); var queryResult = graphQLCompiler.Compile(gql, claims); result = await queryResult.ExecuteQueryAsync(context, serviceProvider, gql.OperationName); } catch (Exception ex) { // error with the whole query result = new QueryResult { Errors = { new GraphQLError(ex.InnerException != null ? ex.InnerException.Message : ex.Message) } }; } return result; } private void SetupIntrospectionTypesAndField() { // evaluate Fields lazily so we don't end up in endless loop Type<Models.TypeElement>("__Type").ReplaceField("fields", new { includeDeprecated = false }, (t, p) => SchemaIntrospection.BuildFieldsForType(this, t.Name).Where(f => p.includeDeprecated ? f.IsDeprecated || !f.IsDeprecated : !f.IsDeprecated).ToList(), "Fields available on type"); ReplaceField("__schema", db => SchemaIntrospection.Make(this), "Introspection of the schema", "__Schema"); ReplaceField("__type", new { name = ArgumentHelper.Required<string>() }, (db, p) => SchemaIntrospection.Make(this).Types.Where(s => s.Name == p.name).First(), "Query a type by name", "__Type"); } /// <summary> /// Add a new type into the schema with TBaseType as it's context /// </summary> /// <param name="name">Name of the type</param> /// <param name="description">description of the type</param> /// <typeparam name="TBaseType"></typeparam> /// <returns></returns> public SchemaType<TBaseType> AddType<TBaseType>(string name, string description) { var tt = new SchemaType<TBaseType>(this, name, description); types.Add(name, tt); return tt; } public ISchemaType AddType(Type contextType, string name, string description) { var tt = new SchemaType<object>(this, contextType, name, description); types.Add(name, tt); return tt; } public ISchemaProvider RemoveType<TType>() { return RemoveType(Type(typeof(TType)).Name); } public ISchemaProvider RemoveType(string schemaType) { types.Remove(schemaType); return this; } /// <summary> /// Add a GQL Input type to the schema. Input types are objects used in arguments of fields or mutations /// </summary> /// <param name="name"></param> /// <param name="description"></param> /// <typeparam name="TBaseType"></typeparam> /// <returns></returns> public SchemaType<TBaseType> AddInputType<TBaseType>(string name, string description) { var tt = new SchemaType<TBaseType>(this, name, description, true); types.Add(name, tt); return tt; } /// <summary> /// Add any methods marked with GraphQLMutationAttribute in the given type to the schema. Names are added as lowerCaseCamel` /// </summary> /// <param name="mutationClassInstance"></param> /// <typeparam name="TType"></typeparam> public void AddMutationFrom<TType>(TType mutationClassInstance) { foreach (var method in mutationClassInstance.GetType().GetMethods()) { if (method.GetCustomAttribute(typeof(GraphQLMutationAttribute)) is GraphQLMutationAttribute attribute) { var isAsync = method.GetCustomAttribute(typeof(AsyncStateMachineAttribute)) != null; string name = SchemaGenerator.ToCamelCaseStartsLower(method.Name); var claims = method.GetCustomAttributes(typeof(GraphQLAuthorizeAttribute)).Cast<GraphQLAuthorizeAttribute>(); var requiredClaims = new RequiredClaims(claims); var actualReturnType = GetTypeFromMutationReturn(isAsync ? method.ReturnType.GetGenericArguments()[0] : method.ReturnType); var typeName = GetSchemaTypeNameForDotnetType(actualReturnType); var returnType = new GqlTypeInfo(() => GetReturnType(typeName), actualReturnType); var mutationType = new MutationType(this, name, returnType, mutationClassInstance, method, attribute.Description, requiredClaims, isAsync); mutations[name] = mutationType; } } } private ISchemaType GetReturnType(string typeName) { if (types.ContainsKey(typeName)) return types[typeName]; return null; } public bool HasMutation(string method) { return mutations.ContainsKey(method); } /// <summary> /// Add a mapping from a Dotnet type to a GQL schema type. Make sure you have added the GQL type /// in the schema as a Scalar type or full type /// </summary> /// <param name="gqlType">The GQL schema type in full form. E.g. [Int!]!, [Int], Int, etc.</param> /// <typeparam name="TFrom"></typeparam> public void AddTypeMapping<TFrom>(string gqlType) { var typeInfo = GqlTypeInfo.FromGqlType(this, typeof(TFrom), gqlType); // add mapping customTypeMappings.Add(typeof(TFrom), typeInfo); SetupIntrospectionTypesAndField(); } public GqlTypeInfo GetCustomTypeMapping(Type dotnetType) { if (customTypeMappings.ContainsKey(dotnetType)) return customTypeMappings[dotnetType]; return null; } /// <summary> /// Adds a new type into the schema. The name defaults to the TBaseType name /// </summary> /// <param name="description"></param> /// <typeparam name="TBaseType"></typeparam> /// <returns></returns> public SchemaType<TBaseType> AddType<TBaseType>(string description) { var name = typeof(TBaseType).Name; return AddType<TBaseType>(name, description); } /// <summary> /// Add a field to the root type. This is where you define top level objects/names that you can query. /// The name defaults to the MemberExpression from selection modified to lowerCamelCase /// </summary> /// <param name="selection"></param> /// <param name="description"></param> /// <param name="returnSchemaType"></param> public Field AddField<TReturn>(Expression<Func<TContextType, TReturn>> selection, string description, string returnSchemaType = null, bool? isNullable = null) { var exp = ExpressionUtil.CheckAndGetMemberExpression(selection); return AddField(SchemaGenerator.ToCamelCaseStartsLower(exp.Member.Name), selection, description, returnSchemaType, isNullable); } /// <summary> /// Add a field to the root type. This is where you define top level objects/names that you can query. /// Note the name you use is case sensistive. We recommend following GraphQL and useCamelCase as this library will for methods that use Expressions. /// </summary> /// <param name="name"></param> /// <param name="selection"></param> /// <param name="description"></param> /// <param name="returnSchemaType"></param> public Field AddField<TReturn>(string name, Expression<Func<TContextType, TReturn>> selection, string description, string returnSchemaType = null, bool? isNullable = null) { return Type<TContextType>().AddField(name, selection, description, returnSchemaType, isNullable); } public Field ReplaceField<TParams, TReturn>(Expression<Func<TContextType, object>> selection, TParams argTypes, Expression<Func<TContextType, TParams, TReturn>> selectionExpression, string description, string returnSchemaType = null, bool? isNullable = null) { var exp = ExpressionUtil.CheckAndGetMemberExpression(selection); var name = SchemaGenerator.ToCamelCaseStartsLower(exp.Member.Name); Type<TContextType>().RemoveField(name); return Type<TContextType>().AddField(name, argTypes, selectionExpression, description, returnSchemaType, isNullable); } public Field ReplaceField<TReturn>(string name, Expression<Func<TContextType, TReturn>> selectionExpression, string description, string returnSchemaType = null, bool? isNullable = null) { Type<TContextType>().RemoveField(name); return Type<TContextType>().AddField(name, selectionExpression, description, returnSchemaType, isNullable); } public Field ReplaceField<TParams, TReturn>(string name, TParams argTypes, Expression<Func<TContextType, TParams, TReturn>> selectionExpression, string description, string returnSchemaType = null, bool? isNullable = null) { Type<TContextType>().RemoveField(name); return Type<TContextType>().AddField(name, argTypes, selectionExpression, description, returnSchemaType, isNullable); } /// <summary> /// Add a field with arguments. /// { /// field(arg: val) {} /// } /// Note the name you use is case sensistive. We recommend following GraphQL and useCamelCase as this library will for methods that use Expressions. /// </summary> /// <param name="name">Field name</param> /// <param name="argTypes">Anonymous object defines the names and types of each argument</param> /// <param name="selectionExpression">The expression that selects the data from TContextType using the arguments</param> /// <param name="returnSchemaType">The schema type to return, it defines the fields available on the return object. If null, defaults to TReturn type mapped in the schema.</param> /// <typeparam name="TParams">Type describing the arguments</typeparam> /// <typeparam name="TReturn">The return entity type that is mapped to a type in the schema</typeparam> /// <returns></returns> public Field AddField<TParams, TReturn>(string name, TParams argTypes, Expression<Func<TContextType, TParams, TReturn>> selectionExpression, string description, string returnSchemaType = null, bool? isNullable = null) { return Type<TContextType>().AddField(name, argTypes, selectionExpression, description, returnSchemaType, isNullable); } /// <summary> /// Add a field to the root query. /// Note the name you use is case sensistive. We recommend following GraphQL and useCamelCase as this library will for methods that use Expressions. /// </summary> /// <param name="field"></param> public Field AddField(Field field) { return types[queryContextName].AddField(field); } /// <summary> /// Get registered type by TType name /// </summary> /// <typeparam name="TType"></typeparam> /// <returns></returns> public SchemaType<TType> Type<TType>() { // look up by the actual type not the name var schemaType = (SchemaType<TType>)Type(typeof(TType)); return schemaType; } public ISchemaType Type(Type dotnetType) { // look up by the actual type not the name var schemaType = types.Values.FirstOrDefault(t => t.ContextType == dotnetType); if (schemaType == null && customTypeMappings.ContainsKey(dotnetType)) { schemaType = customTypeMappings[dotnetType].SchemaType; } if (schemaType == null) throw new EntityGraphQLCompilerException($"No schema type found for dotnet type {dotnetType.Name}. Make sure you add it or add a type mapping"); return schemaType; } public SchemaType<TType> Type<TType>(string typeName) { var schemaType = (SchemaType<TType>)types[typeName]; return schemaType; } public ISchemaType Type(string typeName) { var schemaType = types[typeName]; return schemaType; } // ISchemaProvider interface public Type ContextType { get { return types[queryContextName].ContextType; } } public bool TypeHasField(string typeName, string identifier, IEnumerable<string> fieldArgs, ClaimsIdentity claims) { if (!types.ContainsKey(typeName)) return false; var t = types[typeName]; if (!t.HasField(identifier)) { if ((fieldArgs == null || !fieldArgs.Any()) && t.HasField(identifier)) { var field = t.GetField(identifier, claims); if (field != null) { // if there are defaults for all, continue if (field.RequiredArgumentNames.Any()) { throw new EntityGraphQLCompilerException($"Field '{identifier}' missing required argument(s) '{string.Join(", ", field.RequiredArgumentNames)}'"); } return true; } else { throw new EntityGraphQLCompilerException($"Field '{identifier}' not found on current context '{typeName}'"); } } return false; } return true; } public bool TypeHasField(Type type, string identifier, IEnumerable<string> fieldArgs, ClaimsIdentity claims) { return TypeHasField(type.Name, identifier, fieldArgs, claims); } public List<ISchemaType> EnumTypes() { return types.Values.Where(t => t.IsEnum).ToList(); } public string GetActualFieldName(string typeName, string identifier, ClaimsIdentity claims) { if (types.ContainsKey(typeName) && types[typeName].HasField(identifier)) return types[typeName].GetField(identifier, claims).Name; if (typeName == queryContextName && types[queryContextName].HasField(identifier)) return types[queryContextName].GetField(identifier, claims).Name; if (mutations.Keys.Any(k => k.ToLower() == identifier.ToLower())) return mutations.Keys.First(k => k.ToLower() == identifier.ToLower()); throw new EntityGraphQLCompilerException($"Field {identifier} not found on type {typeName}"); } public IField GetFieldOnContext(Expression context, string fieldName, ClaimsIdentity claims) { if (context.Type == ContextType && mutations.ContainsKey(fieldName)) { var mutation = mutations[fieldName]; if (!AuthUtil.IsAuthorized(claims, mutation.AuthorizeClaims)) { throw new EntityGraphQLAccessException($"You do not have access to mutation '{fieldName}'. You require any of the following security claims [{string.Join(", ", mutation.AuthorizeClaims.Claims.SelectMany(r => r))}]"); } return mutation; } if (types.ContainsKey(GetSchemaTypeNameForDotnetType(context.Type))) { var field = types[GetSchemaTypeNameForDotnetType(context.Type)].GetField(fieldName, claims); return field; } throw new EntityGraphQLCompilerException($"No field or mutation '{fieldName}' found in schema."); } public ExpressionResult GetExpressionForField(Expression context, string typeName, string fieldName, Dictionary<string, ExpressionResult> args, ClaimsIdentity claims) { if (!types.ContainsKey(typeName)) throw new EntityQuerySchemaException($"{typeName} not found in schema."); var field = types[typeName].GetField(fieldName, claims); var result = new ExpressionResult(field.Resolve ?? Expression.Property(context, fieldName), field.Services); if (field.ArgumentTypesObject != null) { var argType = field.ArgumentTypesObject.GetType(); // get the values for the argument anonymous type object constructor var propVals = new Dictionary<PropertyInfo, object>(); var fieldVals = new Dictionary<FieldInfo, object>(); // if they used AddField("field", new { id = Required<int>() }) the compiler makes properties and a constructor with the values passed in foreach (var argField in argType.GetProperties()) { var val = BuildArgumentFromMember(args, field, argField.Name, argField.PropertyType, argField.GetValue(field.ArgumentTypesObject)); // if this was a EntityQueryType we actually get a Func from BuildArgumentFromMember but the anonymous type requires EntityQueryType<>. We marry them here, this allows users to EntityQueryType<> as a Func in LINQ methods while not having it defined until runtime if (argField.PropertyType.IsConstructedGenericType && argField.PropertyType.GetGenericTypeDefinition() == typeof(EntityQueryType<>)) { // make sure we create a new instance and not update the schema var entityQuery = Activator.CreateInstance(argField.PropertyType); // set Query var hasValue = val != null; if (hasValue) { var genericProp = entityQuery.GetType().GetProperty("Query"); genericProp.SetValue(entityQuery, ((ExpressionResult)val).Expression); } propVals.Add(argField, entityQuery); } else { if (val != null && val.GetType() != argField.PropertyType) val = ExpressionUtil.ChangeType(val, argField.PropertyType); propVals.Add(argField, val); } } // The auto argument is built at runtime from LinqRuntimeTypeBuilder which just makes public fields // they could also use a custom class, so we need to look for both fields and properties foreach (var argField in argType.GetFields()) { var val = BuildArgumentFromMember(args, field, argField.Name, argField.FieldType, argField.GetValue(field.ArgumentTypesObject)); fieldVals.Add(argField, val); } // create a copy of the anonymous object. It will have the default values set // there is only 1 constructor for the anonymous type that takes all the property values var con = argType.GetConstructor(propVals.Keys.Select(v => v.PropertyType).ToArray()); object parameters; if (con != null) { parameters = con.Invoke(propVals.Values.ToArray()); foreach (var item in fieldVals) { item.Key.SetValue(parameters, item.Value); } } else { // expect an empty constructor con = argType.GetConstructor(new Type[0]); parameters = con.Invoke(new object[0]); foreach (var item in fieldVals) { item.Key.SetValue(parameters, item.Value); } foreach (var item in propVals) { item.Key.SetValue(parameters, item.Value); } } // tell them this expression has another parameter var argParam = Expression.Parameter(argType, $"arg_{argType.Name}"); result.Expression = new ParameterReplacer().ReplaceByType(result.Expression, argType, argParam); result.AddConstantParameter(argParam, parameters); } // the expressions we collect have a different starting parameter. We need to change that var paramExp = field.FieldParam; result.Expression = new ParameterReplacer().Replace(result.Expression, paramExp, context); return result; } private static object BuildArgumentFromMember(Dictionary<string, ExpressionResult> args, Field field, string memberName, Type memberType, object defaultValue) { string argName = memberName; // check we have required arguments if (memberType.GetGenericArguments().Any() && memberType.GetGenericTypeDefinition() == typeof(RequiredField<>)) { if (args == null || !args.ContainsKey(argName)) { throw new EntityGraphQLCompilerException($"Field '{field.Name}' missing required argument '{argName}'"); } var item = Expression.Lambda(args[argName]).Compile().DynamicInvoke(); var constructor = memberType.GetConstructor(new[] { item.GetType() }); if (constructor == null) { // we might need to change the type foreach (var c in memberType.GetConstructors()) { var parameters = c.GetParameters(); if (parameters.Count() == 1) { item = ExpressionUtil.ChangeType(item, parameters[0].ParameterType); constructor = memberType.GetConstructor(new[] { item.GetType() }); break; } } } if (constructor == null) { throw new EntityGraphQLCompilerException($"Could not find a constructor for type {memberType.Name} that takes value '{item}'"); } var typedVal = constructor.Invoke(new[] { item }); return typedVal; } else if (defaultValue != null && defaultValue.GetType().IsConstructedGenericType && defaultValue.GetType().GetGenericTypeDefinition() == typeof(EntityQueryType<>)) { return args != null && args.ContainsKey(argName) ? args[argName] : null; } else if (args != null && args.ContainsKey(argName)) { return Expression.Lambda(args[argName]).Compile().DynamicInvoke(); } else { // set the default value return defaultValue; } } /// <summary> /// Give a Dotnet type it finds the matching schema type name /// </summary> /// <param name="type"></param> /// <returns></returns> public string GetSchemaTypeNameForDotnetType(Type type) { type = GetTypeFromMutationReturn(type); if (type.IsEnumerableOrArray()) { type = type.GetGenericArguments()[0]; } if (customTypeMappings.ContainsKey(type)) return customTypeMappings[type].SchemaType.Name; if (type == types[queryContextName].ContextType) return type.Name; foreach (var eType in types.Values) { if (eType.ContextType == type) return eType.Name; } throw new EntityGraphQLCompilerException($"No mapped entity found for type '{type}'"); } /// <summary> /// Return the actual return type of a mutation - strips out the Expression<Func<>> /// </summary> /// <param name="type"></param> /// <returns></returns> public Type GetTypeFromMutationReturn(Type type) { if (type.GetTypeInfo().BaseType == typeof(LambdaExpression)) { // This should be Expression<Func<Context, ReturnType>> type = type.GetGenericArguments()[0].GetGenericArguments()[1]; } return type; } public bool HasType(string typeName) { return types.ContainsKey(typeName); } public bool HasType(Type type) { if (type == types[queryContextName].ContextType) return true; foreach (var eType in types.Values) { if (eType.ContextType == type) return true; } return false; } /// <summary> /// Builds a GraphQL schema file /// </summary> /// <returns></returns> public string GetGraphQLSchema() { var extraMappings = customTypeMappings.ToDictionary(k => k.Key, v => v.Value); return SchemaGenerator.Make(this); } [Obsolete("Use AddScalarType")] public void AddCustomScalarType(Type clrType, string gqlTypeName, string description, bool required = false) { AddScalarType(clrType, gqlTypeName, description); } [Obsolete("Use AddScalarType")] public void AddCustomScalarType<TType>(string gqlTypeName, string description, bool required = false) { AddScalarType<TType>(gqlTypeName, description); } public ISchemaType AddScalarType(Type clrType, string gqlTypeName, string description) { var schemaType = (ISchemaType)Activator.CreateInstance(typeof(SchemaType<>).MakeGenericType(clrType), this, gqlTypeName, description, false, false, true); types.Add(gqlTypeName, schemaType); return schemaType; } public ISchemaType AddScalarType<TType>(string gqlTypeName, string description) { var schemaType = new SchemaType<TType>(this, gqlTypeName, description, false, false, true); types.Add(gqlTypeName, schemaType); return schemaType; } public IEnumerable<Field> GetQueryFields() { return types[queryContextName].GetFields(); } public IEnumerable<ISchemaType> GetNonContextTypes() { return types.Values.Where(s => s.Name != queryContextName).ToList(); } public IEnumerable<ISchemaType> GetScalarTypes() { return types.Values.Where(t => t.IsScalar); } public IEnumerable<MutationType> GetMutations() { return mutations.Values.ToList(); } /// <summary> /// Remove type and any field that returns that type /// </summary> /// <typeparam name="TSchemaType"></typeparam> public void RemoveTypeAndAllFields<TSchemaType>() { this.RemoveTypeAndAllFields(typeof(TSchemaType).Name); } /// <summary> /// Remove type and any field that returns that type /// </summary> /// <param name="typeName"></param> public void RemoveTypeAndAllFields(string typeName) { foreach (var context in types.Values) { RemoveFieldsOfType(typeName, context); } types.Remove(typeName); } private void RemoveFieldsOfType(string schemaType, ISchemaType contextType) { foreach (var field in contextType.GetFields().ToList()) { if (field.ReturnType.SchemaType.Name == schemaType) { contextType.RemoveField(field.Name); } } } public ISchemaType AddEnum(string name, Type type, string description) { var schemaType = new SchemaType<object>(this, type, name, description, false, true); types.Add(name, schemaType); return schemaType.AddAllFields(); } public IDirectiveProcessor GetDirective(string name) { if (directives.ContainsKey(name)) return directives[name]; throw new EntityGraphQLCompilerException($"Directive {name} not defined in schema"); } public IEnumerable<IDirectiveProcessor> GetDirectives() { return directives.Values.ToList(); } public void AddDirective(string name, IDirectiveProcessor directive) { if (directives.ContainsKey(name)) throw new EntityGraphQLCompilerException($"Directive {name} already exists on schema"); directives.Add(name, directive); } public void PopulateFromContext(bool autoCreateIdArguments, bool autoCreateEnumTypes, Func<MemberInfo, string> fieldNamer = null) { SchemaBuilder.FromObject(this, autoCreateIdArguments, autoCreateEnumTypes, fieldNamer); } } }
47.836653
282
0.596541
[ "MIT" ]
anilbabukb/EntityGraphQL
src/EntityGraphQL/Schema/SchemaProvider.cs
36,021
C#
using RestWithASPNET.Model; using RestWithASPNET.Model.Context; using RestWithASPNET.Repository.Generic; using System; using System.Collections.Generic; using System.Linq; namespace RestWithASPNET.Repository { public class PersonRepository : GenericRepository<Person>, IPersonRepository { public PersonRepository(MySQLContext context) : base (context) { } public Person Disable(long id) { if (_context.Persons.Any(p => p.Id.Equals(id))) return null; var user = _context.Persons.SingleOrDefault(p => p.Id.Equals(id)); if (user != null) { user.Enabled = false; try { _context.Entry(user).CurrentValues.SetValues(user); _context.SaveChanges(); } catch (Exception) { throw; } } return user; } public List<Person> FindByName(string firstName, string lastName) { if (!string.IsNullOrWhiteSpace(firstName) && !string.IsNullOrWhiteSpace(lastName)) { return _context.Persons.Where( p => p.FirstName.Contains(firstName) && (p.LastName.Contains(lastName))).ToList(); } else if (string.IsNullOrWhiteSpace(firstName) && !string.IsNullOrWhiteSpace(lastName)) { return _context.Persons.Where( p => p.LastName.Contains(lastName)).ToList(); } else if (!string.IsNullOrWhiteSpace(firstName) && string.IsNullOrWhiteSpace(lastName)) { return _context.Persons.Where( p => p.FirstName.Contains(firstName)).ToList(); } return null; } } }
31.915254
98
0.536909
[ "Apache-2.0" ]
dschaly/RESTWithASP-NET5
02_RestWithASPNET_Person/RestWithASPNET/RestWithASPNET/Repository/PersonRepository.cs
1,885
C#
using System.Windows.Input; namespace Infinity.Commands; public abstract class CommandBase : ICommand { public static bool DefaultUseCommandManager { get; set; } = true; public abstract bool CanExecute(object? parameter); public abstract void Execute(object? parameter); public abstract event EventHandler? CanExecuteChanged; #region Static Methods public static void Subscribe(EventHandler? canExecuteChangedHandler) { CommandManager.RequerySuggested += canExecuteChangedHandler; } public static void Unsubscribe(EventHandler? canExecuteChangedHandler) { CommandManager.RequerySuggested -= canExecuteChangedHandler; } public static void InvalidateRequerySuggested() { CommandManager.InvalidateRequerySuggested(); } #endregion }
28.928571
76
0.751852
[ "MIT" ]
Khaled-Janada/AC_Charts
toolkits/Infinity.Mvvm/Commands/CommandBase.cs
812
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("04. Songs")] [assembly: System.Reflection.AssemblyConfigurationAttribute("Debug")] [assembly: System.Reflection.AssemblyFileVersionAttribute("1.0.0.0")] [assembly: System.Reflection.AssemblyInformationalVersionAttribute("1.0.0")] [assembly: System.Reflection.AssemblyProductAttribute("04. Songs")] [assembly: System.Reflection.AssemblyTitleAttribute("04. Songs")] [assembly: System.Reflection.AssemblyVersionAttribute("1.0.0.0")] // Generated by the MSBuild WriteCodeFragment class.
41.666667
81
0.625
[ "MIT" ]
dradoslavov/Technology-Fundamentals
07. Objects-and-Classes-Lab/04. Songs/obj/Debug/netcoreapp2.1/04. Songs.AssemblyInfo.cs
1,000
C#
using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Windows; // 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("WpfProximityModuleDemo")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("WpfProximityModuleDemo")] [assembly: AssemblyCopyright("Copyright © 2010")] [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)] //In order to begin building localizable applications, set //<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file //inside a <PropertyGroup>. For example, if you are using US english //in your source files, set the <UICulture> to en-US. Then uncomment //the NeutralResourceLanguage attribute below. Update the "en-US" in //the line below to match the UICulture setting in the project file. //[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)] [assembly: ThemeInfo( ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located //(used if a resource is not found in the page, // or application resource dictionaries) ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located //(used if a resource is not found in the page, // app, or any theme specific resource dictionaries) )] // 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")]
41.160714
97
0.738829
[ "MIT" ]
slgrobotics/TrackRoamer
src/Hardware/ProximityModule/WpfProximityModuleDemo/WpfProximityModuleDemo/Properties/AssemblyInfo.cs
2,308
C#
using System; using System.Collections.Generic; using System.Configuration; using System.Data; using System.Linq; using System.Threading.Tasks; using System.Windows; namespace XtoX { /// <summary> /// Interaction logic for App.xaml /// </summary> public partial class App : Application { } }
17.666667
42
0.698113
[ "MIT" ]
ZacharyWalsh57/XtoX
XtoX/App.xaml.cs
320
C#
using Newtonsoft.Json; namespace RiotGamesApi.Libraries.Lol.v3.StaticEndPoints.Runes { public class ImageDto { // [JsonProperty("full")] public string full { get; set; } // [JsonProperty("group")] public string group { get; set; } // [JsonProperty("sprite")] public string sprite { get; set; } // [JsonProperty("h")] public int h { get; set; } // [JsonProperty("w")] public int w { get; set; } // [JsonProperty("y")] public int y { get; set; } [JsonProperty("x")] public int x { get; set; } } }
19.823529
61
0.488131
[ "MIT" ]
msx752/RiotGamesAPI
RiotGamesApi/Libraries/Lol/v3/StaticEndPoints/Runes/ImageDto.cs
676
C#
// **************************************************************** // Copyright 2008, Charlie Poole // This is free software licensed under the NUnit license. You may // obtain a copy of the license at http://nunit.org. // **************************************************************** using System; namespace NUnit.Core { public class Logger { private string name; private string fullname; public Logger(string name) { this.fullname = this.name = name; int index = fullname.LastIndexOf('.'); if (index >= 0) this.name = fullname.Substring(index + 1); } #region Error public void Error(string message) { Log(InternalTraceLevel.Error, message); } public void Error(string message, params object[] args) { Log(InternalTraceLevel.Error, message, args); } public void Error(string message, Exception ex) { if (InternalTrace.Level >= InternalTraceLevel.Error) { InternalTrace.Log(InternalTraceLevel.Error, message, name, ex); } } #endregion #region Warning public void Warning(string message) { Log(InternalTraceLevel.Warning, message); } public void Warning(string message, params object[] args) { Log(InternalTraceLevel.Warning, message, args); } #endregion #region Info public void Info(string message) { Log(InternalTraceLevel.Info, message); } public void Info(string message, params object[] args) { Log(InternalTraceLevel.Info, message, args); } #endregion #region Debug public void Debug(string message) { Log(InternalTraceLevel.Verbose, message); } public void Debug(string message, params object[] args) { Log(InternalTraceLevel.Verbose, message, args); } #endregion #region Helper Methods public void Log(InternalTraceLevel level, string message) { if (InternalTrace.Level >= level) InternalTrace.Log(level, message, name); } private void Log(InternalTraceLevel level, string format, params object[] args) { if (InternalTrace.Level >= level) Log(level, string.Format( format, args ) ); } #endregion } }
28.414894
88
0.507301
[ "MIT" ]
acken/AutoTest.Net
lib/NUnit/src/NUnit-2.6.0.12051/src/NUnitCore/core/Logger.cs
2,673
C#
using Kara.Framework.Common.Mvc.JsUpload; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Web.Mvc; namespace Kara.Framework.Common.Mvc.Helpers { public static class JsUploadHtmlHelper { public static MvcHtmlString JsUpload(this HtmlHelper htmlHelper, JsUploadParam param) { var sb = new System.Text.StringBuilder(); sb.AppendLine(@" <form method=""post"" action=""[JsUploadParam.UploadUrl]"">"); sb.AppendLine(@" <div style=""overflow-y:auto"" class=""panel"">"); sb.AppendLine(@" <input name=""files"" id=""files"" type=""file"" />"); sb.AppendLine(@" <div class=""pull-right"" style=""margin-top:5px;"">"); sb.AppendLine(@" <button id=""jsUpload_btnReset"" type=""button"" class=""k-button hidden"">Reset</button>"); sb.AppendLine(@" </div>"); sb.AppendLine(@" </div>"); sb.AppendLine(@" </form>"); sb.AppendLine(@""); sb.AppendLine(@" <script type=""text/javascript"">"); sb.AppendLine(@" var [JsUploadParam.JsNamespace] = {};"); sb.AppendLine(@" [JsUploadParam.JsNamespace].btnReset = ""#jsUpload_btnReset"";"); sb.AppendLine(@" [JsUploadParam.JsNamespace].reset = function () {"); sb.AppendLine(@" $("".k-upload-files.k-reset"").find(""li"").parent().remove();"); sb.AppendLine(@" };"); sb.AppendLine(@" [JsUploadParam.JsNamespace].showReset = function () {"); sb.AppendLine(@" $([JsUploadParam.JsNamespace].btnReset).removeClass(""hidden"");"); sb.AppendLine(@" }"); sb.AppendLine(@""); sb.AppendLine(@" $(document).ready(function () {"); sb.AppendLine(@" $(""#files"").kendoUpload({"); sb.AppendLine(@" async: {"); sb.AppendLine(@" saveUrl: "" [JsUploadParam.UploadUrl]"","); sb.AppendLine(@" autoUpload: true"); sb.AppendLine(@" },"); sb.AppendLine(@" select: [JsUploadParam.JsNamespace].showReset"); sb.AppendLine(@" });"); sb.AppendLine(@" $([JsUploadParam.JsNamespace].btnReset).bind(""click"", function () {"); sb.AppendLine(@" [JsUploadParam.JsNamespace].reset();"); sb.AppendLine(@" });"); sb.AppendLine(@" });"); sb.AppendLine(@""); sb.AppendLine(@" </script>"); var script = sb.ToString(); script = JsControlHelper.ReplaceParamWithValue(typeof(JsUploadParam), param, script); return MvcHtmlString.Create(script); } } }
51.206897
132
0.513468
[ "MIT" ]
student-accommodation-one/Kara.Framework.Common.Mvc
Helpers/JsUploadHtmlHelper.cs
2,972
C#
using SubterfugeCore.Core.Entities; using SubterfugeCore.Core.Entities.Positions; using SubterfugeCore.Core.GameEvents.Base; using SubterfugeCore.Core.Interfaces; using SubterfugeCore.Core.Timing; namespace SubterfugeCore.Core.GameEvents.NaturalGameEvents { /// <summary> /// Friendly sub arrival /// </summary> public class FriendlySubArrive : NaturalGameEvent { Sub _arrivingSub; Outpost _outpost; /// <summary> /// Friendly sub arrival event /// </summary> /// <param name="combatant1">Combatant 1</param> /// <param name="combatant2">Combatant 2</param> /// <param name="occursAt">Tick of sub arrival</param> public FriendlySubArrive(ICombatable combatant1, ICombatable combatant2, GameTick occursAt) : base(occursAt, Priority.NATURAL_PRIORITY_6) { this._arrivingSub = (Sub)(combatant1 is Sub ? combatant1 : combatant2); this._outpost = (Outpost)(combatant1 is Outpost ? combatant1 : combatant2); } /// <summary> /// Undoes the sub's arrival /// </summary> /// <returns>If the event was undone</returns> public override bool BackwardAction(TimeMachine timeMachine, GameState state) { if (base.EventSuccess) { this._outpost.RemoveDrillers(this._arrivingSub.GetDrillerCount()); this._outpost.GetSpecialistManager() .RemoveSpecialists(this._arrivingSub.GetSpecialistManager().GetSpecialists()); state.AddSub(this._arrivingSub); return true; } else { return false; } } /// <summary> /// Perfoms a friendly sub arrival /// </summary> /// <returns>If the event was successful</returns> public override bool ForwardAction(TimeMachine timeMachine, GameState state) { if (state.SubExists(this._arrivingSub) && state.OutpostExists(this._outpost)) { this._outpost.AddDrillers(this._arrivingSub.GetDrillerCount()); this._outpost.GetSpecialistManager().AddSpecialists(this._arrivingSub.GetSpecialistManager().GetSpecialists()); state.RemoveSub(this._arrivingSub); base.EventSuccess = true; } else { base.EventSuccess = false; } return base.EventSuccess; } /// <summary> /// Determines if the event was successful. /// </summary> /// <returns>If the event is successful</returns> public override bool WasEventSuccessful() { return base.EventSuccess; } } }
35.56962
145
0.590391
[ "CC0-1.0" ]
pandabear15/Remake-Core
Core/SubterfugeCore/Core/GameEvents/NaturalGameEvents/combat/FriendlySubArrive.cs
2,812
C#
/* * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the ram-2018-01-04.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using System.Net; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.RAM.Model { /// <summary> /// The invitation was already accepted. /// </summary> #if !PCL && !NETSTANDARD [Serializable] #endif public partial class ResourceShareInvitationAlreadyAcceptedException : AmazonRAMException { /// <summary> /// Constructs a new ResourceShareInvitationAlreadyAcceptedException with the specified error /// message. /// </summary> /// <param name="message"> /// Describes the error encountered. /// </param> public ResourceShareInvitationAlreadyAcceptedException(string message) : base(message) {} /// <summary> /// Construct instance of ResourceShareInvitationAlreadyAcceptedException /// </summary> /// <param name="message"></param> /// <param name="innerException"></param> public ResourceShareInvitationAlreadyAcceptedException(string message, Exception innerException) : base(message, innerException) {} /// <summary> /// Construct instance of ResourceShareInvitationAlreadyAcceptedException /// </summary> /// <param name="innerException"></param> public ResourceShareInvitationAlreadyAcceptedException(Exception innerException) : base(innerException) {} /// <summary> /// Construct instance of ResourceShareInvitationAlreadyAcceptedException /// </summary> /// <param name="message"></param> /// <param name="innerException"></param> /// <param name="errorType"></param> /// <param name="errorCode"></param> /// <param name="requestId"></param> /// <param name="statusCode"></param> public ResourceShareInvitationAlreadyAcceptedException(string message, Exception innerException, ErrorType errorType, string errorCode, string requestId, HttpStatusCode statusCode) : base(message, innerException, errorType, errorCode, requestId, statusCode) {} /// <summary> /// Construct instance of ResourceShareInvitationAlreadyAcceptedException /// </summary> /// <param name="message"></param> /// <param name="errorType"></param> /// <param name="errorCode"></param> /// <param name="requestId"></param> /// <param name="statusCode"></param> public ResourceShareInvitationAlreadyAcceptedException(string message, ErrorType errorType, string errorCode, string requestId, HttpStatusCode statusCode) : base(message, errorType, errorCode, requestId, statusCode) {} #if !PCL && !NETSTANDARD /// <summary> /// Constructs a new instance of the ResourceShareInvitationAlreadyAcceptedException class with serialized data. /// </summary> /// <param name="info">The <see cref="T:System.Runtime.Serialization.SerializationInfo" /> that holds the serialized object data about the exception being thrown.</param> /// <param name="context">The <see cref="T:System.Runtime.Serialization.StreamingContext" /> that contains contextual information about the source or destination.</param> /// <exception cref="T:System.ArgumentNullException">The <paramref name="info" /> parameter is null. </exception> /// <exception cref="T:System.Runtime.Serialization.SerializationException">The class name is null or <see cref="P:System.Exception.HResult" /> is zero (0). </exception> protected ResourceShareInvitationAlreadyAcceptedException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) : base(info, context) { } /// <summary> /// Sets the <see cref="T:System.Runtime.Serialization.SerializationInfo" /> with information about the exception. /// </summary> /// <param name="info">The <see cref="T:System.Runtime.Serialization.SerializationInfo" /> that holds the serialized object data about the exception being thrown.</param> /// <param name="context">The <see cref="T:System.Runtime.Serialization.StreamingContext" /> that contains contextual information about the source or destination.</param> /// <exception cref="T:System.ArgumentNullException">The <paramref name="info" /> parameter is a null reference (Nothing in Visual Basic). </exception> #if BCL35 [System.Security.Permissions.SecurityPermission( System.Security.Permissions.SecurityAction.LinkDemand, Flags = System.Security.Permissions.SecurityPermissionFlag.SerializationFormatter)] #endif [System.Security.SecurityCritical] // These FxCop rules are giving false-positives for this method [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2123:OverrideLinkDemandsShouldBeIdenticalToBase")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2134:MethodsMustOverrideWithConsistentTransparencyFxCopRule")] public override void GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { base.GetObjectData(info, context); } #endif } }
49.379032
189
0.693778
[ "Apache-2.0" ]
JeffAshton/aws-sdk-net
sdk/src/Services/RAM/Generated/Model/ResourceShareInvitationAlreadyAcceptedException.cs
6,123
C#
namespace Veruthian.Library.Collections { public interface IMutableIndex<K, V> : IIndex<K, V>, IMutableLookup<K, V> { } public interface IMutableIndex<V> : IMutableIndex<int, V>, IIndex<V> { } }
19.083333
77
0.624454
[ "MIT" ]
Veruthas/Dotnet-Veruthian.Library
Solution/Projects/Veruthian.Library/Collections/IMutableIndex.cs
229
C#
// Copyright 2004-2011 Castle Project - http://www.castleproject.org/ // // 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 CastleTests { using System; using System.Collections.Generic; using Castle.Core; using Castle.MicroKernel; using Castle.MicroKernel.Handlers; using Castle.MicroKernel.Registration; using Castle.MicroKernel.Resolvers; using Castle.MicroKernel.Tests.ClassComponents; using Castle.Windsor.Proxy; using Castle.Windsor.Tests.MicroKernel; using CastleTests.Components; using NUnit.Framework; [TestFixture] public class MicroKernelTestCase : AbstractContainerTestCase { [Test] [Bug("IOC-327")] public void ReleaseComponent_null_silently_ignored_doesnt_throw() { Assert.DoesNotThrow(() => Kernel.ReleaseComponent(null)); } [Test] public void AddClassComponentWithInterface() { Kernel.Register(Component.For<CustomerImpl>().Named("key")); Assert.IsTrue(Kernel.HasComponent("key")); } [Test] public void AddClassComponentWithNoInterface() { Kernel.Register(Component.For(typeof(DefaultCustomer)).Named("key")); Assert.IsTrue(Kernel.HasComponent("key")); } [Test] public void AddClassThatHasTwoParametersOfSameTypeAndNoOverloads() { Kernel.Register(Component.For(typeof(ClassWithTwoParametersWithSameType)).Named("test")); Kernel.Register(Component.For<ICommon>().ImplementedBy(typeof(CommonImpl1)).Named("test2")); var resolved = Kernel.Resolve(typeof(ClassWithTwoParametersWithSameType), new Dictionary<object, object>()); Assert.IsNotNull(resolved); } [Test] public void AddCommonComponent() { Kernel.Register(Component.For<ICustomer>().ImplementedBy<CustomerImpl>().Named("key")); Assert.IsTrue(Kernel.HasComponent("key")); } [Test] public void AddComponentInstance() { var customer = new CustomerImpl(); Kernel.Register(Component.For<ICustomer>().Named("key").Instance(customer)); Assert.IsTrue(Kernel.HasComponent("key")); var customer2 = Kernel.Resolve<CustomerImpl>("key"); Assert.AreSame(customer, customer2); customer2 = Kernel.Resolve<ICustomer>() as CustomerImpl; Assert.AreSame(customer, customer2); } [Test] public void AddComponentInstance2() { var customer = new CustomerImpl(); Kernel.Register(Component.For<CustomerImpl>().Named("key").Instance(customer)); Assert.IsTrue(Kernel.HasComponent("key")); var customer2 = Kernel.Resolve<CustomerImpl>("key"); Assert.AreSame(customer, customer2); customer2 = Kernel.Resolve<CustomerImpl>(); Assert.AreSame(customer, customer2); } [Test] public void AddComponentInstance_ByService() { var customer = new CustomerImpl(); Kernel.Register(Component.For<ICustomer>().Instance(customer)); Assert.AreSame(Kernel.Resolve<ICustomer>(), customer); } [Test] public void AdditionalParametersShouldNotBePropagatedInTheDependencyChain() { Kernel.Register( Component.For<ICustomer>().ImplementedBy<CustomerImpl>().Named("cust").LifeStyle.Transient); Kernel.Register(Component.For<ExtendedCustomer>().Named("custex").LifeStyle.Transient); var dictionary = new Dictionary<string, object> { { "Name", "name" }, { "Address", "address" }, { "Age", "18" } }; var customer = Kernel.Resolve<ICustomer>("cust", dictionary); Assert.AreEqual("name", customer.Name); Assert.AreEqual("address", customer.Address); Assert.AreEqual(18, customer.Age); var custImpl = customer as CustomerImpl; Assert.IsNotNull(custImpl.ExtendedCustomer); Assert.IsNull(custImpl.ExtendedCustomer.Address); Assert.IsNull(custImpl.ExtendedCustomer.Name); Assert.AreEqual(0, custImpl.ExtendedCustomer.Age); } [Test] public void Can_use_custom_dependencyResolver() { var resolver = new NotImplementedDependencyResolver(); var defaultKernel = new DefaultKernel(resolver, new DefaultProxyFactory()); Assert.AreSame(resolver, defaultKernel.Resolver); Assert.AreSame(defaultKernel, resolver.Kernel); } [Test] public void HandlerForClassComponent() { Kernel.Register(Component.For<CustomerImpl>().Named("key")); var handler = Kernel.GetHandler("key"); Assert.IsNotNull(handler); } [Test] public void HandlerForClassWithNoInterface() { Kernel.Register(Component.For<DefaultCustomer>().Named("key")); var handler = Kernel.GetHandler("key"); Assert.IsNotNull(handler); } [Test] public void IOC_50_AddTwoComponentWithSameService_RequestFirstByKey_RemoveFirst_RequestByService_ShouldReturnSecond() { Kernel.Register(Component.For<ICustomer>().ImplementedBy<CustomerImpl>().Named("key")); Kernel.Register(Component.For<ICustomer>().ImplementedBy<CustomerImpl>().Named("key2")); var result = Kernel.Resolve<object>("key"); Assert.IsNotNull(result); result = Kernel.Resolve<ICustomer>(); Assert.IsNotNull(result); } [Test] [ExpectedException(typeof(ComponentRegistrationException))] public void KeyCollision() { Kernel.Register(Component.For<CustomerImpl>().Named("key")); Kernel.Register(Component.For<CustomerImpl>().Named("key")); } [Test] public void ResolveAll() { Kernel.Register(Component.For<ICommon>().ImplementedBy<CommonImpl2>()); Kernel.Register(Component.For<ICommon>().ImplementedBy<CommonImpl1>()); var services = Kernel.ResolveAll<ICommon>(); Assert.AreEqual(2, services.Length); } [Test] public void ResolveAll_does_NOT_account_for_assignable_services() { Kernel.Register(Component.For<ICommon>().ImplementedBy<CommonImpl2>().Named("test")); Kernel.Register(Component.For<ICommonSub1>().ImplementedBy<CommonSub1Impl>().Named("test2")); var services = Kernel.ResolveAll<ICommon>(); Assert.AreEqual(1, services.Length); } [Test] public void ResolveAll_does_handle_multi_service_components() { Kernel.Register(Component.For<ICommon>().ImplementedBy<CommonImpl2>().Named("test")); Kernel.Register(Component.For<ICommonSub1, ICommon>().ImplementedBy<CommonSub1Impl>().Named("test2")); var services = Kernel.ResolveAll<ICommon>(); Assert.AreEqual(2, services.Length); } [Test] public void ResolveAll_resolves_when_dependency_provideded_dynamically() { Kernel.Register(Component.For<ICommon>() .ImplementedBy<CommonImplWithDependency>() .DynamicParameters((k, d) => d.Insert(typeof(ICustomer), new CustomerImpl())) ); var services = Kernel.ResolveAll<ICommon>(); Assert.AreEqual(1, services.Length); } [Test] public void ResolveAll_resolves_when_dependency_provideded_inline() { Kernel.Register(Component.For<ICommon>().ImplementedBy(typeof(CommonImplWithDependency)).Named("test")); var services = Kernel.ResolveAll<ICommon>(new Arguments().Insert("customer", new CustomerImpl())); Assert.AreEqual(1, services.Length); } [Test] public void ResolveUsingAddionalParametersForConfigurationInsteadOfServices() { Kernel.Register( Component.For<ICustomer>().ImplementedBy<CustomerImpl>().Named("cust").LifeStyle.Is( LifestyleType.Transient)); var customer = Kernel.Resolve<ICustomer>("cust"); Assert.IsNull(customer.Address); Assert.IsNull(customer.Name); Assert.AreEqual(0, customer.Age); var dictionary = new Dictionary<string, object> { { "Name", "name" }, { "Address", "address" }, { "Age", "18" } }; customer = Kernel.Resolve<ICustomer>("cust", dictionary); Assert.AreEqual("name", customer.Name); Assert.AreEqual("address", customer.Address); Assert.AreEqual(18, customer.Age); } [Test] public void ResolveViaGenerics() { Kernel.Register(Component.For<ICustomer>().ImplementedBy<CustomerImpl>().Named("cust")); Kernel.Register(Component.For<ICustomer>().ImplementedBy<CustomerImpl2>().Named("cust2")); var customer = Kernel.Resolve<ICustomer>("cust"); var dictionary = new Dictionary<string, object> { { "name", "customer2Name" }, { "address", "customer2Address" }, { "age", 18 } }; var customer2 = Kernel.Resolve<ICustomer>("cust2", dictionary); Assert.AreEqual(customer.GetType(), typeof(CustomerImpl)); Assert.AreEqual(customer2.GetType(), typeof(CustomerImpl2)); } [Test] public void Resolve_all_when_dependency_is_missing_throws_DependencyResolverException() { Kernel.Register( Component.For<C>()); // the dependency goes C --> B --> A Assert.Throws<DependencyResolverException>(() => Kernel.ResolveAll<C>(new Arguments { { "fakeDependency", "Stefan!" } })); } [Test] public void Resolve_all_when_dependency_is_unresolvable_throws_HandlerException() { Kernel.Register( Component.For<B>(), Component.For<C>()); // the dependency goes C --> B --> A Assert.Throws<HandlerException>(() => Kernel.ResolveAll<C>()); } [Test] public void ShouldNotRegisterAbstractClassAsComponentImplementation_With_LifestyleType_And_Override_Signature() { Kernel.Register(Component.For<ICommon>().ImplementedBy<BaseCommonComponent>().Named("abstract").LifeStyle.Pooled); var expectedMessage = string.Format( "Type Castle.MicroKernel.Tests.ClassComponents.BaseCommonComponent is abstract.{0} As such, it is not possible to instansiate it as implementation of service 'abstract'. Did you forget to proxy it?", Environment.NewLine); var exception = Assert.Throws(typeof(ComponentRegistrationException), () => Kernel.Resolve<ICommon>("abstract")); Assert.AreEqual(expectedMessage, exception.Message); } [Test] public void ShouldNotRegisterAbstractClassAsComponentImplementation_With_LifestyleType_Signature() { Kernel.Register(Component.For<ICommon>().ImplementedBy<BaseCommonComponent>().Named("abstract").LifeStyle.Pooled); var expectedMessage = string.Format( "Type Castle.MicroKernel.Tests.ClassComponents.BaseCommonComponent is abstract.{0} As such, it is not possible to instansiate it as implementation of service 'abstract'. Did you forget to proxy it?", Environment.NewLine); var exception = Assert.Throws(typeof(ComponentRegistrationException), () => Kernel.Resolve<ICommon>("abstract")); Assert.AreEqual(expectedMessage, exception.Message); } [Test] public void ShouldNotRegisterAbstractClassAsComponentImplementation_With_Simple_Signature() { Kernel.Register(Component.For<ICommon>().ImplementedBy<BaseCommonComponent>().Named("abstract")); var expectedMessage = string.Format( "Type Castle.MicroKernel.Tests.ClassComponents.BaseCommonComponent is abstract.{0} As such, it is not possible to instansiate it as implementation of service 'abstract'. Did you forget to proxy it?", Environment.NewLine); var exception = Assert.Throws(typeof(ComponentRegistrationException), () => Kernel.Resolve<ICommon>("abstract")); Assert.AreEqual(expectedMessage, exception.Message); } [Test] public void ShouldNotRegisterAbstractClass_With_LifestyleType_And_Override_Signature() { Kernel.Register(Component.For<BaseCommonComponent>().Named("abstract").LifeStyle.Pooled); var expectedMessage = string.Format( "Type Castle.MicroKernel.Tests.ClassComponents.BaseCommonComponent is abstract.{0} As such, it is not possible to instansiate it as implementation of service 'abstract'. Did you forget to proxy it?", Environment.NewLine); var exception = Assert.Throws<ComponentRegistrationException>(() => Kernel.Resolve<ICommon>("abstract")); Assert.AreEqual(expectedMessage, exception.Message); } [Test] public void ShouldNotRegisterAbstractClass_With_LifestyleType_Signature() { Kernel.Register(Component.For<BaseCommonComponent>().Named("abstract").LifeStyle.Pooled); var expectedMessage = string.Format( "Type Castle.MicroKernel.Tests.ClassComponents.BaseCommonComponent is abstract.{0} As such, it is not possible to instansiate it as implementation of service 'abstract'. Did you forget to proxy it?", Environment.NewLine); var exception = Assert.Throws(typeof(ComponentRegistrationException), () => Kernel.Resolve<ICommon>("abstract")); Assert.AreEqual(expectedMessage, exception.Message); } [Test] public void ShouldNotRegisterAbstractClass_With_Simple_Signature() { Kernel.Register(Component.For<BaseCommonComponent>().Named("abstract")); var expectedMessage = string.Format( "Type Castle.MicroKernel.Tests.ClassComponents.BaseCommonComponent is abstract.{0} As such, it is not possible to instansiate it as implementation of service 'abstract'. Did you forget to proxy it?", Environment.NewLine); var exception = Assert.Throws(typeof(ComponentRegistrationException), () => Kernel.Resolve<ICommon>("abstract")); Assert.AreEqual(expectedMessage, exception.Message); } [Test] public void Subsystems_are_case_insensitive() { Assert.IsNotNull(Kernel.GetSubSystem(SubSystemConstants.ConfigurationStoreKey)); Assert.IsNotNull(Kernel.GetSubSystem(SubSystemConstants.ConfigurationStoreKey.ToLower())); Assert.IsNotNull(Kernel.GetSubSystem(SubSystemConstants.ConfigurationStoreKey.ToUpper())); } [Test] [ExpectedException(typeof(ComponentNotFoundException))] public void UnregisteredComponentByKey() { Kernel.Register(Component.For<CustomerImpl>().Named("key1")); Kernel.Resolve<object>("key2"); } [Test] [ExpectedException(typeof(ComponentNotFoundException))] public void UnregisteredComponentByService() { Kernel.Register(Component.For<CustomerImpl>().Named("key1")); Kernel.Resolve<IDisposable>(); } } }
37.213368
205
0.716151
[ "Apache-2.0" ]
flcdrg/Windsor
src/Castle.Windsor.Tests/MicroKernelTestCase.cs
14,476
C#
using System; using System.Collections.Generic; using UnityEngine.Experimental.Input.Controls; using UnityEngine.Experimental.Input.Layouts; using UnityEngine.Experimental.Input.LowLevel; using UnityEngine.Experimental.Input.Utilities; namespace UnityEngine.Experimental.Input.LowLevel { public struct JoystickState : IInputStateTypeInfo { public static FourCC kFormat { get { return new FourCC('J', 'O', 'Y'); } } [InputControl(name = "hat", layout = "Dpad", usage = "Hatswitch")] [InputControl(name = "trigger", layout = "Button", usages = new[] { "PrimaryTrigger", "PrimaryAction" }, bit = (int)Button.Trigger)] public int buttons; [InputControl(layout = "Stick", usage = "Primary2DMotion")] public Vector2 stick; public enum Button { // IMPORTANT: Order has to match what is expected by DpadControl. HatSwitchUp, HatSwitchDown, HatSwitchLeft, HatSwitchRight, Trigger } public FourCC GetFormat() { return kFormat; } } } namespace UnityEngine.Experimental.Input { // A joystick with an arbitrary number of buttons and axes. // By default comes with just a trigger, a potentially twistable // stick and an optional single hatswitch. [InputControlLayout(stateType = typeof(JoystickState))] public class Joystick : InputDevice { public ButtonControl trigger { get; private set; } public StickControl stick { get; private set; } // Optional features. These may be null. public AxisControl twist { get; private set; } public DpadControl hat { get; private set; } ////REVIEW: are these really useful? // List of all buttons and axes on the joystick. public ReadOnlyArray<ButtonControl> buttons { get { return new ReadOnlyArray<ButtonControl>(m_Buttons); } } public ReadOnlyArray<AxisControl> axes { get { return new ReadOnlyArray<AxisControl>(m_Axes); } } public static Joystick current { get; internal set; } protected override void FinishSetup(InputDeviceBuilder builder) { var buttons = new List<ButtonControl>(); var axes = new List<AxisControl>(); FindControlsRecursive(this, buttons, x => !(x.parent is StickControl) && !(x.parent is DpadControl)); FindControlsRecursive(this, axes, x => !(x is ButtonControl)); if (buttons.Count > 0) m_Buttons = buttons.ToArray(); if (axes.Count > 0) m_Axes = axes.ToArray(); // Mandatory controls. trigger = builder.GetControl<ButtonControl>("{PrimaryTrigger}"); stick = builder.GetControl<StickControl>("{Primary2DMotion}"); // Optional controls. twist = builder.TryGetControl<AxisControl>("{Twist}"); hat = builder.TryGetControl<DpadControl>("{Hatswitch}"); base.FinishSetup(builder); } public override void MakeCurrent() { base.MakeCurrent(); current = this; } protected override void OnRemoved() { base.OnRemoved(); if (current == this) current = null; } ////TODO: move this into InputControl private void FindControlsRecursive<TControl>(InputControl parent, List<TControl> controls, Func<TControl, bool> filter) where TControl : InputControl { var parentAsTControl = parent as TControl; if (parentAsTControl != null && filter(parentAsTControl)) { controls.Add(parentAsTControl); } var children = parent.children; var childCount = children.Count; for (var i = 0; i < childCount; ++i) { var child = parent.children[i]; FindControlsRecursive<TControl>(child, controls, filter); } } private ButtonControl[] m_Buttons; private AxisControl[] m_Axes; } }
32.343511
140
0.590748
[ "MIT" ]
DrPaulRobertson/custom-controller-demos
DistanceDemo/Library/PackageCache/com.unity.inputsystem@0.2.0-preview/InputSystem/Devices/Joystick.cs
4,237
C#
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. namespace System.Data.Entity.Internal { using System.Collections.ObjectModel; using System.Collections.Specialized; using System.Linq; // <summary> // Extends <see cref="SortableBindingList{T}" /> to create a sortable binding list that stays in // sync with an underlying <see cref="ObservableCollection{T}" />. That is, when items are added // or removed from the binding list, they are added or removed from the ObservableCollecion, and // vice-versa. // </summary> // <typeparam name="T"> The list element type. </typeparam> internal class ObservableBackedBindingList<T> : SortableBindingList<T> { #region Fields and constructors private bool _addingNewInstance; private T _addNewInstance; private T _cancelNewInstance; private readonly ObservableCollection<T> _obervableCollection; private bool _inCollectionChanged; private bool _changingObservableCollection; // <summary> // Initializes a new instance of a binding list backed by the given <see cref="ObservableCollection{T}" /> // </summary> // <param name="obervableCollection"> The obervable collection. </param> public ObservableBackedBindingList(ObservableCollection<T> obervableCollection) : base(obervableCollection.ToList()) { _obervableCollection = obervableCollection; _obervableCollection.CollectionChanged += ObservableCollectionChanged; } #endregion #region BindingList overrides // <summary> // Creates a new item to be added to the binding list. // </summary> // <returns> The new item. </returns> protected override object AddNewCore() { _addingNewInstance = true; _addNewInstance = (T)base.AddNewCore(); return _addNewInstance; } // <summary> // Cancels adding of a new item that was started with AddNew. // </summary> // <param name="itemIndex"> Index of the item. </param> public override void CancelNew(int itemIndex) { if (itemIndex >= 0 && itemIndex < Count && Equals(base[itemIndex], _addNewInstance)) { _cancelNewInstance = _addNewInstance; _addNewInstance = default(T); _addingNewInstance = false; } base.CancelNew(itemIndex); } // <summary> // Removes all items from the binding list and underlying ObservableCollection. // </summary> protected override void ClearItems() { foreach (var entity in Items) { RemoveFromObservableCollection(entity); } base.ClearItems(); } // <summary> // Ends the process of adding a new item that was started with AddNew. // </summary> // <param name="itemIndex"> Index of the item. </param> public override void EndNew(int itemIndex) { if (itemIndex >= 0 && itemIndex < Count && Equals(base[itemIndex], _addNewInstance)) { AddToObservableCollection(_addNewInstance); _addNewInstance = default(T); _addingNewInstance = false; } base.EndNew(itemIndex); } // <summary> // Inserts the item into the binding list at the given index. // </summary> // <param name="index"> The index. </param> // <param name="item"> The item. </param> protected override void InsertItem(int index, T item) { base.InsertItem(index, item); if (!_addingNewInstance && index >= 0 && index <= Count) { AddToObservableCollection(item); } } // <summary> // Removes the item at the specified index. // </summary> // <param name="index"> The index. </param> protected override void RemoveItem(int index) { if (index >= 0 && index < Count && Equals(base[index], _cancelNewInstance)) { _cancelNewInstance = default(T); } else { RemoveFromObservableCollection(base[index]); } base.RemoveItem(index); } // <summary> // Sets the item into the list at the given position. // </summary> // <param name="index"> The index to insert at. </param> // <param name="item"> The item. </param> protected override void SetItem(int index, T item) { var entity = base[index]; base.SetItem(index, item); if (index >= 0 && index < Count) { // Check to see if the user is trying to set an item that is currently being added via AddNew // If so then the list should not continue the AddNew; but instead add the item // that is being passed in. if (Equals(entity, _addNewInstance)) { _addNewInstance = default(T); _addingNewInstance = false; } else { RemoveFromObservableCollection(entity); } AddToObservableCollection(item); } } #endregion #region ObservaleCollection management // <summary> // Event handler to update the binding list when the underlying observable collection changes. // </summary> // <param name="sender"> The sender. </param> // <param name="e"> Data indicating how the collection has changed. </param> private void ObservableCollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { // Don't try to change the binding list if the original change came from the binding list // and the ObervableCollection is just being changed to match it. if (!_changingObservableCollection) { try { // We are about to change the underlying binding list. We want to prevent those // changes trying to go back into the ObservableCollection, so we set a flag // to prevent that. _inCollectionChanged = true; if (e.Action == NotifyCollectionChangedAction.Reset) { Clear(); } if (e.Action == NotifyCollectionChangedAction.Remove || e.Action == NotifyCollectionChangedAction.Replace) { foreach (T entity in e.OldItems) { Remove(entity); } } if (e.Action == NotifyCollectionChangedAction.Add || e.Action == NotifyCollectionChangedAction.Replace) { foreach (T entity in e.NewItems) { Add(entity); } } } finally { _inCollectionChanged = false; } } } // <summary> // Adds the item to the underlying observable collection. // </summary> // <param name="item"> The item. </param> private void AddToObservableCollection(T item) { // Don't try to change the ObervableCollection if the original change // came from the ObservableCollection if (!_inCollectionChanged) { try { // We are about to change the ObservableCollection based on the binding list. // We don't want to try to put that change into the ObservableCollection again, // so we set a flag to prevent this. _changingObservableCollection = true; _obervableCollection.Add(item); } finally { _changingObservableCollection = false; } } } // <summary> // Removes the item from the underlying from observable collection. // </summary> // <param name="item"> The item. </param> private void RemoveFromObservableCollection(T item) { // Don't try to change the ObervableCollection if the original change // came from the ObservableCollection if (!_inCollectionChanged) { try { // We are about to change the ObservableCollection based on the binding list. // We don't want to try to put that change into the ObservableCollection again, // so we set a flag to prevent this. _changingObservableCollection = true; _obervableCollection.Remove(item); } finally { _changingObservableCollection = false; } } } #endregion } }
36.165441
132
0.519162
[ "Apache-2.0" ]
Cireson/EntityFramework6
src/EntityFramework/Internal/ObservableBackedBindingList`.cs
9,837
C#
using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Authentication.JwtBearer; using Microsoft.AspNetCore.Builder; namespace SoftwareEstimation.Authentication.JwtBearer { public static class JwtTokenMiddleware { public static IApplicationBuilder UseJwtTokenMiddleware(this IApplicationBuilder app, string schema = JwtBearerDefaults.AuthenticationScheme) { return app.Use(async (ctx, next) => { if (ctx.User.Identity?.IsAuthenticated != true) { var result = await ctx.AuthenticateAsync(schema); if (result.Succeeded && result.Principal != null) { ctx.User = result.Principal; } } await next(); }); } } }
31.962963
149
0.573581
[ "MIT" ]
makonhakony/Software-Estimation
aspnet-core/src/SoftwareEstimation.Web.Core/Authentication/JwtBearer/JwtTokenMiddleware.cs
865
C#
// c:\program files (x86)\windows kits\10\include\10.0.18362.0\um\dxva.h(898,5) using System; using System.Runtime.InteropServices; namespace DirectN { [StructLayout(LayoutKind.Sequential, Pack = 1)] public partial struct _DXVA_Deblock_H264__union_0__struct_0 { [MarshalAs(UnmanagedType.ByValArray, SizeConst = 1)] [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public byte[] __bits; public byte ReservedBit { get => InteropRuntime.GetByte(__bits, 0, 1); set { if (__bits == null) __bits = new byte[1]; InteropRuntime.SetByte(value, __bits, 0, 1); } } public byte FieldModeCurrentMbFlag { get => InteropRuntime.GetByte(__bits, 1, 1); set { if (__bits == null) __bits = new byte[1]; InteropRuntime.SetByte(value, __bits, 1, 1); } } public byte FieldModeLeftMbFlag { get => InteropRuntime.GetByte(__bits, 2, 1); set { if (__bits == null) __bits = new byte[1]; InteropRuntime.SetByte(value, __bits, 2, 1); } } public byte FieldModeAboveMbFlag { get => InteropRuntime.GetByte(__bits, 3, 1); set { if (__bits == null) __bits = new byte[1]; InteropRuntime.SetByte(value, __bits, 3, 1); } } public byte FilterInternal8x8EdgesFlag { get => InteropRuntime.GetByte(__bits, 4, 1); set { if (__bits == null) __bits = new byte[1]; InteropRuntime.SetByte(value, __bits, 4, 1); } } public byte FilterInternal4x4EdgesFlag { get => InteropRuntime.GetByte(__bits, 5, 1); set { if (__bits == null) __bits = new byte[1]; InteropRuntime.SetByte(value, __bits, 5, 1); } } public byte FilterLeftMbEdgeFlag { get => InteropRuntime.GetByte(__bits, 6, 1); set { if (__bits == null) __bits = new byte[1]; InteropRuntime.SetByte(value, __bits, 6, 1); } } public byte FilterTopMbEdgeFlag { get => InteropRuntime.GetByte(__bits, 7, 1); set { if (__bits == null) __bits = new byte[1]; InteropRuntime.SetByte(value, __bits, 7, 1); } } } }
85.043478
190
0.690184
[ "MIT" ]
riQQ/DirectN
DirectN/DirectN/Generated/_DXVA_Deblock_H264__union_0__struct_0.cs
1,958
C#
using System; using System.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms; using System.Text; using System.Xml; using System.IO; using Oranikle.Report.Engine; namespace Oranikle.ReportDesigner { /// <summary> /// Summary description for DialogDataSourceRef. /// </summary> internal class DialogDataSources : System.Windows.Forms.Form { DesignXmlDraw _Draw; string _FileName; // file name of open file; used to obtain directory private Oranikle.Studio.Controls.CustomTextControl tbFilename; private Oranikle.Studio.Controls.StyledButton bGetFilename; private Oranikle.Studio.Controls.StyledComboBox cbDataProvider; private Oranikle.Studio.Controls.CustomTextControl tbConnection; private Oranikle.Studio.Controls.StyledCheckBox ckbIntSecurity; private Oranikle.Studio.Controls.CustomTextControl tbPrompt; private Oranikle.Studio.Controls.StyledButton bOK; private Oranikle.Studio.Controls.StyledButton bCancel; private Oranikle.Studio.Controls.StyledButton bTestConnection; private System.Windows.Forms.ListBox lbDataSources; private Oranikle.Studio.Controls.StyledButton bRemove; private Oranikle.Studio.Controls.StyledButton bAdd; private Oranikle.Studio.Controls.StyledCheckBox chkSharedDataSource; private System.Windows.Forms.Label label1; private System.Windows.Forms.Label lDataProvider; private System.Windows.Forms.Label lConnectionString; private System.Windows.Forms.Label lPrompt; private Oranikle.Studio.Controls.CustomTextControl tbDSName; private Oranikle.Studio.Controls.StyledButton bExprConnect; /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.Container components = null; internal DialogDataSources(string filename, DesignXmlDraw draw) { _Draw = draw; _FileName = filename; // // Required for Windows Form Designer support // InitializeComponent(); InitValues(); } private void InitValues() { // Populate the DataProviders cbDataProvider.Items.Clear(); string[] items = RdlEngineConfig.GetProviders(); cbDataProvider.Items.AddRange(items); // // Obtain the existing DataSets info // XmlNode rNode = _Draw.GetReportNode(); XmlNode dsNode = _Draw.GetNamedChildNode(rNode, "DataSources"); if (dsNode == null) return; foreach (XmlNode dNode in dsNode) { if (dNode.Name != "DataSource") continue; XmlAttribute nAttr = dNode.Attributes["Name"]; if (nAttr == null) // shouldn't really happen continue; DataSourceValues dsv = new DataSourceValues(nAttr.Value); dsv.Node = dNode; dsv.DataSourceReference = _Draw.GetElementValue(dNode, "DataSourceReference", null); if (dsv.DataSourceReference == null) { // this is not a data source reference dsv.bDataSourceReference = false; dsv.DataSourceReference = ""; XmlNode cpNode = DesignXmlDraw.FindNextInHierarchy(dNode, "ConnectionProperties", "ConnectString"); dsv.ConnectionString = cpNode == null? "": cpNode.InnerText; XmlNode datap = DesignXmlDraw.FindNextInHierarchy(dNode, "ConnectionProperties", "DataProvider"); dsv.DataProvider = datap == null? "": datap.InnerText; XmlNode p = DesignXmlDraw.FindNextInHierarchy(dNode, "ConnectionProperties", "Prompt"); dsv.Prompt = p == null? "": p.InnerText; } else { // we have a data source reference dsv.bDataSourceReference = true; dsv.ConnectionString = ""; dsv.DataProvider = ""; dsv.Prompt = ""; } this.lbDataSources.Items.Add(dsv); } if (lbDataSources.Items.Count > 0) lbDataSources.SelectedIndex = 0; else this.bOK.Enabled = false; } /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose( bool disposing ) { if( disposing ) { if(components != null) { components.Dispose(); } } base.Dispose( disposing ); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.tbFilename = new Oranikle.Studio.Controls.CustomTextControl(); this.bGetFilename = new Oranikle.Studio.Controls.StyledButton(); this.lDataProvider = new System.Windows.Forms.Label(); this.cbDataProvider = new Oranikle.Studio.Controls.StyledComboBox(); this.lConnectionString = new System.Windows.Forms.Label(); this.tbConnection = new Oranikle.Studio.Controls.CustomTextControl(); this.ckbIntSecurity = new Oranikle.Studio.Controls.StyledCheckBox(); this.lPrompt = new System.Windows.Forms.Label(); this.tbPrompt = new Oranikle.Studio.Controls.CustomTextControl(); this.bOK = new Oranikle.Studio.Controls.StyledButton(); this.bCancel = new Oranikle.Studio.Controls.StyledButton(); this.bTestConnection = new Oranikle.Studio.Controls.StyledButton(); this.lbDataSources = new System.Windows.Forms.ListBox(); this.bRemove = new Oranikle.Studio.Controls.StyledButton(); this.bAdd = new Oranikle.Studio.Controls.StyledButton(); this.chkSharedDataSource = new Oranikle.Studio.Controls.StyledCheckBox(); this.label1 = new System.Windows.Forms.Label(); this.tbDSName = new Oranikle.Studio.Controls.CustomTextControl(); this.bExprConnect = new Oranikle.Studio.Controls.StyledButton(); this.SuspendLayout(); // // tbFilename // this.tbFilename.AddX = 0; this.tbFilename.AddY = 0; this.tbFilename.AllowSpace = false; this.tbFilename.BorderColor = System.Drawing.Color.LightGray; this.tbFilename.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.tbFilename.ChangeVisibility = false; this.tbFilename.ChildControl = null; this.tbFilename.ConvertEnterToTab = true; this.tbFilename.ConvertEnterToTabForDialogs = false; this.tbFilename.Decimals = 0; this.tbFilename.DisplayList = new object[0]; this.tbFilename.HitText = Oranikle.Studio.Controls.HitText.String; this.tbFilename.Location = new System.Drawing.Point(192, 112); this.tbFilename.Name = "tbFilename"; this.tbFilename.OnDropDownCloseFocus = true; this.tbFilename.SelectType = 0; this.tbFilename.Size = new System.Drawing.Size(216, 20); this.tbFilename.TabIndex = 2; this.tbFilename.UseValueForChildsVisibilty = false; this.tbFilename.Value = true; this.tbFilename.TextChanged += new System.EventHandler(this.tbFilename_TextChanged); // // bGetFilename // this.bGetFilename.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(245)))), ((int)(((byte)(245)))), ((int)(((byte)(245))))); this.bGetFilename.BackColor2 = System.Drawing.Color.FromArgb(((int)(((byte)(225)))), ((int)(((byte)(225)))), ((int)(((byte)(225))))); this.bGetFilename.BackFillMode = System.Drawing.Drawing2D.LinearGradientMode.ForwardDiagonal; this.bGetFilename.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(200)))), ((int)(((byte)(200)))), ((int)(((byte)(200))))); this.bGetFilename.FlatStyle = System.Windows.Forms.FlatStyle.Flat; this.bGetFilename.Font = new System.Drawing.Font("Arial", 9F); this.bGetFilename.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(90)))), ((int)(((byte)(90)))), ((int)(((byte)(90))))); this.bGetFilename.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft; this.bGetFilename.Location = new System.Drawing.Point(424, 112); this.bGetFilename.Name = "bGetFilename"; this.bGetFilename.OverriddenSize = null; this.bGetFilename.Size = new System.Drawing.Size(24, 21); this.bGetFilename.TabIndex = 3; this.bGetFilename.Text = "..."; this.bGetFilename.UseVisualStyleBackColor = true; this.bGetFilename.Click += new System.EventHandler(this.bGetFilename_Click); // // lDataProvider // this.lDataProvider.Location = new System.Drawing.Point(8, 152); this.lDataProvider.Name = "lDataProvider"; this.lDataProvider.Size = new System.Drawing.Size(80, 23); this.lDataProvider.TabIndex = 7; this.lDataProvider.Text = "Data provider"; // // cbDataProvider // this.cbDataProvider.AutoAdjustItemHeight = false; this.cbDataProvider.BorderColor = System.Drawing.Color.LightGray; this.cbDataProvider.ConvertEnterToTabForDialogs = false; this.cbDataProvider.DrawMode = System.Windows.Forms.DrawMode.OwnerDrawVariable; this.cbDataProvider.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.cbDataProvider.FlatStyle = System.Windows.Forms.FlatStyle.Flat; this.cbDataProvider.Items.AddRange(new object[] { "SQL", "ODBC", "OLEDB"}); this.cbDataProvider.Location = new System.Drawing.Point(96, 152); this.cbDataProvider.Name = "cbDataProvider"; this.cbDataProvider.SeparatorColor = System.Drawing.Color.FromArgb(((int)(((byte)(90)))), ((int)(((byte)(90)))), ((int)(((byte)(90))))); this.cbDataProvider.SeparatorMargin = 1; this.cbDataProvider.SeparatorStyle = System.Drawing.Drawing2D.DashStyle.Solid; this.cbDataProvider.SeparatorWidth = 1; this.cbDataProvider.Size = new System.Drawing.Size(144, 21); this.cbDataProvider.TabIndex = 4; this.cbDataProvider.SelectedIndexChanged += new System.EventHandler(this.cbDataProvider_SelectedIndexChanged); // // lConnectionString // this.lConnectionString.Location = new System.Drawing.Point(8, 192); this.lConnectionString.Name = "lConnectionString"; this.lConnectionString.Size = new System.Drawing.Size(100, 16); this.lConnectionString.TabIndex = 10; this.lConnectionString.Text = "Connection string"; // // tbConnection // this.tbConnection.AddX = 0; this.tbConnection.AddY = 0; this.tbConnection.AllowSpace = false; this.tbConnection.BorderColor = System.Drawing.Color.LightGray; this.tbConnection.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.tbConnection.ChangeVisibility = false; this.tbConnection.ChildControl = null; this.tbConnection.ConvertEnterToTab = true; this.tbConnection.ConvertEnterToTabForDialogs = false; this.tbConnection.Decimals = 0; this.tbConnection.DisplayList = new object[0]; this.tbConnection.HitText = Oranikle.Studio.Controls.HitText.String; this.tbConnection.Location = new System.Drawing.Point(16, 216); this.tbConnection.Multiline = true; this.tbConnection.Name = "tbConnection"; this.tbConnection.OnDropDownCloseFocus = true; this.tbConnection.SelectType = 0; this.tbConnection.Size = new System.Drawing.Size(424, 40); this.tbConnection.TabIndex = 6; this.tbConnection.UseValueForChildsVisibilty = false; this.tbConnection.Value = true; this.tbConnection.TextChanged += new System.EventHandler(this.tbConnection_TextChanged); // // ckbIntSecurity // this.ckbIntSecurity.FlatStyle = System.Windows.Forms.FlatStyle.Flat; this.ckbIntSecurity.ForeColor = System.Drawing.Color.Black; this.ckbIntSecurity.Location = new System.Drawing.Point(280, 152); this.ckbIntSecurity.Name = "ckbIntSecurity"; this.ckbIntSecurity.Size = new System.Drawing.Size(144, 24); this.ckbIntSecurity.TabIndex = 5; this.ckbIntSecurity.Text = "Use integrated security"; this.ckbIntSecurity.CheckedChanged += new System.EventHandler(this.ckbIntSecurity_CheckedChanged); // // lPrompt // this.lPrompt.Location = new System.Drawing.Point(8, 272); this.lPrompt.Name = "lPrompt"; this.lPrompt.Size = new System.Drawing.Size(432, 16); this.lPrompt.TabIndex = 12; this.lPrompt.Text = "(Optional) Enter the prompt displayed when asking for database credentials "; // // tbPrompt // this.tbPrompt.AddX = 0; this.tbPrompt.AddY = 0; this.tbPrompt.AllowSpace = false; this.tbPrompt.BorderColor = System.Drawing.Color.LightGray; this.tbPrompt.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.tbPrompt.ChangeVisibility = false; this.tbPrompt.ChildControl = null; this.tbPrompt.ConvertEnterToTab = true; this.tbPrompt.ConvertEnterToTabForDialogs = false; this.tbPrompt.Decimals = 0; this.tbPrompt.DisplayList = new object[0]; this.tbPrompt.HitText = Oranikle.Studio.Controls.HitText.String; this.tbPrompt.Location = new System.Drawing.Point(16, 296); this.tbPrompt.Name = "tbPrompt"; this.tbPrompt.OnDropDownCloseFocus = true; this.tbPrompt.SelectType = 0; this.tbPrompt.Size = new System.Drawing.Size(424, 20); this.tbPrompt.TabIndex = 7; this.tbPrompt.UseValueForChildsVisibilty = false; this.tbPrompt.Value = true; this.tbPrompt.TextChanged += new System.EventHandler(this.tbPrompt_TextChanged); // // bOK // this.bOK.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(245)))), ((int)(((byte)(245)))), ((int)(((byte)(245))))); this.bOK.BackColor2 = System.Drawing.Color.FromArgb(((int)(((byte)(225)))), ((int)(((byte)(225)))), ((int)(((byte)(225))))); this.bOK.BackFillMode = System.Drawing.Drawing2D.LinearGradientMode.ForwardDiagonal; this.bOK.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(200)))), ((int)(((byte)(200)))), ((int)(((byte)(200))))); this.bOK.FlatStyle = System.Windows.Forms.FlatStyle.Flat; this.bOK.Font = new System.Drawing.Font("Arial", 9F); this.bOK.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(90)))), ((int)(((byte)(90)))), ((int)(((byte)(90))))); this.bOK.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft; this.bOK.Location = new System.Drawing.Point(272, 344); this.bOK.Name = "bOK"; this.bOK.OverriddenSize = null; this.bOK.Size = new System.Drawing.Size(75, 23); this.bOK.TabIndex = 9; this.bOK.Text = "OK"; this.bOK.UseVisualStyleBackColor = true; this.bOK.Click += new System.EventHandler(this.bOK_Click); // // bCancel // this.bCancel.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(245)))), ((int)(((byte)(245)))), ((int)(((byte)(245))))); this.bCancel.BackColor2 = System.Drawing.Color.FromArgb(((int)(((byte)(225)))), ((int)(((byte)(225)))), ((int)(((byte)(225))))); this.bCancel.BackFillMode = System.Drawing.Drawing2D.LinearGradientMode.ForwardDiagonal; this.bCancel.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(200)))), ((int)(((byte)(200)))), ((int)(((byte)(200))))); this.bCancel.CausesValidation = false; this.bCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel; this.bCancel.FlatStyle = System.Windows.Forms.FlatStyle.Flat; this.bCancel.Font = new System.Drawing.Font("Arial", 9F); this.bCancel.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(90)))), ((int)(((byte)(90)))), ((int)(((byte)(90))))); this.bCancel.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft; this.bCancel.Location = new System.Drawing.Point(368, 344); this.bCancel.Name = "bCancel"; this.bCancel.OverriddenSize = null; this.bCancel.Size = new System.Drawing.Size(75, 23); this.bCancel.TabIndex = 10; this.bCancel.Text = "Cancel"; this.bCancel.UseVisualStyleBackColor = true; // // bTestConnection // this.bTestConnection.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(245)))), ((int)(((byte)(245)))), ((int)(((byte)(245))))); this.bTestConnection.BackColor2 = System.Drawing.Color.FromArgb(((int)(((byte)(225)))), ((int)(((byte)(225)))), ((int)(((byte)(225))))); this.bTestConnection.BackFillMode = System.Drawing.Drawing2D.LinearGradientMode.ForwardDiagonal; this.bTestConnection.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(200)))), ((int)(((byte)(200)))), ((int)(((byte)(200))))); this.bTestConnection.FlatStyle = System.Windows.Forms.FlatStyle.Flat; this.bTestConnection.Font = new System.Drawing.Font("Arial", 9F); this.bTestConnection.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(90)))), ((int)(((byte)(90)))), ((int)(((byte)(90))))); this.bTestConnection.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft; this.bTestConnection.Location = new System.Drawing.Point(16, 344); this.bTestConnection.Name = "bTestConnection"; this.bTestConnection.OverriddenSize = null; this.bTestConnection.Size = new System.Drawing.Size(96, 21); this.bTestConnection.TabIndex = 8; this.bTestConnection.Text = "Test Connection"; this.bTestConnection.UseVisualStyleBackColor = true; this.bTestConnection.Click += new System.EventHandler(this.bTestConnection_Click); // // lbDataSources // this.lbDataSources.Location = new System.Drawing.Point(16, 8); this.lbDataSources.Name = "lbDataSources"; this.lbDataSources.Size = new System.Drawing.Size(120, 82); this.lbDataSources.TabIndex = 11; this.lbDataSources.SelectedIndexChanged += new System.EventHandler(this.lbDataSources_SelectedIndexChanged); // // bRemove // this.bRemove.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(245)))), ((int)(((byte)(245)))), ((int)(((byte)(245))))); this.bRemove.BackColor2 = System.Drawing.Color.FromArgb(((int)(((byte)(225)))), ((int)(((byte)(225)))), ((int)(((byte)(225))))); this.bRemove.BackFillMode = System.Drawing.Drawing2D.LinearGradientMode.ForwardDiagonal; this.bRemove.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(200)))), ((int)(((byte)(200)))), ((int)(((byte)(200))))); this.bRemove.FlatStyle = System.Windows.Forms.FlatStyle.Flat; this.bRemove.Font = new System.Drawing.Font("Arial", 9F); this.bRemove.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(90)))), ((int)(((byte)(90)))), ((int)(((byte)(90))))); this.bRemove.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft; this.bRemove.Location = new System.Drawing.Point(144, 40); this.bRemove.Name = "bRemove"; this.bRemove.OverriddenSize = null; this.bRemove.Size = new System.Drawing.Size(56, 21); this.bRemove.TabIndex = 20; this.bRemove.Text = "Remove"; this.bRemove.UseVisualStyleBackColor = true; this.bRemove.Click += new System.EventHandler(this.bRemove_Click); // // bAdd // this.bAdd.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(245)))), ((int)(((byte)(245)))), ((int)(((byte)(245))))); this.bAdd.BackColor2 = System.Drawing.Color.FromArgb(((int)(((byte)(225)))), ((int)(((byte)(225)))), ((int)(((byte)(225))))); this.bAdd.BackFillMode = System.Drawing.Drawing2D.LinearGradientMode.ForwardDiagonal; this.bAdd.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(200)))), ((int)(((byte)(200)))), ((int)(((byte)(200))))); this.bAdd.FlatStyle = System.Windows.Forms.FlatStyle.Flat; this.bAdd.Font = new System.Drawing.Font("Arial", 9F); this.bAdd.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(90)))), ((int)(((byte)(90)))), ((int)(((byte)(90))))); this.bAdd.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft; this.bAdd.Location = new System.Drawing.Point(144, 8); this.bAdd.Name = "bAdd"; this.bAdd.OverriddenSize = null; this.bAdd.Size = new System.Drawing.Size(56, 21); this.bAdd.TabIndex = 19; this.bAdd.Text = "Add"; this.bAdd.UseVisualStyleBackColor = true; this.bAdd.Click += new System.EventHandler(this.bAdd_Click); // // chkSharedDataSource // this.chkSharedDataSource.FlatStyle = System.Windows.Forms.FlatStyle.Flat; this.chkSharedDataSource.ForeColor = System.Drawing.Color.Black; this.chkSharedDataSource.Location = new System.Drawing.Point(8, 112); this.chkSharedDataSource.Name = "chkSharedDataSource"; this.chkSharedDataSource.Size = new System.Drawing.Size(184, 16); this.chkSharedDataSource.TabIndex = 1; this.chkSharedDataSource.Text = "Shared Data Source Reference"; this.chkSharedDataSource.CheckedChanged += new System.EventHandler(this.chkSharedDataSource_CheckedChanged); // // label1 // this.label1.Location = new System.Drawing.Point(216, 8); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(104, 23); this.label1.TabIndex = 22; this.label1.Text = "Data Source Name"; // // tbDSName // this.tbDSName.AddX = 0; this.tbDSName.AddY = 0; this.tbDSName.AllowSpace = false; this.tbDSName.BorderColor = System.Drawing.Color.LightGray; this.tbDSName.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.tbDSName.ChangeVisibility = false; this.tbDSName.ChildControl = null; this.tbDSName.ConvertEnterToTab = true; this.tbDSName.ConvertEnterToTabForDialogs = false; this.tbDSName.Decimals = 0; this.tbDSName.DisplayList = new object[0]; this.tbDSName.HitText = Oranikle.Studio.Controls.HitText.String; this.tbDSName.Location = new System.Drawing.Point(216, 24); this.tbDSName.Name = "tbDSName"; this.tbDSName.OnDropDownCloseFocus = true; this.tbDSName.SelectType = 0; this.tbDSName.Size = new System.Drawing.Size(216, 20); this.tbDSName.TabIndex = 0; this.tbDSName.UseValueForChildsVisibilty = false; this.tbDSName.Value = true; this.tbDSName.TextChanged += new System.EventHandler(this.tbDSName_TextChanged); this.tbDSName.Validating += new System.ComponentModel.CancelEventHandler(this.tbDSName_Validating); // // bExprConnect // this.bExprConnect.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(245)))), ((int)(((byte)(245)))), ((int)(((byte)(245))))); this.bExprConnect.BackColor2 = System.Drawing.Color.FromArgb(((int)(((byte)(225)))), ((int)(((byte)(225)))), ((int)(((byte)(225))))); this.bExprConnect.BackFillMode = System.Drawing.Drawing2D.LinearGradientMode.ForwardDiagonal; this.bExprConnect.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(200)))), ((int)(((byte)(200)))), ((int)(((byte)(200))))); this.bExprConnect.FlatStyle = System.Windows.Forms.FlatStyle.Flat; this.bExprConnect.Font = new System.Drawing.Font("Arial", 8.25F, ((System.Drawing.FontStyle)((System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic))), System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.bExprConnect.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(90)))), ((int)(((byte)(90)))), ((int)(((byte)(90))))); this.bExprConnect.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft; this.bExprConnect.Location = new System.Drawing.Point(416, 192); this.bExprConnect.Name = "bExprConnect"; this.bExprConnect.OverriddenSize = null; this.bExprConnect.Size = new System.Drawing.Size(22, 21); this.bExprConnect.TabIndex = 23; this.bExprConnect.Tag = "pright"; this.bExprConnect.Text = "fx"; this.bExprConnect.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; this.bExprConnect.UseVisualStyleBackColor = true; this.bExprConnect.Click += new System.EventHandler(this.bExprConnect_Click); // // DialogDataSources // this.AcceptButton = this.bOK; this.AutoScaleBaseSize = new System.Drawing.Size(5, 13); this.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(228)))), ((int)(((byte)(241)))), ((int)(((byte)(249))))); this.CancelButton = this.bCancel; this.ClientSize = new System.Drawing.Size(456, 374); this.Controls.Add(this.bExprConnect); this.Controls.Add(this.tbDSName); this.Controls.Add(this.label1); this.Controls.Add(this.chkSharedDataSource); this.Controls.Add(this.bRemove); this.Controls.Add(this.bAdd); this.Controls.Add(this.lbDataSources); this.Controls.Add(this.bTestConnection); this.Controls.Add(this.bCancel); this.Controls.Add(this.bOK); this.Controls.Add(this.tbPrompt); this.Controls.Add(this.lPrompt); this.Controls.Add(this.ckbIntSecurity); this.Controls.Add(this.tbConnection); this.Controls.Add(this.lConnectionString); this.Controls.Add(this.cbDataProvider); this.Controls.Add(this.lDataProvider); this.Controls.Add(this.bGetFilename); this.Controls.Add(this.tbFilename); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog; this.MaximizeBox = false; this.MinimizeBox = false; this.Name = "DialogDataSources"; this.ShowInTaskbar = false; this.SizeGripStyle = System.Windows.Forms.SizeGripStyle.Hide; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent; this.Text = "DataSources in Report"; this.ResumeLayout(false); this.PerformLayout(); } #endregion public void Apply() { XmlNode rNode = _Draw.GetReportNode(); _Draw.RemoveElement(rNode, "DataSources"); // remove old DataSources if (this.lbDataSources.Items.Count <= 0) return; // nothing in list? all done XmlNode dsNode = _Draw.SetElement(rNode, "DataSources", null); foreach (DataSourceValues dsv in lbDataSources.Items) { if (dsv.Name == null || dsv.Name.Length <= 0) continue; // shouldn't really happen XmlNode dNode = _Draw.CreateElement(dsNode, "DataSource", null); // Create the name attribute _Draw.SetElementAttribute(dNode, "Name", dsv.Name); if (dsv.bDataSourceReference) { _Draw.SetElement(dNode, "DataSourceReference", dsv.DataSourceReference); continue; } // must fill out the connection properties XmlNode cNode = _Draw.CreateElement(dNode, "ConnectionProperties", null); _Draw.SetElement(cNode, "DataProvider", dsv.DataProvider); _Draw.SetElement(cNode, "ConnectString", dsv.ConnectionString); _Draw.SetElement(cNode, "IntegratedSecurity", dsv.IntegratedSecurity? "true": "false"); if (dsv.Prompt != null && dsv.Prompt.Length > 0) _Draw.SetElement(cNode, "Prompt", dsv.Prompt); } } private void bGetFilename_Click(object sender, System.EventArgs e) { OpenFileDialog ofd = new OpenFileDialog(); ofd.Filter = "Data source reference files (*.dsr)|*.dsr" + "|All files (*.*)|*.*"; ofd.FilterIndex = 1; if (tbFilename.Text.Length > 0) ofd.FileName = tbFilename.Text; else ofd.FileName = "*.dsr"; ofd.Title = "Specify Data Source Reference File Name"; ofd.DefaultExt = "dsr"; ofd.AddExtension = true; try { if (_FileName != null) ofd.InitialDirectory = Path.GetDirectoryName(_FileName); } catch { } try { if (ofd.ShowDialog() == DialogResult.OK) { try { string dsr = DesignerUtility.RelativePathTo( Path.GetDirectoryName(_FileName), Path.GetDirectoryName(ofd.FileName)); string f = Path.GetFileNameWithoutExtension(ofd.FileName); tbFilename.Text = dsr == "" ? f : dsr + Path.DirectorySeparatorChar + f; } catch { tbFilename.Text = Path.GetFileNameWithoutExtension(ofd.FileName); } } } finally { ofd.Dispose(); } } private void tbFilename_TextChanged(object sender, System.EventArgs e) { int cur = lbDataSources.SelectedIndex; if (cur < 0) return; DataSourceValues dsv = lbDataSources.Items[cur] as DataSourceValues; if (dsv == null) return; dsv.DataSourceReference = tbFilename.Text; return; } private void bOK_Click(object sender, System.EventArgs e) { // Verify there are no duplicate names in the data sources Hashtable ht = new Hashtable(this.lbDataSources.Items.Count+1); foreach (DataSourceValues dsv in lbDataSources.Items) { if (dsv.Name == null || dsv.Name.Length == 0) { MessageBox.Show(this, "Name must be specified for all DataSources.", "Data Sources"); return; } if (!ReportNames.IsNameValid(dsv.Name)) { MessageBox.Show(this, string.Format("Name '{0}' contains invalid characters.", dsv.Name), "Data Sources"); return; } string name = (string) ht[dsv.Name]; if (name != null) { MessageBox.Show(this, string.Format("Each DataSource must have a unique name. '{0}' is repeated.", dsv.Name), "Data Sources"); return; } ht.Add(dsv.Name, dsv.Name); } // apply the result Apply(); DialogResult = DialogResult.OK; } private void bTestConnection_Click(object sender, System.EventArgs e) { if (DesignerUtility.TestConnection(this.cbDataProvider.Text, tbConnection.Text)) MessageBox.Show("Connection succeeded!", "Test Connection"); } private void tbDSName_TextChanged(object sender, System.EventArgs e) { int cur = lbDataSources.SelectedIndex; if (cur < 0) return; DataSourceValues dsv = lbDataSources.Items[cur] as DataSourceValues; if (dsv == null) return; if (dsv.Name == tbDSName.Text) return; dsv.Name = tbDSName.Text; // text doesn't change in listbox; force change by removing and re-adding item lbDataSources.BeginUpdate(); lbDataSources.Items.RemoveAt(cur); lbDataSources.Items.Insert(cur, dsv); lbDataSources.SelectedIndex = cur; lbDataSources.EndUpdate(); } private void chkSharedDataSource_CheckedChanged(object sender, System.EventArgs e) { int cur = lbDataSources.SelectedIndex; if (cur < 0) return; DataSourceValues dsv = lbDataSources.Items[cur] as DataSourceValues; if (dsv == null) return; dsv.bDataSourceReference = chkSharedDataSource.Checked; bool bEnableDataSourceRef = chkSharedDataSource.Checked; // shared data source fields tbFilename.Enabled = bEnableDataSourceRef; bGetFilename.Enabled = bEnableDataSourceRef; // in report data source cbDataProvider.Enabled = !bEnableDataSourceRef; tbConnection.Enabled = !bEnableDataSourceRef; ckbIntSecurity.Enabled = !bEnableDataSourceRef; tbPrompt.Enabled = !bEnableDataSourceRef; bTestConnection.Enabled = !bEnableDataSourceRef; lDataProvider.Enabled = !bEnableDataSourceRef; lConnectionString.Enabled = !bEnableDataSourceRef; lPrompt.Enabled = !bEnableDataSourceRef; } private void lbDataSources_SelectedIndexChanged(object sender, System.EventArgs e) { int cur = lbDataSources.SelectedIndex; if (cur < 0) return; DataSourceValues dsv = lbDataSources.Items[cur] as DataSourceValues; if (dsv == null) return; tbDSName.Text = dsv.Name; cbDataProvider.Text = dsv.DataProvider; tbConnection.Text = dsv.ConnectionString; ckbIntSecurity.Checked = dsv.IntegratedSecurity; this.tbFilename.Text = dsv.DataSourceReference; tbPrompt.Text = dsv.Prompt; this.chkSharedDataSource.Checked = dsv.bDataSourceReference; chkSharedDataSource_CheckedChanged(this.chkSharedDataSource, e); // force message } private void bAdd_Click(object sender, System.EventArgs e) { DataSourceValues dsv = new DataSourceValues("datasource"); int cur = this.lbDataSources.Items.Add(dsv); lbDataSources.SelectedIndex = cur; this.tbDSName.Focus(); } private void bRemove_Click(object sender, System.EventArgs e) { int cur = lbDataSources.SelectedIndex; if (cur < 0) return; lbDataSources.Items.RemoveAt(cur); if (lbDataSources.Items.Count <= 0) return; cur--; if (cur < 0) cur = 0; lbDataSources.SelectedIndex = cur; } private void tbDSName_Validating(object sender, System.ComponentModel.CancelEventArgs e) { int cur = lbDataSources.SelectedIndex; if (cur < 0) return; if (!ReportNames.IsNameValid(tbDSName.Text)) { e.Cancel = true; MessageBox.Show(this, string.Format("Name '{0}' contains invalid characters.", tbDSName.Text), "Data Sources"); } } private void tbConnection_TextChanged(object sender, System.EventArgs e) { int cur = lbDataSources.SelectedIndex; if (cur < 0) return; DataSourceValues dsv = lbDataSources.Items[cur] as DataSourceValues; if (dsv == null) return; dsv.ConnectionString = tbConnection.Text; } private void tbPrompt_TextChanged(object sender, System.EventArgs e) { int cur = lbDataSources.SelectedIndex; if (cur < 0) return; DataSourceValues dsv = lbDataSources.Items[cur] as DataSourceValues; if (dsv == null) return; dsv.Prompt = tbPrompt.Text; } private void cbDataProvider_SelectedIndexChanged(object sender, System.EventArgs e) { int cur = lbDataSources.SelectedIndex; if (cur < 0) return; DataSourceValues dsv = lbDataSources.Items[cur] as DataSourceValues; if (dsv == null) return; dsv.DataProvider = cbDataProvider.Text; } private void ckbIntSecurity_CheckedChanged(object sender, System.EventArgs e) { int cur = lbDataSources.SelectedIndex; if (cur < 0) return; DataSourceValues dsv = lbDataSources.Items[cur] as DataSourceValues; if (dsv == null) return; dsv.IntegratedSecurity = ckbIntSecurity.Checked; } private void bExprConnect_Click(object sender, System.EventArgs e) { DialogExprEditor ee = new DialogExprEditor(_Draw, this.tbConnection.Text, null, false); try { DialogResult dr = ee.ShowDialog(); if (dr == DialogResult.OK) tbConnection.Text = ee.Expression; } finally { ee.Dispose(); } } } class DataSourceValues { string _Name; bool _bDataSourceReference; string _DataSourceReference; string _DataProvider; string _ConnectionString; bool _IntegratedSecurity; string _Prompt; XmlNode _Node; internal DataSourceValues(string name) { _Name = name; } internal string Name { get {return _Name;} set {_Name = value;} } internal bool bDataSourceReference { get {return _bDataSourceReference;} set {_bDataSourceReference = value;} } internal string DataSourceReference { get {return _DataSourceReference;} set {_DataSourceReference = value;} } internal string DataProvider { get {return _DataProvider;} set {_DataProvider = value;} } internal string ConnectionString { get {return _ConnectionString;} set {_ConnectionString = value;} } internal bool IntegratedSecurity { get {return _IntegratedSecurity;} set {_IntegratedSecurity = value;} } internal string Prompt { get {return _Prompt;} set {_Prompt = value;} } internal XmlNode Node { get {return _Node;} set {_Node = value;} } override public string ToString() { return _Name; } } }
42.441704
222
0.635269
[ "Apache-2.0" ]
hnjm/rdlc.report.engine
Oranikle.ReportDesigner/DialogDataSources.cs
37,858
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; namespace CodeGenerator.HttpUtilities; // C code for Algorithm L (Lexicographic combinations) in Section 7.2.1.3 of The Art of Computer Programming, Volume 4A: Combinatorial Algorithms, Part 1 : internal sealed class CombinationsWithoutRepetition<T> : IEnumerator<T[]> { private bool _firstElement; private int[] _pointers; private T[] _nElements; private readonly int _p; public CombinationsWithoutRepetition(T[] nElements, int p) { if (nElements.Length < p) { throw new ArgumentOutOfRangeException(nameof(p)); } _nElements = nElements; _p = p; Current = new T[p]; ResetCurrent(); } public T[] Current { get; private set; } object IEnumerator.Current => Current; public bool MoveNext() { if (_firstElement) { _firstElement = false; return true; } var p = _p; var pointers = _pointers; var current = Current; var nElements = _nElements; var index = 1; while (pointers[index] + 1 == pointers[index + 1]) { var j1 = index - 1; pointers[index] = j1; current[j1] = nElements[j1]; ++index; } if (index > p) { return false; } current[index - 1] = nElements[++pointers[index]]; return true; } private void ResetCurrent() { var p = _p; if (_pointers == null) { _pointers = new int[p + 3]; } var pointers = _pointers; var current = Current; var nElements = _nElements; pointers[0] = 0; for (int j = 1; j <= _p; j++) { pointers[j] = j - 1; } pointers[_p + 1] = nElements.Length; pointers[_p + 2] = 0; for (int j = _p; j > 0; j--) { current[j - 1] = nElements[pointers[j]]; } _firstElement = true; } public void Reset() { Array.Clear(Current, 0, Current.Length); Current = null; ResetCurrent(); } public void Dispose() { _nElements = null; Current = null; _pointers = null; } }
22.95283
155
0.531032
[ "MIT" ]
Akarachudra/kontur-aspnetcore-fork
src/Servers/Kestrel/tools/CodeGenerator/HttpUtilities/CombinationsWithoutRepetition.cs
2,433
C#
using System; using Xunit; namespace Confluent.Kafka.IntegrationTests { public partial class Tests { [Theory, MemberData(nameof(OAuthBearerKafkaParameters))] public void OAuthBearerToken_PublishConsume(string bootstrapServers) { LogToFileStartTest(); if (string.IsNullOrEmpty(bootstrapServers)) { // skip test if oauth enabled broker is not specified. return; } const string principal = "Tester"; var issuedAt = DateTimeOffset.UtcNow; var expiresAt = issuedAt.AddMinutes(5); var token = Util.GetUnsecuredJwt(principal, "requiredScope", issuedAt, expiresAt); void Callback(IClient client, string cfg) { client.OAuthBearerSetToken(token, expiresAt.ToUnixTimeMilliseconds(), principal); } var message = new Message<string, string> { Key = $"{Guid.NewGuid()}", Value = $"{DateTimeOffset.UtcNow:T}" }; var config = new ClientConfig { BootstrapServers = bootstrapServers, SecurityProtocol = SecurityProtocol.SaslPlaintext, SaslMechanism = SaslMechanism.OAuthBearer }; var producerConfig = new ProducerConfig(config); var consumerConfig = new ConsumerConfig(config) { GroupId = $"{Guid.NewGuid()}", AutoOffsetReset = AutoOffsetReset.Earliest }; var producer = new ProducerBuilder<string, string>(producerConfig) .SetOAuthBearerTokenRefreshHandler(Callback) .Build(); var consumer = new ConsumerBuilder<string, string>(consumerConfig) .SetOAuthBearerTokenRefreshHandler(Callback) .Build(); consumer.Subscribe(partitionedTopic); producer.Produce(partitionedTopic, message); producer.Flush(TimeSpan.FromSeconds(30)); var received = consumer.Consume(TimeSpan.FromSeconds(30)); Assert.NotNull(received); consumer.Commit(received); Assert.Equal(message.Key, received.Message.Key); Assert.Equal(message.Value, received.Message.Value); LogToFileEndTest(); } [Theory, MemberData(nameof(OAuthBearerKafkaParameters))] public void OAuthBearerToken_PublishConsume_InvalidScope(string bootstrapServers) { LogToFileStartTest(); if (string.IsNullOrEmpty(bootstrapServers)) { // skip test if oauth enabled broker is not specified. return; } const string principal = "Tester"; var issuedAt = DateTimeOffset.UtcNow; var expiresAt = issuedAt.AddMinutes(5); var token = Util.GetUnsecuredJwt(principal, "invalidScope", issuedAt, expiresAt); void Callback(IClient client, string cfg) { client.OAuthBearerSetToken(token, expiresAt.ToUnixTimeMilliseconds(), principal); } var message = new Message<string, string> { Key = $"{Guid.NewGuid()}", Value = $"{DateTimeOffset.UtcNow:T}" }; var config = new ClientConfig { BootstrapServers = bootstrapServers, SecurityProtocol = SecurityProtocol.SaslPlaintext, SaslMechanism = SaslMechanism.OAuthBearer }; var producerConfig = new ProducerConfig(config); var consumerConfig = new ConsumerConfig(config) { GroupId = $"{Guid.NewGuid()}", AutoOffsetReset = AutoOffsetReset.Earliest }; Error producerError = null; var producer = new ProducerBuilder<string, string>(producerConfig) .SetOAuthBearerTokenRefreshHandler(Callback) .SetErrorHandler((p, e) => producerError = e) .Build(); Error consumerError = null; var consumer = new ConsumerBuilder<string, string>(consumerConfig) .SetOAuthBearerTokenRefreshHandler(Callback) .SetErrorHandler((c, e) => consumerError = e) .Build(); consumer.Subscribe(partitionedTopic); producer.Produce(partitionedTopic, message); producer.Flush(TimeSpan.FromSeconds(5)); consumer.Consume(TimeSpan.FromSeconds(5)); AssertError(producerError); AssertError(consumerError); LogToFileEndTest(); void AssertError(Error error) { Assert.NotNull(error); Assert.True(error.IsError); Assert.True(error.IsLocalError); Assert.False(error.IsBrokerError); Assert.False(error.IsFatal); Assert.Equal(ErrorCode.Local_AllBrokersDown, error.Code); Assert.EndsWith("brokers are down", error.Reason); } } [Theory, MemberData(nameof(OAuthBearerKafkaParameters))] public void OAuthBearerToken_PublishConsume_SetFailure(string bootstrapServers) { LogToFileStartTest(); if (string.IsNullOrEmpty(bootstrapServers)) { // skip test if oauth enabled broker is not specified. return; } var errorMessage = $"{Guid.NewGuid()}"; void TokenCallback(IClient client, string cfg) { client.OAuthBearerSetTokenFailure(errorMessage); } var message = new Message<string, string> { Key = $"{Guid.NewGuid()}", Value = $"{Guid.NewGuid()}" }; var config = new ClientConfig { BootstrapServers = bootstrapServers, SecurityProtocol = SecurityProtocol.SaslPlaintext, SaslMechanism = SaslMechanism.OAuthBearer }; // test Producer var producerConfig = new ProducerConfig(config); Error producerError = null; var producer = new ProducerBuilder<string, string>(producerConfig) .SetOAuthBearerTokenRefreshHandler(TokenCallback) .SetErrorHandler((p, e) => producerError = e) .Build(); producer.Produce(singlePartitionTopic, message); producer.Flush(TimeSpan.Zero); AssertError(producerError); // test Consumer var consumerConfig = new ConsumerConfig(config) { GroupId = $"{Guid.NewGuid()}" }; Error consumerError = null; var consumer = new ConsumerBuilder<string, string>(consumerConfig) .SetOAuthBearerTokenRefreshHandler(TokenCallback) .SetErrorHandler((c, e) => consumerError = e) .Build(); consumer.Subscribe(singlePartitionTopic); consumer.Consume(TimeSpan.Zero); AssertError(consumerError); LogToFileEndTest(); void AssertError(Error error) { Assert.NotNull(error); Assert.True(error.IsError); Assert.True(error.IsLocalError); Assert.False(error.IsBrokerError); Assert.False(error.IsFatal); Assert.Equal(ErrorCode.Local_Authentication, error.Code); Assert.EndsWith(errorMessage, error.Reason); } } } }
36.716981
97
0.561151
[ "Apache-2.0" ]
3schwartz/confluent-kafka-dotnet
test/Confluent.Kafka.IntegrationTests/Tests/OauthBearerToken_PublishConsume.cs
7,784
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Windows.Foundation; using Windows.UI; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Media; using ElementType = P42.Uno.Controls.TargetedPopup; namespace P42.Uno.Controls { public static class TargetedPopupExtensions { public static TElement Content<TElement>(this TElement element, object value) where TElement : ElementType { element.XamlContent = value; return element; } #region Alignment public static TElement Center<TElement>(this TElement element) where TElement : ElementType { element.VerticalAlignment = Windows.UI.Xaml.VerticalAlignment.Center; element.HorizontalAlignment = Windows.UI.Xaml.HorizontalAlignment.Center; return element; } public static TElement Stretch<TElement>(this TElement element) where TElement : ElementType { element.VerticalAlignment = Windows.UI.Xaml.VerticalAlignment.Stretch; element.HorizontalAlignment = Windows.UI.Xaml.HorizontalAlignment.Stretch; return element; } #region Vertical Alignment public static TElement VerticalAlignment<TElement>(this TElement element, VerticalAlignment verticalAlignment) where TElement : ElementType { element.VerticalAlignment = verticalAlignment; return element; } public static TElement Top<TElement>(this TElement element) where TElement : ElementType { element.VerticalAlignment = Windows.UI.Xaml.VerticalAlignment.Top; return element; } public static TElement CenterVertical<TElement>(this TElement element) where TElement : ElementType { element.VerticalAlignment = Windows.UI.Xaml.VerticalAlignment.Center; return element; } public static TElement Bottom<TElement>(this TElement element) where TElement : ElementType { element.VerticalAlignment = Windows.UI.Xaml.VerticalAlignment.Bottom; return element; } public static TElement StretchVertical<TElement>(this TElement element) where TElement : ElementType { element.VerticalAlignment = Windows.UI.Xaml.VerticalAlignment.Stretch; return element; } #endregion #region Horizontal Alignment public static TElement HorizontalAlignment<TElement>(this TElement element, HorizontalAlignment horizontalAlignment) where TElement : ElementType { element.HorizontalAlignment = horizontalAlignment; return element; } public static TElement Left<TElement>(this TElement element) where TElement : ElementType { element.HorizontalAlignment = Windows.UI.Xaml.HorizontalAlignment.Left; return element; } public static TElement CenterHorizontal<TElement>(this TElement element) where TElement : ElementType { element.HorizontalAlignment = Windows.UI.Xaml.HorizontalAlignment.Center; return element; } public static TElement Right<TElement>(this TElement element) where TElement : ElementType { element.HorizontalAlignment = Windows.UI.Xaml.HorizontalAlignment.Right; return element; } public static TElement StretchHorizontal<TElement>(this TElement element) where TElement : ElementType { element.HorizontalAlignment = Windows.UI.Xaml.HorizontalAlignment.Stretch; return element; } #endregion #endregion #region Margin public static TElement Margin<TElement>(this TElement element, double value) where TElement : ElementType { element.Margin = new Thickness(value); return element; } public static TElement Margin<TElement>(this TElement element, double horizontal, double vertical) where TElement : ElementType { element.Margin = new Thickness(horizontal, vertical, horizontal, vertical); return element; } public static TElement Margin<TElement>(this TElement element, double left, double top, double right, double bottom) where TElement : ElementType { element.Margin = new Thickness(left, top, right, bottom); return element; } public static TElement Margin<TElement>(this TElement element, Thickness margin) where TElement : ElementType { element.Margin = margin; return element; } #endregion #region Padding public static TElement Padding<TElement>(this TElement element, double value) where TElement : ElementType { element.Padding = new Thickness(value); return element; } public static TElement Padding<TElement>(this TElement element, double horizontal, double vertical) where TElement : ElementType { element.Padding = new Thickness(horizontal, vertical, horizontal, vertical); return element; } public static TElement Padding<TElement>(this TElement element, double left, double top, double right, double bottom) where TElement : ElementType { element.Padding = new Thickness(left, top, right, bottom); return element; } public static TElement Padding<TElement>(this TElement element, Thickness padding) where TElement : ElementType { element.Padding = padding; return element; } #endregion public static TElement HasShadow<TElement>(this TElement element, bool value = true) where TElement : ElementType { element.HasShadow = value; return element; } public static TElement PopAfter<TElement>(this TElement element, TimeSpan value) where TElement : ElementType { element.PopAfter = value; return element; } public static TElement Target<TElement>(this TElement element, UIElement value) where TElement : ElementType { element.Target = value; return element; } #region Pointer Properties public static TElement PointerBias<TElement>(this TElement element, double value) where TElement : ElementType { element.PointerBias = value; return element; } public static TElement PointerCornerRadius<TElement>(this TElement element, double value) where TElement : ElementType { element.PointerCornerRadius = value; return element; } #region Pointer Direction public static TElement PreferredPointerDirection<TElement>(this TElement element, PointerDirection value) where TElement : ElementType { element.PreferredPointerDirection = value; return element; } public static TElement FallbackPointerDirection<TElement>(this TElement element, PointerDirection value) where TElement : ElementType { element.FallbackPointerDirection = value; return element; } public static TElement PreferredPointerDown<TElement>(this TElement element) where TElement : ElementType { element.PreferredPointerDirection = P42.Uno.Controls.PointerDirection.Down; return element; } public static TElement PreferredPointerUp<TElement>(this TElement element) where TElement : ElementType { element.PreferredPointerDirection = P42.Uno.Controls.PointerDirection.Up; return element; } public static TElement PreferredPointerLeft<TElement>(this TElement element) where TElement : ElementType { element.PreferredPointerDirection = P42.Uno.Controls.PointerDirection.Left; return element; } public static TElement PreferredPointerRight<TElement>(this TElement element) where TElement : ElementType { element.PreferredPointerDirection = P42.Uno.Controls.PointerDirection.Right; return element; } public static TElement PreferredPointerHorizontal<TElement>(this TElement element) where TElement : ElementType { element.PreferredPointerDirection = P42.Uno.Controls.PointerDirection.Horizontal; return element; } public static TElement PreferredPointerVertical<TElement>(this TElement element) where TElement : ElementType { element.PreferredPointerDirection = P42.Uno.Controls.PointerDirection.Vertical; return element; } public static TElement PreferredPointerAny<TElement>(this TElement element) where TElement : ElementType { element.PreferredPointerDirection = P42.Uno.Controls.PointerDirection.Any; return element; } public static TElement FallbackPointerDown<TElement>(this TElement element) where TElement : ElementType { element.FallbackPointerDirection = P42.Uno.Controls.PointerDirection.Down; return element; } public static TElement FallbackPointerUp<TElement>(this TElement element) where TElement : ElementType { element.FallbackPointerDirection = P42.Uno.Controls.PointerDirection.Up; return element; } public static TElement FallbackPointerLeft<TElement>(this TElement element) where TElement : ElementType { element.FallbackPointerDirection = P42.Uno.Controls.PointerDirection.Left; return element; } public static TElement FallbackPointerRight<TElement>(this TElement element) where TElement : ElementType { element.FallbackPointerDirection = P42.Uno.Controls.PointerDirection.Right; return element; } public static TElement FallbackPointerHorizontal<TElement>(this TElement element) where TElement : ElementType { element.FallbackPointerDirection = P42.Uno.Controls.PointerDirection.Horizontal; return element; } public static TElement FallbackPointerVertical<TElement>(this TElement element) where TElement : ElementType { element.FallbackPointerDirection = P42.Uno.Controls.PointerDirection.Vertical; return element; } public static TElement FallbackPointerAny<TElement>(this TElement element) where TElement : ElementType { element.FallbackPointerDirection = P42.Uno.Controls.PointerDirection.Any; return element; } #endregion public static TElement PointerLength<TElement>(this TElement element, double value) where TElement : ElementType { element.PointerLength = value; return element; } public static TElement PointerTipRadius<TElement>(this TElement element, double value) where TElement : ElementType { element.PointerTipRadius = value; return element; } #endregion #region LightDismiss Properties public static TElement IsLightDismissEnabled<TElement>(this TElement element, bool value = true) where TElement : ElementType { element.IsLightDismissEnabled = value; return element; } public static TElement LightDismissOverlayMode<TElement>(this TElement element, LightDismissOverlayMode value) where TElement : ElementType { element.LightDismissOverlayMode = value; return element; } /* public static TElement LightDismissOverlayBrush<TElement>(this TElement element, Brush value) where TElement : ElementType { element.LightDismissOverlayBrush = value; return element; } public static TElement LightDismissOverlayBrush<TElement>(this TElement element, Color value) where TElement : ElementType { element.LightDismissOverlayBrush = new SolidColorBrush(value); return element; } public static TElement LightDismissOverlayBrush<TElement>(this TElement element, string value) where TElement : ElementType { element.LightDismissOverlayBrush = new SolidColorBrush(P42.Utils.Uno.ColorExtensions.ColorFromString(value)); return element; } */ #endregion } }
53.241206
148
0.796791
[ "MIT" ]
baskren/P42.Uno.Controls
P42.Uno.Controls/Popups/Extensions/TargetedPopupExtensions.shared.cs
10,597
C#
using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging; using System; using System.Collections.Concurrent; using System.IO; using System.Runtime.InteropServices.ComTypes; using System.Text; using System.Text.RegularExpressions; using System.Threading; using Umbraco.Cms.Core; using Umbraco.Cms.Core.Hosting; using Umbraco.Cms.Core.IO; using Umbraco.Cms.Core.Models; using Umbraco.Cms.Core.Services; using Umbraco.Cms.Core.Strings; using Umbraco.Extensions; namespace uSync.AutoTemplates { public class TemplateWatcher : IRegisteredObject { private readonly IApplicationShutdownRegistry _hostingLifetime; private readonly FileSystemWatcher _watcher; private readonly ILogger<TemplateWatcher> _logger; private readonly IFileService _fileService; private readonly IShortStringHelper _shortStringHelper; private readonly IHostingEnvironment _hostingEnvironment; private readonly IFileSystem _templateFileSystem; private readonly string _viewsFolder; private bool _enabled; private bool _deleteMissing; private int _delay; public TemplateWatcher( IConfiguration configuration, IApplicationShutdownRegistry hostingLifetime, ILogger<TemplateWatcher> logger, IFileService fileService, FileSystems fileSystems, IShortStringHelper shortStringHelper, IHostingEnvironment hostingEnvironment) { _fileService = fileService; _shortStringHelper = shortStringHelper; _hostingEnvironment = hostingEnvironment; _hostingLifetime = hostingLifetime; _logger = logger; _templateFileSystem = fileSystems.MvcViewsFileSystem; _viewsFolder = _hostingEnvironment.MapPathContentRoot(Constants.SystemDirectories.MvcViews); // // use appsettings.json to turn on/off. // // "uSync" : { // "AutoTemplates" : { // "Enabled": true, // "Delete": false // } // } // _enabled = configuration.GetValue<bool>("uSync:AutoTemplates:Enabled", false); // by default this might be off. _deleteMissing = configuration.GetValue<bool>("uSync:AutoTemplates:Delete", false); _delay = configuration.GetValue<int>("uSync:AutoTemplates:Delay", 1000); // wait. _hostingLifetime.RegisterObject(this); _watcher = new FileSystemWatcher(_viewsFolder); _watcher.Changed += Watcher_FileChanged; _watcher.Deleted += Watcher_FileDeleted; _watcher.Renamed += Watcher_Renamed; } public void WatchViewsFolder() { if (!_enabled) return; _watcher.EnableRaisingEvents = true; } private void Watcher_Renamed(object sender, RenamedEventArgs e) { if (!_enabled) return; Thread.Sleep(_delay); var oldAlias = GetAliasFromFileName(e.OldName); var template = _fileService.GetTemplate(oldAlias); if (template != null) { template.Alias = GetAliasFromFileName(e.Name); template.Name = Path.GetFileNameWithoutExtension(e.Name); _fileService.SaveTemplate(template); } } private void Watcher_FileDeleted(object sender, FileSystemEventArgs e) { if (_enabled && _deleteMissing) { Thread.Sleep(_delay); var alias = GetAliasFromFileName(e.Name); SafeDeleteTemplate(alias); } } private void Watcher_FileChanged(object sender, FileSystemEventArgs e) { if (!_enabled) return; Thread.Sleep(_delay); CheckFile(e.Name); } public void CheckViewsFolder() { if (!_enabled) return; var views = _templateFileSystem.GetFiles(".", "*.cshtml"); foreach (var view in views) { CheckFile(view); } if (_deleteMissing) { CheckTemplates(); } } private void CheckTemplates() { var templates = _fileService.GetTemplates(); foreach (var template in templates) { if (!_templateFileSystem.FileExists(template.Alias + ".cshtml")) { SafeDeleteTemplate(template.Alias); } } } private static object lockObject = new Object(); private void CheckFile(string filename) { try { if (!_templateFileSystem.FileExists(filename)) return; _logger.LogInformation("Checking {filename} template", filename); var fileAlias = GetAliasFromFileName(filename); // is this from a save inside umbraco ? // sometimes there can be a double trigger - if (IsQueued(fileAlias)) return; lock (lockObject) { var text = GetFileContents(filename); var match = Regex.Match(text, AutoTemplates.LayoutRegEx); if (match == null || match.Groups.Count != 2) return; var layoutFile = match.Groups[1].Value.Trim('"'); var fileMasterAlias = GetAliasFromFileName(layoutFile); var template = _fileService.GetTemplate(fileAlias); if (template != null) { var currentMaster = string.IsNullOrWhiteSpace(template.MasterTemplateAlias) ? "null" : template.MasterTemplateAlias; if (fileMasterAlias != currentMaster) { template.SetMasterTemplate(GetMasterTemplate(fileMasterAlias)); SafeSaveTemplate(template); return; } } else { // doesn't exist template = new Template(_shortStringHelper, Path.GetFileNameWithoutExtension(filename), fileAlias); template.SetMasterTemplate(GetMasterTemplate(fileMasterAlias)); template.Content = text; SafeSaveTemplate(template); return; } } } catch (Exception ex) { _logger.LogWarning(ex, "Exeption while checking template file {filename}", filename); } } private ITemplate GetMasterTemplate(string alias) { if (alias == "null") return null; return _fileService.GetTemplate(alias); } private void SafeDeleteTemplate(string alias) { try { _fileService.DeleteTemplate(alias); } catch (Exception ex) { _logger.LogWarning(ex, "Exeption while attempting to delete template {alias}", alias); } } private void SafeSaveTemplate(ITemplate template) { _watcher.EnableRaisingEvents = false; _fileService.SaveTemplate(template); _watcher.EnableRaisingEvents = true; } private string GetFileContents(string filename) { using (Stream stream = _templateFileSystem.OpenFile(filename)) using (var reader = new StreamReader(stream, Encoding.UTF8, true)) { return reader.ReadToEnd(); } } private string GetAliasFromFileName(string filename) => Path.GetFileNameWithoutExtension(filename).ToSafeAlias(_shortStringHelper, false); public void Stop(bool immediate) { _hostingLifetime.UnregisterObject(this); } ConcurrentDictionary<string, bool> QueuedItems = new ConcurrentDictionary<string, bool>(); public void QueueChange(string alias) { QueuedItems.TryAdd(alias.ToLower(), true); } public bool IsQueued(string alias) { if (QueuedItems.TryRemove(alias.ToLower(), out bool flag)) return flag; return false; } } }
32.074074
140
0.561316
[ "MPL-2.0", "MPL-2.0-no-copyleft-exception" ]
JohanPlate/uSync
uSync.AutoTemplates/TemplateWatcher.cs
8,662
C#
// Title: HTTP Tools // Author: Emily Heiner // // MIT License // Copyright(c) 2017-2018 Emily Heiner (emilysamantha80@gmail.com) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Web.UI; namespace ESH.Utility { public class HttpTools { /// <summary> /// POST data and Redirect to the specified url using the specified page. /// </summary> /// <param name="page">The page which will be the referrer page.</param> /// <param name="destinationUrl">The destination Url to which /// the post and redirection is occuring.</param> /// <param name="data">The data should be posted.</param> /// <Author>Samer Abu Rabie</Author> /// <see cref="http://www.codeproject.com/Articles/37539/Redirect-and-POST-in-ASP-NET"/> public static string RedirectAndPOST(Page page, string destinationUrl, Dictionary<string, string> data) { //Prepare the Posting form string strForm = PreparePOSTForm(destinationUrl, data); //Add a literal control the specified page holding //the Post Form, this is to submit the Posting form with the request. if (page != null) { page.Controls.Add(new LiteralControl(strForm)); } return strForm; } /// <summary> /// This method prepares an Html form which holds all data /// in hidden field in the addetion to form submitting script. /// </summary> /// <param name="url">The destination Url to which the post and redirection /// will occur, the Url can be in the same App or ouside the App.</param> /// <param name="data">A collection of data that /// will be posted to the destination Url.</param> /// <returns>Returns a string representation of the Posting form.</returns> /// <Author>Samer Abu Rabie</Author> public static String PreparePOSTForm(string url, Dictionary<string, string> data) { //Set a name for the form string formID = "PostForm"; //Build the form using the specified data to be posted. StringBuilder strForm = new StringBuilder(); strForm.Append("<form id=\"" + formID + "\" name=\"" + formID + "\" action=\"" + url + "\" method=\"POST\">"); foreach (var key in data) { strForm.Append("<input type=\"hidden\" name=\"" + key.Key + "\" value=\"" + key.Value + "\">"); } strForm.Append("</form>"); //Build the JavaScript which will do the Posting operation. StringBuilder strScript = new StringBuilder(); strScript.Append("<script language=\"javascript\">"); strScript.Append("var v" + formID + " = document." + formID + ";"); strScript.Append("v" + formID + ".submit();"); strScript.Append("</script>"); //Return the form and the script concatenated. //(The order is important, Form then JavaScript) return strForm.ToString() + strScript.ToString(); } } }
44.59596
111
0.618573
[ "MIT" ]
EmilySamantha80/ESH
ESH/Utility/HttpTools.cs
4,417
C#
using Microsoft.EntityFrameworkCore.Migrations; namespace MCloudServer.Migrations { public partial class list_visibility : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.AddColumn<int>( name: "visibility", table: "lists", nullable: false, defaultValue: 0); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropColumn( name: "visibility", table: "lists"); } } }
27.041667
72
0.548536
[ "MIT" ]
Leao9203/MusicCloudServer
Migrations/20200918065115_list_visibility.cs
651
C#
using TwitchLib.Client.Models; namespace Twitcher.Controllers { public class Controller { public TwitcherClient Client { get; set; } public ChatMessage Message { get; set; } public string MentionPattern { get; } = "@{DisplayName}, "; protected void Send(string message) { Client.Bot.SendMessage(Message.Channel, message); } protected void SendAnswer(string message) { Client.Bot.SendMessage(Message.Channel, MentionPattern.Replace("{DisplayName}", Message.DisplayName) + message); } protected void SendAnswer(string message, string userName) { Client.Bot.SendMessage(Message.Channel, MentionPattern.Replace("{DisplayName}", userName) + message); } } }
27.689655
124
0.630137
[ "MIT" ]
LiphiTC/Twitcher
src/Twitcher.Controllers/Controller.cs
803
C#
using Brilliancy.Soccer.Common.Helpers; using Microsoft.EntityFrameworkCore.Migrations; namespace Brilliancy.Soccer.DbAccess.Migrations { public partial class NlogTableCreate : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.Sql(ResourceHelper.GetResourceAsString("NLogTableInit.sql", typeof(NlogTableCreate))); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.Sql(ResourceHelper.GetResourceAsString("NLogTableInitDrop.sql", typeof(NlogTableCreate))); } } }
32.947368
119
0.728435
[ "MIT" ]
marcinjarczewski/Soccer
Brilliancy.Soccer.DbAccess/Migrations/20220331140702_NlogTableCreate.cs
628
C#
using Autofac; using Raven.Client; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Web.Optimization; using System.Web.Routing; using Raven.Client.Extensions; using Raven.Client.Document; using Autofac.Integration.Mvc; using AspNet.Identity.RavenDB.Stores; using AspNet.Identity.RavenDB.Sample.Mvc.Models; using Microsoft.AspNet.Identity; using System.Reflection; namespace AspNet.Identity.RavenDB.Sample.Mvc { public class MvcApplication : System.Web.HttpApplication { protected void Application_Start() { AreaRegistration.RegisterAllAreas(); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); const string RavenDefaultDatabase = "Users"; ContainerBuilder builder = new ContainerBuilder(); builder.Register(c => { IDocumentStore store = new DocumentStore { Url = "http://localhost:8080", DefaultDatabase = RavenDefaultDatabase }.Initialize(); store.DatabaseCommands.EnsureDatabaseExists(RavenDefaultDatabase); return store; }).As<IDocumentStore>().SingleInstance(); builder.Register(c => c.Resolve<IDocumentStore>().OpenAsyncSession()).As<IAsyncDocumentSession>().InstancePerHttpRequest(); builder.Register(c => new RavenUserStore<ApplicationUser>(c.Resolve<IAsyncDocumentSession>(), false)).As<IUserStore<ApplicationUser>>().InstancePerHttpRequest(); builder.RegisterType<UserManager<ApplicationUser>>().InstancePerHttpRequest(); builder.RegisterControllers(Assembly.GetExecutingAssembly()); DependencyResolver.SetResolver(new AutofacDependencyResolver(builder.Build())); } } }
37.163636
174
0.667319
[ "MIT" ]
petedavis/AspNet.Identity.RavenDB
samples/AspNet.Identity.RavenDB.Sample.Mvc/Global.asax.cs
2,046
C#
using System.Collections.Generic; namespace ShoelessJoeWebApi.Core.CoreModels { public class CoreSchool { public int SchoolId { get; set; } public string SchoolName { get; set; } public CoreAddress Address { get; set; } public int AddressId { get; set; } public List<CoreUser> Students { get; set; } = new List<CoreUser>(); } }
24
76
0.630208
[ "MIT" ]
TClaypool00/ShoelessJoeApiV2
ShoelessJoeWebApi.Core/CoreModels/CoreSchool.cs
386
C#
#region License // // MIT License // // CoiniumServ - Crypto Currency Mining Pool Server Software // // Copyright (C) 2013 - 2017, CoiniumServ Project // Copyright (C) 2017 - 2021 The Merit Foundation // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // #endregion using System; namespace CoiniumServ.Daemon.Responses { /// <summary> /// <remarks> /// https://github.com/bitcoin/bips/blob/master/bip-0022.mediawiki#Transactions%20Object%20Format /// </remarks> /// </summary> public class BlockTemplateTransaction : IHash { /// <summary> /// transaction data encoded in hexadecimal (byte-for-byte) /// </summary> public string Data { get; set; } /// <summary> /// other transactions before this one (by 1-based index in "transactions" list) that must be present in the final block if this one is; /// if key is not present, dependencies are unknown and clients MUST NOT assume there aren't any /// </summary> public int[] Depends { get; set; } /// <summary> /// hash with witness encoded in little-endian hexadecimal /// </summary> public string Hash { get; set; } /// <summary> /// hash without witness encoded in little-endian hexadecimal /// </summary> public string TxId { get; set; } /// <summary> /// if provided and true, this transaction must be in the final block /// </summary> public bool Required { get; set; } /// <summary> /// total number of SigOps, as counted for purposes of block limits; if key is not present, sigop count is unknown and clients MUST NOT assume /// there aren't any /// </summary> public int Sigops { get; set; } // Get hash without witness public string GetHashNoWitness() { return TxId; } } }
38.177215
150
0.645557
[ "MIT" ]
meritlabs/CoiniumServ
src/CoiniumServ/Daemon/Responses/BlockTemplateTransaction.cs
3,018
C#
// Universal Cross-Platform Voice Chat MeoPlay Copyright (C) 2021 MeoPlay <contact@meoplay.com> All Rights Reserved. using System; using System.IO; using UnrealBuildTool; using System.Collections.Generic; public class UniversalVoiceChatPro : ModuleRules { public UniversalVoiceChatPro(ReadOnlyTargetRules Target) : base(Target) { PCHUsage = ModuleRules.PCHUsageMode.UseExplicitOrSharedPCHs; PublicIncludePaths.AddRange( new string[] { // ... add public include paths required here ... } ); PrivateIncludePaths.AddRange( new string[] { } ); PublicDependencyModuleNames.AddRange( new string[] { "Core", "AudioMixer", "AudioCaptureCore", "AudioCapture" // ... add other public dependencies that you statically link with here ... } ); PrivateDependencyModuleNames.AddRange( new string[] { "CoreUObject", "Engine", "Slate", "SlateCore", "AudioMixer", "Voice", "AudioCapture", "AudioCaptureCore" // ... add private dependencies that you statically link with here ... } ); DynamicallyLoadedModuleNames.AddRange( new string[] { // ... add any modules that your module loads dynamically here ... } ); if (Target.Platform.IsInGroup(UnrealPlatformGroup.Windows)) { AddEngineThirdPartyPrivateStaticDependencies(Target, "DirectSound"); } else if (Target.Platform == UnrealTargetPlatform.Mac) { PublicFrameworks.AddRange(new string[] { "CoreAudio", "AudioUnit", "AudioToolbox" }); } else if (Target.IsInPlatformGroup(UnrealPlatformGroup.Linux)) { AddEngineThirdPartyPrivateStaticDependencies(Target, "SDL2"); } if (Target.Platform.IsInGroup(UnrealPlatformGroup.Windows) || Target.Platform == UnrealTargetPlatform.Mac) { PrivateDependencyModuleNames.Add("AudioCaptureRtAudio"); } else if (Target.Platform == UnrealTargetPlatform.PS4) { PrivateDependencyModuleNames.Add("AudioCaptureSony"); } else if (Target.Platform == UnrealTargetPlatform.IOS) { PrivateDependencyModuleNames.Add("AudioCaptureAudioUnit"); PrivateDependencyModuleNames.Add("Core"); PrivateDependencyModuleNames.Add("AudioCaptureCore"); PublicFrameworks.AddRange(new string[] { "CoreAudio", "AVFoundation", "AudioToolbox" }); } else if (Target.Platform == UnrealTargetPlatform.Android && Target.Platform != UnrealTargetPlatform.Lumin) { PrivateDependencyModuleNames.Add("AudioCaptureAndroid"); } else if (Target.Platform == UnrealTargetPlatform.Switch) { PrivateDependencyModuleNames.Add("AudioCaptureSwitch"); } AddEngineThirdPartyPrivateStaticDependencies(Target, "libOpus"); if (Target.Platform == UnrealTargetPlatform.Android) { PublicDependencyModuleNames.AddRange(new string[] { "Launch", "ApplicationCore" }); string BuildPath = Utils.MakePathRelativeTo(ModuleDirectory, Target.RelativeEnginePath); AdditionalPropertiesForReceipt.Add("AndroidPlugin", Path.Combine(BuildPath, "MeoPlayVoiceChat_AndroidAPL.xml")); } if (Target.Platform == UnrealTargetPlatform.IOS) { PrivateDependencyModuleNames.Add("IOSRuntimeSettings"); PublicFrameworks.Add("AVFoundation"); string PluginPath = Utils.MakePathRelativeTo(ModuleDirectory, Target.RelativeEnginePath); AdditionalPropertiesForReceipt.Add("IOSPlugin", Path.Combine(PluginPath, "MeoPlayVoiceChat_IOSAPL.xml")); } } }
31.918033
124
0.637648
[ "MIT" ]
GamerGambit/SpaceBois
Plugins/UniversalVoiceChatPro/Source/UniversalVoiceChatPro/UniversalVoiceChatPro.build.cs
3,894
C#
// Copyright (C) 2003-2010 Xtensive LLC. // All rights reserved. // For conditions of distribution and use, see license. using System; using System.Collections; using System.Collections.Generic; namespace Xtensive.Sql.Dml { [Serializable] public class SqlQueryExpression : SqlStatement, ISqlQueryExpression { private readonly ISqlQueryExpression left; private readonly ISqlQueryExpression right; private readonly bool all; public ISqlQueryExpression Left { get { return left; } } public ISqlQueryExpression Right { get { return right; } } public bool All { get { return all; } } internal override object Clone(SqlNodeCloneContext context) { if (context.NodeMapping.ContainsKey(this)) return context.NodeMapping[this]; SqlQueryExpression clone = new SqlQueryExpression(NodeType, (ISqlQueryExpression)((SqlNode) left).Clone(context), (ISqlQueryExpression)((SqlNode) right).Clone(context), all); context.NodeMapping[this] = clone; return clone; } #region IEnumerable<ISqlQueryExpression> Members public IEnumerator<ISqlQueryExpression> GetEnumerator() { foreach (ISqlQueryExpression expression in left) yield return expression; foreach (ISqlQueryExpression expression in right) yield return expression; yield break; } IEnumerator IEnumerable.GetEnumerator() { return ((IEnumerable<ISqlQueryExpression>)this).GetEnumerator(); } #endregion #region ISqlCompileUnit Members public override void AcceptVisitor(ISqlVisitor visitor) { visitor.Visit(this); } #endregion #region ISqlQueryExpression Members public SqlQueryExpression Except(ISqlQueryExpression operand) { return SqlDml.Except(this, operand); } public SqlQueryExpression ExceptAll(ISqlQueryExpression operand) { return SqlDml.ExceptAll(this, operand); } public SqlQueryExpression Intersect(ISqlQueryExpression operand) { return SqlDml.Intersect(this, operand); } public SqlQueryExpression IntersectAll(ISqlQueryExpression operand) { return SqlDml.IntersectAll(this, operand); } public SqlQueryExpression Union(ISqlQueryExpression operand) { return SqlDml.Union(this, operand); } public SqlQueryExpression UnionAll(ISqlQueryExpression operand) { return SqlDml.UnionAll(this, operand); } #endregion // Constructor internal SqlQueryExpression(SqlNodeType nodeType, ISqlQueryExpression left, ISqlQueryExpression right, bool all) : base(nodeType) { this.left = left; this.right = right; this.all = all; } } }
24.158333
117
0.659883
[ "MIT" ]
SergeiPavlov/dataobjects-net
DataObjects/Sql/Dml/Statements/SqlQueryExpression.cs
2,899
C#
using System; namespace MORR.Core.CLI.Output { /// <summary> /// The ConsoleFormat formats any output to the CMD console. It prints /// additional indications for error or debug messages for the user. /// </summary> public class ConsoleFormatter : IConsoleFormatter { /// <summary> /// Defines whether the current output is verbose. /// </summary> public bool IsVerbose { get; set; } = false; private const string debugPrefix = "DEBUG: "; private const string errorPrefix = "ERROR: "; /// <summary> /// Prints an error using the exceptions description. /// </summary> /// <param name="exception">The exception used to infer the error output.</param> public void PrintError(Exception exception) { Console.WriteLine(errorPrefix + exception.Message); } /// <summary> /// Prints a debug message. This may not result in an output /// if the formatter is not in an verbose state. /// </summary> /// <param name="message">The debug message to be printed.</param> public void PrintDebug(string message) { if (IsVerbose) Print(debugPrefix + message); } /// <summary> /// Prints message no matter the state of the formatter. /// </summary> /// <param name="message"></param> public void Print(string message) { Console.WriteLine(message); } /// <summary> /// Reads a single line. /// </summary> /// <returns>A single line in form of a string which was read by the formatter</returns> public string Read() { return Console.ReadLine(); } } }
32
96
0.570313
[ "MIT" ]
insightmind/MORR
application/Core/CLI/Output/ConsoleFormatter.cs
1,794
C#
using System.Collections.Generic; using FluentAssertions; using Moq; using NUnit.Framework; using Tailviewer.BusinessLogic.DataSources; using Tailviewer.Settings; using Tailviewer.Ui.Controls.MainPanel.Raw.QuickNavigation; namespace Tailviewer.Test.Ui.Controls.QuickNavigation { [TestFixture] public sealed class QuickNavigationViewModelTest { private Mock<IDataSources> _dataSources; private List<IDataSource> _sources; [SetUp] public void Setup() { _dataSources = new Mock<IDataSources>(); _sources = new List<IDataSource>(); _dataSources.Setup(x => x.Sources).Returns(_sources); } [Test] [Description("Verifies that suggestions are updated once the search term is changed")] public void TestSearch1() { var viewModel = new QuickNavigationViewModel(_dataSources.Object); _sources.Add(CreateSingleDataSource("Tailviewer.log")); viewModel.Suggestions.Should().BeNullOrEmpty(); viewModel.SearchTerm = "TAIL"; viewModel.Suggestions.Should().HaveCount(1); } [Test] [Description("Verifies that the suggestion contains the original path with the original case, not the one of the search term")] public void TestSearch2() { var viewModel = new QuickNavigationViewModel(_dataSources.Object); _sources.Add(CreateSingleDataSource("Tailviewer.log")); viewModel.SearchTerm = "AIL"; var suggestion = viewModel.Suggestions[0]; suggestion.Should().NotBeNull(); suggestion.Prefix.Should().Be("T"); suggestion.Midfix.Should().Be("ail"); suggestion.Postfix.Should().Be("viewer.log"); } [Test] [Description("Verifies that no suggestion is created when nothing matches")] public void TestSearch3() { var viewModel = new QuickNavigationViewModel(_dataSources.Object); _sources.Add(CreateSingleDataSource("A")); _sources.Add(CreateSingleDataSource("AA")); viewModel.SearchTerm = "B"; viewModel.Suggestions.Should().BeNullOrEmpty(); viewModel.SelectedSuggestion.Should().BeNull(); } [Test] [Description("Verifies that the first suggestion is selected by default")] public void TestSearch4() { var viewModel = new QuickNavigationViewModel(_dataSources.Object); _sources.Add(CreateSingleDataSource("A")); _sources.Add(CreateSingleDataSource("AA")); viewModel.SearchTerm = "A"; viewModel.Suggestions.Should().HaveCount(2); viewModel.SelectedSuggestion.Should().Be(viewModel.Suggestions[0]); } [Test] [Description("Verifies that the merged data source is found")] public void TestSearch5() { var viewModel = new QuickNavigationViewModel(_dataSources.Object); _sources.Add(CreateMergedDataSource("Foobar")); _sources.Add(CreateSingleDataSource("Foo")); viewModel.SearchTerm = "Foo"; viewModel.Suggestions.Should().HaveCount(2); } [Test] public void TestChooseSuggestion() { var viewModel = new QuickNavigationViewModel(_dataSources.Object); _sources.Add(CreateSingleDataSource("A")); _sources.Add(CreateSingleDataSource("AA")); viewModel.SearchTerm = "AA"; viewModel.Suggestions.Should().HaveCount(1); var suggestion = viewModel.Suggestions[0]; viewModel.ChooseDataSourceCommand.CanExecute(suggestion).Should().BeTrue(); using (var monitor = viewModel.Monitor()) { viewModel.ChooseDataSourceCommand.Execute(suggestion); monitor.Should().Raise(nameof(QuickNavigationViewModel.DataSourceChosen)); } } private static IDataSource CreateSingleDataSource(string fileName) { var dataSource = new Mock<IDataSource>(); dataSource.Setup(x => x.FullFileName).Returns(fileName); return dataSource.Object; } private static IDataSource CreateMergedDataSource(string sourceName) { var dataSource = new Mock<IDataSource>(); dataSource.Setup(x => x.Settings).Returns(new DataSource {DisplayName = sourceName}); return dataSource.Object; } } }
30.92
129
0.741527
[ "MIT" ]
hezlog/Tailviewer
src/Tailviewer.Test/Ui/Controls/QuickNavigation/QuickNavigationViewModelTest.cs
3,867
C#
#region Copyright & License /* Copyright (c) 2022, Integrated Solutions, Inc. 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 Integrated Solutions, Inc. 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 OWNER 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. */ #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Runtime.Serialization; namespace ISI.Extensions.Telephony.MessageBus.Calls.DataTransferObjects { [DataContract] public class OnOutboundVoiceRequest : IOnVoiceCallRequest { [DataMember(Name = "handlerKey", EmitDefaultValue = false)] public string HandlerKey { get; set; } [DataMember(Name = "handlerJobKey", EmitDefaultValue = false)] public string HandlerJobKey { get; set; } [DataMember(Name = "accountKey", EmitDefaultValue = false)] public string AccountKey { get; set; } [DataMember(Name = "sessionKey", EmitDefaultValue = false)] public string SessionKey { get; set; } [DataMember(Name = "from", EmitDefaultValue = false)] public string From { get; set; } [DataMember(Name = "fromCity", EmitDefaultValue = false)] public string FromCity { get; set; } [DataMember(Name = "fromState", EmitDefaultValue = false)] public string FromState { get; set; } [DataMember(Name = "fromZip", EmitDefaultValue = false)] public string FromZip { get; set; } [DataMember(Name = "fromCountry", EmitDefaultValue = false)] public string FromCountry { get; set; } [DataMember(Name = "to", EmitDefaultValue = false)] public string To { get; set; } [DataMember(Name = "toCity", EmitDefaultValue = false)] public string ToCity { get; set; } [DataMember(Name = "toState", EmitDefaultValue = false)] public string ToState { get; set; } [DataMember(Name = "toZip", EmitDefaultValue = false)] public string ToZip { get; set; } [DataMember(Name = "toCountry", EmitDefaultValue = false)] public string ToCountry { get; set; } [DataMember(Name = "callStatus", EmitDefaultValue = false)] public CallStatus? CallStatus { get; set; } [DataMember(Name = "direction", EmitDefaultValue = false)] public Direction? Direction { get; set; } [DataMember(Name = "forwardedFrom", EmitDefaultValue = false)] public string ForwardedFrom { get; set; } [DataMember(Name = "callerName", EmitDefaultValue = false)] public string CallerName { get; set; } [DataMember(Name = "apiVersion", EmitDefaultValue = false)] public string ApiVersion { get; set; } [DataMember(Name = "digits", EmitDefaultValue = false)] public string Digits { get; set; } } }
43.707865
754
0.749871
[ "BSD-3-Clause" ]
ISI-Extensions/ISI.Extensions
src/ISI.Extensions.Telephony.MessageBus/Calls/DataTransferObjects/OnOutboundVoiceRequest.cs
3,890
C#
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.DynamicData; using System.Web.UI; using System.Web.UI.WebControls; namespace Chapter12Dynamic { public partial class Default_EditEntityTemplate : System.Web.DynamicData.EntityTemplateUserControl { private MetaColumn currentColumn; protected override void OnLoad(EventArgs e) { foreach (MetaColumn column in Table.GetScaffoldColumns(Mode, ContainerType)) { currentColumn = column; Control item = new DefaultEntityTemplate._NamingContainer(); EntityTemplate1.ItemTemplate.InstantiateIn(item); EntityTemplate1.Controls.Add(item); } } protected void Label_Init(object sender, EventArgs e) { Label label = (Label)sender; label.Text = currentColumn.DisplayName; } protected void Label_PreRender(object sender, EventArgs e) { Label label = (Label)sender; DynamicControl dynamicControl = (DynamicControl)label.FindControl("DynamicControl"); FieldTemplateUserControl ftuc = dynamicControl.FieldTemplate as FieldTemplateUserControl; if (ftuc != null && ftuc.DataControl != null) { label.AssociatedControlID = ftuc.DataControl.GetUniqueIDRelativeTo(label); } } protected void DynamicControl_Init(object sender, EventArgs e) { DynamicControl dynamicControl = (DynamicControl)sender; dynamicControl.DataField = currentColumn.Name; } } }
29.588235
100
0.719682
[ "MIT" ]
julielerman/ProgrammingEntityFrameworkBook
Programming EF 2nd Edition/2e Chapter 12 ASPNET Apps/Chapter12Dynamic/DynamicData/EntityTemplates/Default_Edit.ascx.cs
1,511
C#
// MIT License // // Copyright (c) 2016-2018 Wojciech Nagórski // Michael DeMond // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. using System.Collections.Generic; using System.Reflection; using ExtendedXmlSerializer.Core.Sources; namespace ExtendedXmlSerializer.ReflectionModel { sealed class ArrayDimensions : ItemsBase<int> { readonly TypeInfo _type; public ArrayDimensions(TypeInfo type) { _type = type; } public override IEnumerator<int> GetEnumerator() { var type = _type; while (type.IsArray) { yield return type.GetArrayRank(); type = type.GetElementType() .GetTypeInfo(); } } } }
33.74
81
0.737996
[ "MIT" ]
SuricateCan/ExtendedXmlSerializer
src/ExtendedXmlSerializer/ReflectionModel/ArrayDimensions.cs
1,690
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace TabelaDeVisualizacaoDeValores.Properties { [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0")] internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase { private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings()))); public static Settings Default { get { return defaultInstance; } } } }
39.259259
151
0.601887
[ "MIT" ]
HenocEtienne2512/Git
29-07-2019 a 20-08-2019/TabelaDeVisualizacaoDeValores/TabelaDeVisualizacaoDeValores/Properties/Settings.Designer.cs
1,062
C#
using Microsoft.Xna.Framework; namespace Nez.UI { public interface IInputListener { void OnMouseEnter(); void OnMouseExit(); /// <summary> /// if true is returned then onMouseDown/Up will be called else they will not be called /// </summary> /// <returns><c>true</c>, if mouse pressed was oned, <c>false</c> otherwise.</returns> /// <param name="mousePos">Mouse position.</param> bool OnMousePressed(System.Numerics.Vector2 mousePos); /// <summary> /// called when the mouse moves only on an element that returned true for onMousePressed. It is safe to call stage.removeInputFocusListener /// here if you are uninterested in the onMouseUp event. /// </summary> /// <param name="mousePos">Mouse position.</param> void OnMouseMoved(System.Numerics.Vector2 mousePos); /// <summary> /// called when the mouse button is released /// </summary> /// <param name="mousePos">Mouse position.</param> void OnMouseUp(System.Numerics.Vector2 mousePos); /// <summary> /// if true is returned the scroll event will be consumed by the Element /// </summary> /// <returns>The mouse scrolled.</returns> bool OnMouseScrolled(int mouseWheelDelta); } }
32.135135
141
0.70143
[ "Apache-2.0", "MIT" ]
Paramecium13/Nez
Nez.Portable/UI/Base/IInputListener.cs
1,191
C#
// ----------------------------------------------------------------------- // <copyright file="ServiceDataException.cs" company="Plantarium Co."> // Plantarium, MIT // </copyright> // ----------------------------------------------------------------------- namespace Plantarium.Service.Common.Exceptions { using System; /// <summary> /// The service data exception. /// </summary> /// <typeparam name="T">The type.</typeparam> /// <seealso cref="Plantarium.Service.Common.Exceptions.ServiceDataException" /> /// <seealso cref="System.Exception" /> public class ServiceDataException<T> : ServiceDataException { /// <summary> /// Initializes a new instance of the <see cref="ServiceDataException{T}"/> class. /// </summary> public ServiceDataException() { } /// <summary> /// Initializes a new instance of the <see cref="ServiceDataException{T}"/> class. /// </summary> /// <param name="message">The message that describes the error.</param> public ServiceDataException(string message) : base(message) { } /// <summary> /// Initializes a new instance of the <see cref="ServiceDataException{T}"/> class. /// </summary> /// <param name="message">The error message that explains the reason for the exception.</param> /// <param name="innerException">The exception that is the cause of the current exception, or a null reference (Nothing in Visual Basic) if no inner exception is specified.</param> public ServiceDataException(string message, Exception innerException) : base(message, innerException) { } } /// <summary> /// The service data exception. /// </summary> /// <seealso cref="Plantarium.Service.Common.Exceptions.ServiceDataException" /> public class ServiceDataException : Exception { /// <summary> /// Initializes a new instance of the <see cref="ServiceDataException" /> class. /// </summary> public ServiceDataException() : base() { } /// <summary> /// Initializes a new instance of the <see cref="ServiceDataException" /> class. /// </summary> /// <param name="message">The message that describes the error.</param> public ServiceDataException(string message) : base(message) { } /// <summary> /// Initializes a new instance of the <see cref="ServiceDataException" /> class. /// </summary> /// <param name="message">The error message that explains the reason for the exception.</param> /// <param name="innerException">The exception that is the cause of the current exception, or a null reference (Nothing in Visual Basic) if no inner exception is specified.</param> public ServiceDataException(string message, Exception innerException) : base(message, innerException) { } } }
40.554054
188
0.594469
[ "MIT" ]
Plantarium-Co/Plantarium
src/Service/Plantarium.Service.Common/Exceptions/ServiceDataException.cs
3,003
C#
using System; using System.Xml.Serialization; using System.ComponentModel.DataAnnotations; using BroadWorksConnector.Ocip.Validation; using System.Collections.Generic; namespace BroadWorksConnector.Ocip.Models { /// <summary> /// Request to get a sip device type. /// See Also: SystemDeviceTypeGetRequest /// The response is either SystemSIPDeviceTypeGetResponse19 or ErrorResponse. /// Replaced by: SystemSIPDeviceTypeGetRequest19sp1 /// <see cref="SystemDeviceTypeGetRequest"/> /// <see cref="SystemSIPDeviceTypeGetResponse19"/> /// <see cref="ErrorResponse"/> /// <see cref="SystemSIPDeviceTypeGetRequest19sp1"/> /// </summary> [Serializable] [XmlRoot(Namespace = "")] [Groups(@"[{""__type"":""Sequence:#BroadWorksConnector.Ocip.Validation"",""id"":""ab0042aa512abc10edb3c55e4b416b0b:31818""}]")] public class SystemSIPDeviceTypeGetRequest19 : BroadWorksConnector.Ocip.Models.C.OCIRequest { private string _deviceType; [XmlElement(ElementName = "deviceType", IsNullable = false, Namespace = "")] [Group(@"ab0042aa512abc10edb3c55e4b416b0b:31818")] [MinLength(1)] [MaxLength(40)] public string DeviceType { get => _deviceType; set { DeviceTypeSpecified = true; _deviceType = value; } } [XmlIgnore] protected bool DeviceTypeSpecified { get; set; } } }
31.531915
131
0.653171
[ "MIT" ]
JTOne123/broadworks-connector-net
BroadworksConnector/Ocip/Models/SystemSIPDeviceTypeGetRequest19.cs
1,482
C#
using Agiil.Domain.TicketCriterionConvertionStrategies; using Agiil.Domain.Tickets.Specs; using Agiil.Domain.TicketSearch; using Agiil.Tests.Attributes; using Moq; using NUnit.Framework; using AutoFixture.NUnit3; using System; using System.Collections.Generic; using System.Linq; using CSF.Collections; namespace Agiil.Tests.TicketCriterionConvertionStrategies { [TestFixture,Parallelizable] public class HasAllLabelsConversionStrategyTests { [Test,AutoMoqData] public void GetMetadata_returns_metadata_which_matches_a_criterion_for_labels_hasallof_some_parameters() { // Arrange var criterion = Criterion.FromElementAndPredicateFunctionWithConstantValues("labels", "hasallof", "one", "two"); var sut = HasAllLabelsConversionStrategy.GetMetadata(); // Act var result = sut.CanConvert(criterion); // Assert Assert.That(result, Is.True); } [Test,AutoMoqData] public void GetMetadata_returns_metadata_which_does_not_match_a_criterion_with_no_parameters() { // Arrange var criterion = Criterion.FromElementAndPredicateFunctionWithConstantValues("labels", "hasallof"); var sut = HasAllLabelsConversionStrategy.GetMetadata(); // Act var result = sut.CanConvert(criterion); // Assert Assert.That(result, Is.False); } [Test,AutoMoqData] public void GetMetadata_returns_metadata_which_does_not_match_a_criterion_for_the_element_ticket() { // Arrange var criterion = Criterion.FromElementAndPredicateFunctionWithConstantValues("ticket", "hasallof", "one", "two"); var sut = HasAllLabelsConversionStrategy.GetMetadata(); // Act var result = sut.CanConvert(criterion); // Assert Assert.That(result, Is.False); } [Test,AutoMoqData] public void GetMetadata_returns_metadata_which_does_not_match_a_criterion_for_the_predicate_function_hasanyof() { // Arrange var criterion = Criterion.FromElementAndPredicateFunctionWithConstantValues("labels", "hasanyof", "one", "two"); var sut = HasAllLabelsConversionStrategy.GetMetadata(); // Act var result = sut.CanConvert(criterion); // Assert Assert.That(result, Is.False); } [Test,AutoMoqData] public void ConvertToSpecification_resolves_all_values_using_resolver([Frozen] IResolvesValue resolver, HasAllLabelsConversionStrategy sut, string[] resolvedValues) { // Arrange Mock.Get(resolver) .Setup(x => x.ResolveAll<string>(It.IsAny<IList<Value>>())) .Returns(resolvedValues); var criterion = Criterion.FromElementAndPredicateFunctionWithConstantValues("labels", "hasallof", "one", "two"); var expectedParams = new [] { ConstantValue.FromConstant("one"), ConstantValue.FromConstant("two"), } .Cast<Value>() .ToList(); // Act sut.ConvertToSpecification(criterion); // Assert Mock.Get(resolver).Verify(x => x.ResolveAll<string>(It.Is<IList<Value>>(l => new SetEqualityComparer<Value>().Equals(l, expectedParams))), Times.Once); } [Test,AutoMoqData] public void ConvertToSpecification_returns_instance_of_spec([Frozen] IResolvesValue resolver, HasAllLabelsConversionStrategy sut, string[] paramValues, string[] resolvedValues) { // Arrange Mock.Get(resolver) .Setup(x => x.ResolveAll<string>(It.IsAny<IList<Value>>())) .Returns(resolvedValues); var criterion = Criterion.FromElementAndPredicateFunctionWithConstantValues("labels", "hasallof", paramValues); // Act var result = sut.ConvertToSpecification(criterion); // Assert Assert.That(result, Is.Not.Null); Assert.That(result, Is.InstanceOf<HasAllLabels>()); } [Test,AutoMoqData] public void ConvertToSpecification_initialises_label_names_with_resolved_values([Frozen] IResolvesValue resolver, HasAllLabelsConversionStrategy sut, string[] paramValues, string[] resolvedValues) { // Arrange Mock.Get(resolver) .Setup(x => x.ResolveAll<string>(It.IsAny<IList<Value>>())) .Returns(resolvedValues); var criterion = Criterion.FromElementAndPredicateFunctionWithConstantValues("labels", "hasallof", paramValues); // Act var result = sut.ConvertToSpecification(criterion); // Assert Assert.That((result as HasAllLabels)?.LabelNames, Is.EqualTo(resolvedValues)); } } }
36.789855
157
0.626551
[ "MIT" ]
csf-dev/agiil
Tests/Agiil.Tests.Domain/TicketCriterionConvertionStrategies/HasAllLabelsConversionStrategyTests.cs
5,079
C#
// HO=False using System; // using System; using System.Collections.Generic; // using System.Collections.Generic; using System.Linq; // using System.Linq; using System.Text; // using System.Text; // namespace Charlotte // namespace Charlotte { // { public struct AccessCustomNeonRoute // public struct I2Point { // { // HO=False public static int OutputExpressAlbiorixSection; // public static int ADM_a_17378807676757043874_03856719444905205253_z_Count; // HO=False public void EmitEqualBismuthAsset(int AcceptOptionalGraceBundle) // public void ADM_a_17378807676757043874_03856719444905205253_z_AddToCount(int ADM_a_17378807676757043874_03856719444905205253_z_valueForAdd) { // { OutputExpressAlbiorixSection += AcceptOptionalGraceBundle; // ADM_a_17378807676757043874_03856719444905205253_z_Count += ADM_a_17378807676757043874_03856719444905205253_z_valueForAdd; } // } // HO=False public void OverrideStaticWhiteContainer(int DocumentInlineIronLink, int CompressAnonymousOganessonNetwork, int ValidateAlternativeTungstenPost, int CorrectTemporaryLovelyCommunication) // public void ADM_a_17378807676757043874_03856719444905205253_z_Overload_04(int ADM_a_17378807676757043874_03856719444905205253_z_a, int ADM_a_17378807676757043874_03856719444905205253_z_b, int ADM_a_17378807676757043874_03856719444905205253_z_c, int ADM_a_17378807676757043874_03856719444905205253_z_d) { // { var ConfigureFollowingEuropaTerms = new[] // var ADM_a_17378807676757043874_03856719444905205253_z_infos = new[] { // { new { ArchiveActiveSunsetParameter = DocumentInlineIronLink, SwitchValidCallistoLogic = CompressAnonymousOganessonNetwork }, // new { ADM_a_17378807676757043874_03856719444905205253_z_Info_P1 = ADM_a_17378807676757043874_03856719444905205253_z_a, ADM_a_17378807676757043874_03856719444905205253_z_Info_P2 = ADM_a_17378807676757043874_03856719444905205253_z_b }, new { ArchiveActiveSunsetParameter = ValidateAlternativeTungstenPost, SwitchValidCallistoLogic = CorrectTemporaryLovelyCommunication }, // new { ADM_a_17378807676757043874_03856719444905205253_z_Info_P1 = ADM_a_17378807676757043874_03856719444905205253_z_c, ADM_a_17378807676757043874_03856719444905205253_z_Info_P2 = ADM_a_17378807676757043874_03856719444905205253_z_d }, }; // }; this.EmitEqualBismuthAsset(DocumentInlineIronLink); // this.ADM_a_17378807676757043874_03856719444905205253_z_AddToCount(ADM_a_17378807676757043874_03856719444905205253_z_a); this.EmitEqualBismuthAsset(CompressAnonymousOganessonNetwork); // this.ADM_a_17378807676757043874_03856719444905205253_z_AddToCount(ADM_a_17378807676757043874_03856719444905205253_z_b); this.EmitEqualBismuthAsset(ValidateAlternativeTungstenPost); // this.ADM_a_17378807676757043874_03856719444905205253_z_AddToCount(ADM_a_17378807676757043874_03856719444905205253_z_c); this.EmitEqualBismuthAsset(CorrectTemporaryLovelyCommunication); // this.ADM_a_17378807676757043874_03856719444905205253_z_AddToCount(ADM_a_17378807676757043874_03856719444905205253_z_d); if (ConfigureFollowingEuropaTerms[0].ArchiveActiveSunsetParameter == this.WriteCleanAmourSchedule()) this.BreakOpenEpimetheusNote(ConfigureFollowingEuropaTerms[0].SwitchValidCallistoLogic); // if (ADM_a_17378807676757043874_03856719444905205253_z_infos[0].ADM_a_17378807676757043874_03856719444905205253_z_Info_P1 == this.ADM_a_17378807676757043874_03856719444905205253_z_NextCount()) this.ADM_a_17378807676757043874_03856719444905205253_z_AddToCount_02(ADM_a_17378807676757043874_03856719444905205253_z_infos[0].ADM_a_17378807676757043874_03856719444905205253_z_Info_P2); if (ConfigureFollowingEuropaTerms[1].ArchiveActiveSunsetParameter == this.WriteCleanAmourSchedule()) this.BreakOpenEpimetheusNote(ConfigureFollowingEuropaTerms[1].SwitchValidCallistoLogic); // if (ADM_a_17378807676757043874_03856719444905205253_z_infos[1].ADM_a_17378807676757043874_03856719444905205253_z_Info_P1 == this.ADM_a_17378807676757043874_03856719444905205253_z_NextCount()) this.ADM_a_17378807676757043874_03856719444905205253_z_AddToCount_02(ADM_a_17378807676757043874_03856719444905205253_z_infos[1].ADM_a_17378807676757043874_03856719444905205253_z_Info_P2); } // } // HO=False public int TriggerSpecificAluminiumCallback() { return EditStaticEinsteiniumOperation() == 0 ? 1 : StoreExtraPotassiumTransaction; } // public int ADM_a_08121501203783650155_10865107356980712211_z_GetInt_7() { return ADM_a_08121501203783650155_10865107356980712211_z_GetInt_6() == 0 ? 1 : ADM_a_08121501203783650155_10865107356980712211_z_Count_7; } // HO=False public static int StoreExtraPotassiumTransaction; // public static int ADM_a_08121501203783650155_10865107356980712211_z_Count_7; // HO=False public static int PrepareCustomFenrirLink; // public static int ADM_a_08121501203783650155_10865107356980712211_z_Count_9; // HO=False public int EditStaticEinsteiniumOperation() { return InlineAbstractHeartTransaction() + StartUnusedSparkleDeprecation; } // public int ADM_a_08121501203783650155_10865107356980712211_z_GetInt_6() { return ADM_a_08121501203783650155_10865107356980712211_z_GetInt_5() + ADM_a_08121501203783650155_10865107356980712211_z_Count_6; } // HO=False public static AccessCustomNeonRoute operator +(AccessCustomNeonRoute BlockExistingRutheniumHealth, AccessCustomNeonRoute EqualCurrentOberonImage) // public static I2Point operator +(I2Point a, I2Point b) { // { return new AccessCustomNeonRoute(BlockExistingRutheniumHealth.SendMinimumPlutoUsage + EqualCurrentOberonImage.SendMinimumPlutoUsage, BlockExistingRutheniumHealth.AppendUnsupportedUraniumEntry + EqualCurrentOberonImage.AppendUnsupportedUraniumEntry); // return new I2Point(a.X + b.X, a.Y + b.Y); } // } // // HO=False public int ShowDedicatedTitaniaColumn() { return InvokeMockArielCore() == 0 ? 1 : AddMatchingFontaineNotice; } // public int ADM_a_08121501203783650155_10865107356980712211_z_GetInt_1() { return ADM_a_08121501203783650155_10865107356980712211_z_GetInt_0() == 0 ? 1 : ADM_a_08121501203783650155_10865107356980712211_z_Count_1; } // HO=False public static int ContributeInlineEukeladePriority; // public static int ADM_a_08121501203783650155_10865107356980712211_z_Count_12; // HO=False public static int UndoUnknownBebhionnHierarchy; // public static int ADM_a_08121501203783650155_10865107356980712211_z_Count_3; // HO=False public static int AddMatchingFontaineNotice; // public static int ADM_a_08121501203783650155_10865107356980712211_z_Count_1; // HO=False public static int SupportBooleanMermaidSign; // public static int ADM_a_08121501203783650155_10865107356980712211_z_Count_0; // HO=False public WarnPreferredPanOption HackAvailableDubniumPadding() // public D2Point ToD2Point() { // { return new WarnPreferredPanOption(this.SendMinimumPlutoUsage, this.AppendUnsupportedUraniumEntry); // return new D2Point(this.X, this.Y); } // } // // HO=False public void RenamePrivateOsmiumClipboard(int DocumentInlineIronLink, int CompressAnonymousOganessonNetwork) // public void ADM_a_17378807676757043874_03856719444905205253_z_Overload_02(int ADM_a_17378807676757043874_03856719444905205253_z_a, int ADM_a_17378807676757043874_03856719444905205253_z_b) { // { this.ShareManualCarbonUsage(DocumentInlineIronLink, CompressAnonymousOganessonNetwork, this.WriteCleanAmourSchedule()); // this.ADM_a_17378807676757043874_03856719444905205253_z_Overload_03(ADM_a_17378807676757043874_03856719444905205253_z_a, ADM_a_17378807676757043874_03856719444905205253_z_b, this.ADM_a_17378807676757043874_03856719444905205253_z_NextCount()); } // } // HO=False public void BreakOpenEpimetheusNote(int LinkCompletePuckLibrary) // public void ADM_a_17378807676757043874_03856719444905205253_z_AddToCount_02(int ADM_a_17378807676757043874_03856719444905205253_z_valueForAdd_02) { // { OutputExpressAlbiorixSection -= LinkCompletePuckLibrary; // ADM_a_17378807676757043874_03856719444905205253_z_Count -= ADM_a_17378807676757043874_03856719444905205253_z_valueForAdd_02; UsePrivateJarnsaxaPost(); // ADM_a_17378807676757043874_03856719444905205253_z_Overload_00(); } // } // HO=False public int InitializeNativeSodiumNotice() { return LoadInlineSeaborgiumModifier() == 1 ? 1 : ContributeInlineEukeladePriority; } // public int ADM_a_08121501203783650155_10865107356980712211_z_GetInt_12() { return ADM_a_08121501203783650155_10865107356980712211_z_GetInt_11() == 1 ? 1 : ADM_a_08121501203783650155_10865107356980712211_z_Count_12; } // HO=False public AccessCustomNeonRoute(int LicenseBinaryThebeCopyright, int IterateBlankRadiumDeclaration) // public I2Point(int x, int y) { // { this.SendMinimumPlutoUsage = LicenseBinaryThebeCopyright; // this.X = x; this.AppendUnsupportedUraniumEntry = IterateBlankRadiumDeclaration; // this.Y = y; } // } // // HO=False public static int StartUnauthorizedIndiumSchema; // public static int ADM_a_08121501203783650155_10865107356980712211_z_Count_4; // HO=False public static int StartUnusedSparkleDeprecation; // public static int ADM_a_08121501203783650155_10865107356980712211_z_Count_6; // HO=False public int HackConditionalAstatineListener() { return ShowDedicatedTitaniaColumn() + MergeEqualMimasRepository; } // public int ADM_a_08121501203783650155_10865107356980712211_z_GetInt_2() { return ADM_a_08121501203783650155_10865107356980712211_z_GetInt_1() + ADM_a_08121501203783650155_10865107356980712211_z_Count_2; } // HO=False public int InvokeMockArielCore() { return SupportBooleanMermaidSign; } // public int ADM_a_08121501203783650155_10865107356980712211_z_GetInt_0() { return ADM_a_08121501203783650155_10865107356980712211_z_Count_0; } // HO=False public int WriteCleanAmourSchedule() // public int ADM_a_17378807676757043874_03856719444905205253_z_NextCount() { // { return OutputExpressAlbiorixSection++; // return ADM_a_17378807676757043874_03856719444905205253_z_Count++; } // } // HO=False public int ControlRawHolmiumTarget() { return ReferMinorDarmstadtiumSwitch() != 1 ? 1 : PrepareCustomFenrirLink; } // public int ADM_a_08121501203783650155_10865107356980712211_z_GetInt_9() { return ADM_a_08121501203783650155_10865107356980712211_z_GetInt_8() != 1 ? 1 : ADM_a_08121501203783650155_10865107356980712211_z_Count_9; } // HO=False public int InlineAbstractHeartTransaction() { return DistributeGeneralPaaliaqRestriction() != 0 ? 1 : ReportLatestScandiumTarget; } // public int ADM_a_08121501203783650155_10865107356980712211_z_GetInt_5() { return ADM_a_08121501203783650155_10865107356980712211_z_GetInt_4() != 0 ? 1 : ADM_a_08121501203783650155_10865107356980712211_z_Count_5; } // HO=False public static int MergeEqualMimasRepository; // public static int ADM_a_08121501203783650155_10865107356980712211_z_Count_2; // HO=False public int DistributeGeneralPaaliaqRestriction() { return ParseCustomBlossomStyle() != 0 ? 0 : StartUnauthorizedIndiumSchema; } // public int ADM_a_08121501203783650155_10865107356980712211_z_GetInt_4() { return ADM_a_08121501203783650155_10865107356980712211_z_GetInt_3() != 0 ? 0 : ADM_a_08121501203783650155_10865107356980712211_z_Count_4; } // HO=False public int AppendUnsupportedUraniumEntry; // public int Y; // // HO=False public void ShareManualCarbonUsage(int DocumentInlineIronLink, int CompressAnonymousOganessonNetwork, int ValidateAlternativeTungstenPost) // public void ADM_a_17378807676757043874_03856719444905205253_z_Overload_03(int ADM_a_17378807676757043874_03856719444905205253_z_a, int ADM_a_17378807676757043874_03856719444905205253_z_b, int ADM_a_17378807676757043874_03856719444905205253_z_c) { // { this.OverrideStaticWhiteContainer(DocumentInlineIronLink, CompressAnonymousOganessonNetwork, ValidateAlternativeTungstenPost, this.WriteCleanAmourSchedule()); // this.ADM_a_17378807676757043874_03856719444905205253_z_Overload_04(ADM_a_17378807676757043874_03856719444905205253_z_a, ADM_a_17378807676757043874_03856719444905205253_z_b, ADM_a_17378807676757043874_03856719444905205253_z_c, this.ADM_a_17378807676757043874_03856719444905205253_z_NextCount()); } // } // HO=False public int LoadInlineSeaborgiumModifier() { return HighlightAbstractManganeseReference() != 0 ? 0 : DestroyCoreBerylliumValue; } // public int ADM_a_08121501203783650155_10865107356980712211_z_GetInt_11() { return ADM_a_08121501203783650155_10865107356980712211_z_GetInt_10() != 0 ? 0 : ADM_a_08121501203783650155_10865107356980712211_z_Count_11; } // HO=False public void FailStaticKatyushaLock(int DocumentInlineIronLink) // public void ADM_a_17378807676757043874_03856719444905205253_z_Overload_01(int ADM_a_17378807676757043874_03856719444905205253_z_a) { // { this.RenamePrivateOsmiumClipboard(DocumentInlineIronLink, this.WriteCleanAmourSchedule()); // this.ADM_a_17378807676757043874_03856719444905205253_z_Overload_02(ADM_a_17378807676757043874_03856719444905205253_z_a, this.ADM_a_17378807676757043874_03856719444905205253_z_NextCount()); } // } // HO=False public static int ConnectNextAtlasChild; // public static int ADM_a_08121501203783650155_10865107356980712211_z_Count_10; // HO=False public void UsePrivateJarnsaxaPost() // public void ADM_a_17378807676757043874_03856719444905205253_z_Overload_00() { // { this.FailStaticKatyushaLock(this.WriteCleanAmourSchedule()); // this.ADM_a_17378807676757043874_03856719444905205253_z_Overload_01(this.ADM_a_17378807676757043874_03856719444905205253_z_NextCount()); } // } // HO=False public int HighlightAbstractManganeseReference() { return ControlRawHolmiumTarget() != 0 ? 1 : ConnectNextAtlasChild; } // public int ADM_a_08121501203783650155_10865107356980712211_z_GetInt_10() { return ADM_a_08121501203783650155_10865107356980712211_z_GetInt_9() != 0 ? 1 : ADM_a_08121501203783650155_10865107356980712211_z_Count_10; } // HO=False public int SendMinimumPlutoUsage; // public int X; // HO=False public static int LoadPhysicalEuantheInterface; // public static int ADM_a_08121501203783650155_10865107356980712211_z_Count_8; // HO=False public static AccessCustomNeonRoute operator /(AccessCustomNeonRoute BlockExistingRutheniumHealth, int EqualCurrentOberonImage) // public static I2Point operator /(I2Point a, int b) { // { return new AccessCustomNeonRoute(BlockExistingRutheniumHealth.SendMinimumPlutoUsage / EqualCurrentOberonImage, BlockExistingRutheniumHealth.AppendUnsupportedUraniumEntry / EqualCurrentOberonImage); // return new I2Point(a.X / b, a.Y / b); } // } // HO=False public static int DestroyCoreBerylliumValue; // public static int ADM_a_08121501203783650155_10865107356980712211_z_Count_11; // HO=False public static AccessCustomNeonRoute operator *(AccessCustomNeonRoute BlockExistingRutheniumHealth, int EqualCurrentOberonImage) // public static I2Point operator *(I2Point a, int b) { // { return new AccessCustomNeonRoute(BlockExistingRutheniumHealth.SendMinimumPlutoUsage * EqualCurrentOberonImage, BlockExistingRutheniumHealth.AppendUnsupportedUraniumEntry * EqualCurrentOberonImage); // return new I2Point(a.X * b, a.Y * b); } // } // // HO=False public static int ReportLatestScandiumTarget; // public static int ADM_a_08121501203783650155_10865107356980712211_z_Count_5; // HO=False public static AccessCustomNeonRoute operator -(AccessCustomNeonRoute BlockExistingRutheniumHealth, AccessCustomNeonRoute EqualCurrentOberonImage) // public static I2Point operator -(I2Point a, I2Point b) { // { return new AccessCustomNeonRoute(BlockExistingRutheniumHealth.SendMinimumPlutoUsage - EqualCurrentOberonImage.SendMinimumPlutoUsage, BlockExistingRutheniumHealth.AppendUnsupportedUraniumEntry - EqualCurrentOberonImage.AppendUnsupportedUraniumEntry); // return new I2Point(a.X - b.X, a.Y - b.Y); } // } // // HO=False public int ParseCustomBlossomStyle() { return HackConditionalAstatineListener() == 1 ? 0 : UndoUnknownBebhionnHierarchy; } // public int ADM_a_08121501203783650155_10865107356980712211_z_GetInt_3() { return ADM_a_08121501203783650155_10865107356980712211_z_GetInt_2() == 1 ? 0 : ADM_a_08121501203783650155_10865107356980712211_z_Count_3; } // HO=False public int ReferMinorDarmstadtiumSwitch() { return TriggerSpecificAluminiumCallback() == 1 ? 0 : LoadPhysicalEuantheInterface; } // public int ADM_a_08121501203783650155_10865107356980712211_z_GetInt_8() { return ADM_a_08121501203783650155_10865107356980712211_z_GetInt_7() == 1 ? 0 : ADM_a_08121501203783650155_10865107356980712211_z_Count_8; } // HO=False } // } } // }
61
385
0.838339
[ "MIT" ]
soleil-taruto/Hatena
a20201226/Confused_01/tmpsol_mid/Elsa20200001/Commons/I2Point.cs
16,716
C#
using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using EncompassRest.Utilities; namespace EncompassRest.Loans.Associates { /// <summary> /// The Loan Associates Apis. /// </summary> public interface ILoanAssociates : ILoanApiObject { /// <summary> /// Assigns a loan associate to a milestone based on the specified milestone or milestone-free ID and log ID. /// </summary> /// <param name="logId">The milestone or milestone-free log ID.</param> /// <param name="associate">The loan associate to assign.</param> /// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <see cref="CancellationToken.None"/>.</param> /// <returns></returns> Task AssignAssociateAsync(string logId, LoanAssociate associate, CancellationToken cancellationToken = default); /// <summary> /// Assigns a loan associate to a milestone based on the specified milestone or milestone-free ID and log ID from raw json. /// </summary> /// <param name="logId">The milestone or milestone-free log ID.</param> /// <param name="associate">The loan associate to assign as raw json.</param> /// <param name="queryString">The query string to include in the request.</param> /// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <see cref="CancellationToken.None"/>.</param> /// <returns></returns> Task AssignAssociateRawAsync(string logId, string associate, string? queryString = null, CancellationToken cancellationToken = default); /// <summary> /// Retrieves information about a loan associate based on the milestone or milestone-free role ID. The response includes the associate's role and contact information. /// </summary> /// <param name="logId">The milestone or milestone-free log ID.</param> /// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <see cref="CancellationToken.None"/>.</param> /// <returns></returns> Task<LoanAssociate> GetAssociateAsync(string logId, CancellationToken cancellationToken = default); /// <summary> /// Retrieves information about a loan associate based on the milestone or milestone-free role ID as raw json. /// </summary> /// <param name="logId">The milestone or milestone-free log ID.</param> /// <param name="queryString">The query string to include in the request.</param> /// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <see cref="CancellationToken.None"/>.</param> /// <returns></returns> Task<string> GetAssociateRawAsync(string logId, string? queryString = null, CancellationToken cancellationToken = default); /// <summary> /// Retrieves a list of loan associates involved with the loan. The response includes role and contact information for each loan associate. /// </summary> /// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <see cref="CancellationToken.None"/>.</param> /// <returns></returns> Task<List<LoanAssociate>> GetAssociatesAsync(CancellationToken cancellationToken = default); /// <summary> /// Retrieves a list of loan associates involved with the loan. The response includes role and contact information for each loan associate. /// </summary> /// <param name="userId">When provided, returns information about the Encompass user associated with the loan.</param> /// <param name="roleId">When provided, returns information about all Encompass users associated with the specified role ID.</param> /// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <see cref="CancellationToken.None"/>.</param> /// <returns></returns> Task<List<LoanAssociate>> GetAssociatesAsync(string? userId, string? roleId, CancellationToken cancellationToken = default); /// <summary> /// Retrieves a list of loan associates involved with the loan as raw json. /// </summary> /// <param name="queryString">The query string to include in the request.</param> /// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <see cref="CancellationToken.None"/>.</param> /// <returns></returns> Task<string> GetAssociatesRawAsync(string? queryString = null, CancellationToken cancellationToken = default); /// <summary> /// Unassigns a loan associate from a milestone based on the specified milestone or milestone-free ID. /// </summary> /// <param name="logId">The milestone or milestone-free log ID.</param> /// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <see cref="CancellationToken.None"/>.</param> /// <returns></returns> Task<bool> TryUnassignAssociateAsync(string logId, CancellationToken cancellationToken = default); /// <summary> /// Unassigns a loan associate from a milestone based on the specified milestone or milestone-free ID. /// </summary> /// <param name="logId">The milestone or milestone-free log ID.</param> /// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <see cref="CancellationToken.None"/>.</param> /// <returns></returns> Task UnassignAssociateAsync(string logId, CancellationToken cancellationToken = default); } /// <summary> /// The Loan Associates Apis. /// </summary> public sealed class LoanAssociates : LoanApiObject, ILoanAssociates { internal LoanAssociates(EncompassRestClient client, string loanId) : base(client, loanId, "associates") { } /// <summary> /// Retrieves a list of loan associates involved with the loan. The response includes role and contact information for each loan associate. /// </summary> /// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <see cref="CancellationToken.None"/>.</param> /// <returns></returns> public Task<List<LoanAssociate>> GetAssociatesAsync(CancellationToken cancellationToken = default) => GetAssociatesAsync(null, null, cancellationToken); /// <summary> /// Retrieves a list of loan associates involved with the loan. The response includes role and contact information for each loan associate. /// </summary> /// <param name="userId">When provided, returns information about the Encompass user associated with the loan.</param> /// <param name="roleId">When provided, returns information about all Encompass users associated with the specified role ID.</param> /// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <see cref="CancellationToken.None"/>.</param> /// <returns></returns> public Task<List<LoanAssociate>> GetAssociatesAsync(string? userId, string? roleId, CancellationToken cancellationToken = default) { var queryParameters = new QueryParameters(); if (!string.IsNullOrEmpty(userId)) { queryParameters.Add("userId", userId); } if (!string.IsNullOrEmpty(roleId)) { queryParameters.Add("roleId", roleId); } return GetDirtyListAsync<LoanAssociate>(null, queryParameters.ToString(), nameof(GetAssociatesAsync), null, cancellationToken); } /// <summary> /// Retrieves a list of loan associates involved with the loan as raw json. /// </summary> /// <param name="queryString">The query string to include in the request.</param> /// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <see cref="CancellationToken.None"/>.</param> /// <returns></returns> public Task<string> GetAssociatesRawAsync(string? queryString = null, CancellationToken cancellationToken = default) => GetRawAsync(null, queryString, nameof(GetAssociatesRawAsync), null, cancellationToken); /// <summary> /// Retrieves information about a loan associate based on the milestone or milestone-free role ID. The response includes the associate's role and contact information. /// </summary> /// <param name="logId">The milestone or milestone-free log ID.</param> /// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <see cref="CancellationToken.None"/>.</param> /// <returns></returns> public Task<LoanAssociate> GetAssociateAsync(string logId, CancellationToken cancellationToken = default) { Preconditions.NotNullOrEmpty(logId, nameof(logId)); return GetAsync<LoanAssociate>(logId, null, nameof(GetAssociateAsync), logId, cancellationToken); } /// <summary> /// Retrieves information about a loan associate based on the milestone or milestone-free role ID as raw json. /// </summary> /// <param name="logId">The milestone or milestone-free log ID.</param> /// <param name="queryString">The query string to include in the request.</param> /// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <see cref="CancellationToken.None"/>.</param> /// <returns></returns> public Task<string> GetAssociateRawAsync(string logId, string? queryString = null, CancellationToken cancellationToken = default) { Preconditions.NotNullOrEmpty(logId, nameof(logId)); return GetRawAsync(logId, queryString, nameof(GetAssociateRawAsync), logId, cancellationToken); } /// <summary> /// Assigns a loan associate to a milestone based on the specified milestone or milestone-free ID and log ID. /// </summary> /// <param name="logId">The milestone or milestone-free log ID.</param> /// <param name="associate">The loan associate to assign.</param> /// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <see cref="CancellationToken.None"/>.</param> /// <returns></returns> public Task AssignAssociateAsync(string logId, LoanAssociate associate, CancellationToken cancellationToken = default) { Preconditions.NotNullOrEmpty(logId, nameof(logId)); Preconditions.NotNull(associate, nameof(associate)); Preconditions.NotNullOrEmpty(associate.Id, $"{nameof(associate)}.{nameof(associate.Id)}"); Preconditions.NotNullOrEmpty(associate.LoanAssociateType.Value, $"{nameof(associate)}.{nameof(associate.LoanAssociateType)}"); return PutAsync(logId, null, JsonStreamContent.Create(associate), nameof(AssignAssociateAsync), logId, cancellationToken); } /// <summary> /// Assigns a loan associate to a milestone based on the specified milestone or milestone-free ID and log ID from raw json. /// </summary> /// <param name="logId">The milestone or milestone-free log ID.</param> /// <param name="associate">The loan associate to assign as raw json.</param> /// <param name="queryString">The query string to include in the request.</param> /// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <see cref="CancellationToken.None"/>.</param> /// <returns></returns> public Task AssignAssociateRawAsync(string logId, string associate, string? queryString = null, CancellationToken cancellationToken = default) { Preconditions.NotNullOrEmpty(logId, nameof(logId)); Preconditions.NotNullOrEmpty(associate, nameof(associate)); return PutAsync(logId, queryString, new JsonStringContent(associate), nameof(AssignAssociateRawAsync), logId, cancellationToken); } /// <summary> /// Unassigns a loan associate from a milestone based on the specified milestone or milestone-free ID. /// </summary> /// <param name="logId">The milestone or milestone-free log ID.</param> /// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <see cref="CancellationToken.None"/>.</param> /// <returns></returns> [Obsolete("Undocumented API")] public Task<bool> TryUnassignAssociateAsync(string logId, CancellationToken cancellationToken = default) { Preconditions.NotNullOrEmpty(logId, nameof(logId)); return TryDeleteAsync(logId, null, cancellationToken); } /// <summary> /// Unassigns a loan associate from a milestone based on the specified milestone or milestone-free ID. /// </summary> /// <param name="logId">The milestone or milestone-free log ID.</param> /// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <see cref="CancellationToken.None"/>.</param> /// <returns></returns> [Obsolete("Undocumented API")] public Task UnassignAssociateAsync(string logId, CancellationToken cancellationToken = default) { Preconditions.NotNullOrEmpty(logId, nameof(logId)); return DeleteAsync(logId, null, cancellationToken); } } }
63.848624
215
0.677491
[ "MIT" ]
Oxymoron290/EncompassRest
src/EncompassRest/Loans/Associates/LoanAssociates.cs
13,921
C#
namespace Apex.ConnectApi { using ApexSharp; using ApexSharp.ApexAttributes; using ApexSharp.Implementation; using global::Apex.System; /// <summary> /// https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_ConnectAPI_QuestionAndAnswers_static_methods.htm#apex_ConnectAPI_QuestionAndAnswers_static_methods /// </summary> public class QuestionAndAnswers { // infrastructure public QuestionAndAnswers(dynamic self) { Self = self; } dynamic Self { get; set; } static dynamic Implementation { get { return Implementor.GetImplementation(typeof(QuestionAndAnswers)); } } // API public static QuestionAndAnswersSuggestions getSuggestions(string communityId, string q, string subjectId, bool includeArticles, int maxResults) { return Implementation.getSuggestions(communityId, q, subjectId, includeArticles, maxResults); } public static void setTestGetSuggestions(string communityId, string q, string subjectId, bool includeArticles, int maxResults, QuestionAndAnswersSuggestions result) { Implementation.setTestGetSuggestions(communityId, q, subjectId, includeArticles, maxResults, result); } public static QuestionAndAnswersCapability updateQuestionAndAnswers(string communityId, string feedElementId, QuestionAndAnswersCapabilityInput questionAndAnswersCapability) { return Implementation.updateQuestionAndAnswers(communityId, feedElementId, questionAndAnswersCapability); } public object clone() { return Self.clone(); } } }
34.764706
184
0.681331
[ "MIT" ]
apexsharp/apexsharp
Apex/ConnectApi/QuestionAndAnswers.cs
1,773
C#
// Copyright 2016 SerilogTimings Contributors // // 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 Serilog; using Serilog.Events; using SerilogTimings.Configuration; namespace SerilogTimings.Extensions { /// <summary> /// Extends <see cref="ILogger"/> with timed operations. /// </summary> public static class LoggerOperationExtensions { /// <summary> /// Begin a new timed operation. The return value must be disposed to complete the operation. /// </summary> /// <param name="logger">The logger through which the timing will be recorded.</param> /// <param name="messageTemplate">A log message describing the operation, in message template format.</param> /// <param name="args">Arguments to the log message. These will be stored and captured only when the /// operation completes, so do not pass arguments that are mutated during the operation.</param> /// <returns>An <see cref="Operation"/> object.</returns> public static IDisposable TimeOperation(this ILogger logger, string messageTemplate, params object[] args) { return new Operation(logger, messageTemplate, args, CompletionBehaviour.Complete, LogEventLevel.Information, LogEventLevel.Warning); } /// <summary> /// Begin a new timed operation. The return value must be completed using <see cref="Operation.Complete()"/>, /// or disposed to record abandonment. /// </summary> /// <param name="logger">The logger through which the timing will be recorded.</param> /// <param name="messageTemplate">A log message describing the operation, in message template format.</param> /// <param name="args">Arguments to the log message. These will be stored and captured only when the /// operation completes, so do not pass arguments that are mutated during the operation.</param> /// <returns>An <see cref="Operation"/> object.</returns> public static Operation BeginOperation(this ILogger logger, string messageTemplate, params object[] args) { return new Operation(logger, messageTemplate, args, CompletionBehaviour.Abandon, LogEventLevel.Information, LogEventLevel.Warning); } /// <summary> /// Configure the logging levels used for completion and abandonment events. /// </summary> /// <param name="logger">The logger through which the timing will be recorded.</param> /// <param name="completion">The level of the event to write on operation completion.</param> /// <param name="abandonment">The level of the event to write on operation abandonment; if not /// specified, the <paramref name="completion"/> level will be used.</param> /// <returns>An object from which timings with the configured levels can be made.</returns> /// <remarks>If neither <paramref name="completion"/> nor <paramref name="abandonment"/> is enabled /// on the logger at the time of the call, a no-op result is returned.</remarks> public static LevelledOperation OperationAt(this ILogger logger, LogEventLevel completion, LogEventLevel? abandonment = null) { if (logger == null) throw new ArgumentNullException(nameof(logger)); var appliedAbandonment = abandonment ?? completion; if (!logger.IsEnabled(completion) && (appliedAbandonment == completion || !logger.IsEnabled(appliedAbandonment))) { return LevelledOperation.None; } return new LevelledOperation(logger, completion, appliedAbandonment); } } }
53.278481
144
0.680447
[ "Apache-2.0" ]
EamonHetherton/serilog-timings
src/SerilogTimings/Extensions/LoggerOperationExtensions.cs
4,211
C#
namespace BlockChanPro.Model.Contracts { public class TransactionSigned { public Transaction Data { get; } public Hash Sign { get; } public TransactionSigned(Transaction data, Hash sign) { Data = data; Sign = sign; } } }
17.214286
55
0.688797
[ "MIT" ]
iZakaroN/BlockChainPro
Model/Contracts/TransactionSigned.cs
241
C#
 #pragma warning disable 649 // We don't care about unused fields here, because they are mapped with the input file. namespace GitHubLabeler.DataStructures { internal class GitHubIssueTransformed { public string ID; public string Area; //public float[] Label; // -> Area dictionarized public string Title; //public float[] TitleFeaturized; // -> Title Featurized public string Description; //public float[] DescriptionFeaturized; // -> Description Featurized } } //public Scalar<bool> label { get; set; } //public Scalar<float> score { get; set; }
30.666667
115
0.641304
[ "MIT" ]
27theworldinurhand/machinelearning-samples
samples/csharp/end-to-end-apps/MulticlassClassification-GitHubLabeler/GitHubLabeler/GitHubLabelerConsoleApp/DataStructures/GitHubIssueTransformed.cs
646
C#
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #region Using directives using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Management.Automation; using System.Management.Automation.Runspaces; using System.Globalization; using Microsoft.Management.Infrastructure.Options; #endregion namespace Microsoft.Management.Infrastructure.CimCmdlets { #region CimSessionWrapper internal class CimSessionWrapper { #region members /// <summary> /// Id of the cimsession. /// </summary> public uint SessionId { get { return this.sessionId; } } private uint sessionId; /// <summary> /// InstanceId of the cimsession. /// </summary> public Guid InstanceId { get { return this.instanceId; } } private Guid instanceId; /// <summary> /// Name of the cimsession. /// </summary> public string Name { get { return this.name; } } private string name; /// <summary> /// Computer name of the cimsession. /// </summary> public string ComputerName { get { return this.computerName; } } private string computerName; /// <summary> /// Wrapped cimsession object. /// </summary> public CimSession CimSession { get { return this.cimSession; } } private CimSession cimSession; /// <summary> /// Computer name of the cimsession. /// </summary> public string Protocol { get { switch (protocol) { case ProtocolType.Dcom: return "DCOM"; case ProtocolType.Default: case ProtocolType.Wsman: default: return "WSMAN"; } } } internal ProtocolType GetProtocolType() { return protocol; } private ProtocolType protocol; /// <summary> /// PSObject that wrapped the cimSession. /// </summary> private PSObject psObject; #endregion internal CimSessionWrapper( uint theSessionId, Guid theInstanceId, string theName, string theComputerName, CimSession theCimSession, ProtocolType theProtocol) { this.sessionId = theSessionId; this.instanceId = theInstanceId; this.name = theName; this.computerName = theComputerName; this.cimSession = theCimSession; this.psObject = null; this.protocol = theProtocol; } internal PSObject GetPSObject() { if (psObject == null) { psObject = new PSObject(this.cimSession); psObject.Properties.Add(new PSNoteProperty(CimSessionState.idPropName, this.sessionId)); psObject.Properties.Add(new PSNoteProperty(CimSessionState.namePropName, this.name)); psObject.Properties.Add(new PSNoteProperty(CimSessionState.instanceidPropName, this.instanceId)); psObject.Properties.Add(new PSNoteProperty(CimSessionState.computernamePropName, this.ComputerName)); psObject.Properties.Add(new PSNoteProperty(CimSessionState.protocolPropName, this.Protocol)); } else { psObject.Properties[CimSessionState.idPropName].Value = this.SessionId; psObject.Properties[CimSessionState.namePropName].Value = this.name; psObject.Properties[CimSessionState.instanceidPropName].Value = this.instanceId; psObject.Properties[CimSessionState.computernamePropName].Value = this.ComputerName; psObject.Properties[CimSessionState.protocolPropName].Value = this.Protocol; } return psObject; } } #endregion #region CimSessionState /// <summary> /// <para> /// Class used to hold all cimsession related status data related to a runspace. /// Including the CimSession cache, session counters for generating session name. /// </para> /// </summary> internal class CimSessionState : IDisposable { #region private members /// <summary> /// Default session name. /// If a name is not passed, then the session is given the name CimSession<int>, /// where <int> is the next available session number. /// For example, CimSession1, CimSession2, etc... /// </summary> internal static string CimSessionClassName = "CimSession"; /// <summary> /// CimSession object name. /// </summary> internal static string CimSessionObject = "{CimSession Object}"; /// <summary> /// <para> /// CimSession object path, which is identifying a cimsession object /// </para> /// </summary> internal static string SessionObjectPath = @"CimSession id = {0}, name = {2}, ComputerName = {3}, instance id = {1}"; /// <summary> /// Id property name of cimsession wrapper object. /// </summary> internal static string idPropName = "Id"; /// <summary> /// Instanceid property name of cimsession wrapper object. /// </summary> internal static string instanceidPropName = "InstanceId"; /// <summary> /// Name property name of cimsession wrapper object. /// </summary> internal static string namePropName = "Name"; /// <summary> /// Computer name property name of cimsession object. /// </summary> internal static string computernamePropName = "ComputerName"; /// <summary> /// Protocol name property name of cimsession object. /// </summary> internal static string protocolPropName = "Protocol"; /// <summary> /// <para> /// session counter bound to current runspace. /// </para> /// </summary> private UInt32 sessionNameCounter; /// <summary> /// <para> /// Dictionary used to holds all CimSessions in current runspace by session name. /// </para> /// </summary> private Dictionary<string, HashSet<CimSessionWrapper>> curCimSessionsByName; /// <summary> /// <para> /// Dictionary used to holds all CimSessions in current runspace by computer name. /// </para> /// </summary> private Dictionary<string, HashSet<CimSessionWrapper>> curCimSessionsByComputerName; /// <summary> /// <para> /// Dictionary used to holds all CimSessions in current runspace by instance ID. /// </para> /// </summary> private Dictionary<Guid, CimSessionWrapper> curCimSessionsByInstanceId; /// <summary> /// <para> /// Dictionary used to holds all CimSessions in current runspace by session id. /// </para> /// </summary> private Dictionary<UInt32, CimSessionWrapper> curCimSessionsById; /// <summary> /// <para> /// Dictionary used to link CimSession object with PSObject. /// </para> /// </summary> private Dictionary<CimSession, CimSessionWrapper> curCimSessionWrapper; #endregion /// <summary> /// <para> /// constructor /// </para> /// </summary> internal CimSessionState() { sessionNameCounter = 1; curCimSessionsByName = new Dictionary<string, HashSet<CimSessionWrapper>>( StringComparer.OrdinalIgnoreCase); curCimSessionsByComputerName = new Dictionary<string, HashSet<CimSessionWrapper>>( StringComparer.OrdinalIgnoreCase); curCimSessionsByInstanceId = new Dictionary<Guid, CimSessionWrapper>(); curCimSessionsById = new Dictionary<uint, CimSessionWrapper>(); curCimSessionWrapper = new Dictionary<CimSession, CimSessionWrapper>(); } /// <summary> /// <para> /// Get sessions count. /// </para> /// </summary> /// <returns>The count of session objects in current runspace.</returns> internal int GetSessionsCount() { return this.curCimSessionsById.Count; } /// <summary> /// <para> /// Generates an unique session id. /// </para> /// </summary> /// <returns>Unique session id under current runspace.</returns> internal UInt32 GenerateSessionId() { return this.sessionNameCounter++; } #region IDisposable /// <summary> /// <para> /// Indicates whether this object was disposed or not /// </para> /// </summary> private bool _disposed; /// <summary> /// <para> /// Dispose() calls Dispose(true). /// Implement IDisposable. Do not make this method virtual. /// A derived class should not be able to override this method. /// </para> /// </summary> public void Dispose() { Dispose(true); // This object will be cleaned up by the Dispose method. // Therefore, you should call GC.SuppressFinalize to // take this object off the finalization queue // and prevent finalization code for this object // from executing a second time. GC.SuppressFinalize(this); } /// <summary> /// <para> /// Dispose(bool disposing) executes in two distinct scenarios. /// If disposing equals true, the method has been called directly /// or indirectly by a user's code. Managed and unmanaged resources /// can be disposed. /// If disposing equals false, the method has been called by the /// runtime from inside the finalizer and you should not reference /// other objects. Only unmanaged resources can be disposed. /// </para> /// </summary> /// <param name="disposing">Whether it is directly called.</param> protected virtual void Dispose(bool disposing) { if (!this._disposed) { if (disposing) { // free managed resources Cleanup(); this._disposed = true; } // free native resources if there are any } } /// <summary> /// <para> /// Performs application-defined tasks associated with freeing, releasing, or /// resetting unmanaged resources. /// </para> /// </summary> public void Cleanup() { foreach (CimSession session in curCimSessionWrapper.Keys) { session.Dispose(); } curCimSessionWrapper.Clear(); curCimSessionsByName.Clear(); curCimSessionsByComputerName.Clear(); curCimSessionsByInstanceId.Clear(); curCimSessionsById.Clear(); sessionNameCounter = 1; } #endregion #region Add CimSession to/remove CimSession from cache /// <summary> /// <para> /// Add new CimSession object to cache /// </para> /// </summary> /// <param name="session"></param> /// <param name="sessionId"></param> /// <param name="instanceId"></param> /// <param name="name"></param> /// <returns></returns> internal PSObject AddObjectToCache( CimSession session, UInt32 sessionId, Guid instanceId, string name, string computerName, ProtocolType protocol) { CimSessionWrapper wrapper = new CimSessionWrapper( sessionId, instanceId, name, computerName, session, protocol); HashSet<CimSessionWrapper> objects; if (!this.curCimSessionsByComputerName.TryGetValue(computerName, out objects)) { objects = new HashSet<CimSessionWrapper>(); this.curCimSessionsByComputerName.Add(computerName, objects); } objects.Add(wrapper); if (!this.curCimSessionsByName.TryGetValue(name, out objects)) { objects = new HashSet<CimSessionWrapper>(); this.curCimSessionsByName.Add(name, objects); } objects.Add(wrapper); this.curCimSessionsByInstanceId.Add(instanceId, wrapper); this.curCimSessionsById.Add(sessionId, wrapper); this.curCimSessionWrapper.Add(session, wrapper); return wrapper.GetPSObject(); } /// <summary> /// <para> /// Generates remove session message by given wrapper object. /// </para> /// </summary> /// <param name="psObject"></param> internal string GetRemoveSessionObjectTarget(PSObject psObject) { string message = string.Empty; if (psObject.BaseObject is CimSession) { UInt32 id = 0x0; Guid instanceId = Guid.Empty; string name = string.Empty; string computerName = string.Empty; if (psObject.Properties[idPropName].Value is UInt32) { id = Convert.ToUInt32(psObject.Properties[idPropName].Value, null); } if (psObject.Properties[instanceidPropName].Value is Guid) { instanceId = (Guid)psObject.Properties[instanceidPropName].Value; } if (psObject.Properties[namePropName].Value is string) { name = (string)psObject.Properties[namePropName].Value; } if (psObject.Properties[computernamePropName].Value is string) { computerName = (string)psObject.Properties[computernamePropName].Value; } message = string.Format(CultureInfo.CurrentUICulture, SessionObjectPath, id, instanceId, name, computerName); } return message; } /// <summary> /// <para> /// Remove given <see cref="PSObject"/> object from cache /// </para> /// </summary> /// <param name="psObject"></param> internal void RemoveOneSessionObjectFromCache(PSObject psObject) { DebugHelper.WriteLogEx(); if (psObject.BaseObject is CimSession) { RemoveOneSessionObjectFromCache(psObject.BaseObject as CimSession); } } /// <summary> /// <para> /// Remove given <see cref="CimSession"/> object from cache /// </para> /// </summary> /// <param name="session"></param> internal void RemoveOneSessionObjectFromCache(CimSession session) { DebugHelper.WriteLogEx(); if (!this.curCimSessionWrapper.ContainsKey(session)) { return; } CimSessionWrapper wrapper = this.curCimSessionWrapper[session]; string name = wrapper.Name; string computerName = wrapper.ComputerName; DebugHelper.WriteLog("name {0}, computername {1}, id {2}, instanceId {3}", 1, name, computerName, wrapper.SessionId, wrapper.InstanceId); HashSet<CimSessionWrapper> objects; if (this.curCimSessionsByComputerName.TryGetValue(computerName, out objects)) { objects.Remove(wrapper); } if (this.curCimSessionsByName.TryGetValue(name, out objects)) { objects.Remove(wrapper); } RemoveSessionInternal(session, wrapper); } /// <summary> /// <para> /// Remove given <see cref="CimSession"/> object from partial of the cache only. /// </para> /// </summary> /// <param name="session"></param> /// <param name="psObject"></param> private void RemoveSessionInternal(CimSession session, CimSessionWrapper wrapper) { DebugHelper.WriteLogEx(); this.curCimSessionsByInstanceId.Remove(wrapper.InstanceId); this.curCimSessionsById.Remove(wrapper.SessionId); this.curCimSessionWrapper.Remove(session); session.Dispose(); } #endregion #region Query CimSession from cache /// <summary> /// <para> /// Add ErrorRecord to list. /// </para> /// </summary> /// <param name="errRecords"></param> /// <param name="propertyName"></param> /// <param name="propertyValue"></param> private void AddErrorRecord( ref List<ErrorRecord> errRecords, string propertyName, object propertyValue) { errRecords.Add( new ErrorRecord( new CimException(string.Format(CultureInfo.CurrentUICulture, Strings.CouldNotFindCimsessionObject, propertyName, propertyValue)), string.Empty, ErrorCategory.ObjectNotFound, null)); } /// <summary> /// Query session list by given id array. /// </summary> /// <param name="ids"></param> /// <returns>List of session wrapper objects.</returns> internal IEnumerable<PSObject> QuerySession(IEnumerable<UInt32> ids, out IEnumerable<ErrorRecord> errorRecords) { HashSet<PSObject> sessions = new HashSet<PSObject>(); HashSet<uint> sessionIds = new HashSet<uint>(); List<ErrorRecord> errRecords = new List<ErrorRecord>(); errorRecords = errRecords; // NOTES: use template function to implement this will save duplicate code foreach (UInt32 id in ids) { if (this.curCimSessionsById.ContainsKey(id)) { if (!sessionIds.Contains(id)) { sessionIds.Add(id); sessions.Add(this.curCimSessionsById[id].GetPSObject()); } } else { AddErrorRecord(ref errRecords, idPropName, id); } } return sessions; } /// <summary> /// Query session list by given instance id array. /// </summary> /// <param name="instanceIds"></param> /// <returns>List of session wrapper objects.</returns> internal IEnumerable<PSObject> QuerySession(IEnumerable<Guid> instanceIds, out IEnumerable<ErrorRecord> errorRecords) { HashSet<PSObject> sessions = new HashSet<PSObject>(); HashSet<uint> sessionIds = new HashSet<uint>(); List<ErrorRecord> errRecords = new List<ErrorRecord>(); errorRecords = errRecords; foreach (Guid instanceid in instanceIds) { if (this.curCimSessionsByInstanceId.ContainsKey(instanceid)) { CimSessionWrapper wrapper = this.curCimSessionsByInstanceId[instanceid]; if (!sessionIds.Contains(wrapper.SessionId)) { sessionIds.Add(wrapper.SessionId); sessions.Add(wrapper.GetPSObject()); } } else { AddErrorRecord(ref errRecords, instanceidPropName, instanceid); } } return sessions; } /// <summary> /// Query session list by given name array. /// </summary> /// <param name="nameArray"></param> /// <returns>List of session wrapper objects.</returns> internal IEnumerable<PSObject> QuerySession(IEnumerable<string> nameArray, out IEnumerable<ErrorRecord> errorRecords) { HashSet<PSObject> sessions = new HashSet<PSObject>(); HashSet<uint> sessionIds = new HashSet<uint>(); List<ErrorRecord> errRecords = new List<ErrorRecord>(); errorRecords = errRecords; foreach (string name in nameArray) { bool foundSession = false; WildcardPattern pattern = new WildcardPattern(name, WildcardOptions.IgnoreCase); foreach (KeyValuePair<string, HashSet<CimSessionWrapper>> kvp in this.curCimSessionsByName) { if (pattern.IsMatch(kvp.Key)) { HashSet<CimSessionWrapper> wrappers = kvp.Value; foundSession = (wrappers.Count > 0); foreach (CimSessionWrapper wrapper in wrappers) { if (!sessionIds.Contains(wrapper.SessionId)) { sessionIds.Add(wrapper.SessionId); sessions.Add(wrapper.GetPSObject()); } } } } if (!foundSession && !WildcardPattern.ContainsWildcardCharacters(name)) { AddErrorRecord(ref errRecords, namePropName, name); } } return sessions; } /// <summary> /// Query session list by given computer name array. /// </summary> /// <param name="computernameArray"></param> /// <returns>List of session wrapper objects.</returns> internal IEnumerable<PSObject> QuerySessionByComputerName( IEnumerable<string> computernameArray, out IEnumerable<ErrorRecord> errorRecords) { HashSet<PSObject> sessions = new HashSet<PSObject>(); HashSet<uint> sessionIds = new HashSet<uint>(); List<ErrorRecord> errRecords = new List<ErrorRecord>(); errorRecords = errRecords; foreach (string computername in computernameArray) { bool foundSession = false; if (this.curCimSessionsByComputerName.ContainsKey(computername)) { HashSet<CimSessionWrapper> wrappers = this.curCimSessionsByComputerName[computername]; foundSession = (wrappers.Count > 0); foreach (CimSessionWrapper wrapper in wrappers) { if (!sessionIds.Contains(wrapper.SessionId)) { sessionIds.Add(wrapper.SessionId); sessions.Add(wrapper.GetPSObject()); } } } if (!foundSession) { AddErrorRecord(ref errRecords, computernamePropName, computername); } } return sessions; } /// <summary> /// Query session list by given session objects array. /// </summary> /// <param name="cimsessions"></param> /// <returns>List of session wrapper objects.</returns> internal IEnumerable<PSObject> QuerySession(IEnumerable<CimSession> cimsessions, out IEnumerable<ErrorRecord> errorRecords) { HashSet<PSObject> sessions = new HashSet<PSObject>(); HashSet<uint> sessionIds = new HashSet<uint>(); List<ErrorRecord> errRecords = new List<ErrorRecord>(); errorRecords = errRecords; foreach (CimSession cimsession in cimsessions) { if (this.curCimSessionWrapper.ContainsKey(cimsession)) { CimSessionWrapper wrapper = this.curCimSessionWrapper[cimsession]; if (!sessionIds.Contains(wrapper.SessionId)) { sessionIds.Add(wrapper.SessionId); sessions.Add(wrapper.GetPSObject()); } } else { AddErrorRecord(ref errRecords, CimSessionClassName, CimSessionObject); } } return sessions; } /// <summary> /// Query session wrapper object. /// </summary> /// <param name="cimsessions"></param> /// <returns>Session wrapper.</returns> internal CimSessionWrapper QuerySession(CimSession cimsession) { CimSessionWrapper wrapper; this.curCimSessionWrapper.TryGetValue(cimsession, out wrapper); return wrapper; } /// <summary> /// Query session object with given CimSessionInstanceID. /// </summary> /// <param name="cimSessionInstanceId"></param> /// <returns>CimSession object.</returns> internal CimSession QuerySession(Guid cimSessionInstanceId) { if (this.curCimSessionsByInstanceId.ContainsKey(cimSessionInstanceId)) { CimSessionWrapper wrapper = this.curCimSessionsByInstanceId[cimSessionInstanceId]; return wrapper.CimSession; } return null; } #endregion } #endregion #region CimSessionBase /// <summary> /// <para> /// Base class of all session operation classes. /// All sessions created will be held in a ConcurrentDictionary:cimSessions. /// It manages the lifecycle of the sessions being created for each /// runspace according to the state of the runspace. /// </para> /// </summary> internal class CimSessionBase { #region constructor /// <summary> /// Constructor. /// </summary> public CimSessionBase() { this.sessionState = cimSessions.GetOrAdd( CurrentRunspaceId, delegate (Guid instanceId) { if (Runspace.DefaultRunspace != null) { Runspace.DefaultRunspace.StateChanged += DefaultRunspace_StateChanged; } return new CimSessionState(); }); } #endregion #region members /// <summary> /// <para> /// Thread safe static dictionary to store session objects associated /// with each runspace, which is identified by a GUID. NOTE: cmdlet /// can running parallelly under more than one runspace(s). /// </para> /// </summary> internal static ConcurrentDictionary<Guid, CimSessionState> cimSessions = new ConcurrentDictionary<Guid, CimSessionState>(); /// <summary> /// <para> /// Default runspace id /// </para> /// </summary> internal static Guid defaultRunspaceId = Guid.Empty; /// <summary> /// <para> /// Object used to hold all CimSessions and status data bound /// to current runspace. /// </para> /// </summary> internal CimSessionState sessionState; /// <summary> /// Get current runspace id. /// </summary> private static Guid CurrentRunspaceId { get { if (Runspace.DefaultRunspace != null) { return Runspace.DefaultRunspace.InstanceId; } else { return CimSessionBase.defaultRunspaceId; } } } #endregion public static CimSessionState GetCimSessionState() { CimSessionState state = null; cimSessions.TryGetValue(CurrentRunspaceId, out state); return state; } /// <summary> /// <para> /// clean up the dictionaries if the runspace is closed or broken. /// </para> /// </summary> /// <param name="sender">Runspace.</param> /// <param name="e">Event args.</param> private static void DefaultRunspace_StateChanged(object sender, RunspaceStateEventArgs e) { Runspace runspace = (Runspace)sender; switch (e.RunspaceStateInfo.State) { case RunspaceState.Broken: case RunspaceState.Closed: CimSessionState state; if (cimSessions.TryRemove(runspace.InstanceId, out state)) { DebugHelper.WriteLog(string.Format(CultureInfo.CurrentUICulture, DebugHelper.runspaceStateChanged, runspace.InstanceId, e.RunspaceStateInfo.State)); state.Dispose(); } runspace.StateChanged -= DefaultRunspace_StateChanged; break; default: break; } } } #endregion #region CimTestConnection #endregion #region CimNewSession /// <summary> /// <para> /// <c>CimNewSession</c> is the class to create cimSession /// based on given <c>NewCimSessionCommand</c>. /// </para> /// </summary> internal class CimNewSession : CimSessionBase, IDisposable { /// <summary> /// CimTestCimSessionContext. /// </summary> internal class CimTestCimSessionContext : XOperationContextBase { /// <summary> /// <para> /// Constructor /// </para> /// </summary> /// <param name="theProxy"></param> /// <param name="wrapper"></param> internal CimTestCimSessionContext( CimSessionProxy theProxy, CimSessionWrapper wrapper) { this.proxy = theProxy; this.cimSessionWrapper = wrapper; this.nameSpace = null; } /// <summary> /// <para>namespace</para> /// </summary> internal CimSessionWrapper CimSessionWrapper { get { return this.cimSessionWrapper; } } private CimSessionWrapper cimSessionWrapper; } /// <summary> /// <para> /// constructor /// </para> /// </summary> internal CimNewSession() : base() { this.cimTestSession = new CimTestSession(); this._disposed = false; } /// <summary> /// Create a new <see cref="CimSession"/> base on given cmdlet /// and its parameter. /// </summary> /// <param name="cmdlet"></param> /// <param name="sessionOptions"></param> /// <param name="credential"></param> internal void NewCimSession(NewCimSessionCommand cmdlet, CimSessionOptions sessionOptions, CimCredential credential) { DebugHelper.WriteLogEx(); IEnumerable<string> computerNames = ConstValue.GetComputerNames(cmdlet.ComputerName); foreach (string computerName in computerNames) { CimSessionProxy proxy; if (sessionOptions == null) { DebugHelper.WriteLog("Create CimSessionOption due to NewCimSessionCommand has null sessionoption", 1); sessionOptions = CimSessionProxy.CreateCimSessionOption(computerName, cmdlet.OperationTimeoutSec, credential); } proxy = new CimSessionProxyTestConnection(computerName, sessionOptions); string computerNameValue = (computerName == ConstValue.NullComputerName) ? ConstValue.LocalhostComputerName : computerName; CimSessionWrapper wrapper = new CimSessionWrapper(0, Guid.Empty, cmdlet.Name, computerNameValue, proxy.CimSession, proxy.Protocol); CimTestCimSessionContext context = new CimTestCimSessionContext(proxy, wrapper); proxy.ContextObject = context; // Skip test the connection if user intend to if (cmdlet.SkipTestConnection.IsPresent) { AddSessionToCache(proxy.CimSession, context, new CmdletOperationBase(cmdlet)); } else { // CimSession will be returned as part of TestConnection this.cimTestSession.TestCimSession(computerName, proxy); } } } /// <summary> /// <para> /// Add session to global cache /// </para> /// </summary> /// <param name="cimSession"></param> /// <param name="context"></param> /// <param name="cmdlet"></param> internal void AddSessionToCache(CimSession cimSession, XOperationContextBase context, CmdletOperationBase cmdlet) { DebugHelper.WriteLogEx(); CimTestCimSessionContext testCimSessionContext = context as CimTestCimSessionContext; UInt32 sessionId = this.sessionState.GenerateSessionId(); string originalSessionName = testCimSessionContext.CimSessionWrapper.Name; string sessionName = (originalSessionName != null) ? originalSessionName : string.Format(CultureInfo.CurrentUICulture, @"{0}{1}", CimSessionState.CimSessionClassName, sessionId); // detach CimSession from the proxy object CimSession createdCimSession = testCimSessionContext.Proxy.Detach(); PSObject psObject = this.sessionState.AddObjectToCache( createdCimSession, sessionId, createdCimSession.InstanceId, sessionName, testCimSessionContext.CimSessionWrapper.ComputerName, testCimSessionContext.Proxy.Protocol); cmdlet.WriteObject(psObject, null); } /// <summary> /// <para> /// process all actions in the action queue /// </para> /// </summary> /// <param name="cmdletOperation"> /// wrapper of cmdlet, <seealso cref="CmdletOperationBase"/> for details /// </param> public void ProcessActions(CmdletOperationBase cmdletOperation) { this.cimTestSession.ProcessActions(cmdletOperation); } /// <summary> /// <para> /// process remaining actions until all operations are completed or /// current cmdlet is terminated by user /// </para> /// </summary> /// <param name="cmdletOperation"> /// wrapper of cmdlet, <seealso cref="CmdletOperationBase"/> for details /// </param> public void ProcessRemainActions(CmdletOperationBase cmdletOperation) { this.cimTestSession.ProcessRemainActions(cmdletOperation); } #region private members /// <summary> /// <para> /// <see cref="CimTestSession"/> object. /// </para> /// </summary> private CimTestSession cimTestSession; #endregion // private members #region IDisposable /// <summary> /// <para> /// Indicates whether this object was disposed or not /// </para> /// </summary> protected bool Disposed { get { return _disposed; } } private bool _disposed; /// <summary> /// <para> /// Dispose() calls Dispose(true). /// Implement IDisposable. Do not make this method virtual. /// A derived class should not be able to override this method. /// </para> /// </summary> public void Dispose() { Dispose(true); // This object will be cleaned up by the Dispose method. // Therefore, you should call GC.SuppressFinalize to // take this object off the finalization queue // and prevent finalization code for this object // from executing a second time. GC.SuppressFinalize(this); } /// <summary> /// <para> /// Dispose(bool disposing) executes in two distinct scenarios. /// If disposing equals true, the method has been called directly /// or indirectly by a user's code. Managed and unmanaged resources /// can be disposed. /// If disposing equals false, the method has been called by the /// runtime from inside the finalizer and you should not reference /// other objects. Only unmanaged resources can be disposed. /// </para> /// </summary> /// <param name="disposing">Whether it is directly called.</param> protected virtual void Dispose(bool disposing) { if (!this._disposed) { if (disposing) { // free managed resources this.cimTestSession.Dispose(); this._disposed = true; } // free native resources if there are any } } #endregion } #endregion #region CimGetSession /// <summary> /// <para> /// Get CimSession based on given id/instanceid/computername/name /// </para> /// </summary> internal class CimGetSession : CimSessionBase { /// <summary> /// Constructor. /// </summary> public CimGetSession() : base() { } /// <summary> /// Get <see cref="CimSession"/> objects based on the given cmdlet /// and its parameter. /// </summary> /// <param name="cmdlet"></param> public void GetCimSession(GetCimSessionCommand cmdlet) { DebugHelper.WriteLogEx(); IEnumerable<PSObject> sessionToGet = null; IEnumerable<ErrorRecord> errorRecords = null; switch (cmdlet.ParameterSetName) { case CimBaseCommand.ComputerNameSet: if (cmdlet.ComputerName == null) { sessionToGet = this.sessionState.QuerySession(ConstValue.DefaultSessionName, out errorRecords); } else { sessionToGet = this.sessionState.QuerySessionByComputerName(cmdlet.ComputerName, out errorRecords); } break; case CimBaseCommand.SessionIdSet: sessionToGet = this.sessionState.QuerySession(cmdlet.Id, out errorRecords); break; case CimBaseCommand.InstanceIdSet: sessionToGet = this.sessionState.QuerySession(cmdlet.InstanceId, out errorRecords); break; case CimBaseCommand.NameSet: sessionToGet = this.sessionState.QuerySession(cmdlet.Name, out errorRecords); break; default: break; } if (sessionToGet != null) { foreach (PSObject psobject in sessionToGet) { cmdlet.WriteObject(psobject); } } if (errorRecords != null) { foreach (ErrorRecord errRecord in errorRecords) { cmdlet.WriteError(errRecord); } } } #region helper methods #endregion } #endregion #region CimRemoveSession /// <summary> /// <para> /// Get CimSession based on given id/instanceid/computername/name /// </para> /// </summary> internal class CimRemoveSession : CimSessionBase { /// <summary> /// Remove session action string. /// </summary> internal static string RemoveCimSessionActionName = "Remove CimSession"; /// <summary> /// Constructor. /// </summary> public CimRemoveSession() : base() { } /// <summary> /// Remove the <see cref="CimSession"/> objects based on given cmdlet /// and its parameter. /// </summary> /// <param name="cmdlet"></param> public void RemoveCimSession(RemoveCimSessionCommand cmdlet) { DebugHelper.WriteLogEx(); IEnumerable<PSObject> sessionToRemove = null; IEnumerable<ErrorRecord> errorRecords = null; switch (cmdlet.ParameterSetName) { case CimBaseCommand.CimSessionSet: sessionToRemove = this.sessionState.QuerySession(cmdlet.CimSession, out errorRecords); break; case CimBaseCommand.ComputerNameSet: sessionToRemove = this.sessionState.QuerySessionByComputerName(cmdlet.ComputerName, out errorRecords); break; case CimBaseCommand.SessionIdSet: sessionToRemove = this.sessionState.QuerySession(cmdlet.Id, out errorRecords); break; case CimBaseCommand.InstanceIdSet: sessionToRemove = this.sessionState.QuerySession(cmdlet.InstanceId, out errorRecords); break; case CimBaseCommand.NameSet: sessionToRemove = this.sessionState.QuerySession(cmdlet.Name, out errorRecords); break; default: break; } if (sessionToRemove != null) { foreach (PSObject psobject in sessionToRemove) { if (cmdlet.ShouldProcess(this.sessionState.GetRemoveSessionObjectTarget(psobject), RemoveCimSessionActionName)) { this.sessionState.RemoveOneSessionObjectFromCache(psobject); } } } if (errorRecords != null) { foreach (ErrorRecord errRecord in errorRecords) { cmdlet.WriteError(errRecord); } } } } #endregion #region CimTestSession /// <summary> /// Class <see cref="CimTestSession"/>, which is used to /// test cimsession and execute async operations. /// </summary> internal class CimTestSession : CimAsyncOperation { /// <summary> /// Constructor. /// </summary> internal CimTestSession() : base() { } /// <summary> /// Test the session connection with /// given <see cref="CimSessionProxy"/> object. /// </summary> /// <param name="computerName"></param> /// <param name="proxy"></param> internal void TestCimSession( string computerName, CimSessionProxy proxy) { DebugHelper.WriteLogEx(); this.SubscribeEventAndAddProxytoCache(proxy); proxy.TestConnectionAsync(); } } #endregion }
34.041316
190
0.537715
[ "MIT" ]
BluPerf/PowerShell
src/Microsoft.Management.Infrastructure.CimCmdlets/CimSessionOperations.cs
44,492
C#
using System; using System.Diagnostics.CodeAnalysis; using System.Linq.Expressions; namespace DotNext.Linq.Expressions { /// <summary> /// Represents <c>for</c> loop as expression. /// </summary> /// <seealso href="https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/for">for Statement</seealso> public sealed class ForExpression : Expression, ILoopLabels { internal interface IBuilder : ILoopLabels { Expression MakeCondition(ParameterExpression loopVar); Expression MakeIteration(ParameterExpression loopVar); Expression MakeBody(ParameterExpression loopVar); } /// <summary> /// Represents expression builder. /// </summary> /// <seealso cref="Builder(Expression)"/> public sealed class LoopBuilder : IBuilder, IExpressionBuilder<ForExpression> { /// <summary> /// Represents constructor of loop condition. /// </summary> /// <param name="loopVar">The loop variable.</param> /// <returns>The condition of loop continuation. Must be of type <see cref="bool"/>.</returns> public delegate Expression Condition(ParameterExpression loopVar); /// <summary> /// Represents constructor of loop iteration. /// </summary> /// <param name="loopVar">The loop variable.</param> /// <returns>The loop iteration.</returns> public delegate Expression Iteration(ParameterExpression loopVar); /// <summary> /// Represents constructor of loop body. /// </summary> /// <param name="loopVar">The loop variable.</param> /// <param name="continueLabel">A label that can be used to produce <see cref="Expression.Continue(LabelTarget)"/> expression.</param> /// <param name="breakLabel">A label that can be used to produce <see cref="Expression.Break(LabelTarget)"/> expression.</param> /// <returns>The loop body.</returns> public delegate Expression Statement(ParameterExpression loopVar, LabelTarget continueLabel, LabelTarget breakLabel); private readonly LabelTarget continueLabel, breakLabel; private readonly Expression initialization; private Iteration? iteration; private Condition? condition; private Statement? body; internal LoopBuilder(Expression initialization) { this.initialization = initialization; breakLabel = Label(typeof(void), "break"); continueLabel = Label(typeof(void), "continueLabel"); } /// <summary> /// Defines loop condition. /// </summary> /// <param name="condition">A delegate used to construct condition.</param> /// <returns><c>this</c> builder.</returns> /// <seealso cref="Condition"/> public LoopBuilder While(Condition condition) { this.condition = condition; return this; } /// <summary> /// Defines loop body. /// </summary> /// <param name="body">A delegate used to construct loop body.</param> /// <returns><c>this</c> builder.</returns> /// <seealso cref="Statement"/> public LoopBuilder Do(Statement body) { this.body = body; return this; } /// <summary> /// Constructs loop iteration statement. /// </summary> /// <param name="iteration">A delegate used to construct iteration statement.</param> /// <returns><c>this</c> builder.</returns> /// <see cref="Iteration"/> public LoopBuilder Iterate(Iteration iteration) { this.iteration = iteration; return this; } [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600", Justification = "It's a member of internal interface")] LabelTarget ILoopLabels.BreakLabel => breakLabel; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600", Justification = "It's a member of internal interface")] LabelTarget ILoopLabels.ContinueLabel => continueLabel; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600", Justification = "It's a member of internal interface")] Expression IBuilder.MakeCondition(ParameterExpression loopVar) => condition is null ? Constant(true) : condition(loopVar); [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600", Justification = "It's a member of internal interface")] Expression IBuilder.MakeIteration(ParameterExpression loopVar) => iteration is null ? Empty() : iteration(loopVar); [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600", Justification = "It's a member of internal interface")] Expression IBuilder.MakeBody(ParameterExpression loopVar) => body is null ? Empty() : body(loopVar, continueLabel, breakLabel); /// <summary> /// Constructs a new instance of <see cref="ForExpression"/>. /// </summary> /// <returns>The constructed instance of <see cref="ForExpression"/>.</returns> public ForExpression Build() => new ForExpression(initialization, this); } private Expression? body; internal ForExpression(Expression initialization, LabelTarget continueLabel, LabelTarget breakLabel, LoopBuilder.Condition condition) { Initialization = initialization; LoopVar = Variable(initialization.Type, "loop_var"); Test = condition(LoopVar); if (Test.Type != typeof(bool)) throw new ArgumentException(ExceptionMessages.TypeExpected<bool>(), nameof(condition)); ContinueLabel = continueLabel ?? Label(typeof(void), "continue"); BreakLabel = breakLabel ?? Label(typeof(void), "break"); } internal ForExpression(Expression initialization, IBuilder builder) : this(initialization, builder.ContinueLabel, builder.BreakLabel, builder.MakeCondition) { body = builder.MakeBody(LoopVar).AddPrologue(false, Continue(ContinueLabel), builder.MakeIteration(LoopVar)); } /// <summary> /// Creates a builder of <see cref="ForExpression"/>. /// </summary> /// <param name="initialization">Loop variable initialization expression.</param> /// <returns>A new instance of builder.</returns> public static LoopBuilder Builder(Expression initialization) => new LoopBuilder(initialization); /// <summary> /// Represents condition of the loop continuation. /// </summary> public Expression Test { get; } /// <summary> /// Represents loop variable initialization expression. /// </summary> public Expression Initialization { get; } /// <summary> /// Represents loop variable initialized by <see cref="Initialization"/>. /// </summary> public ParameterExpression LoopVar { get; } /// <summary> /// Gets label that is used by the loop body as a break statement target. /// </summary> public LabelTarget BreakLabel { get; } /// <summary> /// Gets label that is used by the loop body as a continue statement target. /// </summary> public LabelTarget ContinueLabel { get; } /// <summary> /// Gets body of this loop. /// </summary> public Expression Body { get => body ?? Empty(); internal set => body = value; } /// <summary> /// Always returns <see cref="ExpressionType.Extension"/>. /// </summary> public override ExpressionType NodeType => ExpressionType.Extension; /// <summary> /// Always returns <see cref="void"/>. /// </summary> public override Type Type => typeof(void); /// <summary> /// Always returns <see langword="true"/> because /// this expression is <see cref="ExpressionType.Extension"/>. /// </summary> public override bool CanReduce => true; /// <summary> /// Translates this expression into predefined set of expressions /// using Lowering technique. /// </summary> /// <returns>Translated expression.</returns> public override Expression Reduce() { Expression body = Condition(Test, Body, Goto(BreakLabel), typeof(void)); body = Loop(body, BreakLabel); return Block(typeof(void), Sequence.Singleton(LoopVar), Assign(LoopVar, Initialization), body); } } }
42.971429
146
0.598848
[ "MIT" ]
GerardSmit/dotNext
src/DotNext.Metaprogramming/Linq/Expressions/ForExpression.cs
9,024
C#
using Binance.Net.Objects.Spot.SpotData; using Kucoin.Net.Objects; using SolBo.Shared.Domain.Enums; using SolBo.Shared.Extensions; using System; namespace SolBo.Shared.Domain.Statics { public static class LogGenerator { public static string ValidationSuccess(string ruleAttribute) => $"Validation SUCCESS => {ruleAttribute}"; public static string ValidationError(string ruleAttribute, string attributeValue) => $"Validation ERROR => {ruleAttribute} => Value => {attributeValue} => BAD"; public static string SaveSuccess(string version) => $"[{version}] Save SUCCESS"; public static string SaveError(string version) => $"[{version}] Save ERROR"; public static string SequenceSuccess(string sequenceName, string attribute) => $"{sequenceName} SUCCESS => {attribute}"; public static string SequenceError(string sequenceName, string attribute) => $"{sequenceName} ERROR => {attribute}"; public static string SequenceException(string sequenceName, Exception e) => $"{sequenceName} EXCEPTION => {e.GetFullMessage()}"; public static string ModeStart(string modeName) => $"{modeName} START"; public static string ModeEnd(string modeName) => $"{modeName} END"; public static string ModeExecuted(string modeName) => $"{modeName} EXECUTED"; public static string Off(MarketOrderType orderType) => $"{orderType.GetDescription()} => OFF"; public static string BuyStepSuccess(decimal priceCurrent, decimal average, string change) => $"{MarketOrderType.BUYING.GetDescription()} " + $"=> CURRENT PRICE => ({priceCurrent}) " + $"=> DECREASED => CALCULATED AVERAGE " + $"=> ({average}) => BY ({change})"; public static string BuyStepError(decimal priceCurrent, decimal average, string change, string needed) => $"{MarketOrderType.BUYING.GetDescription()} " + $"=> CURRENT PRICE => ({priceCurrent}) " + $"=> INCREASED => CALCULATED AVERAGE " + $"=> ({average}) => BY ({change}) " + $"=> NEEDED DECREASED CHANGE => ({needed})"; public static string SellStepSuccess(SellType sellType, decimal priceCurrent, decimal average, string change) => $"{MarketOrderType.SELLING.GetDescription()} " + $"=> CURRENT PRICE => ({priceCurrent}) " + $"=> INCREASED => {sellType.GetDescription()} " + $"=> ({average}) => BY ({change})"; public static string SellStepError(SellType sellType, decimal priceCurrent, decimal average, string change, string needed) => $"{MarketOrderType.SELLING.GetDescription()} " + $"=> CURRENT PRICE => ({priceCurrent}) " + $"=> DECREASED => {sellType.GetDescription()} " + $"=> ({average}) => BY ({change}) " + $"=> NEEDED INCREASED CHANGE => ({needed})"; public static string StopLossStepSuccess(SellType sellType, decimal priceCurrent, decimal average, string change) => $"{MarketOrderType.STOPLOSS.GetDescription()} " + $"=> CURRENT PRICE => ({priceCurrent}) " + $"=> DECREASED => {sellType.GetDescription()} " + $"=> ({average}) => BY ({change})"; public static string StopLossStepError(SellType sellType, decimal priceCurrent, decimal average, string change, string needed) => $"{MarketOrderType.STOPLOSS.GetDescription()} " + $"=> CURRENT PRICE => ({priceCurrent}) " + $"=> DECREASED => {sellType.GetDescription()} " + $"=> ({average}) => BY ({change}) " + $"=> NEEDED DECREASED CHANGE => ({needed})"; public static string PriceMarketSuccess(MarketOrderType orderType) => $"{orderType.GetDescription()} => ORDER => EXCHANGE => PLACED"; public static string PriceMarketError(MarketOrderType orderType) => $"{orderType.GetDescription()} => ORDER => EXCHANGE => NOT PLACED"; public static string OrderMarketSuccess(MarketOrderType orderType) => $"{orderType.GetDescription()} => ORDER => EXCHANGE => SUCCEED"; public static string OrderMarketError(MarketOrderType orderType, string message = "") { var result = string.IsNullOrWhiteSpace(message) ? string.Empty : $"=> {message}"; return $"{orderType.GetDescription()} => ORDER => EXCHANGE => NOT SUCCEED {result}"; } public static string TradeResultStart(string orderId) => $"ORDER ({orderId}) => START"; public static string TradeResultEnd(string orderId, decimal average, decimal quantity, decimal commission) => $"ORDER ({orderId}) => END => AVERAGE => {average} => Quantity (all) => {quantity} => Commision (all) => {commission}"; public static string TradeResultEndKucoin(string orderId) => $"ORDER ({orderId}) => END"; public static string TradeResult(MarketOrderType orderType, BinanceOrderTrade order) => $"{orderType.GetDescription()} => TRADE ({order.TradeId}) => Price => {order.Price} => Quantity {order.Quantity} => Commission {order.Commission} ({order.CommissionAsset})"; public static string TradeResultKucoin(MarketOrderType orderType, KucoinOrder order, decimal price) => $"{orderType.GetDescription()} => TRADE ({order.Id}) => Price => {price} => Quantity {order.DealQuantity.ToKucoinRound()} => Commission {order.Fee.ToKucoinRound()} ({order.FeeCurrency})"; public static string ExecuteMarketSuccess(MarketOrderType orderType, decimal bought) { return bought == 0 ? $"{orderType.GetDescription()} => PRICE => REACHED" : $"{orderType.GetDescription()} => PRICE => REACHED => BOUGHT => ({bought})"; } public static string ExecuteMarketError(MarketOrderType orderType, decimal bought) { return bought == 0 ? $"{orderType.GetDescription()} => PRICE => NOT REACHED" : $"{orderType.GetDescription()} => PRICE => NOT REACHED => BOUGHT => ({bought})"; } public static string ModeTypeSuccess(string sequenceName, string attribute) => $"{sequenceName} ON => {attribute}"; public static string ModeTypeError(string sequenceName, string attribute) => $"{sequenceName} OFF => {attribute}"; public static string AverageTypeSuccess(string sequenceName, string attribute) => $"{sequenceName} ON => {attribute}"; public static string AverageTypeError(string sequenceName, string attribute) => $"{sequenceName} OFF => {attribute}"; public static string ExchangeLog(string baseAsset, string quoteAsset, string error = "") => string.IsNullOrWhiteSpace(error) ? $"EXCHANGE ASSETS => BASE => ({baseAsset}) => QUOTE => ({quoteAsset})" : $"EXCHANGE ASSETS => ERROR => {error}"; public static string NotificationTitleStart => "Hello! my dear Trader :)"; public static string NotificationMessageStart => "I've started working for <strong>You</strong>.<br>" + " Join our <a href=\"https://t.me/joinchat/JmoiyRyhQp5o7Ts1ZezFQA\">Telegram Group</a>.<br><br>" + " Please visit <a href=\"https://cryptodev.tv\">https://cryptodev.tv</a>"; public static string NotificationTitle(EnvironmentType workingType, MarketOrderType marketOrderType, string symbol) => $"[{workingType.GetDescription()}] => {marketOrderType.GetDescription()} [{symbol}]"; public static string NotificationMessage(decimal average, decimal price, decimal percentage) => $"Average: {average}<br>Price: {price}<br>Change: {percentage}"; } }
56.735714
202
0.617525
[ "MIT" ]
CryptoDevTV/SolBo
SolBo/SolBo.Shared/Domain/Statics/LogGenerator.cs
7,945
C#
// Copyright (c) 2010-2014 SharpDX - Alexandre Mutel // // 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 SharpDX.Mathematics; using SharpDX.Toolkit.Serialization; namespace SharpDX.Toolkit.Graphics { public partial class SpriteFontData { /// <summary> /// Description of a glyph (a single character) /// </summary> public struct Glyph : IDataSerializable { /// <summary> /// Unicode codepoint. /// </summary> public int Character; /// <summary> /// Glyph image data (may only use a portion of a larger bitmap). /// </summary> public Rectangle Subrect; /// <summary> /// Layout information. /// </summary> public Vector2 Offset; /// <summary> /// Advance X /// </summary> public float XAdvance; /// <summary> /// Index to a bitmap stored in <see cref="SpriteFontData.Bitmaps"/>. /// </summary> public int BitmapIndex; void IDataSerializable.Serialize(BinarySerializer serializer) { serializer.Serialize(ref Character); serializer.Serialize(ref Subrect); serializer.Serialize(ref Offset); serializer.Serialize(ref XAdvance); serializer.Serialize(ref BitmapIndex); } } } }
37.147059
82
0.625099
[ "MIT" ]
baetz-daniel/Toolkit
Source/Toolkit/SharpDX.Toolkit/Graphics/SpriteFontData.Glyph.cs
2,528
C#
// ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ // **NOTE** This file was generated by a tool and any changes will be overwritten. // <auto-generated/> // Template Source: Templates\CSharp\Requests\EntityCollectionResponse.cs.tt namespace Microsoft.Graph { using System.Collections.Generic; using System.Runtime.Serialization; using Newtonsoft.Json; /// <summary> /// The type DeviceAppManagementWdacSupplementalPoliciesCollectionResponse. /// </summary> [JsonObject(MemberSerialization = MemberSerialization.OptIn)] public class DeviceAppManagementWdacSupplementalPoliciesCollectionResponse { /// <summary> /// Gets or sets the <see cref="IDeviceAppManagementWdacSupplementalPoliciesCollectionPage"/> value. /// </summary> [JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName ="value", Required = Newtonsoft.Json.Required.Default)] public IDeviceAppManagementWdacSupplementalPoliciesCollectionPage Value { get; set; } /// <summary> /// Gets or sets additional data. /// </summary> [JsonExtensionData(ReadData = true)] public IDictionary<string, object> AdditionalData { get; set; } } }
43.970588
153
0.643478
[ "MIT" ]
OfficeGlobal/msgraph-beta-sdk-dotnet
src/Microsoft.Graph/Requests/Generated/DeviceAppManagementWdacSupplementalPoliciesCollectionResponse.cs
1,495
C#
using Microsoft.VisualStudio.TestTools.UnitTesting; namespace Tests { [TestClass] public class CTests { [TestMethod] public void TestMethod1() { var input = @"3 3 5 -1"; var output = @"12 8 10"; Tester.InOutTest(() => Tasks.C.Solve(), input, output); } [TestMethod] public void TestMethod2() { var input = @"5 1 1 1 2 0"; var output = @"4 4 4 2 4"; Tester.InOutTest(() => Tasks.C.Solve(), input, output); } [TestMethod] public void TestMethod3() { var input = @"6 -679 -2409 -3258 3095 -3291 -4462"; var output = @"21630 21630 19932 8924 21630 19288"; Tester.InOutTest(() => Tasks.C.Solve(), input, output); } } }
17.808511
67
0.494624
[ "CC0-1.0" ]
AconCavy/AtCoder.Tasks.CS
ABC/ABC092/Tests/CTests.cs
837
C#
using Godot; using System; public class ColorListEntryEditor : HBoxContainer { [Signal] public delegate void deleted(ColorListEntryEditor node); [Signal] public delegate void changed(ColorListEntryEditor node, Color color); public override void _Ready() { GetNode<ColorPickerButton>("ColorPickerButton").Connect("color_changed", this, nameof(Signal_OnChanged)); GetNode<Button>("DeleteButton").Connect("pressed", this, nameof(Signal_OnDelete)); } private void Signal_OnDelete() { EmitSignal(nameof(deleted), this); QueueFree(); } private void Signal_OnChanged(Color color) { EmitSignal(nameof(changed), this, color); } }
25.607143
113
0.684798
[ "MIT" ]
spacechase0/StardewEditor3
Util/ColorListEntryEditor.cs
717
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.WafV2.Inputs { public sealed class WebAclRuleStatementRateBasedStatementScopeDownStatementOrStatementStatementAndStatementStatementRegexPatternSetReferenceStatementFieldToMatchSingleQueryArgumentGetArgs : Pulumi.ResourceArgs { /// <summary> /// The name of the query header to inspect. This setting must be provided as lower case characters. /// </summary> [Input("name", required: true)] public Input<string> Name { get; set; } = null!; public WebAclRuleStatementRateBasedStatementScopeDownStatementOrStatementStatementAndStatementStatementRegexPatternSetReferenceStatementFieldToMatchSingleQueryArgumentGetArgs() { } } }
39.884615
213
0.756991
[ "ECL-2.0", "Apache-2.0" ]
Otanikotani/pulumi-aws
sdk/dotnet/WafV2/Inputs/WebAclRuleStatementRateBasedStatementScopeDownStatementOrStatementStatementAndStatementStatementRegexPatternSetReferenceStatementFieldToMatchSingleQueryArgumentGetArgs.cs
1,037
C#
using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Text; using Microsoft.Ajax.Utilities; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace DllUnitTest { /// <summary> /// Summary description for SourceDirective /// </summary> [TestClass] public class SourceDirective { private const string OutputFolder = @"Dll\Output"; private const string ExpectedFolder = @"Dll\Expected"; private const string InputFolder = @"Dll\Input"; public SourceDirective() { } private TestContext testContextInstance; /// <summary> ///Gets or sets the test context which provides ///information about and functionality for the current test run. ///</summary> public TestContext TestContext { get { return testContextInstance; } set { testContextInstance = value; } } [TestMethod] public void SourceChange() { const string FileName = "SourceChange.js"; const string OriginalFileContext = "NULL"; // get the source code string source; var inputPath = Path.Combine(InputFolder, FileName); Trace.Write("Source: "); Trace.WriteLine(inputPath); using (var reader = new StreamReader(inputPath)) { source = reader.ReadToEnd(); } Trace.WriteLine(source); Trace.WriteLine(""); Trace.WriteLine("-----------------------"); Trace.WriteLine(""); // get the expected results string expected; var expectedPath = new FileInfo(Path.Combine(ExpectedFolder, FileName)); Trace.Write("Expected: "); Trace.WriteLine(inputPath); using (var reader = new StreamReader(expectedPath.FullName)) { expected = reader.ReadToEnd(); } Trace.WriteLine(expected); Trace.WriteLine(""); Trace.WriteLine("-----------------------"); Trace.WriteLine(""); // parse the source, keeping track of the errors var errors = new List<ContextError>(); var parser = new JSParser(); parser.CompilerError += (sender, ea) => { errors.Add(ea.Error); }; var settings = new CodeSettings() { LocalRenaming = LocalRenaming.KeepAll }; var block = parser.Parse(new DocumentContext(source) { FileContext = OriginalFileContext }, settings); var minified = OutputVisitor.Apply(block, parser.Settings); // write the output so we can diagnose later if we need to if (!Directory.Exists(OutputFolder)) { Directory.CreateDirectory(OutputFolder); } var actualPath = new FileInfo(Path.Combine(OutputFolder, FileName)); Trace.Write("Actual: "); Trace.WriteLine(actualPath); using (var writer = new StreamWriter(actualPath.FullName, false, Encoding.UTF8)) { writer.Write(minified); } Trace.WriteLine(minified); Trace.WriteLine(""); Trace.WriteLine("-----------------------"); Trace.WriteLine(""); Trace.WriteLine("Output Comparison:"); Trace.WriteLine(string.Format("odd.exe \"{0}\" \"{1}\"", expectedPath.FullName, actualPath.FullName)); Trace.WriteLine(""); // and compare them -- they should be equal Assert.IsTrue(string.CompareOrdinal(minified, expected) == 0, "actual is not the expected"); var expectedErrors = new[] { new {FileContext = "anonfunc.js", StartLine = 2, EndLine = 2, StartColumn = 20, EndColumn = 21, ErrorCode = "JS1010"}, new {FileContext = "anonfunc.js", StartLine = 5, EndLine = 5, StartColumn = 3, EndColumn = 4, ErrorCode = "JS1195"}, new {FileContext = "addclass.js", StartLine = 2, EndLine = 2, StartColumn = 8, EndColumn = 14, ErrorCode = "JS1135"}, new {FileContext = "addclass.js", StartLine = 10, EndLine = 10, StartColumn = 42, EndColumn = 48, ErrorCode = "JS1135"}, }; // now, the errors should be the same -- in particular we are looking for the line/column // numbers and source path. they should be what got reset by the ///#SOURCE comments, not the // real values from the source file. Trace.WriteLine("Errors:"); foreach (var error in errors) { Trace.WriteLine(error.ToString()); var foundIt = false; foreach (var expectedError in expectedErrors) { if (expectedError.StartLine == error.StartLine && expectedError.EndLine == error.EndLine && expectedError.StartColumn == error.StartColumn && expectedError.EndColumn == error.EndColumn && string.CompareOrdinal(expectedError.FileContext, error.File) == 0 && string.CompareOrdinal(expectedError.ErrorCode, error.ErrorCode) == 0) { foundIt = true; break; } } Assert.IsTrue(foundIt, "Unexpected error"); } Trace.WriteLine(""); } } }
36.910256
136
0.53074
[ "MIT" ]
Microsoft/ajaxmin
DllUnitTest/SourceDirective.cs
5,760
C#
using System; namespace MIMP.Window { public class ScreenEventArgs : EventArgs { public IScreen Screen { get; } public ScreenEventArgs(IScreen screen) { Screen = screen ?? throw new ArgumentNullException(nameof(screen)); } } }
16.055556
79
0.602076
[ "MIT" ]
DavenaHack/WIMP
src/MIMP.Window/ScreenEventArgs.cs
291
C#
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Immutable; using System.Diagnostics; using System.Reflection.Metadata; using System.Runtime.InteropServices; using System.Threading; using Roslyn.Utilities; namespace Microsoft.DiaSymReader.PortablePdb { internal sealed class PortablePdbReader : IDisposable { private readonly MetadataReader _metadataReader; private readonly GCHandle _pinnedImage; private LazyMetadataImport _lazyMetadataImport; internal IntPtr ImagePtr => _pinnedImage.AddrOfPinnedObject(); internal int ImageSize { get; } internal PortablePdbReader(byte[] buffer, int size, LazyMetadataImport metadataImport) { Debug.Assert(metadataImport != null); _metadataReader = CreateMetadataReader(buffer, size, out _pinnedImage); _lazyMetadataImport = metadataImport; ImageSize = size; } internal unsafe static MetadataReader CreateMetadataReader(byte[] buffer, int size, out GCHandle pinnedImage) { Debug.Assert(buffer != null); Debug.Assert(size >= 0 && size <= buffer.Length); pinnedImage = GCHandle.Alloc(buffer, GCHandleType.Pinned); return new MetadataReader((byte*)pinnedImage.AddrOfPinnedObject(), size); } internal bool MatchesModule(Guid guid, uint stamp, int age) { return age == 1 && IdEquals(MetadataReader.DebugMetadataHeader.Id, guid, stamp); } internal static bool IdEquals(ImmutableArray<byte> left, Guid rightGuid, uint rightStamp) { if (left.Length != 20) { // invalid id return false; } byte[] guidBytes = rightGuid.ToByteArray(); for (int i = 0; i < guidBytes.Length; i++) { if (guidBytes[i] != left[i]) { return false; } } byte[] stampBytes = BitConverter.GetBytes(rightStamp); for (int i = 0; i < stampBytes.Length; i++) { if (stampBytes[i] != left[guidBytes.Length + i]) { return false; } } return true; } internal IMetadataImport GetMetadataImport() { if (IsDisposed) { throw new ObjectDisposedException(nameof(SymReader)); } return _lazyMetadataImport.GetMetadataImport(); } internal MetadataReader MetadataReader { get { if (IsDisposed) { throw new ObjectDisposedException(nameof(SymReader)); } return _metadataReader; } } internal bool IsDisposed { get { return _lazyMetadataImport == null; } } public void Dispose() { if (!IsDisposed) { _pinnedImage.Free(); _lazyMetadataImport.Dispose(); _lazyMetadataImport = null; } } } }
29.465517
161
0.548274
[ "Apache-2.0" ]
HaloFour/roslyn
src/Debugging/Microsoft.DiaSymReader.PortablePdb/PortablePdbReader.cs
3,420
C#
using LogicAPI.Server.Components; using LogicLog; using System; namespace potatochips { public class HexDisplay : LogicComponent { private bool _data0 { get { return base.Inputs[0].On; } } private bool _data1 { get { return base.Inputs[1].On; } } private bool _data2 { get { return base.Inputs[2].On; } } private bool _data3 { get { return base.Inputs[3].On; } } private bool _out0 { set { base.Outputs[0].On = value; } } private bool _out1 { set { base.Outputs[1].On = value; } } private bool _out2 { set { base.Outputs[2].On = value; } } private bool _out3 { set { base.Outputs[3].On = value; } } private bool _out4 { set { base.Outputs[4].On = value; } } private bool _out5 { set { base.Outputs[5].On = value; } } private bool _out6 { set { base.Outputs[6].On = value; } } private int _data { get { return (_data3 ? 1 : 0) + (_data2 ? 2 : 0) + (_data1 ? 4 : 0) + (_data0 ? 8 : 0); } } private int _out { set { _out0 = (value & 0x01) != 0; _out1 = (value & 0x02) != 0; _out2 = (value & 0x04) != 0; _out3 = (value & 0x08) != 0; _out4 = (value & 0x10) != 0; _out5 = (value & 0x20) != 0; _out6 = (value & 0x40) != 0; } } private byte[] table = new byte[] { 0b01111110, 0b00110000, 0b01101101, 0b01111001, 0b00110011, 0b01011011, 0b01011111, 0b01110000, 0b01111111, 0b01111011, 0b01110111, 0b00011111, 0b01001110, 0b00111101, 0b01001111, 0b01000111 }; protected override void DoLogicUpdate() { _out = table[_data]; } } }
17.113043
89
0.477134
[ "MIT" ]
Vandesm14/Potato-Chips
src/server/HexDisplay.cs
1,968
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; public partial class IdentifierType: ICommonType { public object GetValue() { return this.Value; } public void SetValue(object fieldValue) { this.Value = fieldValue?.ToString(); } } public partial class TextType : ICommonType { public object GetValue() { return this.Value; } public void SetValue(object fieldValue) { this.Value = fieldValue?.ToString(); } } public partial class DateType : ICommonType { public object GetValue() { return this.Value; } public void SetValue(object fieldValue) { if (fieldValue != null) { this.Value = DateTime.Parse(fieldValue.ToString()); } } } public partial class NumericType : ICommonType { public object GetValue() { return this.Value; } public void SetValue(object fieldValue) { if (fieldValue != null) { this.Value = Decimal.Parse(fieldValue.ToString()); } } } public partial class TimeType : ICommonType { public object GetValue() { return this.Value; } public void SetValue(object fieldValue) { if (fieldValue != null) { this.Value = DateTime.Parse(fieldValue.ToString()); } } } public partial class IndicatorType : ICommonType { public object GetValue() { return this.Value; } public void SetValue(object fieldValue) { if (fieldValue != null && !string.IsNullOrEmpty(fieldValue.ToString())) { this.Value = bool.Parse(fieldValue.ToString()); } } } public partial class MeasureType : ICommonType { public object GetValue() { return this.Value; } public void SetValue(object fieldValue) { if (fieldValue != null) { this.Value = decimal.Parse(fieldValue.ToString()); } } } public partial class AmountType : ICommonType { public object GetValue() { return this.Value; } public void SetValue(object fieldValue) { if (fieldValue != null) { this.Value = decimal.Parse(fieldValue.ToString()); } } } public partial class QuantityType : ICommonType { public object GetValue() { return this.Value; } public void SetValue(object fieldValue) { if (fieldValue != null) { this.Value = decimal.Parse(fieldValue.ToString()); } } } public partial class CodeType : ICommonType { public object GetValue() { return this.Value; } public void SetValue(object fieldValue) { this.Value = fieldValue?.ToString(); } } public partial class BinaryObjectType : ICommonType { public object GetValue() { return this.Value; } public void SetValue(object fieldValue) { this.Value = (byte[])fieldValue; } }
16.630208
79
0.569057
[ "MIT" ]
WEBCON-BPS/BPSExt-PEF
WebCon.BpsExt.PEF/CustomActions/XmlHelper/xsd_output_ext.cs
3,195
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using JMW.Collections; using JMW.IO; namespace JMW.Networking.Junos.Parser { public class Tokenizer { private readonly string _objectStart = @"{"; private readonly string _objectStop = @"}"; private readonly string _arrayStart = @"["; private readonly string _arrayStop = @"]"; private readonly string _commentBlockStart = @"/*"; private readonly string _commentStart = @"#"; private readonly string _LineStop = @";"; internal LineTrackingReader _reader; public Token Token { get; } public static readonly string INVALID_UNICODE_ERROR = "Invalid Character Encoding for parsing instruction input"; internal bool _inWord = false; internal bool _eof = false; internal int Line { get { return _reader.Line; } } internal int Column { get { return _reader.Column; } } public Tokenizer(string template) : this(new StringReader(template)) { } public Tokenizer(TextReader reader) { _reader = new LineTrackingReader(reader); Token = new Token(); } public TokenType Next() { try { if (_eof) { return setupErrorToken("EOF"); } Token.Line = Line; Token.Column = Column; if (_inWord) { _inWord = false; // you have a word, is it a property or an object? if (maybeReadObjectStart()) { return consumeObjectStart(); } // ignore empty words. if (Token.Value.Length > 0) { Token.Type = TokenType.Word; return Token.Type; } } if (maybeReadArrayStart()) { return consumeArrayStart(); } if (maybeReadCommentBlockStart()) { return consumeCommentBlockStart(); } if (maybeReadCommentStart()) { return consumeComment(); } if (maybeReadObjectStop()) { return consumeObjectStop(); } if (maybeReadArrayStop()) { return consumeArrayStop(); } if (maybeReadLineStop()) { return consumeLineStop(); } if (maybeReadWord()) { return consumeWord(); } return consumeWhitespace(); } catch (Exception ex) { return setupErrorToken(ex.Message); } } private TokenType setupErrorToken(string msg) { return setupErrorToken(msg, Line, Column); } private TokenType setupErrorToken(string msg, int line, int column) { Token.Type = TokenType.Error; Token.Value = msg; Token.Line = line; Token.Column = column; return Token.Type; } internal TokenType consumeUntil(int cc, TokenType type) { Token.Type = type; var c = _reader.Read(); var value = new List<char>(); while (c != cc && c != 0) { value.Add((char)c); c = _reader.Read(); // This is the unicode invalid character. If we encounter this it means we parsed the // template with an invalid encoding. Or the template was stored with an invalid // encoding. if (c == '\uffff') { return setupErrorToken(INVALID_UNICODE_ERROR); } } if (c == -1) { _eof = true; } else if (c != cc) { _reader.PushBack((char)c); } Token.Value = new string(value.ToArray()); return type; } internal TokenType consumeComment() { var c = _reader.Read(); if (c == -1) { _eof = true; return setupErrorToken("EOF"); } _reader.PushBack(new[] { (char)c }); consumeUntil('\n', TokenType.Comment); Token.Value = Token.Value.TrimEnd('\r', '\n'); return Token.Type; } internal TokenType consumeObjectStart() { Token.Type = TokenType.ObjectStart; return Token.Type; } internal TokenType consumeObjectStop() { Token.Value = string.Empty; Token.Type = TokenType.ObjectStop; return Token.Type; } internal TokenType consumeArrayStart() { Token.Type = TokenType.ArrayStart; return Token.Type; } internal TokenType consumeCommentBlockStart() { var text = new RingBuffer<char>(2); var c = _reader.Read(); text.Add((char)c); while (!(text[0] == '*' && text[1] == '/')) // ignore the ';', its optional. { c = _reader.Read(); // This is the unicode invalid character. If we encounter this it means we parsed the // template with an invalid encoding. Or the template was stored with an invalid // encoding. if (c == '\uffff') { return setupErrorToken(INVALID_UNICODE_ERROR); } text.Add((char)c); } if (c == -1) { _eof = true; } return Next(); } internal TokenType consumeArrayStop() { Token.Value = string.Empty; Token.Type = TokenType.ArrayStop; return Token.Type; } internal TokenType consumeLineStop() { Token.Value = string.Empty; Token.Type = TokenType.LineStop; return Token.Type; } internal TokenType consumeWord() { var unacceptable = "[]{}#;".ToCharArray(); var identifier = new List<char>(); var c = _reader.Read(); if ((char) c == '"') { _inWord = true; _reader.PushBack((char)c); return consumeQuotedString(); } while (!Char.IsWhiteSpace((char)c) && !unacceptable.Contains((char)c)) { identifier.Add((char)c); c = _reader.Read(); // This is the unicode invalid character. If we encounter this it means we parsed the // template with an invalid encoding. Or the template was stored with an invalid // encoding. if (c == '\uffff') { return setupErrorToken(INVALID_UNICODE_ERROR); } } if (c == -1) { _eof = true; } else { _reader.PushBack((char)c); } _inWord = true; Token.Type = TokenType.Word; Token.Value = new string(identifier.ToArray()); return consumeWhitespace(); } internal TokenType consumeQuotedString() { var text = new StringBuilder(); var c = _reader.Read(); if (c == 34) c = _reader.Read(); else { return Next(); } text.Append((char) c); while (c != 34) // ignore the ';', its optional. { c = _reader.Read(); // This is the unicode invalid character. If we encounter this it means we parsed the // template with an invalid encoding. Or the template was stored with an invalid // encoding. if (c == '\uffff') { return setupErrorToken(INVALID_UNICODE_ERROR); } text.Append((char)c); } if (c == -1) { _eof = true; } Token.Value = text.ToString().Trim('"'); Token.Type = TokenType.Word; return Next(); } internal TokenType consumeWhitespace() { var c = _reader.Read(); while (c != -1 && Char.IsWhiteSpace((char)c)) // ignore the ';', its optional. { c = _reader.Read(); // This is the unicode invalid character. If we encounter this it means we parsed the // template with an invalid encoding. Or the template was stored with an invalid // encoding. if (c == '\uffff') { return setupErrorToken(INVALID_UNICODE_ERROR); } } if (c == -1) { _eof = true; } else { _reader.PushBack((char)c); } return Next(); } internal bool maybeReadWord() { readText(" ", out var buf, out var n); _reader.PushBack(buf.Take(n).ToArray()); var c = buf.First(); var unacceptable = "{}[]#;".ToCharArray(); if (!unacceptable.Contains(c)) return true; return false; } internal bool maybeReadCommentStart() { return maybeReadText(_commentStart); } internal bool maybeReadObjectStart() { return maybeReadText(_objectStart); } internal bool maybeReadObjectStop() { return maybeReadText(_objectStop); } internal bool maybeReadArrayStart() { return maybeReadText(_arrayStart); } internal bool maybeReadCommentBlockStart() { return maybeReadText(_commentBlockStart); } internal bool maybeReadArrayStop() { return maybeReadText(_arrayStop); } internal bool maybeReadLineStop() { return maybeReadText(_LineStop); } internal bool maybeReadBeginPropertyValue() { var c = _reader.Read(); _reader.PushBack((char)c); if (c == '"' || c == '\'') return true; return false; } internal bool maybeReadText(string text) { readText(text, out var buf, out var n); var ok = (n == text.Length && new String(buf) == text); if (!ok) { _reader.PushBack(buf.Take(n).ToArray()); } return ok; } private void readText(string text, out char[] buf, out int n) { buf = new char[text.Length]; n = _reader.Read(buf); if (n == 0) { _eof = true; } } } }
29.245823
122
0.431288
[ "MIT" ]
walljm/JMW.Extensions
JMW.Networking/Junos/Parser/Tokenizer.cs
12,256
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Examples.Entities { public class GroupLegacyEntity { public virtual int Id { get; set; } public virtual int GroupNo { get; set; } public virtual string Name { get; set; } public virtual ISet<ItemLegacyEntity> Items { get; set; } } }
20.4
65
0.671569
[ "MIT" ]
rungwiroon/QSS.Base
src/Examples/Entities/GroupLegacyEntity.cs
410
C#
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using ByteBee.Framework.Configuring.Abstractions; using ByteBee.Framework.Configuring.Abstractions.DataClasses; namespace ByteBee.Framework.Configuring { public sealed class StandardConfigProvider : IConfigProvider { private readonly IConfigManager _source; public StandardConfigProvider(IConfigManager source) { _source = source; } public TConfig Get<TConfig>() { Type typeObject = typeof(TConfig); Type sourceType = typeof(IConfigManager); var config = Activator.CreateInstance<TConfig>(); ConfigSectionAttribute sectionAttribute = typeObject .GetCustomAttributes(true) .OfType<ConfigSectionAttribute>() .FirstOrDefault(); MethodInfo getMethod = sourceType.GetMethod("GetOrDefault"); if (getMethod == null) { throw new MissingMethodException("IConfigManager", "GetOrDefault"); } IEnumerable<PropertyInfo> properties = typeObject.GetProperties(); foreach (PropertyInfo property in properties) { ConfigKeyAttribute keyAttribute = property.GetCustomAttributes(true) .OfType<ConfigKeyAttribute>().FirstOrDefault(); string section = sectionAttribute?.Name ?? typeObject.Name; string key = keyAttribute?.Name ?? property.Name; Type propType = property.PropertyType; MethodInfo generic = getMethod.MakeGenericMethod(propType); object value = generic.Invoke(_source, new object[] {section, key}); property.SetValue(config, value); } return config; } } }
31.966102
84
0.61983
[ "MIT" ]
ByteBee/ByteBee
Configuring/StandardConfigProvider.cs
1,888
C#
//------------------------------------------------------------ // Game Framework // Copyright © 2013-2021 Jiang Yin. All rights reserved. // Homepage: https://gameframework.cn/ // Feedback: mailto:ellan@gameframework.cn //------------------------------------------------------------ namespace StarForce { /// <summary> /// 界面编号。 /// </summary> public enum UIFormId : byte { Undefined = 0, /// <summary> /// 弹出框。 /// </summary> DialogForm = 1, /// <summary> /// 主菜单。 /// </summary> MenuForm = 100, /// <summary> /// 设置。 /// </summary> SettingForm = 101, /// <summary> /// 关于。 /// </summary> AboutForm = 102, } }
20.447368
63
0.384813
[ "MIT" ]
963148894/StarForceOrign
Assets/GameMain/Scripts/UI/UIFormId.cs
818
C#
/* * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the elasticbeanstalk-2010-12-01.normal.json service model. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Net; using System.Text; using System.Xml.Serialization; using Amazon.ElasticBeanstalk.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; namespace Amazon.ElasticBeanstalk.Model.Internal.MarshallTransformations { /// <summary> /// Response Unmarshaller for CheckDNSAvailability operation /// </summary> public class CheckDNSAvailabilityResponseUnmarshaller : XmlResponseUnmarshaller { public override AmazonWebServiceResponse Unmarshall(XmlUnmarshallerContext context) { CheckDNSAvailabilityResponse response = new CheckDNSAvailabilityResponse(); context.Read(); int targetDepth = context.CurrentDepth; while (context.ReadAtDepth(targetDepth)) { if (context.IsStartElement) { if(context.TestExpression("CheckDNSAvailabilityResult", 2)) { UnmarshallResult(context, response); continue; } if (context.TestExpression("ResponseMetadata", 2)) { response.ResponseMetadata = ResponseMetadataUnmarshaller.Instance.Unmarshall(context); } } } return response; } private static void UnmarshallResult(XmlUnmarshallerContext context, CheckDNSAvailabilityResponse response) { int originalDepth = context.CurrentDepth; int targetDepth = originalDepth + 1; if (context.IsStartOfDocument) targetDepth += 2; while (context.ReadAtDepth(originalDepth)) { if (context.IsStartElement || context.IsAttribute) { if (context.TestExpression("Available", targetDepth)) { var unmarshaller = BoolUnmarshaller.Instance; response.Available = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("FullyQualifiedCNAME", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; response.FullyQualifiedCNAME = unmarshaller.Unmarshall(context); continue; } } } return; } public override AmazonServiceException UnmarshallException(XmlUnmarshallerContext context, Exception innerException, HttpStatusCode statusCode) { ErrorResponse errorResponse = ErrorResponseUnmarshaller.GetInstance().Unmarshall(context); return new AmazonElasticBeanstalkException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode); } private static CheckDNSAvailabilityResponseUnmarshaller _instance = new CheckDNSAvailabilityResponseUnmarshaller(); internal static CheckDNSAvailabilityResponseUnmarshaller GetInstance() { return _instance; } public static CheckDNSAvailabilityResponseUnmarshaller Instance { get { return _instance; } } } }
37.025424
171
0.607691
[ "Apache-2.0" ]
ermshiperete/aws-sdk-net
AWSSDK_DotNet35/Amazon.ElasticBeanstalk/Model/Internal/MarshallTransformations/CheckDNSAvailabilityResponseUnmarshaller.cs
4,369
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; [CreateAssetMenu(fileName = "RamenDish", menuName = "ScriptableObjects/HiraganaCharacters/RamenDish", order = 4)] public class RamenDishes : ScriptableObject { [SerializeField] string dishName; [SerializeField] List<Character> listOfCharacter = new List<Character>(); [SerializeField] string dishDescription; [SerializeField] Sprite dishSprite; public void Add(Character character) { listOfCharacter.Add(character); } public Character GetById(int idx) { return listOfCharacter[idx]; } public Character GetAndRemoveById(int idx) { Character returnable = listOfCharacter[idx]; listOfCharacter.RemoveAt(idx); return returnable; } public string GetDishName() { return dishName; } public string GetDishDesc() { return dishDescription; } public Sprite GetDishSprite() { return dishSprite; } }
22.777778
113
0.677073
[ "MIT" ]
aantonb2018/LearnWithRamenRepository
LearnWithRamen/Assets/Scripts/RamenDishes.cs
1,025
C#
// CodeContracts // // Copyright (c) Microsoft Corporation // // All rights reserved. // // MIT License // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // File System.Web.UI.WebControls.DataBoundControl.cs // Automatically generated contract file. using System.Collections.Generic; using System.IO; using System.Text; using System.Diagnostics.Contracts; using System; // Disable the "this variable is not used" warning as every field would imply it. #pragma warning disable 0414 // Disable the "this variable is never assigned to". #pragma warning disable 0649 // Disable the "this variable is never used". #pragma warning disable 0169 // Disable the "new keyword not required" warning. #pragma warning disable 0109 // Disable the "extern without DllImport" warning. #pragma warning disable 0626 // Disable the "could hide other member" warning, can happen on certain properties. #pragma warning disable 0108 namespace System.Web.UI.WebControls { abstract public partial class DataBoundControl : BaseDataBoundControl { #region Methods and constructors protected virtual new System.Web.UI.DataSourceSelectArguments CreateDataSourceSelectArguments () { return default(System.Web.UI.DataSourceSelectArguments); } protected DataBoundControl () { } protected virtual new System.Web.UI.DataSourceView GetData () { return default(System.Web.UI.DataSourceView); } protected virtual new System.Web.UI.IDataSource GetDataSource () { return default(System.Web.UI.IDataSource); } protected void MarkAsDataBound () { } protected override void OnDataPropertyChanged () { } protected virtual new void OnDataSourceViewChanged (Object sender, EventArgs e) { } protected internal override void OnLoad (EventArgs e) { } protected override void OnPagePreLoad (Object sender, EventArgs e) { } protected internal virtual new void PerformDataBinding (System.Collections.IEnumerable data) { } protected override void PerformSelect () { } protected override void ValidateDataSource (Object dataSource) { } #endregion #region Properties and indexers public virtual new string DataMember { get { return default(string); } set { } } public override string DataSourceID { get { return default(string); } set { } } public System.Web.UI.IDataSource DataSourceObject { get { return default(System.Web.UI.IDataSource); } } protected System.Web.UI.DataSourceSelectArguments SelectArguments { get { return default(System.Web.UI.DataSourceSelectArguments); } } #endregion } }
28.362963
463
0.708801
[ "MIT" ]
Acidburn0zzz/CodeContracts
Microsoft.Research/Contracts/System.Web/System.Web.UI.WebControls.DataBoundControl.cs
3,829
C#