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 ObjCRuntime; using System; namespace UIKit { public enum UITextAlignment : long { Left, Center, Right, Justified, Natural } }
10.428571
35
0.691781
[ "Apache-2.0" ]
DavidAlphaFox/mac-samples
MacCustomControl/MacCustomControl/UIKit/UITextAlignment.cs
148
C#
//Copyright (c) 2007. Clarius Consulting, Manas Technology Solutions, InSTEDD //http://code.google.com/p/moq/ //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 Clarius Consulting, Manas Technology Solutions or InSTEDD 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. //[This is the BSD license, see // http://www.opensource.org/licenses/bsd-license.php] using Moq.Language; using Moq.Language.Flow; using Moq.Matchers; using Moq.Properties; using Moq.Proxy; using System; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; using System.Linq.Expressions; using System.Reflection; using System.Text; namespace Moq { internal partial class MethodCall<TMock> : MethodCall, ISetup<TMock> where TMock : class { public MethodCall(Mock mock, Condition condition, Expression originalExpression, MethodInfo method, params Expression[] arguments) : base(mock, condition, originalExpression, method, arguments) { } public IVerifies Raises(Action<TMock> eventExpression, EventArgs args) { return Raises(eventExpression, () => args); } public IVerifies Raises(Action<TMock> eventExpression, Func<EventArgs> func) { return RaisesImpl(eventExpression, func); } public IVerifies Raises(Action<TMock> eventExpression, params object[] args) { return RaisesImpl(eventExpression, args); } } internal class TypeEqualityComparer : IEqualityComparer<Type> { public bool Equals(Type x, Type y) { return y.IsAssignableFrom(x); } public int GetHashCode(Type obj) { return obj.GetHashCode(); } } internal partial class MethodCall : IProxyCall, ICallbackResult, IVerifies, IThrowsResult { // Internal for AsMockExtensions private Expression originalExpression; private Exception thrownException; private Action<object[]> setupCallback; private List<IMatcher> argumentMatchers = new List<IMatcher>(); private bool isOnce; private EventInfo mockEvent; private Delegate mockEventArgsFunc; private object[] mockEventArgsParams; private int? expectedCallCount = null; protected Condition condition; private List<KeyValuePair<int, object>> outValues = new List<KeyValuePair<int, object>>(); private static readonly IEqualityComparer<Type> typesComparer = new TypeEqualityComparer(); public MethodCall(Mock mock, Condition condition, Expression originalExpression, MethodInfo method, params Expression[] arguments) { this.Mock = mock; this.condition = condition; this.originalExpression = originalExpression; this.Method = method; var parameters = method.GetParameters(); for (int index = 0; index < parameters.Length; index++) { var parameter = parameters[index]; var argument = arguments[index]; if (parameter.IsOutArgument()) { var constant = argument.PartialEval() as ConstantExpression; if (constant == null) { throw new NotSupportedException(Resources.OutExpressionMustBeConstantValue); } outValues.Add(new KeyValuePair<int, object>(index, constant.Value)); } else if (parameter.IsRefArgument()) { var constant = argument.PartialEval() as ConstantExpression; if (constant == null) { throw new NotSupportedException(Resources.RefExpressionMustBeConstantValue); } argumentMatchers.Add(new RefMatcher(constant.Value)); } else { var isParamArray = parameter.GetCustomAttribute<ParamArrayAttribute>(true) != null; argumentMatchers.Add(MatcherFactory.CreateMatcher(argument, isParamArray)); } } this.SetFileInfo(); } public string FailMessage { get; set; } public bool IsConditional { get { return condition != null; } } public bool IsVerifiable { get; set; } public bool Invoked { get; set; } // Where the setup was performed. public MethodInfo Method { get; private set; } public string FileName { get; private set; } public int FileLine { get; private set; } public MethodBase TestMethod { get; private set; } public Expression SetupExpression { get { return this.originalExpression; } } public int CallCount { get; private set; } protected internal Mock Mock { get; private set; } [Conditional("DESKTOP")] [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] private void SetFileInfo() { try { var thisMethod = MethodBase.GetCurrentMethod(); var mockAssembly = Assembly.GetExecutingAssembly(); // Move 'till we're at the entry point into Moq API #if !SILVERLIGHT var frame = new StackTrace(true) #else var frame = new StackTrace() #endif .GetFrames() .SkipWhile(f => f.GetMethod() != thisMethod) .SkipWhile(f => f.GetMethod().DeclaringType == null || f.GetMethod().DeclaringType.Assembly == mockAssembly) .FirstOrDefault(); if (frame != null) { this.FileLine = frame.GetFileLineNumber(); #if !SILVERLIGHT this.FileName = Path.GetFileName(frame.GetFileName()); #endif this.TestMethod = frame.GetMethod(); } } catch { // Must NEVER fail, as this is a nice-to-have feature only. } } public void SetOutParameters(ICallContext call) { foreach (var item in this.outValues) { // it's already evaluated here // TODO: refactor so that we call.SetArgumentValue(item.Key, item.Value); } } public virtual bool Matches(ICallContext call) { if (condition != null && !condition.IsTrue) { return false; } var parameters = call.Method.GetParameters(); var args = new List<object>(); for (int i = 0; i < parameters.Length; i++) { if (!parameters[i].IsOutArgument()) { args.Add(call.Arguments[i]); } } if (argumentMatchers.Count == args.Count && this.IsEqualMethodOrOverride(call)) { for (int i = 0; i < argumentMatchers.Count; i++) { if (!argumentMatchers[i].Matches(args[i])) { return false; } } return true; } return false; } public void EvaluatedSuccessfully() { if (condition != null) condition.EvaluatedSuccessfully(); } public virtual void Execute(ICallContext call) { this.Invoked = true; if (setupCallback != null) { setupCallback(call.Arguments); } if (thrownException != null) { throw thrownException; } this.CallCount++; if (this.isOnce && this.CallCount > 1) { throw new MockException( MockException.ExceptionReason.MoreThanOneCall, Times.Once().GetExceptionMessage(FailMessage, SetupExpression.ToStringFixed(), this.CallCount)); } if (expectedCallCount.HasValue && this.CallCount > expectedCallCount) { throw new MockException( MockException.ExceptionReason.MoreThanNCalls, Times.AtMost(expectedCallCount.Value).GetExceptionMessage(FailMessage, SetupExpression.ToStringFixed(), CallCount)); } if (this.mockEvent != null) { if (mockEventArgsParams != null) { this.Mock.DoRaise(this.mockEvent, mockEventArgsParams); } else { var argsFuncType = mockEventArgsFunc.GetType(); if (argsFuncType.IsGenericType && argsFuncType.GetGenericArguments().Length == 1) { this.Mock.DoRaise(this.mockEvent, (EventArgs)mockEventArgsFunc.InvokePreserveStack()); } else { this.Mock.DoRaise(this.mockEvent, (EventArgs)mockEventArgsFunc.InvokePreserveStack(call.Arguments)); } } } } public IThrowsResult Throws(Exception exception) { this.thrownException = exception; return this; } public IThrowsResult Throws<TException>() where TException : Exception, new() { this.thrownException = new TException(); return this; } public ICallbackResult Callback(Action callback) { SetCallbackWithoutArguments(callback); return this; } protected virtual void SetCallbackWithoutArguments(Action callback) { this.setupCallback = delegate { callback(); }; } protected virtual void SetCallbackWithArguments(Delegate callback) { var expectedParams = this.Method.GetParameters(); var actualParams = callback.Method.GetParameters(); if (!callback.HasCompatibleParameterList(expectedParams)) { ThrowParameterMismatch(expectedParams, actualParams); } this.setupCallback = delegate(object[] args) { callback.InvokePreserveStack(args); }; } private static void ThrowParameterMismatch(ParameterInfo[] expected, ParameterInfo[] actual) { throw new ArgumentException(string.Format( CultureInfo.CurrentCulture, "Invalid callback. Setup on method with parameters ({0}) cannot invoke callback with parameters ({1}).", string.Join(",", expected.Select(p => p.ParameterType.Name).ToArray()), string.Join(",", actual.Select(p => p.ParameterType.Name).ToArray()) )); } public void Verifiable() { this.IsVerifiable = true; } public void Verifiable(string failMessage) { this.IsVerifiable = true; this.FailMessage = failMessage; } private bool IsEqualMethodOrOverride(ICallContext call) { if (call.Method == this.Method) { return true; } if (this.Method.DeclaringType.IsAssignableFrom(call.Method.DeclaringType)) { if (!this.Method.Name.Equals(call.Method.Name, StringComparison.Ordinal) || this.Method.ReturnType != call.Method.ReturnType || !this.Method.IsGenericMethod && !call.Method.GetParameterTypes().SequenceEqual(this.Method.GetParameterTypes())) { return false; } if (Method.IsGenericMethod && !call.Method.GetGenericArguments().SequenceEqual(Method.GetGenericArguments(), typesComparer)) { return false; } return true; } return false; } public IVerifies AtMostOnce() { this.isOnce = true; return this; } public IVerifies AtMost(int callCount) { this.expectedCallCount = callCount; return this; } protected IVerifies RaisesImpl<TMock>(Action<TMock> eventExpression, Delegate func) where TMock : class { this.mockEvent = eventExpression.GetEvent((TMock)Mock.Object); this.mockEventArgsFunc = func; return this; } protected IVerifies RaisesImpl<TMock>(Action<TMock> eventExpression, params object[] args) where TMock : class { this.mockEvent = eventExpression.GetEvent((TMock)Mock.Object); this.mockEventArgsParams = args; return this; } public override string ToString() { var message = new StringBuilder(); if (this.FailMessage != null) { message.Append(this.FailMessage).Append(": "); } var lambda = SetupExpression.PartialMatcherAwareEval().ToLambda(); var targetTypeName = lambda.Parameters[0].Type.Name; message.Append(targetTypeName).Append(" ").Append(lambda.ToStringFixed()); if (TestMethod != null && FileName != null && FileLine != 0) { message.AppendFormat( " ({0}() in {1}: line {2})", TestMethod.Name, FileName, FileLine); } return message.ToString().Trim(); } } internal class Condition { private readonly Func<bool> condition; private readonly Action success; public Condition(Func<bool> condition, Action success = null) { this.condition = condition; this.success = success; } public bool IsTrue { get { if (condition != null) return condition(); else return false; } } public void EvaluatedSuccessfully() { if (success != null) success(); } } }
26.596708
132
0.701145
[ "BSD-3-Clause" ]
mizbrodin/moq4
Source/MethodCall.cs
12,928
C#
 public interface IPlayerState { IPlayerState HandleInput(Player player); void EnterState(Player player); void UpdateState(Player player); void ExitState(Player player); }
21
44
0.740741
[ "MIT" ]
DevelopersGuild/Castle-Bashers
Assets/Scripts/Mechanics/Player/Movement States/IPlayerState.cs
191
C#
using System; using System.Collections.Generic; using System.Text; using Microsoft.AspNetCore.Identity.EntityFrameworkCore; using Microsoft.EntityFrameworkCore; namespace BookStore_Inspiration.Data { public class ApplicationDbContext : IdentityDbContext { public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options) { } } }
23.882353
83
0.741379
[ "MIT" ]
EmORz/BookStore
BookStore_Inspiration/Data/ApplicationDbContext.cs
408
C#
using System.Collections.Generic; using System.Collections.ObjectModel; using System.Net.Http.Headers; using System.Web.Http.Description; using DOL.WHD.Section14c.EmailApi.Areas.HelpPage.ModelDescriptions; namespace DOL.WHD.Section14c.EmailApi.Areas.HelpPage.Models { /// <summary> /// The model that represents an API displayed on the help page. /// </summary> public class HelpPageApiModel { /// <summary> /// Initializes a new instance of the <see cref="HelpPageApiModel"/> class. /// </summary> public HelpPageApiModel() { UriParameters = new Collection<ParameterDescription>(); SampleRequests = new Dictionary<MediaTypeHeaderValue, object>(); SampleResponses = new Dictionary<MediaTypeHeaderValue, object>(); ErrorMessages = new Collection<string>(); } /// <summary> /// Gets or sets the <see cref="ApiDescription"/> that describes the API. /// </summary> public ApiDescription ApiDescription { get; set; } /// <summary> /// Gets or sets the <see cref="ParameterDescription"/> collection that describes the URI parameters for the API. /// </summary> public Collection<ParameterDescription> UriParameters { get; private set; } /// <summary> /// Gets or sets the documentation for the request. /// </summary> public string RequestDocumentation { get; set; } /// <summary> /// Gets or sets the <see cref="ModelDescription"/> that describes the request body. /// </summary> public ModelDescription RequestModelDescription { get; set; } /// <summary> /// Gets the request body parameter descriptions. /// </summary> public IList<ParameterDescription> RequestBodyParameters { get { return GetParameterDescriptions(RequestModelDescription); } } /// <summary> /// Gets or sets the <see cref="ModelDescription"/> that describes the resource. /// </summary> public ModelDescription ResourceDescription { get; set; } /// <summary> /// Gets the resource property descriptions. /// </summary> public IList<ParameterDescription> ResourceProperties { get { return GetParameterDescriptions(ResourceDescription); } } /// <summary> /// Gets the sample requests associated with the API. /// </summary> public IDictionary<MediaTypeHeaderValue, object> SampleRequests { get; private set; } /// <summary> /// Gets the sample responses associated with the API. /// </summary> public IDictionary<MediaTypeHeaderValue, object> SampleResponses { get; private set; } /// <summary> /// Gets the error messages associated with this model. /// </summary> public Collection<string> ErrorMessages { get; private set; } private static IList<ParameterDescription> GetParameterDescriptions(ModelDescription modelDescription) { ComplexTypeModelDescription complexTypeModelDescription = modelDescription as ComplexTypeModelDescription; if (complexTypeModelDescription != null) { return complexTypeModelDescription.Properties; } CollectionModelDescription collectionModelDescription = modelDescription as CollectionModelDescription; if (collectionModelDescription != null) { complexTypeModelDescription = collectionModelDescription.ElementDescription as ComplexTypeModelDescription; if (complexTypeModelDescription != null) { return complexTypeModelDescription.Properties; } } return null; } } }
36.888889
123
0.616466
[ "CC0-1.0" ]
18F/dol-whd-14c
DOL.WHD.Section14c.EmailApi/Areas/HelpPage/Models/HelpPageApiModel.cs
3,984
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: IEntityCollectionRequestBuilder.cs.tt namespace Microsoft.Graph { using System; using System.Collections.Generic; /// <summary> /// The interface ICustodianUnifiedGroupSourcesCollectionRequestBuilder. /// </summary> public partial interface ICustodianUnifiedGroupSourcesCollectionRequestBuilder : IBaseRequestBuilder { /// <summary> /// Builds the request. /// </summary> /// <returns>The built request.</returns> ICustodianUnifiedGroupSourcesCollectionRequest Request(); /// <summary> /// Builds the request. /// </summary> /// <param name="options">The query and header options for the request.</param> /// <returns>The built request.</returns> ICustodianUnifiedGroupSourcesCollectionRequest Request(IEnumerable<Option> options); /// <summary> /// Gets an <see cref="IUnifiedGroupSourceRequestBuilder"/> for the specified UnifiedGroupSource. /// </summary> /// <param name="id">The ID for the UnifiedGroupSource.</param> /// <returns>The <see cref="IUnifiedGroupSourceRequestBuilder"/>.</returns> IUnifiedGroupSourceRequestBuilder this[string id] { get; } } }
40.166667
153
0.609366
[ "MIT" ]
GeertVL/msgraph-beta-sdk-dotnet
src/Microsoft.Graph/Generated/requests/ICustodianUnifiedGroupSourcesCollectionRequestBuilder.cs
1,687
C#
#region using System; using System.Collections.Generic; using Confuser.Core.Services; using Confuser.DynCipher.AST; #endregion namespace Confuser.DynCipher.Generation { internal class CipherGenContext { private readonly Variable[] dataVars; private readonly Variable keyVar = new Variable("{KEY}"); private readonly RandomGenerator random; private readonly List<Variable> tempVars = new List<Variable>(); private int tempVarCounter; public CipherGenContext(RandomGenerator random, int dataVarCount) { this.random = random; Block = new StatementBlock(); // new LoopStatement() { Begin = 0, Limit = 4 }; dataVars = new Variable[dataVarCount]; for(var i = 0; i < dataVarCount; i++) dataVars[i] = new Variable("v" + i) {Tag = i}; } public StatementBlock Block { get; } public Expression GetDataExpression(int index) { return new VariableExpression {Variable = dataVars[index]}; } public Expression GetKeyExpression(int index) { return new ArrayIndexExpression { Array = new VariableExpression {Variable = keyVar}, Index = index }; } public CipherGenContext Emit(Statement statement) { Block.Statements.Add(statement); return this; } public IDisposable AcquireTempVar(out VariableExpression exp) { Variable var; if(tempVars.Count == 0) { var = new Variable("t" + tempVarCounter++); } else { var = tempVars[random.NextInt32(tempVars.Count)]; tempVars.Remove(var); } exp = new VariableExpression {Variable = var}; return new TempVarHolder(this, var); } private struct TempVarHolder : IDisposable { private readonly CipherGenContext parent; private readonly Variable tempVar; public TempVarHolder(CipherGenContext p, Variable v) { parent = p; tempVar = v; } public void Dispose() { parent.tempVars.Add(tempVar); } } } }
27.862069
90
0.542079
[ "MIT" ]
Dekryptor/KoiVM-Virtualization
Confuser.DynCipher/Generation/CipherGenContext.cs
2,426
C#
using Xamarin.Forms; namespace PlaygroundLite.Pages { public partial class LinearPage : ContentPage { public LinearPage() { InitializeComponent(); } } }
16.833333
49
0.589109
[ "MIT" ]
filipoff2/MagicGradients
PlaygroundLite/PlaygroundLite/Pages/LinearPage.xaml.cs
204
C#
using System; using System.Collections.Generic; using System.Collections.Specialized; using System.Linq; using Elements.Geometry; using Newtonsoft.Json; namespace Elements.Spatial { /// <summary> /// Represents a "1-dimensional grid", akin to a number line that can be subdivided. /// </summary> /// <example> /// [!code-csharp[Main](../../Elements/test/Grid1dTests.cs?name=example)] /// </example> [JsonConverter(typeof(Elements.Serialization.JSON.JsonInheritanceConverter), "discriminator")] public class Grid1d { #region Properties /// <summary> /// An optional type designation for this cell. /// </summary> public string Type { get; set; } /// <summary> /// Child cells of this Grid. If null, this Grid is a complete cell with no subdivisions. /// </summary> [JsonProperty("Cells", NullValueHandling = NullValueHandling.Ignore)] public List<Grid1d> Cells { get => cells; private set { if (this.parent != null) { //invalidate previously generated 2d grid parent.TryInvalidateGrid(); } cells = value; } } /// <summary> /// Numerical domain of this Grid /// </summary> public Domain1d Domain { get; } /// <summary> /// The base curve at the top level of this grid. /// </summary> /// <value></value> [JsonIgnore] public Curve Curve { get { if (this.curve != null) { return this.curve; } else { if (this.topLevelParentGrid != null) { this.curve = this.topLevelParentGrid.curve; return this.curve; } return null; } } } /// <summary> /// Returns true if this 1D Grid has no subdivisions / sub-grids. /// </summary> public bool IsSingleCell => Cells == null || Cells.Count == 0; #endregion #region Private fields // The curve this was generated from, often a line. // subdivided cells maintain the complete original curve, // rather than a subcurve. internal Curve curve; // we have to maintain an internal curve domain because subsequent subdivisions of a grid // based on a curve retain the entire curve; this domain allows us to map from the subdivided // domain back to the original curve. [JsonProperty("CurveDomain")] internal readonly Domain1d curveDomain; // if this 1d grid is the axis of a 2d grid, this is where we store that reference. If not, it will be null private Grid2d parent; // if this is a cell belonging to a parent grid, this is where we store the very topmost grid. This // is useful in serialization so we only store the base curve once. private Grid1d topLevelParentGrid; [JsonProperty("TopLevelParentCurve", NullValueHandling = NullValueHandling.Ignore)] private Curve topLevelParentCurve { get { // if we ARE the top level grid, we have no top-level grid, so we return the curve if (this.topLevelParentGrid == null) { return this.curve; } else { return null; } } } private List<Grid1d> cells; #endregion #region Constructors /// <summary> /// Do not use this constructor — it is only for serialization purposes. /// </summary> /// <param name="cells"></param> /// <param name="type"></param> /// <param name="domain"></param> /// <param name="topLevelParentCurve"></param> /// <param name="curveDomain"></param> [JsonConstructor] [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public Grid1d(List<Grid1d> cells, string type, Domain1d domain, Curve topLevelParentCurve, Domain1d curveDomain) { if (topLevelParentCurve != null) { // we're deserializing the toplevel grid this.curve = topLevelParentCurve; } this.curveDomain = curveDomain; this.Type = type; this.Domain = domain; this.Cells = cells; } /// <summary> /// Default constructor with optional length parameter /// </summary> /// <param name="length">Length of the grid domain</param> public Grid1d(double length = 1.0) : this(new Domain1d(0, length)) { } /// <summary> /// Construct a 1D Grid from another 1D Grid /// </summary> /// <param name="other"></param> public Grid1d(Grid1d other) { this.curve = other.curve; this.curveDomain = other.curveDomain; this.Domain = other.Domain; if (other.Cells != null) { this.Cells = other.Cells.Select(c => new Grid1d(c)).ToList(); } this.Type = other.Type; } /// <summary> /// Construct a 1D grid from a numerical domain. The geometry will be assumed to lie along the X axis. /// </summary> /// <param name="domain">The 1-dimensional domain for the grid extents.</param> public Grid1d(Domain1d domain) { Domain = domain; curve = new Line(new Vector3(domain.Min, 0, 0), new Vector3(Domain.Max, 0, 0)); curveDomain = domain; } /// <summary> /// Construct a 1D grid from a curve. /// </summary> /// <param name="curve">The curve from which to generate the grid.</param> public Grid1d(Curve curve) { this.curve = curve; Domain = new Domain1d(0, curve.Length()); curveDomain = Domain; } /// <summary> /// This constructor is only for internal use by subdivision / split methods. /// </summary> /// <param name="topLevelParent">The top level grid1d, containing the base curve</param> /// <param name="domain">The domain of the new subdivided segment</param> /// <param name="curveDomain">The entire domain of the parent grid's curve</param> private Grid1d(Grid1d topLevelParent, Domain1d domain, Domain1d curveDomain) { this.topLevelParentGrid = topLevelParent; this.curve = topLevelParent.curve; this.curveDomain = curveDomain; Domain = domain; } #endregion #region Split Methods /// <summary> /// Split the grid at a normalized parameter from 0 to 1 along its domain. /// </summary> /// <param name="t">The parameter at which to split.</param> public void SplitAtParameter(double t) { var pos = t.MapToDomain(Domain); SplitAtPosition(pos); } /// <summary> /// Split the grid at a list of normalized parameters from 0 to 1 along its domain. /// </summary> /// <param name="parameters">A list of parameters at which to split the grid.</param> public void SplitAtParameters(IEnumerable<double> parameters) { foreach (var t in parameters) { SplitAtParameter(t); } } /// <summary> /// Split the grid at a fixed position from the start or end /// </summary> /// <param name="position">The length along the grid at which to split.</param> public void SplitAtPosition(double position) { if (PositionIsAtCellEdge(position)) // already split at this location { return; // swallow silently. } if (!Domain.Includes(position)) { throw new ArgumentException("Cannot split at position outside of cell domain."); } if (IsSingleCell) // simple single split { var newDomains = Domain.SplitAt(position); Cells = new List<Grid1d> { new Grid1d(this, newDomains[0], curveDomain), new Grid1d(this, newDomains[1], curveDomain) }; } else { // find this-level cell to split var index = FindCellIndexAtPosition(position); var cellToSplit = Cells[index]; var isSingleCell = cellToSplit.IsSingleCell; cellToSplit.SplitAtPosition(position); if (isSingleCell) // if we're splitting a cell with no children, we replace it directly with the split cells { var replacementCells = cellToSplit.Cells; if (replacementCells == null) return; // if we tried to split but hit an edge, for instance Cells.RemoveAt(index); Cells.InsertRange(index, replacementCells); } else // otherwise, we split it AND split its parent { if (cellToSplit.PositionIsAtCellEdge(position)) { return; //swallow silently } var newDomains = cellToSplit.Domain.SplitAt(position); var cellsToInsert = new List<Grid1d> { new Grid1d(this, newDomains[0], curveDomain), new Grid1d(this, newDomains[1], curveDomain) }; Cells.RemoveAt(index); cellsToInsert.ForEach(c => c.Cells = new List<Grid1d>()); Cells.InsertRange(index, cellsToInsert); // The split of "cellToSplit" could have resulted in any number of new cells; // these need to be reallocated to the correct parent. var childrenToReallocate = cellToSplit.Cells; foreach (var child in childrenToReallocate) { if (child.Domain.Max <= position) // left of position { cellsToInsert[0].Cells.Add(child); } else // right of position { cellsToInsert[1].Cells.Add(child); } } } } } /// <summary> /// Split a cell at a relative position measured from its domain start or end. /// </summary> /// <param name="position">The relative position at which to split.</param> /// <param name="fromEnd">If true, measure the position from the end rather than the start</param> /// <param name="ignoreOutsideDomain">If true, splits at offsets outside the domain will be silently ignored.</param> public void SplitAtOffset(double position, bool fromEnd = false, bool ignoreOutsideDomain = false) { InternalSplitAtOffset(position, fromEnd, ignoreOutsideDomain, false); } /// <summary> /// This private method is called by public SplitAtOffset, as well as by SplitAtPoint, which calculates its position relative to the /// overall curve domain, rather than relative to the grid's own (possibly different) subdomain. /// </summary> /// <param name="position">The relative position at which to split.</param> /// <param name="fromEnd">If true, measure the position from the end rather than the start</param> /// <param name="ignoreOutsideDomain">If true, splits at offsets outside the domain will be silently ignored.</param> /// <param name="useCurveDomain">If true, the position is measured relative to the top-level curve domain, not the subdomain. </param> private void InternalSplitAtOffset(double position, bool fromEnd = false, bool ignoreOutsideDomain = false, bool useCurveDomain = false) { var domain = useCurveDomain ? curveDomain : Domain; position = fromEnd ? domain.Max - position : domain.Min + position; if (PositionIsAtCellEdge(position)) { return; // this should be swallowed silently rather than left for Domain.Includes to handle. } if (!domain.Includes(position)) { if (ignoreOutsideDomain) { return; } else { throw new Exception("Offset position was beyond the grid's domain."); } } SplitAtPosition(position); } /// <summary> /// Split a cell at a list of relative positions measured from its domain start or end. /// </summary> /// <param name="positions">The relative positions at which to split.</param> /// <param name="fromEnd">If true, measure the position from the end rather than the start</param> public void SplitAtOffsets(IEnumerable<double> positions, bool fromEnd = false) { foreach (var position in positions) { SplitAtOffset(position, fromEnd); } } /// <summary> /// Split the grid at a list of fixed positions from the start or end /// </summary> /// <param name="positions">The lengths along the grid at which to split.</param> public void SplitAtPositions(IEnumerable<double> positions) { foreach (var pos in positions) { SplitAtPosition(pos); } } /// <summary> /// Split the grid at a point in world space. Note that for curved grids an approximate /// point will be used. /// </summary> /// <param name="point"></param> public void SplitAtPoint(Vector3 point) { double posAlongCurve = ClosestPosition(point); InternalSplitAtOffset(posAlongCurve, false, true, true); } /// <summary> /// Get the position along the grid's domain closest to a supplied point. /// </summary> /// <param name="point"></param> public double ClosestPosition(Vector3 point) { // If we have a 2d parent, it's most intuitive to transform the point into grid space before doing this calculation. if (parent != null) { point = parent.toGrid.OfPoint(point); } if (Curve is Polyline pl && pl.Segments().Count() > 1) { var minDist = Double.MaxValue; Vector3 closestPoint = Vector3.Origin; Line[] segments = pl.Segments(); int closestSegment = -1; for (int i = 0; i < segments.Length; i++) { Line seg = segments[i]; var cp = point.ClosestPointOn(seg); var dist = cp.DistanceTo(point); if (dist < minDist) { closestPoint = cp; minDist = dist; closestSegment = i; } } double curvePosition = 0.0; for (int i = 0; i < closestSegment; i++) { curvePosition += segments[i].Length(); } curvePosition += segments[closestSegment].Start.DistanceTo(point); return curvePosition; } var A = Curve.PointAt(0); var B = Curve.PointAt(1); var C = point; var AB = B - A; AB = AB.Unitized(); var AC = C - A; var posAlongCurve = AC.Dot(AB); return posAlongCurve; } /// <summary> /// Split the grid at points in world space. Note that for curved grids an approximate /// point will be used. /// </summary> /// <param name="points">The points at which to split.</param> public void SplitAtPoints(IEnumerable<Vector3> points) { foreach (var pos in points) { SplitAtPoint(pos); } } #endregion #region Divide Methods /// <summary> /// Divide the grid into N even subdivisions. Grids that are already subdivided will fail. /// </summary> /// <param name="n">Number of subdivisions</param> public void DivideByCount(int n) { if (n <= 0) { throw new ArgumentException($"Unable to divide by {n}."); } if (!IsSingleCell) { throw new Exception("This grid already has subdivisions. Maybe you meant to select a subgrid to divide?"); } var newDomains = Domain.DivideByCount(n); Cells = new List<Grid1d>(newDomains.Select(d => new Grid1d(this, d, curveDomain))); } /// <summary> /// Divide a grid by an approximate length. The length will be adjusted to generate whole-number /// subdivisions, governed by an optional DivisionMode. /// </summary> /// <param name="targetLength">The approximate length by which to divide the grid.</param> /// <param name="divisionMode">Whether to permit any size cell, or only larger or smaller cells by rounding up or down.</param> public void DivideByApproximateLength(double targetLength, EvenDivisionMode divisionMode = EvenDivisionMode.Nearest) { if (targetLength <= Vector3.EPSILON) { throw new ArgumentException($"Unable to divide. Target Length {targetLength} is too small."); } var numDivisions = Math.Max(1, Domain.Length / targetLength); int roundedDivisions; switch (divisionMode) { case EvenDivisionMode.RoundUp: roundedDivisions = (int)Math.Ceiling(numDivisions); break; case EvenDivisionMode.RoundDown: roundedDivisions = (int)Math.Floor(numDivisions); break; case EvenDivisionMode.Nearest: default: roundedDivisions = (int)Math.Round(numDivisions); break; } DivideByCount(roundedDivisions); } /// <summary> /// Divide a grid by constant length subdivisions, starting from a point location. /// </summary> /// <param name="length">The length of subdivisions</param> /// <param name="point">The point at which to begin subdividing.</param> public void DivideByFixedLengthFromPoint(double length, Vector3 point) { var position = ClosestPosition(point); DivideByFixedLengthFromPosition(length, position); } /// <summary> /// Divide a grid by constant length subdivisions, starting from a position. /// </summary> /// <param name="length">The length of subdivisions</param> /// <param name="position">The position along the domain at which to begin subdividing.</param> public void DivideByFixedLengthFromPosition(double length, double position) { if (length < Vector3.EPSILON) { throw new ArgumentException($"Length {length} is smaller than tolerance."); } if (!Domain.Includes(position)) { // attempt to pick a position that is within the domain if (position <= Domain.Min) { var diffFromMin = Domain.Min - position; var lengthsAway = Math.Ceiling(diffFromMin / length); position = position + lengthsAway * length; if (position >= Domain.Max) { // no multiple of the length measured from the position intersects the domain. Leave undivided. return; } } else if (position >= Domain.Max) { var diffFromMax = position - Domain.Max; var lengthsAway = Math.Ceiling(diffFromMax / length); position = position - lengthsAway * length; if (position <= Domain.Min) { // no multiple of the length measured from the position intersects the domain. Leave undivided. return; } } } for (double p = position; Domain.Includes(p); p += length) { SplitAtPosition(p); } if (!Domain.Includes(position - length)) return; for (double p = position - length; Domain.Includes(p); p -= length) { SplitAtPosition(p); } } /// <summary> /// Divide a grid by constant length subdivisions, with a variable division mode to control how leftover /// space is handled. /// </summary> /// <param name="length">The division length</param> /// <param name="divisionMode">How to handle leftover / partial remainder panels </param> /// <param name="sacrificialPanels">How many full length panels to sacrifice to make remainder panels longer.</param> public void DivideByFixedLength(double length, FixedDivisionMode divisionMode = FixedDivisionMode.RemainderAtEnd, int sacrificialPanels = 0) { if (length <= Vector3.EPSILON) { throw new ArgumentException($"Unable to divide by length {length}: smaller than tolerance."); } var lengthToFill = Domain.Length; var maxPanelCount = (int)Math.Floor(lengthToFill / length) - sacrificialPanels; if (maxPanelCount < 1) return; var remainderSize = lengthToFill - maxPanelCount * length; if (remainderSize < 0.01) { DivideByCount(maxPanelCount); return; } switch (divisionMode) { case FixedDivisionMode.RemainderAtBothEnds: for (double i = remainderSize / 2.0; i < lengthToFill; i += length) { SplitAtOffset(i); } break; case FixedDivisionMode.RemainderAtStart: for (double i = remainderSize; i < lengthToFill; i += length) { SplitAtOffset(i); } break; case FixedDivisionMode.RemainderAtEnd: for (int i = 1; i < maxPanelCount + 1; i++) { SplitAtOffset(i * length); } break; case FixedDivisionMode.RemainderNearMiddle: // assumes we must have at least 2 full-size panels int panelsOnLeft = maxPanelCount / 2; //integer division, on purpose //make left panels for (int i = 1; i <= panelsOnLeft; i++) { SplitAtOffset(i * length); } //make middle + right panels for (double i = panelsOnLeft * length + remainderSize; i < lengthToFill; i += length) { SplitAtOffset(i); } break; } } /// <summary> /// Divide a grid by a pattern of lengths. Type names will be automatically generated, repetition will be governed by PatternMode, /// and remainder handling will be governed by DivisionMode. /// </summary> /// <param name="lengthPattern">A pattern of lengths to apply to the grid</param> /// <param name="patternMode">How to apply/repeat the pattern</param> /// <param name="divisionMode">How to handle leftover/remainder length</param> public void DivideByPattern(IList<double> lengthPattern, PatternMode patternMode = PatternMode.Cycle, FixedDivisionMode divisionMode = FixedDivisionMode.RemainderAtEnd) { var patternwithNames = new List<(string typeName, double length)>(); for (int i = 0; i < lengthPattern.Count; i++) { patternwithNames.Add((StringExtensions.NumberToString(i), lengthPattern[i])); } DivideByPattern(patternwithNames, patternMode, divisionMode); } /// <summary> /// Divide a grid by a pattern of named lengths. Repetition will be governed by PatternMode, /// and remainder handling will be governed by DivisionMode. /// </summary> /// <param name="lengthPattern">A pattern of lengths to apply to the grid</param> /// <param name="patternMode">How to apply/repeat the pattern</param> /// <param name="divisionMode">How to handle leftover/remainder length</param> public void DivideByPattern(IList<(string typeName, double length)> lengthPattern, PatternMode patternMode = PatternMode.Cycle, FixedDivisionMode divisionMode = FixedDivisionMode.RemainderAtEnd) { if (lengthPattern.Any(p => p.length <= Vector3.EPSILON)) { throw new ArgumentException("One or more of the pattern segments is too small."); } //a list of all the segments that fit in the grid IList<(string typeName, double length)> patternSegments = new List<(string, double)>(); switch (patternMode) { case PatternMode.None: patternSegments = lengthPattern; break; case PatternMode.Cycle: Cycle(lengthPattern, patternSegments); break; case PatternMode.Flip: if (lengthPattern.Count < 3) { Cycle(lengthPattern, patternSegments); break; } var flippedLengthPattern = new List<(string, double)>(lengthPattern); for (int i = lengthPattern.Count - 2; i > 0; i--) { flippedLengthPattern.Add(lengthPattern[i]); } Cycle(flippedLengthPattern, patternSegments); break; } var totalPatternLength = patternSegments.Select(s => s.length).Sum(); if (totalPatternLength > Domain.Length) { throw new ArgumentException("The grid could not be constructed. Pattern length exceeds grid length."); } var remainderSize = Domain.Length - totalPatternLength; switch (divisionMode) { case FixedDivisionMode.RemainderAtBothEnds: DivideWithPatternAndOffset(patternSegments, remainderSize / 2.0); break; case FixedDivisionMode.RemainderAtStart: DivideWithPatternAndOffset(patternSegments, remainderSize); break; case FixedDivisionMode.RemainderAtEnd: DivideWithPatternAndOffset(patternSegments, 0); break; case FixedDivisionMode.RemainderNearMiddle: throw new Exception("Remainder Near Middle is not supported for Pattern-based subdivision."); } } internal Vector3 Evaluate(double t) { if (Curve != null) { var tNormalized = t.MapFromDomain(curveDomain); if (tNormalized > 1 || tNormalized < 0) { throw new Exception("t must be in the curve domain."); } return Curve.PointAt(tNormalized); } else { return new Vector3(t, 0, 0); } } internal void SetParent(Grid2d grid2d) { this.parent = grid2d; } /// <summary> /// Divide by a list of named lengths and an offset from start, used by the DivideByPattern function. /// </summary> /// <param name="patternSegments"></param> /// <param name="offset"></param> private void DivideWithPatternAndOffset(IList<(string typeName, double length)> patternSegments, double offset) { double runningPosition = offset; if (offset > 0) { SplitAtOffset(runningPosition); } for (int i = 0; i < patternSegments.Count; i++) { runningPosition += patternSegments[i].length; SplitAtOffset(runningPosition); } if (Cells == null && patternSegments.Count == 1) { Type = patternSegments[0].typeName; return; } for (int i = 0; i < patternSegments.Count; i++) { var cellOffset = offset > 0 ? 1 : 0; Cells[i + cellOffset].Type = patternSegments[i].typeName; } } /// <summary> /// Populate a list of pattern segments by repeating a pattern up to the length of the grid domain. /// </summary> /// <param name="lengthPattern"></param> /// <param name="patternSegments"></param> private void Cycle(IList<(string typeName, double length)> lengthPattern, IList<(string, double)> patternSegments) { var runningLength = 0.0; int i = 0; while (true) { var segmentToAdd = lengthPattern[i % lengthPattern.Count]; runningLength += segmentToAdd.length; if (runningLength <= Domain.Length) { patternSegments.Add(segmentToAdd); } else { break; } i++; } } internal Vector3 Direction() { if (Curve != null) { return (Curve.PointAt(1) - Curve.PointAt(0)).Unitized(); } else { return Vector3.XAxis; } } internal Vector3 StartPoint() { return Curve.PointAt(curveDomain.Min); } #endregion #region Cell Retrieval /// <summary> /// Retrieve a cell by index /// </summary> /// <param name="i">The index</param> /// <returns>A Grid1d representing the selected cell/segment.</returns> [JsonIgnore] public Grid1d this[int i] { get { if (Cells.Count <= i) { return null; } else { return Cells[i]; } } } /// <summary> /// Retrieve the grid cell (as a Grid1d) at a length along the domain. /// </summary> /// <param name="pos">The position in the grid's domain to find</param> /// <returns>The cell at this position, if found, or this grid if it is a single cell.</returns> public Grid1d FindCellAtPosition(double pos) { var index = FindCellIndexAtPosition(pos); if (index < 0) return this; return Cells[index]; } /// <summary> /// Retrieve the index of the grid cell at a length along the domain. If /// position is exactly on the edge, it returns the righthand cell index. /// </summary> /// <param name="position"></param> /// <returns>Returns the index of the first cell. </returns> private int FindCellIndexAtPosition(double position) { if (!Domain.Includes(position)) { throw new Exception("Position was outside the domain of the grid"); } if (IsSingleCell) { return -1; } else { var domainsSequence = DomainsToSequence(); for (int i = 0; i < domainsSequence.Count - 1; i++) { if (position <= domainsSequence[i + 1]) { return i; } } return Cells.Count - 1; // default to last cell } } private List<double> DomainsToSequence(bool recursive = false) { if (IsSingleCell) { return new List<double> { Domain.Min, Domain.Max }; } var cells = recursive ? GetCells() : Cells; return cells.Select(c => c.Domain.Min).Union(new[] { Cells.Last().Domain.Max }).ToList(); } /// <summary> /// Get the points at the ends and in-between all cells. /// </summary> /// <param name="recursive">If true, separators will be retrieved from child cells as well.</param> /// <returns>A list of Vector3d points representing the boundaries between cells.</returns> public List<Vector3> GetCellSeparators(bool recursive = false) { var values = DomainsToSequence(recursive); var t = values.Select(v => v.MapFromDomain(curveDomain)); var pts = t.Select(t0 => Curve.TransformAt(t0).Origin).ToList(); return pts; } /// <summary> /// Retrieve all grid segment cells recursively. /// For just top-level cells, get the Cells property. /// </summary> /// <returns>A list of all the bottom-level cells / child cells of this grid.</returns> public List<Grid1d> GetCells() { if (IsSingleCell) { return new List<Grid1d> { this }; } List<Grid1d> resultCells = new List<Grid1d>(); foreach (var cell in Cells) { if (cell.IsSingleCell) { resultCells.Add(cell); } else { resultCells.AddRange(cell.GetCells()); } } return resultCells; } /// <summary> /// Retrieve geometric representation of a cell (currently just a line) /// </summary> /// <returns>A curve representing the extents of this grid / cell.</returns> public Curve GetCellGeometry() { if (Curve == null) { //I don't think this should ever happen return new Line(new Vector3(Domain.Min, 0, 0), new Vector3(Domain.Max, 0, 0)); } //TODO: support subcurve output / distance-based rather than parameter-based sampling. var t1 = Domain.Min.MapFromDomain(curveDomain); var t2 = Domain.Max.MapFromDomain(curveDomain); var x1 = Curve.TransformAt(t1); var x2 = Curve.TransformAt(t2); return new Line(x1.Origin, x2.Origin); } #endregion #region Private Methods /// <summary> /// Test if a given position lies nearly on the edge of a cell /// </summary> /// <param name="pos"></param> /// <returns></returns> private bool PositionIsAtCellEdge(double pos) { return Domain.IsCloseToBoundary(pos); } internal Grid1d SpawnSubGrid(Domain1d domain) { return new Grid1d(this, domain, curveDomain); } #endregion } #region Enums /// <summary> /// Methods for repeating a pattern of lengths or types /// </summary> public enum PatternMode { /// <summary> /// No Repeat. For a pattern [A, B, C], split A, B, C panels, and treat the remaining length according to FixedDivisionMode settings. /// </summary> None, /// <summary> /// For a pattern [A, B, C], split at A, B, C, A, B, C, A... /// </summary> Cycle, /// <summary> /// For a pattern [A, B, C], split at A, B, C, B, A, B, C, B, A /// </summary> Flip, } /// <summary> /// Describe how a target length should be treated /// </summary> public enum EvenDivisionMode { /// <summary> /// Closest match for a target length, can be greater or smaller in practice. /// </summary> Nearest, /// <summary> /// Round up the count — Only divide into segments shorter than the target length /// </summary> RoundUp, /// <summary> /// Round down the count — Only divide into segments longer than the target length /// </summary> RoundDown } /// <summary> /// Different ways to handle the "remainder" when dividing an arbitrary length by a fixed size /// </summary> public enum FixedDivisionMode { /// <summary> /// Take the remainder and split it across both ends of the grid /// </summary> RemainderAtBothEnds, /// <summary> /// Locate the remainder at the start of the grid /// </summary> RemainderAtStart, /// <summary> /// Locate the remainder at the end of the grid /// </summary> RemainderAtEnd, /// <summary> /// Locate the remainder at or near the middle of the grid. /// </summary> RemainderNearMiddle } #endregion }
37.399038
202
0.521301
[ "MIT" ]
hypar-io/elements
Elements/src/Spatial/Grid1d.cs
38,903
C#
// ******************************************************************************************************** // Product Name: DotSpatial.Positioning.dll // Description: A library for managing GPS connections. // ******************************************************************************************************** // // The Original Code is from http://gps3.codeplex.com/ version 3.0 // // The Initial Developer of this original code is Jon Pearson. Submitted Oct. 21, 2010 by Ben Tombs (tidyup) // // Contributor(s): (Open source contributors should list themselves and their modifications here). // ------------------------------------------------------------------------------------------------------- // | Developer | Date | Comments // |--------------------------|------------|-------------------------------------------------------------- // | Tidyup (Ben Tombs) | 10/21/2010 | Original copy submitted from modified GPS.Net 3.0 // | Shade1974 (Ted Dunsford) | 10/22/2010 | Added file headers reviewed formatting with resharper. // | VladimirArias (Colombia) | 02/03/2014 | Added hdt nmea sentence for heading orientation // ******************************************************************************************************** using System; using System.Collections.Generic; namespace DotSpatial.Positioning { /// <summary> /// Represents an NMEA sentence which contains latitude and longitude values. /// </summary> public interface IPositionSentence { /// <summary> /// Represents an NMEA sentence which contains a position. /// </summary> Position Position { get; } } /// <summary> /// Represents an NMEA sentence which contains date and time in UTC. /// </summary> public interface IUtcDateTimeSentence { /// <summary> /// Represents an NMEA sentence which contains date and time in UTC. /// </summary> DateTime UtcDateTime { get; } } /// <summary> /// Represents an NMEA sentence which contains time in UTC. /// </summary> public interface IUtcTimeSentence { /// <summary> /// Gets the time in UTC from the IUtcTimeSentence /// </summary> TimeSpan UtcTime { get; } } /// <summary> /// Represents an NMEA sentence which contains differential GPS information. /// </summary> public interface IDifferentialGpsSentence { /// <summary> /// Gets the Differential Gps Station ID /// </summary> int DifferentialGpsStationID { get; } /// <summary> /// Gets the age of the Differential Gps /// </summary> TimeSpan DifferentialGpsAge { get; } } /// <summary> /// Represents an NMEA sentence which describes the current fix. /// </summary> public interface IFixModeSentence { /// <summary> /// Gets the fix mode /// </summary> FixMode FixMode { get; } } /// <summary> /// Represents an NMEA sentence which contains the method used to acquire a fix. /// </summary> public interface IFixMethodSentence { /// <summary> /// The Fix Method /// </summary> FixMethod FixMethod { get; } } /// <summary> /// Represents an NMEA sentence which contains GPS satellite information. /// </summary> public interface ISatelliteCollectionSentence { /// <summary> /// The Satellites /// </summary> IList<Satellite> Satellites { get; } } /// <summary> /// Represents an NMEA sentence which describes how the fix is being obtained. /// </summary> public interface IFixQualitySentence { /// <summary> /// The Fix Quality /// </summary> FixQuality FixQuality { get; } } /// <summary> /// Represents an NMEA sentence which returns the number of GPS satellites involved in the current fix. /// </summary> public interface IFixedSatelliteCountSentence { /// <summary> /// The Fixed Satellite Count /// </summary> int FixedSatelliteCount { get; } } /// <summary> /// Represents an NMEA sentence which contains a list of fixed GPS satellites. /// </summary> public interface IFixedSatellitesSentence { /// <summary> /// the list of FixedSatellites /// </summary> IList<Satellite> FixedSatellites { get; } } /// <summary> /// Represents an NMEA sentence which contains the direction of travel. /// </summary> public interface IBearingSentence { /// <summary> /// the Bearing /// </summary> Azimuth Bearing { get; } } /// <summary> /// Represents an NMEA sentence which contains the direction of heading. /// </summary> public interface IHeadingSentence { /// <summary> /// the Heading /// </summary> Azimuth Heading { get; } } /// <summary> /// Represents an NMEA sentence which contains whether a fix is currently acquired. /// </summary> public interface IFixStatusSentence { /// <summary> /// The Fix Status /// </summary> FixStatus FixStatus { get; } } /// <summary> /// Represents an NMEA sentence which contains /// </summary> public interface ISpeedSentence { /// <summary> /// The Speed /// </summary> Speed Speed { get; } } /// <summary> /// Represents an NMEA sentence which contains /// </summary> public interface IMagneticVariationSentence { /// <summary> /// The Magnetic Variation /// </summary> Longitude MagneticVariation { get; } } /// <summary> /// Represents an NMEA sentence which contains /// </summary> public interface IAltitudeSentence { /// <summary> /// The Altitude /// </summary> Distance Altitude { get; } } /// <summary> /// Represents an NMEA sentence which contains /// </summary> public interface IAltitudeAboveEllipsoidSentence { /// <summary> /// The Altitude Above Ellipsoid /// </summary> Distance AltitudeAboveEllipsoid { get; } } /// <summary> /// Represents an NMEA sentence which contains /// </summary> public interface IGeoidalSeparationSentence { /// <summary> /// The Geoidal Separation /// </summary> Distance GeoidalSeparation { get; } } /// <summary> /// Represents an NMEA sentence which contains /// </summary> public interface IHorizontalDilutionOfPrecisionSentence { /// <summary> /// The Horizontal Dilution of Precision /// </summary> DilutionOfPrecision HorizontalDilutionOfPrecision { get; } } /// <summary> /// Represents an NMEA sentence which contains /// </summary> public interface IVerticalDilutionOfPrecisionSentence { /// <summary> /// The Vertical Dilution of Precision /// </summary> DilutionOfPrecision VerticalDilutionOfPrecision { get; } } /// <summary> /// Represents an NMEA sentence which contains /// </summary> public interface IPositionDilutionOfPrecisionSentence { /// <summary> /// The Position Dilution of Precision (PDOP) /// </summary> DilutionOfPrecision PositionDilutionOfPrecision { get; } } }
30.509653
109
0.527968
[ "MIT" ]
AlexanderSemenyak/DotSpatial
Source/DotSpatial.Positioning/Interfaces.cs
7,904
C#
#region Copyright notice and license // Protocol Buffers - Google's data interchange format // Copyright 2015 Google Inc. All rights reserved. // https://developers.google.com/protocol-buffers/ // // 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 Google 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; using System.Globalization; using System.Text; using Google.Protobuf.Reflection; using Google.Protobuf.WellKnownTypes; using System.IO; using System.Collections.Generic; using System.Linq; using System.Reflection; namespace Google.Protobuf { /// <summary> /// Reflection-based converter from messages to JSON. /// </summary> /// <remarks> /// <para> /// Instances of this class are thread-safe, with no mutable state. /// </para> /// <para> /// This is a simple start to get JSON formatting working. As it's reflection-based, /// it's not as quick as baking calls into generated messages - but is a simpler implementation. /// (This code is generally not heavily optimized.) /// </para> /// </remarks> public sealed class JsonFormatter { internal const string AnyTypeUrlField = "@type"; internal const string AnyDiagnosticValueField = "@value"; internal const string AnyWellKnownTypeValueField = "value"; private const string TypeUrlPrefix = "type.googleapis.com"; private const string NameValueSeparator = ": "; private const string PropertySeparator = ", "; /// <summary> /// Returns a formatter using the default settings. /// </summary> public static JsonFormatter Default { get; } = new JsonFormatter(Settings.Default); // A JSON formatter which *only* exists private static readonly JsonFormatter diagnosticFormatter = new JsonFormatter(Settings.Default); /// <summary> /// The JSON representation of the first 160 characters of Unicode. /// Empty strings are replaced by the static constructor. /// </summary> private static readonly string[] CommonRepresentations = { // C0 (ASCII and derivatives) control characters "\\u0000", "\\u0001", "\\u0002", "\\u0003", // 0x00 "\\u0004", "\\u0005", "\\u0006", "\\u0007", "\\b", "\\t", "\\n", "\\u000b", "\\f", "\\r", "\\u000e", "\\u000f", "\\u0010", "\\u0011", "\\u0012", "\\u0013", // 0x10 "\\u0014", "\\u0015", "\\u0016", "\\u0017", "\\u0018", "\\u0019", "\\u001a", "\\u001b", "\\u001c", "\\u001d", "\\u001e", "\\u001f", // Escaping of " and \ are required by www.json.org string definition. // Escaping of < and > are required for HTML security. "", "", "\\\"", "", "", "", "", "", // 0x20 "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", // 0x30 "", "", "", "", "\\u003c", "", "\\u003e", "", "", "", "", "", "", "", "", "", // 0x40 "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", // 0x50 "", "", "", "", "\\\\", "", "", "", "", "", "", "", "", "", "", "", // 0x60 "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", // 0x70 "", "", "", "", "", "", "", "\\u007f", // C1 (ISO 8859 and Unicode) extended control characters "\\u0080", "\\u0081", "\\u0082", "\\u0083", // 0x80 "\\u0084", "\\u0085", "\\u0086", "\\u0087", "\\u0088", "\\u0089", "\\u008a", "\\u008b", "\\u008c", "\\u008d", "\\u008e", "\\u008f", "\\u0090", "\\u0091", "\\u0092", "\\u0093", // 0x90 "\\u0094", "\\u0095", "\\u0096", "\\u0097", "\\u0098", "\\u0099", "\\u009a", "\\u009b", "\\u009c", "\\u009d", "\\u009e", "\\u009f" }; static JsonFormatter() { for (int i = 0; i < CommonRepresentations.Length; i++) { if (CommonRepresentations[i] == "") { CommonRepresentations[i] = ((char) i).ToString(); } } } private readonly Settings settings; private bool DiagnosticOnly => ReferenceEquals(this, diagnosticFormatter); /// <summary> /// Creates a new formatted with the given settings. /// </summary> /// <param name="settings">The settings.</param> public JsonFormatter(Settings settings) { this.settings = ProtoPreconditions.CheckNotNull(settings, nameof(settings)); } /// <summary> /// Formats the specified message as JSON. /// </summary> /// <param name="message">The message to format.</param> /// <returns>The formatted message.</returns> public string Format(IMessage message) { var writer = new StringWriter(); Format(message, writer); return writer.ToString(); } /// <summary> /// Formats the specified message as JSON. /// </summary> /// <param name="message">The message to format.</param> /// <param name="writer">The TextWriter to write the formatted message to.</param> /// <returns>The formatted message.</returns> public void Format(IMessage message, TextWriter writer) { ProtoPreconditions.CheckNotNull(message, nameof(message)); ProtoPreconditions.CheckNotNull(writer, nameof(writer)); if (message.Descriptor.IsWellKnownType) { WriteWellKnownTypeValue(writer, message.Descriptor, message); } else { WriteMessage(writer, message); } } /// <summary> /// Converts a message to JSON for diagnostic purposes with no extra context. /// </summary> /// <remarks> /// <para> /// This differs from calling <see cref="Format(IMessage)"/> on the default JSON /// formatter in its handling of <see cref="Any"/>. As no type registry is available /// in <see cref="object.ToString"/> calls, the normal way of resolving the type of /// an <c>Any</c> message cannot be applied. Instead, a JSON property named <c>@value</c> /// is included with the base64 data from the <see cref="Any.Value"/> property of the message. /// </para> /// <para>The value returned by this method is only designed to be used for diagnostic /// purposes. It may not be parsable by <see cref="JsonParser"/>, and may not be parsable /// by other Protocol Buffer implementations.</para> /// </remarks> /// <param name="message">The message to format for diagnostic purposes.</param> /// <returns>The diagnostic-only JSON representation of the message</returns> public static string ToDiagnosticString(IMessage message) { ProtoPreconditions.CheckNotNull(message, nameof(message)); return diagnosticFormatter.Format(message); } private void WriteMessage(TextWriter writer, IMessage message) { if (message == null) { WriteNull(writer); return; } if (DiagnosticOnly) { ICustomDiagnosticMessage customDiagnosticMessage = message as ICustomDiagnosticMessage; if (customDiagnosticMessage != null) { writer.Write(customDiagnosticMessage.ToDiagnosticString()); return; } } writer.Write("{ "); bool writtenFields = WriteMessageFields(writer, message, false); writer.Write(writtenFields ? " }" : "}"); } private bool WriteMessageFields(TextWriter writer, IMessage message, bool assumeFirstFieldWritten) { var fields = message.Descriptor.Fields; bool first = !assumeFirstFieldWritten; // First non-oneof fields foreach (var field in fields.InFieldNumberOrder()) { var accessor = field.Accessor; if (field.ContainingOneof != null && field.ContainingOneof.Accessor.GetCaseFieldDescriptor(message) != field) { continue; } // Omit default values unless we're asked to format them, or they're oneofs (where the default // value is still formatted regardless, because that's how we preserve the oneof case). object value = accessor.GetValue(message); if (field.ContainingOneof == null && !settings.FormatDefaultValues && IsDefaultValue(accessor, value)) { continue; } // Okay, all tests complete: let's write the field value... if (!first) { writer.Write(PropertySeparator); } WriteString(writer, accessor.Descriptor.JsonName); writer.Write(NameValueSeparator); WriteValue(writer, value); first = false; } return !first; } // Converted from java/core/src/main/java/com/google/protobuf/Descriptors.java internal static string ToJsonName(string name) { StringBuilder result = new StringBuilder(name.Length); bool isNextUpperCase = false; foreach (char ch in name) { if (ch == '_') { isNextUpperCase = true; } else if (isNextUpperCase) { result.Append(char.ToUpperInvariant(ch)); isNextUpperCase = false; } else { result.Append(ch); } } return result.ToString(); } internal static string FromJsonName(string name) { StringBuilder result = new StringBuilder(name.Length); foreach (char ch in name) { if (char.IsUpper(ch)) { result.Append('_'); result.Append(char.ToLowerInvariant(ch)); } else { result.Append(ch); } } return result.ToString(); } private static void WriteNull(TextWriter writer) { writer.Write("null"); } private static bool IsDefaultValue(IFieldAccessor accessor, object value) { if (accessor.Descriptor.IsMap) { IDictionary dictionary = (IDictionary) value; return dictionary.Count == 0; } if (accessor.Descriptor.IsRepeated) { IList list = (IList) value; return list.Count == 0; } switch (accessor.Descriptor.FieldType) { case FieldType.Bool: return (bool) value == false; case FieldType.Bytes: return (ByteString) value == ByteString.Empty; case FieldType.String: return (string) value == ""; case FieldType.Double: return (double) value == 0.0; case FieldType.SInt32: case FieldType.Int32: case FieldType.SFixed32: case FieldType.Enum: return (int) value == 0; case FieldType.Fixed32: case FieldType.UInt32: return (uint) value == 0; case FieldType.Fixed64: case FieldType.UInt64: return (ulong) value == 0; case FieldType.SFixed64: case FieldType.Int64: case FieldType.SInt64: return (long) value == 0; case FieldType.Float: return (float) value == 0f; case FieldType.Message: case FieldType.Group: // Never expect to get this, but... return value == null; default: throw new ArgumentException("Invalid field type"); } } /// <summary> /// Writes a single value to the given writer as JSON. Only types understood by /// Protocol Buffers can be written in this way. This method is only exposed for /// advanced use cases; most users should be using <see cref="Format(IMessage)"/> /// or <see cref="Format(IMessage, TextWriter)"/>. /// </summary> /// <param name="writer">The writer to write the value to. Must not be null.</param> /// <param name="value">The value to write. May be null.</param> public void WriteValue(TextWriter writer, object value) { if (value == null) { WriteNull(writer); } else if (value is bool) { writer.Write((bool)value ? "true" : "false"); } else if (value is ByteString) { // Nothing in Base64 needs escaping writer.Write('"'); writer.Write(((ByteString)value).ToBase64()); writer.Write('"'); } else if (value is string) { WriteString(writer, (string)value); } else if (value is IDictionary) { WriteDictionary(writer, (IDictionary)value); } else if (value is IList) { WriteList(writer, (IList)value); } else if (value is int || value is uint) { IFormattable formattable = (IFormattable) value; writer.Write(formattable.ToString("d", CultureInfo.InvariantCulture)); } else if (value is long || value is ulong) { writer.Write('"'); IFormattable formattable = (IFormattable) value; writer.Write(formattable.ToString("d", CultureInfo.InvariantCulture)); writer.Write('"'); } else if (value is System.Enum) { if (settings.FormatEnumsAsIntegers) { WriteValue(writer, (int)value); } else { string name = OriginalEnumValueHelper.GetOriginalName(value); if (name != null) { WriteString(writer, name); } else { WriteValue(writer, (int)value); } } } else if (value is float || value is double) { string text = ((IFormattable) value).ToString("r", CultureInfo.InvariantCulture); if (text == "NaN" || text == "Infinity" || text == "-Infinity") { writer.Write('"'); writer.Write(text); writer.Write('"'); } else { writer.Write(text); } } else if (value is IMessage) { Format((IMessage)value, writer); } else { throw new ArgumentException("Unable to format value of type " + value.GetType()); } } /// <summary> /// Central interception point for well-known type formatting. Any well-known types which /// don't need special handling can fall back to WriteMessage. We avoid assuming that the /// values are using the embedded well-known types, in order to allow for dynamic messages /// in the future. /// </summary> private void WriteWellKnownTypeValue(TextWriter writer, MessageDescriptor descriptor, object value) { // Currently, we can never actually get here, because null values are always handled by the caller. But if we *could*, // this would do the right thing. if (value == null) { WriteNull(writer); return; } // For wrapper types, the value will either be the (possibly boxed) "native" value, // or the message itself if we're formatting it at the top level (e.g. just calling ToString on the object itself). // If it's the message form, we can extract the value first, which *will* be the (possibly boxed) native value, // and then proceed, writing it as if we were definitely in a field. (We never need to wrap it in an extra string... // WriteValue will do the right thing.) if (descriptor.IsWrapperType) { if (value is IMessage) { var message = (IMessage) value; value = message.Descriptor.Fields[WrappersReflection.WrapperValueFieldNumber].Accessor.GetValue(message); } WriteValue(writer, value); return; } if (descriptor.FullName == Timestamp.Descriptor.FullName) { WriteTimestamp(writer, (IMessage)value); return; } if (descriptor.FullName == Duration.Descriptor.FullName) { WriteDuration(writer, (IMessage)value); return; } if (descriptor.FullName == FieldMask.Descriptor.FullName) { WriteFieldMask(writer, (IMessage)value); return; } if (descriptor.FullName == Struct.Descriptor.FullName) { WriteStruct(writer, (IMessage)value); return; } if (descriptor.FullName == ListValue.Descriptor.FullName) { var fieldAccessor = descriptor.Fields[ListValue.ValuesFieldNumber].Accessor; WriteList(writer, (IList)fieldAccessor.GetValue((IMessage)value)); return; } if (descriptor.FullName == Value.Descriptor.FullName) { WriteStructFieldValue(writer, (IMessage)value); return; } if (descriptor.FullName == Any.Descriptor.FullName) { WriteAny(writer, (IMessage)value); return; } WriteMessage(writer, (IMessage)value); } private void WriteTimestamp(TextWriter writer, IMessage value) { // TODO: In the common case where this *is* using the built-in Timestamp type, we could // avoid all the reflection at this point, by casting to Timestamp. In the interests of // avoiding subtle bugs, don't do that until we've implemented DynamicMessage so that we can prove // it still works in that case. int nanos = (int) value.Descriptor.Fields[Timestamp.NanosFieldNumber].Accessor.GetValue(value); long seconds = (long) value.Descriptor.Fields[Timestamp.SecondsFieldNumber].Accessor.GetValue(value); writer.Write(Timestamp.ToJson(seconds, nanos, DiagnosticOnly)); } private void WriteDuration(TextWriter writer, IMessage value) { // TODO: Same as for WriteTimestamp int nanos = (int) value.Descriptor.Fields[Duration.NanosFieldNumber].Accessor.GetValue(value); long seconds = (long) value.Descriptor.Fields[Duration.SecondsFieldNumber].Accessor.GetValue(value); writer.Write(Duration.ToJson(seconds, nanos, DiagnosticOnly)); } private void WriteFieldMask(TextWriter writer, IMessage value) { var paths = (IList<string>) value.Descriptor.Fields[FieldMask.PathsFieldNumber].Accessor.GetValue(value); writer.Write(FieldMask.ToJson(paths, DiagnosticOnly)); } private void WriteAny(TextWriter writer, IMessage value) { if (DiagnosticOnly) { WriteDiagnosticOnlyAny(writer, value); return; } string typeUrl = (string) value.Descriptor.Fields[Any.TypeUrlFieldNumber].Accessor.GetValue(value); ByteString data = (ByteString) value.Descriptor.Fields[Any.ValueFieldNumber].Accessor.GetValue(value); string typeName = Any.GetTypeName(typeUrl); MessageDescriptor descriptor = settings.TypeRegistry.Find(typeName); if (descriptor == null) { throw new InvalidOperationException($"Type registry has no descriptor for type name '{typeName}'"); } IMessage message = descriptor.Parser.ParseFrom(data); writer.Write("{ "); WriteString(writer, AnyTypeUrlField); writer.Write(NameValueSeparator); WriteString(writer, typeUrl); if (descriptor.IsWellKnownType) { writer.Write(PropertySeparator); WriteString(writer, AnyWellKnownTypeValueField); writer.Write(NameValueSeparator); WriteWellKnownTypeValue(writer, descriptor, message); } else { WriteMessageFields(writer, message, true); } writer.Write(" }"); } private void WriteDiagnosticOnlyAny(TextWriter writer, IMessage value) { string typeUrl = (string) value.Descriptor.Fields[Any.TypeUrlFieldNumber].Accessor.GetValue(value); ByteString data = (ByteString) value.Descriptor.Fields[Any.ValueFieldNumber].Accessor.GetValue(value); writer.Write("{ "); WriteString(writer, AnyTypeUrlField); writer.Write(NameValueSeparator); WriteString(writer, typeUrl); writer.Write(PropertySeparator); WriteString(writer, AnyDiagnosticValueField); writer.Write(NameValueSeparator); writer.Write('"'); writer.Write(data.ToBase64()); writer.Write('"'); writer.Write(" }"); } private void WriteStruct(TextWriter writer, IMessage message) { writer.Write("{ "); IDictionary fields = (IDictionary) message.Descriptor.Fields[Struct.FieldsFieldNumber].Accessor.GetValue(message); bool first = true; foreach (DictionaryEntry entry in fields) { string key = (string) entry.Key; IMessage value = (IMessage) entry.Value; if (string.IsNullOrEmpty(key) || value == null) { throw new InvalidOperationException("Struct fields cannot have an empty key or a null value."); } if (!first) { writer.Write(PropertySeparator); } WriteString(writer, key); writer.Write(NameValueSeparator); WriteStructFieldValue(writer, value); first = false; } writer.Write(first ? "}" : " }"); } private void WriteStructFieldValue(TextWriter writer, IMessage message) { var specifiedField = message.Descriptor.Oneofs[0].Accessor.GetCaseFieldDescriptor(message); if (specifiedField == null) { throw new InvalidOperationException("Value message must contain a value for the oneof."); } object value = specifiedField.Accessor.GetValue(message); switch (specifiedField.FieldNumber) { case Value.BoolValueFieldNumber: case Value.StringValueFieldNumber: case Value.NumberValueFieldNumber: WriteValue(writer, value); return; case Value.StructValueFieldNumber: case Value.ListValueFieldNumber: // Structs and ListValues are nested messages, and already well-known types. var nestedMessage = (IMessage) specifiedField.Accessor.GetValue(message); WriteWellKnownTypeValue(writer, nestedMessage.Descriptor, nestedMessage); return; case Value.NullValueFieldNumber: WriteNull(writer); return; default: throw new InvalidOperationException("Unexpected case in struct field: " + specifiedField.FieldNumber); } } internal void WriteList(TextWriter writer, IList list) { writer.Write("[ "); bool first = true; foreach (var value in list) { if (!first) { writer.Write(PropertySeparator); } WriteValue(writer, value); first = false; } writer.Write(first ? "]" : " ]"); } internal void WriteDictionary(TextWriter writer, IDictionary dictionary) { writer.Write("{ "); bool first = true; // This will box each pair. Could use IDictionaryEnumerator, but that's ugly in terms of disposal. foreach (DictionaryEntry pair in dictionary) { if (!first) { writer.Write(PropertySeparator); } string keyText; if (pair.Key is string) { keyText = (string) pair.Key; } else if (pair.Key is bool) { keyText = (bool) pair.Key ? "true" : "false"; } else if (pair.Key is int || pair.Key is uint | pair.Key is long || pair.Key is ulong) { keyText = ((IFormattable) pair.Key).ToString("d", CultureInfo.InvariantCulture); } else { if (pair.Key == null) { throw new ArgumentException("Dictionary has entry with null key"); } throw new ArgumentException("Unhandled dictionary key type: " + pair.Key.GetType()); } WriteString(writer, keyText); writer.Write(NameValueSeparator); WriteValue(writer, pair.Value); first = false; } writer.Write(first ? "}" : " }"); } /// <summary> /// Writes a string (including leading and trailing double quotes) to a builder, escaping as required. /// </summary> /// <remarks> /// Other than surrogate pair handling, this code is mostly taken from src/google/protobuf/util/internal/json_escaping.cc. /// </remarks> internal static void WriteString(TextWriter writer, string text) { writer.Write('"'); for (int i = 0; i < text.Length; i++) { char c = text[i]; if (c < 0xa0) { writer.Write(CommonRepresentations[c]); continue; } if (char.IsHighSurrogate(c)) { // Encountered first part of a surrogate pair. // Check that we have the whole pair, and encode both parts as hex. i++; if (i == text.Length || !char.IsLowSurrogate(text[i])) { throw new ArgumentException("String contains low surrogate not followed by high surrogate"); } HexEncodeUtf16CodeUnit(writer, c); HexEncodeUtf16CodeUnit(writer, text[i]); continue; } else if (char.IsLowSurrogate(c)) { throw new ArgumentException("String contains high surrogate not preceded by low surrogate"); } switch ((uint) c) { // These are not required by json spec // but used to prevent security bugs in javascript. case 0xfeff: // Zero width no-break space case 0xfff9: // Interlinear annotation anchor case 0xfffa: // Interlinear annotation separator case 0xfffb: // Interlinear annotation terminator case 0x00ad: // Soft-hyphen case 0x06dd: // Arabic end of ayah case 0x070f: // Syriac abbreviation mark case 0x17b4: // Khmer vowel inherent Aq case 0x17b5: // Khmer vowel inherent Aa HexEncodeUtf16CodeUnit(writer, c); break; default: if ((c >= 0x0600 && c <= 0x0603) || // Arabic signs (c >= 0x200b && c <= 0x200f) || // Zero width etc. (c >= 0x2028 && c <= 0x202e) || // Separators etc. (c >= 0x2060 && c <= 0x2064) || // Invisible etc. (c >= 0x206a && c <= 0x206f)) { HexEncodeUtf16CodeUnit(writer, c); } else { // No handling of surrogates here - that's done earlier writer.Write(c); } break; } } writer.Write('"'); } private const string Hex = "0123456789abcdef"; private static void HexEncodeUtf16CodeUnit(TextWriter writer, char c) { writer.Write("\\u"); writer.Write(Hex[(c >> 12) & 0xf]); writer.Write(Hex[(c >> 8) & 0xf]); writer.Write(Hex[(c >> 4) & 0xf]); writer.Write(Hex[(c >> 0) & 0xf]); } /// <summary> /// Settings controlling JSON formatting. /// </summary> public sealed class Settings { /// <summary> /// Default settings, as used by <see cref="JsonFormatter.Default"/> /// </summary> public static Settings Default { get; } // Workaround for the Mono compiler complaining about XML comments not being on // valid language elements. static Settings() { Default = new Settings(false); } /// <summary> /// Whether fields whose values are the default for the field type (e.g. 0 for integers) /// should be formatted (true) or omitted (false). /// </summary> public bool FormatDefaultValues { get; } /// <summary> /// The type registry used to format <see cref="Any"/> messages. /// </summary> public TypeRegistry TypeRegistry { get; } /// <summary> /// Whether to format enums as ints. Defaults to false. /// </summary> public bool FormatEnumsAsIntegers { get; } /// <summary> /// Creates a new <see cref="Settings"/> object with the specified formatting of default values /// and an empty type registry. /// </summary> /// <param name="formatDefaultValues"><c>true</c> if default values (0, empty strings etc) should be formatted; <c>false</c> otherwise.</param> public Settings(bool formatDefaultValues) : this(formatDefaultValues, TypeRegistry.Empty) { } /// <summary> /// Creates a new <see cref="Settings"/> object with the specified formatting of default values /// and type registry. /// </summary> /// <param name="formatDefaultValues"><c>true</c> if default values (0, empty strings etc) should be formatted; <c>false</c> otherwise.</param> /// <param name="typeRegistry">The <see cref="TypeRegistry"/> to use when formatting <see cref="Any"/> messages.</param> public Settings(bool formatDefaultValues, TypeRegistry typeRegistry) : this(formatDefaultValues, typeRegistry, false) { } /// <summary> /// Creates a new <see cref="Settings"/> object with the specified parameters. /// </summary> /// <param name="formatDefaultValues"><c>true</c> if default values (0, empty strings etc) should be formatted; <c>false</c> otherwise.</param> /// <param name="typeRegistry">The <see cref="TypeRegistry"/> to use when formatting <see cref="Any"/> messages. TypeRegistry.Empty will be used if it is null.</param> /// <param name="formatEnumsAsIntegers"><c>true</c> to format the enums as integers; <c>false</c> to format enums as enum names.</param> private Settings(bool formatDefaultValues, TypeRegistry typeRegistry, bool formatEnumsAsIntegers) { FormatDefaultValues = formatDefaultValues; TypeRegistry = typeRegistry ?? TypeRegistry.Empty; FormatEnumsAsIntegers = formatEnumsAsIntegers; } /// <summary> /// Creates a new <see cref="Settings"/> object with the specified formatting of default values and the current settings. /// </summary> /// <param name="formatDefaultValues"><c>true</c> if default values (0, empty strings etc) should be formatted; <c>false</c> otherwise.</param> public Settings WithFormatDefaultValues(bool formatDefaultValues) => new Settings(formatDefaultValues, TypeRegistry, FormatEnumsAsIntegers); /// <summary> /// Creates a new <see cref="Settings"/> object with the specified type registry and the current settings. /// </summary> /// <param name="typeRegistry">The <see cref="TypeRegistry"/> to use when formatting <see cref="Any"/> messages.</param> public Settings WithTypeRegistry(TypeRegistry typeRegistry) => new Settings(FormatDefaultValues, typeRegistry, FormatEnumsAsIntegers); /// <summary> /// Creates a new <see cref="Settings"/> object with the specified enums formatting option and the current settings. /// </summary> /// <param name="formatEnumsAsIntegers"><c>true</c> to format the enums as integers; <c>false</c> to format enums as enum names.</param> public Settings WithFormatEnumsAsIntegers(bool formatEnumsAsIntegers) => new Settings(FormatDefaultValues, TypeRegistry, formatEnumsAsIntegers); } // Effectively a cache of mapping from enum values to the original name as specified in the proto file, // fetched by reflection. // The need for this is unfortunate, as is its unbounded size, but realistically it shouldn't cause issues. private static class OriginalEnumValueHelper { // TODO: In the future we might want to use ConcurrentDictionary, at the point where all // the platforms we target have it. private static readonly Dictionary<System.Type, Dictionary<object, string>> dictionaries = new Dictionary<System.Type, Dictionary<object, string>>(); internal static string GetOriginalName(object value) { var enumType = value.GetType(); Dictionary<object, string> nameMapping; lock (dictionaries) { if (!dictionaries.TryGetValue(enumType, out nameMapping)) { nameMapping = GetNameMapping(enumType); dictionaries[enumType] = nameMapping; } } string originalName; // If this returns false, originalName will be null, which is what we want. nameMapping.TryGetValue(value, out originalName); return originalName; } #if NET35 // TODO: Consider adding functionality to TypeExtensions to avoid this difference. private static Dictionary<object, string> GetNameMapping(System.Type enumType) => enumType.GetFields(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static) .Where(f => (f.GetCustomAttributes(typeof(OriginalNameAttribute), false) .FirstOrDefault() as OriginalNameAttribute) ?.PreferredAlias ?? true) .ToDictionary(f => f.GetValue(null), f => (f.GetCustomAttributes(typeof(OriginalNameAttribute), false) .FirstOrDefault() as OriginalNameAttribute) // If the attribute hasn't been applied, fall back to the name of the field. ?.Name ?? f.Name); #else private static Dictionary<object, string> GetNameMapping(System.Type enumType) => enumType.GetTypeInfo().DeclaredFields .Where(f => f.IsStatic) .Where(f => f.GetCustomAttributes<OriginalNameAttribute>() .FirstOrDefault()?.PreferredAlias ?? true) .ToDictionary(f => f.GetValue(null), f => f.GetCustomAttributes<OriginalNameAttribute>() .FirstOrDefault() // If the attribute hasn't been applied, fall back to the name of the field. ?.Name ?? f.Name); #endif } } }
43.851249
179
0.5271
[ "MIT" ]
Boltorez1488/UpdateSystem
Shared/Google.Protobuf/JsonFormatter.cs
40,389
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; using Microsoft.Extensions.Logging; namespace MvcSoporte.Areas.Identity.Pages.Account.Manage { public class TwoFactorAuthenticationModel : PageModel { private const string AuthenicatorUriFormat = "otpauth://totp/{0}:{1}?secret={2}&issuer={0}"; private readonly UserManager<IdentityUser> _userManager; private readonly SignInManager<IdentityUser> _signInManager; private readonly ILogger<TwoFactorAuthenticationModel> _logger; public TwoFactorAuthenticationModel( UserManager<IdentityUser> userManager, SignInManager<IdentityUser> signInManager, ILogger<TwoFactorAuthenticationModel> logger) { _userManager = userManager; _signInManager = signInManager; _logger = logger; } public bool HasAuthenticator { get; set; } public int RecoveryCodesLeft { get; set; } [BindProperty] public bool Is2faEnabled { get; set; } public bool IsMachineRemembered { get; set; } [TempData] public string StatusMessage { get; set; } public async Task<IActionResult> OnGet() { var user = await _userManager.GetUserAsync(User); if (user == null) { return NotFound($"Unable to load user with ID '{_userManager.GetUserId(User)}'."); } HasAuthenticator = await _userManager.GetAuthenticatorKeyAsync(user) != null; Is2faEnabled = await _userManager.GetTwoFactorEnabledAsync(user); IsMachineRemembered = await _signInManager.IsTwoFactorClientRememberedAsync(user); RecoveryCodesLeft = await _userManager.CountRecoveryCodesAsync(user); return Page(); } public async Task<IActionResult> OnPost() { var user = await _userManager.GetUserAsync(User); if (user == null) { return NotFound($"Unable to load user with ID '{_userManager.GetUserId(User)}'."); } await _signInManager.ForgetTwoFactorClientAsync(); StatusMessage = "The current browser has been forgotten. When you login again from this browser you will be prompted for your 2fa code."; return RedirectToPage(); } } }
35.676056
149
0.651402
[ "MIT" ]
ProgramDani/MvcSoporte
MvcSoporte/Areas/Identity/Pages/Account/Manage/TwoFactorAuthentication.cshtml.cs
2,535
C#
namespace uTinyRipper.Classes.QualitySettingss { public enum VSyncCount { DontSync = 0, EveryVBlank = 1, EverySecondVBlank = 2, } }
14.6
47
0.69863
[ "MIT" ]
Bluscream/UtinyRipper
uTinyRipperCore/Parser/Classes/QualitySettings/VSyncCount.cs
148
C#
using System.Reflection; using FluentValidation; using MediatR; using Microsoft.Extensions.DependencyInjection; using Ordering.Application.Behaviours; namespace Ordering.Application { public static class ApplicationServiceRegistration { public static IServiceCollection AddApplicationServices(this IServiceCollection services) { services.AddAutoMapper(Assembly.GetExecutingAssembly()); services.AddValidatorsFromAssembly(Assembly.GetExecutingAssembly()); services.AddMediatR(Assembly.GetExecutingAssembly()); services.AddTransient(typeof(IPipelineBehavior<,>), typeof(UnhandledExceptionBehaviour<,>)); services.AddTransient(typeof(IPipelineBehavior<,>), typeof(ValidationBehaviour<,>)); return services; } } }
44.833333
104
0.745973
[ "MIT" ]
mertKarasakal/AspnetMicroservices
src/Services/Ordering/Ordering.Application/ApplicationServiceRegistration.cs
809
C#
using System; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using MonoGame.WpfCore.MonoGameControls; namespace MonoGame.WpfCore { public class MainWindowViewModel : MonoGameViewModel { private SpriteBatch _spriteBatch; private Texture2D _texture; private Vector2 _position; private float _rotation; private Vector2 _origin; private Vector2 _scale; public override void LoadContent() { _spriteBatch = new SpriteBatch(GraphicsDevice); _texture = Content.Load<Texture2D>("monogame-logo"); } public override void Update(GameTime gameTime) { _position = GraphicsDevice.Viewport.Bounds.Center.ToVector2(); _rotation = (float)Math.Sin(gameTime.TotalGameTime.TotalSeconds) / 4f; _origin = _texture.Bounds.Center.ToVector2(); _scale = Vector2.One; } public override void Draw(GameTime gameTime) { GraphicsDevice.Clear(Color.CornflowerBlue); _spriteBatch.Begin(); _spriteBatch.Draw(_texture, _position, null, Color.White, _rotation, _origin, _scale, SpriteEffects.None, 0f); _spriteBatch.End(); } } }
31.825
122
0.645719
[ "MIT" ]
OpenSauce/MonoGame.WpfCore
MonoGame.WpfCore/MainWindowViewModel.cs
1,275
C#
using System.Threading.Tasks; using AngleSharp.Html.Dom; using NUnit.Framework; namespace AngleSharp.ContentExtraction.IntegrationTests { [TestFixture] public class ContentExtractorTests { [Test] public async Task Extract_IntegrationTest() { // Arrange var config = Configuration.Default.WithDefaultLoader(); var address = "https://lenta.ru/articles/2020/05/13/coronausa/"; var context = BrowsingContext.New(config); var document = (IHtmlDocument)await context.OpenAsync(address); var extractor = new ContentExtractor(); // Act extractor.Extract(document); // Assert Assert.Pass(); } } }
27.107143
76
0.610013
[ "MIT" ]
denis-ivanov/AngleSharp.ContentExtraction
AngleSharp.ContentExtraction.IntegrationTests/ContentExtractorTests.cs
759
C#
using FubuMVC.Core.UI.Elements; using FubuMVC.Validation.UI; using FubuTestingSupport; using FubuValidation; using NUnit.Framework; namespace FubuMVC.Validation.Tests.UI { [TestFixture] public class MaximumLengthModifierTester : ValidationElementModifierContext<MaximumLengthModifier> { [Test] public void adds_the_maxlength_attribute_for_maximum_length_rule() { var theRequest = ElementRequest.For(new TargetWithMaxLength(), x => x.Value); tagFor(theRequest).Data<object>("maxlength", x => x.ShouldEqual("10")); } [Test] public void no_maxlength_attribute_when_rule_does_not_exist() { var theRequest = ElementRequest.For(new TargetWithNoMaxLength(), x => x.Value); tagFor(theRequest).Attr("maxlength").ShouldBeEmpty(); } public class TargetWithMaxLength { [MaximumStringLength(10)] public string Value { get; set; } } public class TargetWithNoMaxLength { public string Value { get; set; } } } }
30.236842
103
0.62141
[ "Apache-2.0" ]
DovetailSoftware/fubuvalidation
src/FubuMVC.Validation.Tests/UI/MaximumLengthModifierTester.cs
1,149
C#
using System; using System.IO; using System.Linq; using Microsoft.VisualStudio.TestTools.UnitTesting; using WebCompiler; namespace WebCompilerTest.Minify { [TestClass] public class CssMinifierTests { private const string processingConfigFile = "../../Minify/artifacts/css/"; [TestCleanup] public void Cleanup() { File.Delete("../../Minify/artifacts/css/site.css"); File.Delete("../../Minify/artifacts/css/site.min.css"); } /// <summary> /// Tests that '.min' is automatically appended to a minified file name. /// </summary> /// <remarks> /// For example, the file 'site.css' becomes 'site.min.css' when minified. /// </remarks> [TestMethod, TestCategory("CssMinifier")] public void ShouldAppendMinToOutputFile() { var configPath = Path.Combine(processingConfigFile, "outputfilenomin.json"); var configs = ConfigHandler.GetConfigs(configPath); var outputFile = "site.min.css"; // Capture the name of the resulting (minified) file. string resultFile = string.Empty; FileMinifier.BeforeWritingMinFile += (object sender, MinifyFileEventArgs e) => { resultFile = new FileInfo(e.ResultFile).Name; }; ConfigFileProcessor processor = new ConfigFileProcessor(); var results = processor.Process(configPath, configs, force:true); Assert.AreEqual(outputFile, resultFile); } /// <summary> /// Tests that '.min' is only appended to a minified file name once. /// </summary> /// <remarks> /// For example, the file 'site.min.css' remains unchanged when minified /// as it already contains the '.min' suffix. /// </remarks> [TestMethod, TestCategory("CssMinifier")] public void ShouldAppendMinOnlyOnce() { var configPath = Path.Combine(processingConfigFile, "outputfilemin.json"); var configs = ConfigHandler.GetConfigs(configPath); var outputFile = configs.First().OutputFile; // Capture the name of the resulting (minified) file. string resultFile = string.Empty; FileMinifier.BeforeWritingMinFile += (object sender, MinifyFileEventArgs e) => { resultFile = new FileInfo(e.ResultFile).Name; }; ConfigFileProcessor processor = new ConfigFileProcessor(); var results = processor.Process(configPath, configs, force: true); Assert.AreEqual(outputFile, resultFile); } } }
38.101449
141
0.620768
[ "Apache-2.0" ]
BadgerTaming/WebCompiler
src/WebCompilerTest/Minify/CssMinifierTests.cs
2,631
C#
//----------------------------------------------------------------------------- // Copyright (c) 2012 GarageGames, LLC // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. //----------------------------------------------------------------------------- //--- NightSkyS_07.dae MATERIALS BEGIN --- singleton Material(NightSkyS_07_Night_SkyS_New_07) { mapTo = "Night_SkyS_New_07"; diffuseMap[0] = "data/FPSGameplay/fpstutorial/art/textures/structures/SkyScrapers/SkyS_Night/SkyS_Night_7.dds"; normalMap[0] = ""; specularMap[0] = ""; diffuseColor[0] = "1 1 1 1"; specular[0] = "1 1 1 0"; specularPower[0] = 50; doubleSided = false; translucent = false; translucentBlendOp = "None"; emissive[0] = "1"; constantCubemapGloss = "0.2"; materialTag0 = "Chinatown"; }; //--- NightSkyS_07.dae MATERIALS END --- //--- NightSkyS_05.dae MATERIALS BEGIN --- singleton Material(NightSkyS_05_Night_SkyS_New_05) { mapTo = "Night_SkyS_New_05"; diffuseMap[0] = "data/FPSGameplay/fpstutorial/art/textures/structures/SkyScrapers/SkyS_Night/SkyS_Night_7.dds"; normalMap[0] = ""; specularMap[0] = ""; diffuseColor[0] = "1 1 1 1"; specular[0] = "1 1 1 0"; specularPower[0] = 50; doubleSided = false; translucent = false; translucentBlendOp = "None"; emissive[0] = "1"; constantCubemapGloss = "0.2"; materialTag0 = "Chinatown"; }; //--- NightSkyS_05.dae MATERIALS END --- //--- NightSkyS_01.dae MATERIALS BEGIN --- singleton Material(NightSkyS_01_Night_SkyS_New_01) { mapTo = "Night_SkyS_New_01"; diffuseMap[0] = "data/FPSGameplay/fpstutorial/art/textures/structures/SkyScrapers/SkyS_Night/SkyS_05_night.dds"; normalMap[0] = ""; specularMap[0] = ""; diffuseColor[0] = "1 1 1 1"; specular[0] = "1 1 1 0"; specularPower[0] = 50; doubleSided = false; translucent = false; translucentBlendOp = "None"; emissive[0] = "1"; constantCubemapGloss = "0.2"; materialTag0 = "Chinatown"; }; //--- NightSkyS_01.dae MATERIALS END ---
32.456522
113
0.682184
[ "MIT" ]
Torque3D-GameEngine/T3D-Demos
data/FPSGameplay/fpstutorial/art/shapes/structures/SkyScrapers/NightSkyS/materials.cs
2,986
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 GraphicEditor.Properties { [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0")] internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase { private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings()))); public static Settings Default { get { return defaultInstance; } } } }
34.451613
151
0.582397
[ "MIT" ]
ArtemAhramenko/GraphicEditor
GraphicEditor/Properties/Settings.Designer.cs
1,070
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 SnakeGame.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; } } } }
36.4
152
0.565934
[ "MIT" ]
Brewster35/thecodingtrain
SnakeGame/SnakeGame/Properties/Settings.Designer.cs
1,094
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 qldb-session-2019-07-11.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.QLDBSession.Model { /// <summary> /// Specifies the details of the page to be fetched. /// </summary> public partial class FetchPageRequest { private string _nextPageToken; private string _transactionId; /// <summary> /// Gets and sets the property NextPageToken. /// <para> /// Specifies the next page token of the page to be fetched. /// </para> /// </summary> [AWSProperty(Required=true, Min=4, Max=1024)] public string NextPageToken { get { return this._nextPageToken; } set { this._nextPageToken = value; } } // Check to see if NextPageToken property is set internal bool IsSetNextPageToken() { return this._nextPageToken != null; } /// <summary> /// Gets and sets the property TransactionId. /// <para> /// Specifies the transaction ID of the page to be fetched. /// </para> /// </summary> [AWSProperty(Required=true, Min=22, Max=22)] public string TransactionId { get { return this._transactionId; } set { this._transactionId = value; } } // Check to see if TransactionId property is set internal bool IsSetTransactionId() { return this._transactionId != null; } } }
29.858974
110
0.626449
[ "Apache-2.0" ]
DetlefGolze/aws-sdk-net
sdk/src/Services/QLDBSession/Generated/Model/FetchPageRequest.cs
2,329
C#
// <auto-generated> // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // </auto-generated> namespace Microsoft.Azure.Management.Dns.Fluent { using Microsoft.Azure.Management.ResourceManager.Fluent.Core; using Microsoft.Rest; using Microsoft.Rest.Azure; using Microsoft.Rest.Serialization; using Models; using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; /// <summary> /// The DNS Management Client. /// </summary> public partial class DnsManagementClient : FluentServiceClientBase<DnsManagementClient>, IDnsManagementClient, IAzureClient { /// <summary> /// Gets or sets json serialization settings. /// </summary> public JsonSerializerSettings SerializationSettings { get; private set; } /// <summary> /// Gets or sets json deserialization settings. /// </summary> public JsonSerializerSettings DeserializationSettings { get; private set; } /// <summary> /// Specifies the Azure subscription ID, which uniquely identifies the /// Microsoft Azure subscription. /// </summary> public string SubscriptionId { get; set; } /// <summary> /// Specifies the API version. /// </summary> public string ApiVersion { get; private set; } /// <summary> /// Gets or sets the preferred language for the response. /// </summary> public string AcceptLanguage { get; set; } /// <summary> /// Gets or sets the retry timeout in seconds for Long Running Operations. /// Default value is 30. /// </summary> public int? LongRunningOperationRetryTimeout { get; set; } /// <summary> /// When set to true a unique x-ms-client-request-id value is generated and /// included in each request. Default is true. /// </summary> public bool? GenerateClientRequestId { get; set; } /// <summary> /// Gets the IRecordSetsOperations. /// </summary> public virtual IRecordSetsOperations RecordSets { get; private set; } /// <summary> /// Gets the IZonesOperations. /// </summary> public virtual IZonesOperations Zones { get; private set; } /// <summary> /// Initializes a new instance of the DnsManagementClient class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='credentials'> /// Required. Credentials needed for the client to connect to Azure. /// </param> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public DnsManagementClient(RestClient restClient) : base(restClient) { } /// <summary> /// An optional partial-method to perform custom initialization. /// </summary> partial void CustomInitialize(); /// <summary> /// Initializes client properties. /// </summary> protected override void Initialize() { RecordSets = new RecordSetsOperations(this); Zones = new ZonesOperations(this); BaseUri = new System.Uri("https://management.azure.com"); ApiVersion = "2018-03-01-preview"; AcceptLanguage = "en-US"; LongRunningOperationRetryTimeout = 30; GenerateClientRequestId = true; SerializationSettings = new JsonSerializerSettings { Formatting = Newtonsoft.Json.Formatting.Indented, DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat, DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore, ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize, ContractResolver = new ReadOnlyJsonContractResolver(), Converters = new List<JsonConverter> { new Iso8601TimeSpanConverter() } }; SerializationSettings.Converters.Add(new TransformationJsonConverter()); DeserializationSettings = new JsonSerializerSettings { DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat, DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore, ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize, ContractResolver = new ReadOnlyJsonContractResolver(), Converters = new List<JsonConverter> { new Iso8601TimeSpanConverter() } }; CustomInitialize(); DeserializationSettings.Converters.Add(new TransformationJsonConverter()); DeserializationSettings.Converters.Add(new CloudErrorJsonConverter()); } } }
39.251701
127
0.609185
[ "MIT" ]
AntoineGa/azure-libraries-for-net
src/ResourceManagement/Dns/Generated/DnsManagementClient.cs
5,770
C#
namespace WordnikLib.Results { public struct ReverseDictionary //<CHECKED> { public Definition[] results { get; set; } public int totalResults { get; set; } } }
24.5
50
0.602041
[ "Apache-2.0" ]
mcridah/xawords
WordnikLib/Results/ReverseDictionary.cs
198
C#
using System; using System.Globalization; using System.Linq; using System.Windows.Data; namespace MidiKeyboardResharperCodeNavigator.Converters { public class MultiValueEqualityConverter : IMultiValueConverter { public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture) { return values?.All(o => o?.Equals(values[0]) == true) == true || values?.All(o => o == null) == true; } public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture) { throw new NotImplementedException(); } } }
30.761905
113
0.667183
[ "MIT" ]
JennoVink/MidiKeyboardResharperCodeNavigator
MidiKeyboardResharperCodeNavigator/Converters/MultiValueEqualityConverter.cs
648
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. namespace Microsoft.Azure.Management.Cdn.Fluent.CdnEndpoint.UpdatePremiumEndpoint { using Microsoft.Azure.Management.Cdn.Fluent.CdnEndpoint.Update; /// <summary> /// The stage of an CDN profile endpoint update allowing to specify endpoint properties. /// </summary> public interface IUpdatePremiumEndpoint : Microsoft.Azure.Management.Cdn.Fluent.CdnEndpoint.Update.IUpdate { /// <summary> /// Specifies if HTTPS traffic is allowed. /// </summary> /// <param name="httpsAllowed">If true then HTTPS traffic will be allowed.</param> /// <return>The next stage of the endpoint update.</return> Microsoft.Azure.Management.Cdn.Fluent.CdnEndpoint.UpdatePremiumEndpoint.IUpdatePremiumEndpoint WithHttpsAllowed(bool httpsAllowed); /// <summary> /// Specifies the port for HTTP traffic. /// </summary> /// <param name="httpPort">A port number.</param> /// <return>The next stage of the endpoint update.</return> Microsoft.Azure.Management.Cdn.Fluent.CdnEndpoint.UpdatePremiumEndpoint.IUpdatePremiumEndpoint WithHttpPort(int httpPort); /// <summary> /// Removes CDN custom domain within an endpoint. /// </summary> /// <param name="hostName">A custom domain host name.</param> /// <return>The next stage of the endpoint update.</return> Microsoft.Azure.Management.Cdn.Fluent.CdnEndpoint.UpdatePremiumEndpoint.IUpdatePremiumEndpoint WithoutCustomDomain(string hostName); /// <summary> /// Adds a new CDN custom domain within an endpoint. /// </summary> /// <param name="hostName">A custom domain host name.</param> /// <return>The next stage of the endpoint update.</return> Microsoft.Azure.Management.Cdn.Fluent.CdnEndpoint.UpdatePremiumEndpoint.IUpdatePremiumEndpoint WithCustomDomain(string hostName); /// <summary> /// Specifies the port for HTTPS traffic. /// </summary> /// <param name="httpsPort">A port number.</param> /// <return>The next stage of the endpoint update.</return> Microsoft.Azure.Management.Cdn.Fluent.CdnEndpoint.UpdatePremiumEndpoint.IUpdatePremiumEndpoint WithHttpsPort(int httpsPort); /// <summary> /// Specifies if HTTP traffic is allowed. /// </summary> /// <param name="httpAllowed">If true then HTTP traffic will be allowed.</param> /// <return>The next stage of the endpoint update.</return> Microsoft.Azure.Management.Cdn.Fluent.CdnEndpoint.UpdatePremiumEndpoint.IUpdatePremiumEndpoint WithHttpAllowed(bool httpAllowed); /// <summary> /// Specifies the origin path. /// </summary> /// <param name="originPath">An origin path.</param> /// <return>The next stage of the endpoint update.</return> Microsoft.Azure.Management.Cdn.Fluent.CdnEndpoint.UpdatePremiumEndpoint.IUpdatePremiumEndpoint WithOriginPath(string originPath); /// <summary> /// Specifies the host header. /// </summary> /// <param name="hostHeader">A host header.</param> /// <return>The next stage of the endpoint update.</return> Microsoft.Azure.Management.Cdn.Fluent.CdnEndpoint.UpdatePremiumEndpoint.IUpdatePremiumEndpoint WithHostHeader(string hostHeader); } }
51.231884
140
0.680339
[ "MIT" ]
AntoineGa/azure-libraries-for-net
src/ResourceManagement/Cdn/Domain/CdnEndpoint/UpdatePremiumEndpoint/IUpdatePremiumEndpoint.cs
3,535
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\IEntityCollectionRequest.cs.tt namespace Microsoft.Graph { using System; using System.Collections.Generic; using System.Net.Http; using System.Threading; using System.Linq.Expressions; /// <summary> /// The interface IDeviceCommandsCollectionRequest. /// </summary> public partial interface IDeviceCommandsCollectionRequest : IBaseRequest { /// <summary> /// Adds the specified Command to the collection via POST. /// </summary> /// <param name="command">The Command to add.</param> /// <returns>The created Command.</returns> System.Threading.Tasks.Task<Command> AddAsync(Command command); /// <summary> /// Adds the specified Command to the collection via POST. /// </summary> /// <param name="command">The Command to add.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The created Command.</returns> System.Threading.Tasks.Task<Command> AddAsync(Command command, CancellationToken cancellationToken); /// <summary> /// Gets the collection page. /// </summary> /// <returns>The collection page.</returns> System.Threading.Tasks.Task<IDeviceCommandsCollectionPage> GetAsync(); /// <summary> /// Gets the collection page. /// </summary> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The collection page.</returns> System.Threading.Tasks.Task<IDeviceCommandsCollectionPage> GetAsync(CancellationToken cancellationToken); /// <summary> /// Adds the specified expand value to the request. /// </summary> /// <param name="value">The expand value.</param> /// <returns>The request object to send.</returns> IDeviceCommandsCollectionRequest Expand(string value); /// <summary> /// Adds the specified expand value to the request. /// </summary> /// <param name="expandExpression">The expression from which to calculate the expand value.</param> /// <returns>The request object to send.</returns> IDeviceCommandsCollectionRequest Expand(Expression<Func<Command, object>> expandExpression); /// <summary> /// Adds the specified select value to the request. /// </summary> /// <param name="value">The select value.</param> /// <returns>The request object to send.</returns> IDeviceCommandsCollectionRequest Select(string value); /// <summary> /// Adds the specified select value to the request. /// </summary> /// <param name="selectExpression">The expression from which to calculate the select value.</param> /// <returns>The request object to send.</returns> IDeviceCommandsCollectionRequest Select(Expression<Func<Command, object>> selectExpression); /// <summary> /// Adds the specified top value to the request. /// </summary> /// <param name="value">The top value.</param> /// <returns>The request object to send.</returns> IDeviceCommandsCollectionRequest Top(int value); /// <summary> /// Adds the specified filter value to the request. /// </summary> /// <param name="value">The filter value.</param> /// <returns>The request object to send.</returns> IDeviceCommandsCollectionRequest Filter(string value); /// <summary> /// Adds the specified skip value to the request. /// </summary> /// <param name="value">The skip value.</param> /// <returns>The request object to send.</returns> IDeviceCommandsCollectionRequest Skip(int value); /// <summary> /// Adds the specified orderby value to the request. /// </summary> /// <param name="value">The orderby value.</param> /// <returns>The request object to send.</returns> IDeviceCommandsCollectionRequest OrderBy(string value); } }
42.814815
153
0.612889
[ "MIT" ]
OfficeGlobal/msgraph-beta-sdk-dotnet
src/Microsoft.Graph/Requests/Generated/IDeviceCommandsCollectionRequest.cs
4,624
C#
using System.Linq; using CAFU.Generator.Enumerates; using CAFU.Generator.Structure.Partial; using JetBrains.Annotations; using UnityEditor; namespace CAFU.Generator.Structure.Class.Domain { [UsedImplicitly] public class UseCase : ClassStructureBase { private const string StructureName = "Domain/UseCase"; public override string Name { get; } = StructureName; protected override ParentLayerType ParentLayerType { get; } = ParentLayerType.Domain; protected override LayerType LayerType { get; } = LayerType.UseCase; private string ClassName { get; set; } private bool IsSingleton { get; set; } private bool HasFactory { get; set; } = true; public override void OnGUI() { base.OnGUI(); ClassName = EditorGUILayout.TextField("Class Name", ClassName); IsSingleton = EditorGUILayout.Toggle("Is IsSingleton?", IsSingleton); HasFactory = EditorGUILayout.Toggle("Use Factory?", HasFactory); GeneratorWindow.GetAdditionalOptionRenderDelegateList(LayerType)?.ToList().ForEach(x => x()); } public override void Generate(bool overwrite) { var parameter = new Parameter() { ParentLayerType = ParentLayerType, LayerType = LayerType, InterfaceName = $"I{ClassName}", ClassName = ClassName, IsSingleton = IsSingleton, Overwrite = overwrite, }; parameter.Namespace = CreateNamespace(parameter); GeneratorWindow.GetAdditionalStructureExtensionDelegateList(LayerType)?.ToList().ForEach(x => x(parameter)); parameter.UsingList.Add("CAFU.Core.Domain.UseCase"); parameter.ImplementsInterfaceList.Add(parameter.InterfaceName); var generator = new ScriptGenerator(parameter, CreateTemplatePath(TemplateType.Class, StructureName)); if (HasFactory) { generator.AddPartial(Factory.StructureName, GeneratorWindow.GetPartialStructure(Factory.StructureName).Render(parameter)); } generator.Generate(CreateOutputPath(parameter)); } } }
36.354839
138
0.641083
[ "MIT" ]
umm-projects/cafu_generator
Assets/Editor/Scripts/Structure/Class/Domain/UseCase.cs
2,256
C#
namespace FluentHttp.Tests.HttpHeader { using System; using TechTalk.SpecFlow; using Xunit; [Binding] [StepScope(Feature = "FluentHttpHeader ctor")] public class HttpHeaderCtor { private FluentHttpHeader _fluentHttpHeader; private string _headerName; private string _headerValue; [Given(@"a null fluent http header")] public void GivenANullFluentHttpHeader() { _fluentHttpHeader = null; } [Then(@"name should be ""(.*)""")] public void ThenNameShouldBeHeader_Name(string headerName) { Assert.Equal(headerName, _headerName); } [Then(@"there should be no exception thrown")] public void ThenThereShouldBeNoExceptionThrown() { Assert.Null(_exception); } [Then(@"value should be ""(.*)""")] public void ThenValueShouldBeHeader_Value(string headerValue) { Assert.Equal(headerValue, _headerValue); } [When(@"I create a new fluent http header with ctor params \(""(.*)"" and ""(.*)""\)")] public void WhenICreateANewFluentHttpHeaderWithCtorParamsHeader_NameAndHeader_Value(string headerName, string headerValue) { _fluentHttpHeader = new FluentHttpHeader(headerName, headerValue); } [When(@"I get name")] public void WhenIGetName() { _headerName = _fluentHttpHeader.Name; } [When(@"I get value")] public void WhenIGetValue() { _headerValue = _fluentHttpHeader.Value; } private Exception _exception; #if AGGRESSIVE_CHECK private Exception _exception; [Then(@"it should throw ArgumentOutOfRangeException")] public void ThenItShouldThrowArgumentNullException() { Assert.Equal(typeof(ArgumentOutOfRangeException), _exception.GetType()); } [When(@"I create a new fluent http header with http header name as null")] public void WhenICreateANewFluentHttpHeaderWithHttpHeaderAsNull() { try { _fluentHttpHeader = new FluentHttpHeader(null, "header-value"); } catch (Exception ex) { _exception = ex; } } [When(@"I create a new fluent http header with http header name as string\.Empty")] public void WhenICreateANewFluentHttpHeaderWithHttpHeaderAsString_Empty() { try { _fluentHttpHeader = new FluentHttpHeader(null, "header-value"); } catch (Exception ex) { _exception = ex; } } [When(@"I create a new fluent http header with http header name as """"")] public void WhenICreateANewFluentHttpHeaderWithHttpHeaderAs() { try { _fluentHttpHeader = new FluentHttpHeader("", "header-value"); } catch (Exception ex) { _exception = ex; } } [When(@"I create a new fluent http header with http header name as "" """)] public void WhenICreateANewFluentHttpHeaderWithHttpHeaderNameAs() { try { _fluentHttpHeader = new FluentHttpHeader(" ", "header-value"); } catch (Exception ex) { _exception = ex; } } #endif } }
29.576
131
0.538815
[ "Apache-2.0" ]
prabirshrestha/FluentHttp
src/FluentHttp.Tests/HttpHeader/HttpHeaderCtor.cs
3,699
C#
using Microsoft.Extensions.DependencyInjection; using NetHacksPack.Notifications.Abstractions.Notificators; using NetHacksPack.Notifications.Abstractions.Providers; using NetHacksPack.Notifications.Extensions.SmtpMail.Provider; using System; namespace NetHacksPack.Notifications.Extensions.SmtpMail.DependencyInjection { /// <summary> /// Extension class used to configure the required interfaces from this package /// </summary> public static class SmtpMailServiceExtensions { /// <summary> /// Add all the base interfaces used to send smpt mail notifications /// </summary> /// <param name="services">the container to configure the interfaces</param> /// <param name="configureSmtpMailService">an action that configures the smpt configurations</param> /// <returns></returns> public static IServiceCollection AddSmtpMailNotifications(this IServiceCollection services, Action<SmtpMailOptions> configureSmtpMailService) { services.AddScoped<SmtpEmailNotificatorClient>(); services.AddScoped<INotificator, SmtpEmailNotificatorClient>(); services.AddScoped<INotificatorResolver, EmailResolver>(); services.Configure(configureSmtpMailService); return services; } } }
44.066667
149
0.726172
[ "MIT" ]
EdneySilva/NetHacksPack
src/NetHacksPack.Notifications.Extensions.SmtpMail/DependencyInjection/SmtpMailServiceExtensions.cs
1,324
C#
using Playground.Shared; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.InteropServices.WindowsRuntime; using Windows.Foundation; using Windows.Foundation.Collections; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Controls.Primitives; using Windows.UI.Xaml.Data; using Windows.UI.Xaml.Input; using Windows.UI.Xaml.Media; using Windows.UI.Xaml.Navigation; // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409 namespace Playground { /// <summary> /// An empty page that can be used on its own or navigated to within a Frame. /// </summary> public sealed partial class MainPage : Page { public MainPage() { this.InitializeComponent(); this.DataContext = new DataContext(); } } }
27.090909
106
0.719239
[ "MIT" ]
RoguePlanetoid/UnoPlatform
Presentation/Playground/Playground/Playground.Shared/MainPage.xaml.cs
896
C#
namespace InControl { #if UNITY_EDITOR using UnityEditor; #endif using System; using System.Linq; using UnityEngine; // ReSharper disable StaticMemberInGenericType public abstract class SingletonMonoBehavior<TComponent> : MonoBehaviour where TComponent : MonoBehaviour { static TComponent instance; static bool hasInstance; static int instanceId; static readonly object lockObject = new object(); public static TComponent Instance { get { lock (lockObject) { if (hasInstance) { return instance; } instance = FindFirstInstance(); if (instance == null) { throw new Exception( "The instance of singleton component " + typeof(TComponent) + " was requested, but it doesn't appear to exist in the scene." ); } hasInstance = true; instanceId = instance.GetInstanceID(); return instance; } } } /// <summary> /// Returns true if the object is NOT the singleton instance and should exit early from doing any redundant work. /// It will also log a warning if called from another instance in the editor during play mode. /// </summary> protected bool EnforceSingleton { get { if (GetInstanceID() == Instance.GetInstanceID()) { return false; } if (Application.isPlaying) { enabled = false; } return true; } } /// <summary> /// Returns true if the object is the singleton instance. /// </summary> protected bool IsTheSingleton { get { lock (lockObject) { // We compare against the last known instance ID because Unity destroys objects // in random order and this may get called during teardown when the instance is // already gone. return GetInstanceID() == instanceId; } } } /// <summary> /// Returns true if the object is not the singleton instance. /// </summary> protected bool IsNotTheSingleton { get { lock (lockObject) { // We compare against the last known instance ID because Unity destroys objects // in random order and this may get called during teardown when the instance is // already gone. return GetInstanceID() != instanceId; } } } static TComponent[] FindInstances() { var objects = FindObjectsOfType<TComponent>(); Array.Sort( objects, ( a, b ) => a.transform.GetSiblingIndex().CompareTo( b.transform.GetSiblingIndex() ) ); return objects; } static TComponent FindFirstInstance() { var objects = FindInstances(); return objects.Length > 0 ? objects[0] : null; } // ReSharper disable once VirtualMemberNeverOverridden.Global protected virtual void Awake() { if (Application.isPlaying && Instance) { if (GetInstanceID() != instanceId) { #if UNITY_EDITOR Debug.LogWarning( "A redundant instance (" + name + ") of singleton " + typeof(TComponent) + " is present in the scene.", this ); EditorGUIUtility.PingObject( this ); #endif enabled = false; } // This might be unnecessary, but just to be safe we do it anyway. foreach (var redundantInstance in FindInstances().Where( o => o.GetInstanceID() != instanceId )) { redundantInstance.enabled = false; } } } // ReSharper disable once VirtualMemberNeverOverridden.Global protected virtual void OnDestroy() { lock (lockObject) { if (GetInstanceID() == instanceId) { hasInstance = false; } } } } }
22.301282
154
0.653349
[ "MIT" ]
kojdj0811/Project_Stove11
Assets/InControl/Source/Utility/SingletonMonoBehavior.cs
3,479
C#
// Copyright (c) Brock Allen & Dominick Baier. All rights reserved. // Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information. namespace Dbosoft.IdentityServer.Validation.Models { /// <summary> /// Validation result for device authorization requests /// </summary> public class DeviceAuthorizationRequestValidationResult : ValidationResult { /// <summary> /// Initializes a new instance of the <see cref="DeviceAuthorizationRequestValidationResult"/> class. /// </summary> /// <param name="request">The request.</param> public DeviceAuthorizationRequestValidationResult(ValidatedDeviceAuthorizationRequest request) { IsError = false; ValidatedRequest = request; } /// <summary> /// Initializes a new instance of the <see cref="DeviceAuthorizationRequestValidationResult"/> class. /// </summary> /// <param name="request">The request.</param> /// <param name="error">The error.</param> /// <param name="errorDescription">The error description.</param> public DeviceAuthorizationRequestValidationResult(ValidatedDeviceAuthorizationRequest request, string error, string errorDescription = null) { IsError = true; Error = error; ErrorDescription = errorDescription; ValidatedRequest = request; } /// <summary> /// Gets the validated request. /// </summary> /// <value> /// The validated request. /// </value> public ValidatedDeviceAuthorizationRequest ValidatedRequest { get; } } }
37.217391
148
0.639019
[ "Apache-2.0" ]
dbosoft/IdentityServer
src/IdentityServer/Validation/Models/DeviceAuthorizationRequestValidationResult.cs
1,712
C#
using VerifyTaxiApp.Models; namespace VerifyTaxiApp.ViewModels { public class ItemDetailViewModel : BaseViewModel { public Item Item { get; set; } public ItemDetailViewModel(Item item = null) { Title = item.Text; Item = item; } int quantity = 1; public int Quantity { get { return quantity; } set { SetProperty(ref quantity, value); } } } }
22.238095
53
0.541756
[ "MIT" ]
ignatandrei/IsThisTaxiLegal
applications/VerifyTaxiApp/VerifyTaxiApp/VerifyTaxiApp/ViewModels/ItemDetailViewModel.cs
469
C#
using Pliant.Forest; using Pliant.Grammars; using Pliant.Utilities; namespace Pliant.Charts { public abstract class EarleyItem : ValueEqualityBase<EarleyItem> { protected EarleyItem(DottedRule dottedRule, int origin, IForestNode parseNode) { DottedRule = dottedRule; Origin = origin; ParseNode = parseNode; this.hashCode = (DottedRule, Origin).GetHashCode(); } public DottedRule DottedRule { get; } public int Origin { get; } public IForestNode ParseNode { get; protected set; } public NonTerminal LeftHandSide => DottedRule.Production.LeftHandSide; protected override object ThisHashCode => (DottedRule, Origin); public abstract bool Enqueue(EarleySet set); public override string ToString() { return $"{DottedRule}\t\t({Origin})"; } protected override bool ThisEquals(EarleyItem other) { return DottedRule.Equals(other.DottedRule) && Origin.Equals(other.Origin); } private readonly int hashCode; } }
28.075
86
0.633126
[ "MIT" ]
knutjelitto/Lingu
Pliant/libraries/Pliant/Charts/EarleyItem.cs
1,125
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.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.Azure.Backup { /// <summary> /// Manages an Azure Backup VM Backup Policy. /// /// &gt; This content is derived from https://github.com/terraform-providers/terraform-provider-azurerm/blob/master/website/docs/r/backup_policy_vm.html.markdown. /// </summary> public partial class PolicyVM : Pulumi.CustomResource { /// <summary> /// Configures the Policy backup frequency, times &amp; days as documented in the `backup` block below. /// </summary> [Output("backup")] public Output<Outputs.PolicyVMBackup> Backup { get; private set; } = null!; /// <summary> /// Specifies the name of the Backup Policy. Changing this forces a new resource to be created. /// </summary> [Output("name")] public Output<string> Name { get; private set; } = null!; /// <summary> /// Specifies the name of the Recovery Services Vault to use. Changing this forces a new resource to be created. /// </summary> [Output("recoveryVaultName")] public Output<string> RecoveryVaultName { get; private set; } = null!; /// <summary> /// The name of the resource group in which to create the policy. Changing this forces a new resource to be created. /// </summary> [Output("resourceGroupName")] public Output<string> ResourceGroupName { get; private set; } = null!; /// <summary> /// Configures the policy daily retention as documented in the `retention_daily` block below. Required when backup frequency is `Daily`. /// </summary> [Output("retentionDaily")] public Output<Outputs.PolicyVMRetentionDaily?> RetentionDaily { get; private set; } = null!; /// <summary> /// Configures the policy monthly retention as documented in the `retention_monthly` block below. /// </summary> [Output("retentionMonthly")] public Output<Outputs.PolicyVMRetentionMonthly?> RetentionMonthly { get; private set; } = null!; /// <summary> /// Configures the policy weekly retention as documented in the `retention_weekly` block below. Required when backup frequency is `Weekly`. /// </summary> [Output("retentionWeekly")] public Output<Outputs.PolicyVMRetentionWeekly?> RetentionWeekly { get; private set; } = null!; /// <summary> /// Configures the policy yearly retention as documented in the `retention_yearly` block below. /// </summary> [Output("retentionYearly")] public Output<Outputs.PolicyVMRetentionYearly?> RetentionYearly { get; private set; } = null!; /// <summary> /// A mapping of tags to assign to the resource. /// </summary> [Output("tags")] public Output<ImmutableDictionary<string, string>> Tags { get; private set; } = null!; /// <summary> /// Specifies the timezone. Defaults to `UTC` /// </summary> [Output("timezone")] public Output<string?> Timezone { get; private set; } = null!; /// <summary> /// Create a PolicyVM resource with the given unique name, arguments, and options. /// </summary> /// /// <param name="name">The unique name of the resource</param> /// <param name="args">The arguments used to populate this resource's properties</param> /// <param name="options">A bag of options that control this resource's behavior</param> public PolicyVM(string name, PolicyVMArgs args, CustomResourceOptions? options = null) : base("azure:backup/policyVM:PolicyVM", name, args ?? ResourceArgs.Empty, MakeResourceOptions(options, "")) { } private PolicyVM(string name, Input<string> id, PolicyVMState? state = null, CustomResourceOptions? options = null) : base("azure:backup/policyVM:PolicyVM", name, state, MakeResourceOptions(options, id)) { } private static CustomResourceOptions MakeResourceOptions(CustomResourceOptions? options, Input<string>? id) { var defaultOptions = new CustomResourceOptions { Version = Utilities.Version, }; var merged = CustomResourceOptions.Merge(defaultOptions, options); // Override the ID if one was specified for consistency with other language SDKs. merged.Id = id ?? merged.Id; return merged; } /// <summary> /// Get an existing PolicyVM resource's state with the given name, ID, and optional extra /// properties used to qualify the lookup. /// </summary> /// /// <param name="name">The unique name of the resulting resource.</param> /// <param name="id">The unique provider ID of the resource to lookup.</param> /// <param name="state">Any extra arguments used during the lookup.</param> /// <param name="options">A bag of options that control this resource's behavior</param> public static PolicyVM Get(string name, Input<string> id, PolicyVMState? state = null, CustomResourceOptions? options = null) { return new PolicyVM(name, id, state, options); } } public sealed class PolicyVMArgs : Pulumi.ResourceArgs { /// <summary> /// Configures the Policy backup frequency, times &amp; days as documented in the `backup` block below. /// </summary> [Input("backup", required: true)] public Input<Inputs.PolicyVMBackupArgs> Backup { get; set; } = null!; /// <summary> /// Specifies the name of the Backup Policy. Changing this forces a new resource to be created. /// </summary> [Input("name")] public Input<string>? Name { get; set; } /// <summary> /// Specifies the name of the Recovery Services Vault to use. Changing this forces a new resource to be created. /// </summary> [Input("recoveryVaultName", required: true)] public Input<string> RecoveryVaultName { get; set; } = null!; /// <summary> /// The name of the resource group in which to create the policy. Changing this forces a new resource to be created. /// </summary> [Input("resourceGroupName", required: true)] public Input<string> ResourceGroupName { get; set; } = null!; /// <summary> /// Configures the policy daily retention as documented in the `retention_daily` block below. Required when backup frequency is `Daily`. /// </summary> [Input("retentionDaily")] public Input<Inputs.PolicyVMRetentionDailyArgs>? RetentionDaily { get; set; } /// <summary> /// Configures the policy monthly retention as documented in the `retention_monthly` block below. /// </summary> [Input("retentionMonthly")] public Input<Inputs.PolicyVMRetentionMonthlyArgs>? RetentionMonthly { get; set; } /// <summary> /// Configures the policy weekly retention as documented in the `retention_weekly` block below. Required when backup frequency is `Weekly`. /// </summary> [Input("retentionWeekly")] public Input<Inputs.PolicyVMRetentionWeeklyArgs>? RetentionWeekly { get; set; } /// <summary> /// Configures the policy yearly retention as documented in the `retention_yearly` block below. /// </summary> [Input("retentionYearly")] public Input<Inputs.PolicyVMRetentionYearlyArgs>? RetentionYearly { get; set; } [Input("tags")] private InputMap<string>? _tags; /// <summary> /// A mapping of tags to assign to the resource. /// </summary> public InputMap<string> Tags { get => _tags ?? (_tags = new InputMap<string>()); set => _tags = value; } /// <summary> /// Specifies the timezone. Defaults to `UTC` /// </summary> [Input("timezone")] public Input<string>? Timezone { get; set; } public PolicyVMArgs() { } } public sealed class PolicyVMState : Pulumi.ResourceArgs { /// <summary> /// Configures the Policy backup frequency, times &amp; days as documented in the `backup` block below. /// </summary> [Input("backup")] public Input<Inputs.PolicyVMBackupGetArgs>? Backup { get; set; } /// <summary> /// Specifies the name of the Backup Policy. Changing this forces a new resource to be created. /// </summary> [Input("name")] public Input<string>? Name { get; set; } /// <summary> /// Specifies the name of the Recovery Services Vault to use. Changing this forces a new resource to be created. /// </summary> [Input("recoveryVaultName")] public Input<string>? RecoveryVaultName { get; set; } /// <summary> /// The name of the resource group in which to create the policy. Changing this forces a new resource to be created. /// </summary> [Input("resourceGroupName")] public Input<string>? ResourceGroupName { get; set; } /// <summary> /// Configures the policy daily retention as documented in the `retention_daily` block below. Required when backup frequency is `Daily`. /// </summary> [Input("retentionDaily")] public Input<Inputs.PolicyVMRetentionDailyGetArgs>? RetentionDaily { get; set; } /// <summary> /// Configures the policy monthly retention as documented in the `retention_monthly` block below. /// </summary> [Input("retentionMonthly")] public Input<Inputs.PolicyVMRetentionMonthlyGetArgs>? RetentionMonthly { get; set; } /// <summary> /// Configures the policy weekly retention as documented in the `retention_weekly` block below. Required when backup frequency is `Weekly`. /// </summary> [Input("retentionWeekly")] public Input<Inputs.PolicyVMRetentionWeeklyGetArgs>? RetentionWeekly { get; set; } /// <summary> /// Configures the policy yearly retention as documented in the `retention_yearly` block below. /// </summary> [Input("retentionYearly")] public Input<Inputs.PolicyVMRetentionYearlyGetArgs>? RetentionYearly { get; set; } [Input("tags")] private InputMap<string>? _tags; /// <summary> /// A mapping of tags to assign to the resource. /// </summary> public InputMap<string> Tags { get => _tags ?? (_tags = new InputMap<string>()); set => _tags = value; } /// <summary> /// Specifies the timezone. Defaults to `UTC` /// </summary> [Input("timezone")] public Input<string>? Timezone { get; set; } public PolicyVMState() { } } namespace Inputs { public sealed class PolicyVMBackupArgs : Pulumi.ResourceArgs { [Input("frequency", required: true)] public Input<string> Frequency { get; set; } = null!; [Input("time", required: true)] public Input<string> Time { get; set; } = null!; [Input("weekdays")] private InputList<string>? _weekdays; public InputList<string> Weekdays { get => _weekdays ?? (_weekdays = new InputList<string>()); set => _weekdays = value; } public PolicyVMBackupArgs() { } } public sealed class PolicyVMBackupGetArgs : Pulumi.ResourceArgs { [Input("frequency", required: true)] public Input<string> Frequency { get; set; } = null!; [Input("time", required: true)] public Input<string> Time { get; set; } = null!; [Input("weekdays")] private InputList<string>? _weekdays; public InputList<string> Weekdays { get => _weekdays ?? (_weekdays = new InputList<string>()); set => _weekdays = value; } public PolicyVMBackupGetArgs() { } } public sealed class PolicyVMRetentionDailyArgs : Pulumi.ResourceArgs { [Input("count", required: true)] public Input<int> Count { get; set; } = null!; public PolicyVMRetentionDailyArgs() { } } public sealed class PolicyVMRetentionDailyGetArgs : Pulumi.ResourceArgs { [Input("count", required: true)] public Input<int> Count { get; set; } = null!; public PolicyVMRetentionDailyGetArgs() { } } public sealed class PolicyVMRetentionMonthlyArgs : Pulumi.ResourceArgs { [Input("count", required: true)] public Input<int> Count { get; set; } = null!; [Input("weekdays", required: true)] private InputList<string>? _weekdays; public InputList<string> Weekdays { get => _weekdays ?? (_weekdays = new InputList<string>()); set => _weekdays = value; } [Input("weeks", required: true)] private InputList<string>? _weeks; public InputList<string> Weeks { get => _weeks ?? (_weeks = new InputList<string>()); set => _weeks = value; } public PolicyVMRetentionMonthlyArgs() { } } public sealed class PolicyVMRetentionMonthlyGetArgs : Pulumi.ResourceArgs { [Input("count", required: true)] public Input<int> Count { get; set; } = null!; [Input("weekdays", required: true)] private InputList<string>? _weekdays; public InputList<string> Weekdays { get => _weekdays ?? (_weekdays = new InputList<string>()); set => _weekdays = value; } [Input("weeks", required: true)] private InputList<string>? _weeks; public InputList<string> Weeks { get => _weeks ?? (_weeks = new InputList<string>()); set => _weeks = value; } public PolicyVMRetentionMonthlyGetArgs() { } } public sealed class PolicyVMRetentionWeeklyArgs : Pulumi.ResourceArgs { [Input("count", required: true)] public Input<int> Count { get; set; } = null!; [Input("weekdays", required: true)] private InputList<string>? _weekdays; public InputList<string> Weekdays { get => _weekdays ?? (_weekdays = new InputList<string>()); set => _weekdays = value; } public PolicyVMRetentionWeeklyArgs() { } } public sealed class PolicyVMRetentionWeeklyGetArgs : Pulumi.ResourceArgs { [Input("count", required: true)] public Input<int> Count { get; set; } = null!; [Input("weekdays", required: true)] private InputList<string>? _weekdays; public InputList<string> Weekdays { get => _weekdays ?? (_weekdays = new InputList<string>()); set => _weekdays = value; } public PolicyVMRetentionWeeklyGetArgs() { } } public sealed class PolicyVMRetentionYearlyArgs : Pulumi.ResourceArgs { [Input("count", required: true)] public Input<int> Count { get; set; } = null!; [Input("months", required: true)] private InputList<string>? _months; public InputList<string> Months { get => _months ?? (_months = new InputList<string>()); set => _months = value; } [Input("weekdays", required: true)] private InputList<string>? _weekdays; public InputList<string> Weekdays { get => _weekdays ?? (_weekdays = new InputList<string>()); set => _weekdays = value; } [Input("weeks", required: true)] private InputList<string>? _weeks; public InputList<string> Weeks { get => _weeks ?? (_weeks = new InputList<string>()); set => _weeks = value; } public PolicyVMRetentionYearlyArgs() { } } public sealed class PolicyVMRetentionYearlyGetArgs : Pulumi.ResourceArgs { [Input("count", required: true)] public Input<int> Count { get; set; } = null!; [Input("months", required: true)] private InputList<string>? _months; public InputList<string> Months { get => _months ?? (_months = new InputList<string>()); set => _months = value; } [Input("weekdays", required: true)] private InputList<string>? _weekdays; public InputList<string> Weekdays { get => _weekdays ?? (_weekdays = new InputList<string>()); set => _weekdays = value; } [Input("weeks", required: true)] private InputList<string>? _weeks; public InputList<string> Weeks { get => _weeks ?? (_weeks = new InputList<string>()); set => _weeks = value; } public PolicyVMRetentionYearlyGetArgs() { } } } namespace Outputs { [OutputType] public sealed class PolicyVMBackup { public readonly string Frequency; public readonly string Time; public readonly ImmutableArray<string> Weekdays; [OutputConstructor] private PolicyVMBackup( string frequency, string time, ImmutableArray<string> weekdays) { Frequency = frequency; Time = time; Weekdays = weekdays; } } [OutputType] public sealed class PolicyVMRetentionDaily { public readonly int Count; [OutputConstructor] private PolicyVMRetentionDaily(int count) { Count = count; } } [OutputType] public sealed class PolicyVMRetentionMonthly { public readonly int Count; public readonly ImmutableArray<string> Weekdays; public readonly ImmutableArray<string> Weeks; [OutputConstructor] private PolicyVMRetentionMonthly( int count, ImmutableArray<string> weekdays, ImmutableArray<string> weeks) { Count = count; Weekdays = weekdays; Weeks = weeks; } } [OutputType] public sealed class PolicyVMRetentionWeekly { public readonly int Count; public readonly ImmutableArray<string> Weekdays; [OutputConstructor] private PolicyVMRetentionWeekly( int count, ImmutableArray<string> weekdays) { Count = count; Weekdays = weekdays; } } [OutputType] public sealed class PolicyVMRetentionYearly { public readonly int Count; public readonly ImmutableArray<string> Months; public readonly ImmutableArray<string> Weekdays; public readonly ImmutableArray<string> Weeks; [OutputConstructor] private PolicyVMRetentionYearly( int count, ImmutableArray<string> months, ImmutableArray<string> weekdays, ImmutableArray<string> weeks) { Count = count; Months = months; Weekdays = weekdays; Weeks = weeks; } } } }
34.159794
166
0.590061
[ "ECL-2.0", "Apache-2.0" ]
apollo2030/pulumi-azure
sdk/dotnet/Backup/PolicyVM.cs
19,881
C#
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. #nullable enable namespace Microsoft.AspNetCore.Mvc.ModelBinding { /// <summary> /// A value provider which can filter its contents to remove keys rewritten compared to the request data. /// </summary> public interface IKeyRewriterValueProvider : IValueProvider { /// <summary> /// Filters the value provider to remove keys rewritten compared to the request data. /// </summary> /// <example> /// If the request contains values with keys <c>Model.Property</c> and <c>Collection[index]</c>, the returned /// <see cref="IValueProvider"/> will not match <c>Model[Property]</c> or <c>Collection.index</c>. /// </example> /// <returns> /// The filtered value provider or <see langref="null"/> if the value provider only contains rewritten keys. /// </returns> IValueProvider? Filter(); } }
41
117
0.653846
[ "Apache-2.0" ]
1175169074/aspnetcore
src/Mvc/Mvc.Core/src/ModelBinding/IKeyRewriterValueProvider.cs
1,066
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace openocd.CmsisDap { public static class DapAccessConsts { public const bool LOG_PACKET_BUILDS = false; // Get the connected USB devices public static List<IBackend> _get_interfaces() { if (DapSettings.use_ws) { throw new NotImplementedException(); //return pyDAPAccess.Interface.__init__.INTERFACE[pyDAPAccess.Interface.__init__.ws_backend].getAllConnectedInterface(DAPSettings.ws_host, DAPSettings.ws_port); } else { return DapAccessConfiguration.getAllConnectedInterface(); //return pyDAPAccess.Interface.__init__.INTERFACE[pyDAPAccess.Interface.__init__.usb_backend].getAllConnectedInterface(); } } // Get the unique id from an interface public static string _get_unique_id(IBackend anInterface) { return anInterface.getSerialNumber(); } } public static class DapSettings { public static readonly bool use_ws = false; public static readonly string ws_host = "localhost"; public static readonly UInt16 ws_port = 8081; public static readonly bool limit_packets = false; } }
30.711111
176
0.651954
[ "Apache-2.0" ]
heartacker/PyOCDportToDotNET
VK_pyOCD_Ported/CmsisDap/DapAccessConsts.cs
1,382
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.Azure.Storage.Inputs { public sealed class AccountCustomerManagedKeyGetArgs : Pulumi.ResourceArgs { /// <summary> /// The ID of the Key Vault Key, supplying a version-less key ID will enable auto-rotation of this key. /// </summary> [Input("keyVaultKeyId", required: true)] public Input<string> KeyVaultKeyId { get; set; } = null!; /// <summary> /// The ID of a user assigned identity. /// </summary> [Input("userAssignedIdentityId", required: true)] public Input<string> UserAssignedIdentityId { get; set; } = null!; public AccountCustomerManagedKeyGetArgs() { } } }
31.84375
111
0.654563
[ "ECL-2.0", "Apache-2.0" ]
henriktao/pulumi-azure
sdk/dotnet/Storage/Inputs/AccountCustomerManagedKeyGetArgs.cs
1,019
C#
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="ILanguageOutput.cs" company="DotnetScaffolder"> // MIT // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace DotNetScaffolder.Components.Common.Contract { /// <summary> /// The LanguageOutput interface. /// </summary> public interface ILanguageOutput { } }
34.666667
120
0.353846
[ "MIT" ]
laredoza/.NetScaffolder
src/Projects/Components/Common/Contract/ILanguageOutput.cs
522
C#
using System; using bv.common.Configuration; using bv.model.BLToolkit; using bv.model.Model.Core; using eidss.model.Core.Security; using eidss.model.Trace; namespace eidss.model.WcfService { public static class DataBaseChecker { private static readonly TraceHelper m_Trace = new TraceHelper(TraceHelper.ReportsCategory); private const string TraceTitle = @"Data Adapter"; public static void CheckDbConnection() { try { string dbName; using (DbManagerProxy dbManager = DbManagerFactory.Factory.Create(ModelUserContext.Instance)) { dbName = dbManager.Connection.Database; dbManager.SetCommand(@"select 1").ExecuteNonQuery(); } m_Trace.Trace(TraceTitle, "Database '{0}' connection checked.", dbName); } catch (Exception ex) { m_Trace.TraceError(ex); } } public static void Login() { var manager = new EidssSecurityManager(); int resultCode = manager.LogIn(BaseSettings.DefaultOrganization, BaseSettings.DefaultUser, BaseSettings.DefaultPassword); if (resultCode != 0) { string err = string.Format("Could not login under user {0} from organization {1}.", BaseSettings.DefaultUser, BaseSettings.DefaultOrganization); throw new ApplicationException(err); } m_Trace.Trace(TraceTitle, "EIDSS login successfully."); } public static void Logout() { var manager = new EidssSecurityManager(); manager.LogOut(); m_Trace.Trace(TraceTitle, "EIDSS logout successfully."); } } }
35.763636
110
0.545501
[ "BSD-2-Clause" ]
EIDSS/EIDSS-Legacy
EIDSS v6.1/eidss.core/WcfService/DataBaseChecker.cs
1,969
C#
using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; namespace Sikiro.Tookits.Helper { public static class ExpressionBuilder { /// <summary> /// 默认True条件 /// </summary> /// <typeparam name="T"></typeparam> /// <returns></returns> public static Expression<Func<T, bool>> Init<T>() { return expression => true; } public static Expression<Func<T, bool>> And<T>(this Expression<Func<T, bool>> first, Expression<Func<T, bool>> second) { return first.Compose(second, Expression.AndAlso); } public static Expression<Func<T, bool>> Or<T>(this Expression<Func<T, bool>> first, Expression<Func<T, bool>> second) { return first.Compose(second, Expression.OrElse); } private static Expression<T> Compose<T>(this Expression<T> first, Expression<T> second, Func<Expression, Expression, Expression> merge ) { var map = first.Parameters .Select((oldParam, index) => new { oldParam, newParam = second.Parameters[index] }) .ToDictionary(p => p.newParam, p => p.oldParam); var secondBody = ParameterRebinder.ReplaceParameters(map, second.Body); return Expression.Lambda<T>(merge(first.Body, secondBody), first.Parameters); } } internal class ParameterRebinder : ExpressionVisitor { readonly Dictionary<ParameterExpression, ParameterExpression> _parameterMap; ParameterRebinder(Dictionary<ParameterExpression, ParameterExpression> map) { _parameterMap = map ?? new Dictionary<ParameterExpression, ParameterExpression>(); } public static Expression ReplaceParameters(Dictionary<ParameterExpression, ParameterExpression> map, Expression newParameters) { return new ParameterRebinder(map).Visit(newParameters); } protected override Expression VisitParameter(ParameterExpression newParameters) { if (_parameterMap.TryGetValue(newParameters, out var replacement)) { newParameters = replacement; } return base.VisitParameter(newParameters); } } }
32.861111
108
0.615807
[ "MIT" ]
364988343/Sikiro.RBAC
src/Sikiro.Tookits/Helper/ExpressionBuilder.cs
2,376
C#
using System; //library using System.Collections; namespace TutorialCSharp //namespace { class Program //class { static void Main(string[] args) //method special, automatic run program on this Main method and call a statement { HashList(); HashListVar(); } static Hashtable hashtable = new Hashtable() { { "Me", "Fauzi" }, { 2, "Galih" }, }; static void HashList() { Console.WriteLine("Condition with foreach Dictionary type :"); foreach (DictionaryEntry hash in hashtable) { Console.WriteLine($"Key : {hash.Key}, Value : {hash.Value}"); } } static void HashListVar() { Console.WriteLine("\nCondition with foreach anonymous type :"); //Anonymous type -> var foreach(var hash in hashtable.Keys) { Console.WriteLine($"Key : {hash}, Value : {hashtable[hash]}"); } } } }
27.051282
120
0.519431
[ "MIT" ]
fauzigalih/TutorialCSharp
data/085 Hashtable Anonymous Type.cs
1,055
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 lex-models-2017-04-19.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.LexModelBuildingService.Model { /// <summary> /// Describes the resource that refers to the resource that you are attempting to delete. /// This object is returned as part of the <code>ResourceInUseException</code> exception. /// </summary> public partial class ResourceReference { private string _name; private string _version; /// <summary> /// Gets and sets the property Name. /// <para> /// The name of the resource that is using the resource that you are trying to delete. /// </para> /// </summary> [AWSProperty(Min=1, Max=100)] public string Name { get { return this._name; } set { this._name = value; } } // Check to see if Name property is set internal bool IsSetName() { return this._name != null; } /// <summary> /// Gets and sets the property Version. /// <para> /// The version of the resource that is using the resource that you are trying to delete. /// </para> /// </summary> [AWSProperty(Min=1, Max=64)] public string Version { get { return this._version; } set { this._version = value; } } // Check to see if Version property is set internal bool IsSetVersion() { return this._version != null; } } }
30.063291
108
0.619368
[ "Apache-2.0" ]
DetlefGolze/aws-sdk-net
sdk/src/Services/LexModelBuildingService/Generated/Model/ResourceReference.cs
2,375
C#
using System; using System.Diagnostics; using System.IO; using System.Runtime.InteropServices; using System.Text; namespace elb_utilities.Media { using DWORD = UInt32; using WORD = UInt16; public class WaveFile { private const DWORD ChunkID_Riff = 0x46464952; // FourCC('R', 'I', 'F', 'F'); private const DWORD RiffForm_Wave = 0x45564157; // FourCC('W', 'A', 'V', 'E'); private const DWORD ChunkID_Fmt = 0x20746d66; // FourCC('f', 'm', 't', ' '); private const DWORD ChunkID_Data = 0x61746164; // FourCC('d', 'a', 't', 'a'); //static DWORD FourCC(char a, char b, char c, char d) //{ // return (uint)(a << 0 | b << 8 | c << 16 | d << 24); //} [StructLayout(LayoutKind.Sequential, Pack = 1)] private struct RiffChunk { public uint ChunkID; public uint ChunkSize; } public enum WaveFormat : WORD { PCM = 0x0001 } [StructLayout(LayoutKind.Sequential, Pack = 1)] public struct PCMWaveFormat { public WaveFormat FormatTag; public WORD Channels; public DWORD SamplesPerSec; public DWORD AvgBytesPerSec; public WORD BlockAlign; public WORD BitsPerSample; } public PCMWaveFormat Format { get; } public byte[] SampleData { get; } private WaveFile(PCMWaveFormat format, byte[] sampleData) { Format = format; SampleData = sampleData; } public static WaveFile LoadFromFile(string path) { PCMWaveFormat format = default; byte[] sampleData = null; ref PCMWaveFormat foo = ref format; using (var reader = new BinaryReader(new FileStream(path, FileMode.Open, FileAccess.Read))) { while (reader.BaseStream.Position != reader.BaseStream.Length) { RiffChunk riffChunk = ReadRiffChunk(reader); switch (riffChunk.ChunkID) { case ChunkID_Riff: // read the RIFF form type to check we're loading a wave file uint formType = reader.ReadUInt32(); if (formType != RiffForm_Wave) { throw new InvalidDataException("RIFF form does not match 'WAVE'"); } break; case ChunkID_Fmt: format = reader.ReadStruct<PCMWaveFormat>(); if (format.FormatTag != WaveFormat.PCM) { throw new InvalidDataException("Format tag does not match WAVE_FORMAT_PCM (1)"); } // if the size of the header is larger than the struct then read the extended size and // skip that WORD extendedSize = 0; if (riffChunk.ChunkSize > Marshal.SizeOf<PCMWaveFormat>() && (extendedSize = reader.ReadUInt16()) > 0) { reader.BaseStream.Seek(extendedSize, SeekOrigin.Current); } break; case ChunkID_Data: sampleData = reader.ReadBytes((int)riffChunk.ChunkSize); break; default: // skip over this chunk if we don't recognise it Debug.WriteLine("Unrecognised chunk ID 0x{0:X2} '{1}'", riffChunk.ChunkID, Encoding.ASCII.GetString(BitConverter.GetBytes(riffChunk.ChunkID))); reader.BaseStream.Seek(riffChunk.ChunkSize, SeekOrigin.Current); break; } } } return new WaveFile(format, sampleData); } private static RiffChunk ReadRiffChunk(BinaryReader reader) { return reader.ReadStruct<RiffChunk>(); } } internal static class BinaryReaderExtensions { public static T ReadStruct<T>(this BinaryReader reader) where T : unmanaged { byte[] data = reader.ReadBytes(Marshal.SizeOf<T>()); var handle = GCHandle.Alloc(data, GCHandleType.Pinned); try { return Marshal.PtrToStructure<T>(handle.AddrOfPinnedObject()); } finally { handle.Free(); } } } }
35.058394
171
0.492609
[ "MIT" ]
eightlittlebits/elbsms
elb_utilities/Media/WaveFile.cs
4,805
C#
/** * @file ShaderReferenceOther.cs * @author Hongwei Li(taecg@qq.com) * @created 2018-12-30 * @updated 2020-03-09 * * @brief Shader中的其它语法 */ #if UNITY_EDITOR using System.Collections.Generic; using UnityEditor; using UnityEngine; namespace taecg.tools.shaderReference { public class ShaderReferenceOther : EditorWindow { #region 数据成员 private Vector2 scrollPos; #endregion public void DrawMainGUI () { scrollPos = EditorGUILayout.BeginScrollView (scrollPos); ShaderReferenceUtil.DrawTitle ("Other"); switch (ShaderReferenceEditorWindow.mPipline) { case ShaderReferenceEditorWindow.Pipline.BuildIn: ShaderReferenceUtil.DrawOneContent ("CGPROGRAM/ENDCG", "cg代码的开始与结束."); ShaderReferenceUtil.DrawOneContent ("CGINCLUDE/ENDCG", "通常用于定义多段vert/frag函数,然后这段CG代码会插入到所有Pass的CG中,根据当前Pass的设置来选择加载."); break; case ShaderReferenceEditorWindow.Pipline.URP: ShaderReferenceUtil.DrawOneContent ("include", "#include \"Packages/com.unity.render-pipelines.core/ShaderLibrary/Color.hlsl\"\n" + "#include \"Packages/com.unity.render-pipelines.universal/ShaderLibrary/Core.hlsl\"\n" + "#include \"Packages/com.unity.render-pipelines.universal/ShaderLibrary/Lighting.hlsl\"\n" + "#include \"Packages/com.unity.render-pipelines.universal/ShaderLibrary/ShaderGraphFunctions.hlsl\""); ShaderReferenceUtil.DrawOneContent ("CBUFFER_START(UnityPerMaterial)/CBUFFER_END", "将材质属性面板中的变量定义在这个常量缓冲区中,用于支持SRP Batcher."); ShaderReferenceUtil.DrawOneContent ("HLSLPROGRAM/ENDHLSL", "HLSL代码的开始与结束."); ShaderReferenceUtil.DrawOneContent ("HLSLINCLUDE/ENDHLSL", "通常用于定义多段vert/frag函数,然后这段CG代码会插入到所有Pass的CG中,根据当前Pass的设置来选择加载."); break; } ShaderReferenceUtil.DrawOneContent ("Category{}", "定义一组所有SubShader共享的命令,位于SubShader外面。\n"); ShaderReferenceUtil.DrawOneContent ("LOD", "Shader LOD,可利用脚本来控制LOD级别,通常用于不同配置显示不同的SubShader。"); ShaderReferenceUtil.DrawOneContent ("Fallback \"name\"", "备胎,当Shader中没有任何SubShader可执行时,则执行FallBack。默认值为Off,表示没有备胎。\n示例:FallBack \"Diffuse\""); ShaderReferenceUtil.DrawOneContent ("CustomEditor \"name\"", "自定义材质面板,name为自定义的脚本名称。可利用此功能对材质面板进行个性化自定义。"); ShaderReferenceUtil.DrawOneContent ("Name \"MyPassName\"", "给当前Pass指定名称,以便利用UsePass进行调用。"); ShaderReferenceUtil.DrawOneContent ("UsePass \"Shader/NAME\"", "调用其它Shader中的Pass,注意Pass的名称要全部大写!Shader的路径也要写全,以便能找到具体是哪个Shader的哪个Pass。另外加了UsePass后,也要注意相应的Properties要自行添加。"); ShaderReferenceUtil.DrawOneContent ("GrabPass", "GrabPass{} 抓取当前屏幕存储到_GrabTexture中,每个有此命令的Shader都会每帧执行。\nGrabPass { \"TextureName\" } 抓取当前屏幕存储到自定义的TextureName中,每帧中只有第一个拥有此命令的Shader执行一次。\nGrabPass也支持Name与Tags。"); EditorGUILayout.EndScrollView (); } } } #endif
56.035714
224
0.667304
[ "Apache-2.0" ]
741645596/GameTool
Assets/taecgLibrary/ShaderReference/Editor/ShaderReferenceOther.cs
3,902
C#
using System; namespace Interledger.Net.ILP.Routing { public interface IRoute { ILiquidityCurve Curve { get; } string[] Hops { get; } string SourceLedger { get; } string NextLedger { get; } string DestinationLedger { get; } string TargetPrefix { get; } int MinMessageWindow { get; } DateTime? ExpiresAt { get; set; } object AdditionalInfo { get; } bool IsLocal { get; set; } string SourceAccount { get; } string DestinationAccount { get; } double[][] GetPoints { get; } int DestinationPrecision { get; set; } int DestinationScale { get; set; } double AmountAt(double x); double AmountReverse(double x); IRoute Combine(IRoute alternateRoute); IRoute Join(IRoute tailRoute, TimeSpan expiryDuration); IRoute ShiftY(double dy); IRoute Simplify(int maxPoints); bool IsExpired(DateTime now); string ToJSON(); void BumpExpiration(TimeSpan holdDownTime); } }
33
63
0.607008
[ "MIT" ]
robtyers/Interledger.net
ILP.Routing/IRoute.cs
1,058
C#
namespace GuideEnricher.Tests { using System; using System.Collections.Generic; using Config; using EpisodeMatchMethods; using tvdb; using log4net.Config; using Should; using System.Globalization; using Xunit; using System.Reflection; using System.IO; /// <summary> /// Use this class to test actual episodes against TVDB /// This is useful to test if a series will be matched correctly given a configuration /// </summary> /// These tests are being ignored for now as TVDB is not always responding and slowing down tests /// It's bad practice anyways ;) public class TVDBLibEnrichTest { private List<TestProgram> testPrograms; public TVDBLibEnrichTest() { BasicConfigurator.Configure(); } private void CreateTestData() { this.testPrograms = new List<TestProgram>(); // this.testPrograms.Add(new TestProgram("House", "the fix (153)", 153, "S07E21")); // this.testPrograms.Add(new TestProgram("Chuck", "Chuck versus the last details (83)", 83, "S05E05")); // this.testPrograms.Add(new TestProgram("Family Guy", "Brian sings and swings (70)", 70, "S04E19")); // this.testPrograms.Add(new TestProgram("Family Guy", "Deep Throats", 74, "S04E23")); // this.testPrograms.Add(new TestProgram("The Big Bang Theory", "The Zazzy Substitution", 0, "S04E03")); // this.testPrograms.Add(new TestProgram("Castle", "Pretty Dead (59)", 59, "S03E23")); this.testPrograms.Add(new TestProgram("Shark Tank", "Episode 2", 202, "S02E02")); } [Fact] public void SeriesWithPunctuationsAreMatchedCorrectly() { var matchMethods = new List<IEpisodeMatchMethod>(); var tvDbService = new TvDbService("tvdbCache", Config.Instance.ApiKey); var tvdbLib = new TvdbLibAccess(Config.Instance, matchMethods, tvDbService); var seriesID = tvdbLib.getSeriesId("American Dad"); seriesID.ShouldEqual(73141); } [Fact] public void TestEnricherMethods() { var tvDbService = new TvDbService(Config.Instance.CacheFolder, Config.Instance.ApiKey); var enricher = new TvdbLibAccess(Config.Instance, EpisodeMatchMethodLoader.GetMatchMethods(), tvDbService); this.CreateTestData(); bool pass = true; foreach (var testProgram in this.testPrograms) { try { var series = enricher.GetTvdbSeries(enricher.getSeriesId(testProgram.Title), false); enricher.EnrichProgram(testProgram, series); if (testProgram.EpisodeNumberDisplay == testProgram.ExpectedEpisodeNumberDisplay) { Console.WriteLine(string.Format(CultureInfo.CurrentCulture, "Correctly matched {0} - {1}", testProgram.Title, testProgram.EpisodeNumberDisplay)); } else { Console.WriteLine(string.Format(CultureInfo.CurrentCulture, "Unable to match {0} - {1}", testProgram.Title, testProgram.SubTitle)); pass = false; } } catch (Exception exception) { pass = false; Console.WriteLine(string.Format(CultureInfo.CurrentCulture, "Couldn't match {0} - {1}", testProgram.Title, testProgram.SubTitle)); Console.WriteLine(exception.Message); } } // Assert.True(pass, "Test failed!"); } [Fact] public void TestMappingNameWithID() { var lawOrderProgram = new TestProgram("Law & Order: Special Victims Unit", "Identity", 0, "S06E12"); var seriesNameMap = new Dictionary<string, string>(1); seriesNameMap.Add("Law & Order: Special Victims Unit", "id=75692"); var mockConfig = new Moq.Mock<IConfiguration>(); mockConfig.Setup(x => x.getSeriesNameMap()).Returns(seriesNameMap); var tvDbApi = new TvDbService(GetWorkingDirectory(), Config.Instance.ApiKey); var enricher = new TvdbLibAccess(mockConfig.Object, EpisodeMatchMethodLoader.GetMatchMethods(), tvDbApi); var series = enricher.GetTvdbSeries(enricher.getSeriesId(lawOrderProgram.Title), false); enricher.EnrichProgram(lawOrderProgram, series); Assert.True(lawOrderProgram.EpisodeIsEnriched()); } [Fact] public void TestMappingRegex() { var lawOrderProgram = new TestProgram("Stargate Atlantis123", "Common Ground", 0, "S03E07"); var seriesNameMap = new Dictionary<string, string>(1); seriesNameMap.Add("regex=Stargate Atl.*", "Stargate Atlantis"); var mockConfig = new Moq.Mock<IConfiguration>(); mockConfig.Setup(x => x.getSeriesNameMap()).Returns(seriesNameMap); var tvDbApi = new TvDbService(GetWorkingDirectory(), Config.Instance.ApiKey); var enricher = new TvdbLibAccess(mockConfig.Object, EpisodeMatchMethodLoader.GetMatchMethods(), tvDbApi); var series = enricher.GetTvdbSeries(enricher.getSeriesId(lawOrderProgram.Title), false); enricher.EnrichProgram(lawOrderProgram, series); Assert.True(lawOrderProgram.EpisodeIsEnriched()); } [Fact] public void TestRegularMapping() { var lawOrderProgram = new TestProgram("Stargate Atlantis123", "Common Ground", 0, "S03E07"); var seriesNameMap = new Dictionary<string, string>(1); seriesNameMap.Add("Stargate Atlantis123", "Stargate Atlantis"); var mockConfig = new Moq.Mock<IConfiguration>(); mockConfig.Setup(x => x.getSeriesNameMap()).Returns(seriesNameMap); // var tvDbApi = new TvDbService(GetWorkingDirectory(), Config.Instance.ApiKey); var enricher = new TvdbLibAccess(mockConfig.Object, EpisodeMatchMethodLoader.GetMatchMethods(), tvDbApi); var series = enricher.GetTvdbSeries(enricher.getSeriesId(lawOrderProgram.Title), false); enricher.EnrichProgram(lawOrderProgram, series); Assert.True(lawOrderProgram.EpisodeIsEnriched()); } private static string GetWorkingDirectory() { var codeBaseUrl = new Uri(Assembly.GetExecutingAssembly().CodeBase); var codeBasePath = Uri.UnescapeDataString(codeBaseUrl.AbsolutePath); var dirPath = Path.GetDirectoryName(codeBasePath); return dirPath; } [Fact] public void TestAgathaChristiesMarple() { // Arrange var program = new TestProgram("Agatha Christie's Marple", "Murder at the Vicarage", 0, "S01E02"); var seriesNameMap = new Dictionary<string, string>(1); seriesNameMap.Add("Agatha Christie's Marple", "id=78895"); var mockConfig = new Moq.Mock<IConfiguration>(); mockConfig.Setup(x => x.getSeriesNameMap()).Returns(seriesNameMap); mockConfig.Setup(x => x.UpdateMatchedEpisodes).Returns(true); mockConfig.Setup(x => x.UpdateSubtitlesParameter).Returns(true); var tvDbApi = new TvDbService(GetWorkingDirectory(), Config.Instance.ApiKey); var enricher = new TvdbLibAccess(mockConfig.Object, EpisodeMatchMethodLoader.GetMatchMethods(), tvDbApi); var series = enricher.GetTvdbSeries(enricher.getSeriesId(program.Title), false); // Act enricher.EnrichProgram(program, series); // Assert program.Assert(); } [Fact] public void TestBlueBloods() { // Arrange var program = new TestProgram("Blue Bloods", "Through the Looking Glass", 0, "S05E19"); var seriesNameMap = new Dictionary<string, string>(1); seriesNameMap.Add("Blue Bloods", "id=164981"); var mockConfig = new Moq.Mock<IConfiguration>(); mockConfig.Setup(x => x.getSeriesNameMap()).Returns(seriesNameMap); mockConfig.Setup(x => x.UpdateMatchedEpisodes).Returns(true); mockConfig.Setup(x => x.UpdateSubtitlesParameter).Returns(true); mockConfig.Setup(x => x.GetProperty(Moq.It.Is<string>((c) => c == "TvDbLanguage"))).Returns("en"); var tvDbApi = new TvDbService(GetWorkingDirectory(), Config.Instance.ApiKey); var enricher = new TvdbLibAccess(mockConfig.Object, EpisodeMatchMethodLoader.GetMatchMethods(), tvDbApi); var series = enricher.GetTvdbSeries(enricher.getSeriesId(program.Title), false); // Act enricher.EnrichProgram(program, series); // Assert program.Assert(); } [Fact] public void TestBlackSails() { // Arrange var program = new TestProgram("Black Sails", "XVIII.", 0, "S02E10"); var seriesNameMap = new Dictionary<string, string>(1); //seriesNameMap.Add("Blue Bloods", "id=164981"); var mockConfig = new Moq.Mock<IConfiguration>(); mockConfig.Setup(x => x.getSeriesNameMap()).Returns(seriesNameMap); mockConfig.Setup(x => x.UpdateMatchedEpisodes).Returns(true); mockConfig.Setup(x => x.UpdateSubtitlesParameter).Returns(true); mockConfig.Setup(x => x.GetProperty(Moq.It.Is<string>((c) => c == "TvDbLanguage"))).Returns("en"); var tvDbApi = new TvDbService(GetWorkingDirectory(), Config.Instance.ApiKey); var enricher = new TvdbLibAccess(mockConfig.Object, EpisodeMatchMethodLoader.GetMatchMethods(), tvDbApi); var series = enricher.GetTvdbSeries(enricher.getSeriesId(program.Title), false); // Act enricher.EnrichProgram(program, series); // Assert program.Assert(); } } }
48.526066
169
0.611192
[ "Apache-2.0" ]
ChrisRichner/ARGUS-TV-GuideEnhancer
GuideEnricher.Tests/TVDBLibEnrichTest.cs
10,241
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("PureDev")] [assembly: AssemblyProduct("OauthProvidersCore")] [assembly: AssemblyTrademark("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("34115c4b-8941-4074-8928-85046ca75b99")]
41.75
84
0.785629
[ "MIT" ]
yhnavein/PureDev.OAuth
src/PureDev.OAuth/Properties/AssemblyInfo.cs
837
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using Newtonsoft.Json; namespace BSOA.Json.Converters { public static class JsonToString { public static string Read<TRoot>(JsonReader reader, TRoot root) { return Read(reader); } public static string Read(JsonReader reader) { // Handle null, strings, and DateTime -> string return reader.Value?.ToString(); } public static void Write(JsonWriter writer, string propertyName, string item, string defaultValue = default, bool required = false) { if (required || item != defaultValue) { writer.WritePropertyName(propertyName); writer.WriteValue(item); } } public static void Write(JsonWriter writer, string item) { writer.WriteValue(item); } } }
26.888889
139
0.586777
[ "MIT" ]
microsoft/bion
csharp/BSOA/BSOA.Json/Converters/JsonToString.cs
968
C#
namespace UnityExplorer.CSConsole.Lexers { public class NumberLexer : Lexer { // Maroon protected override Color HighlightColor => new(0.58f, 0.33f, 0.33f, 1.0f); private bool IsNumeric(char c) => char.IsNumber(c) || c == '.'; public override bool TryMatchCurrent(LexerBuilder lexer) { // previous character must be whitespace or delimiter if (!lexer.IsDelimiter(lexer.Previous, true)) return false; if (!IsNumeric(lexer.Current)) return false; while (!lexer.EndOfInput) { lexer.Commit(); if (!IsNumeric(lexer.PeekNext())) break; } return true; } } }
25.354839
82
0.517812
[ "MIT" ]
sinai-dev/Explorer
src/CSConsole/Lexers/NumberLexer.cs
788
C#
namespace IngameScript { public struct RotationSpeed { /// <summary> /// Target time step is 10 ticks, or 1/6th of a second. /// </summary> public const float TimeStepSeconds = 1f/6f; /// <summary> /// Affects actual angular acceleration, depending on remaining rotation distance. /// </summary> public float SpringConstant { get; set; } /// <summary> /// Intended limit on total rotation time. /// </summary> public float TimeTargetSeconds { get; set; } public override string ToString() => $"Spring: {SpringConstant} Time: {TimeTargetSeconds} sec"; } }
33.095238
106
0.572662
[ "Unlicense" ]
alex-davidson/SEScriptDev
Script.Hephaestus.Thrusters/RotationSpeed.cs
697
C#
using RR.Distribuidora.Application.Interfaces; using RR.Distribuidora.Application.ViewModels; using System.Collections.Generic; using System.Web.Http; namespace RR.Distribuidora.WebAPI.Controllers { [RoutePrefix("api/fornecedores-regioes")] public class FornecedorRegiaoController : ApiController { private readonly IFornecedorRegiaoApplicationService fornecedorRegiaoApplicationService; public FornecedorRegiaoController(IFornecedorRegiaoApplicationService fornecedorRegiaoApplicationService) { this.fornecedorRegiaoApplicationService = fornecedorRegiaoApplicationService; } [HttpPost] [Route("criar")] public FornecedorRegiaoViewModel Criar(FornecedorRegiaoViewModel fornecedorRegiaoViewModel) { return fornecedorRegiaoApplicationService.Criar(fornecedorRegiaoViewModel); } [HttpDelete] [Route("deletar/{idFornecedorRegiao}")] public void Deletar(int idFornecedorRegiao) { fornecedorRegiaoApplicationService.Deletar(idFornecedorRegiao); } [HttpGet] [Route("buscar/{idFornecedorRegiao}")] public FornecedorRegiaoViewModel BuscarPorId(int idFornecedorRegiao) { return fornecedorRegiaoApplicationService.BuscarPorId(idFornecedorRegiao); } [HttpGet] [Route("buscar")] public IEnumerable<FornecedorRegiaoViewModel> BuscarTodos() { return fornecedorRegiaoApplicationService.BuscarTodos(); } } }
34.021739
113
0.709904
[ "MIT" ]
ricardorinco/Distribuidora.Backend
src/RR.Distribuidora.WebAPI/Controllers/FornecedorRegiaoController.cs
1,567
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; using vizsgaremek_gyak.Pages; using vizsgaremek_gyak.ViewModels; using vizsgaremek_gyak.Views.Navigation; namespace vizsgaremek_gyak.Views.Pages { /// <summary> /// Interaction logic for ProgramVersion.xaml /// </summary> public partial class ProgramInfo : UserControl { ProgramInfoViewModel programVersionViewModel; public ProgramInfo() { InitializeComponent(); programVersionViewModel = new ProgramInfoViewModel(); this.DataContext = programVersionViewModel; } // Vissza ikonra kattintva visszatér a nyitóoldalra private void Image_PreviewMouseLeftButtonUp(object sender, MouseButtonEventArgs e) { WelcomePage welcomePage = new WelcomePage(); // Statikus osztály ezért az osztály nevét írjuk Navigate.Navigation(welcomePage); } private void btAuthors_Click(object sender, RoutedEventArgs e) { txtAuthors.Text = programVersionViewModel.Authors; } } }
29.285714
90
0.708711
[ "CC0-1.0" ]
2021-2022-vizsgaremek-nappali-14b-gyak/vizsgaremek-gyakrolas-racz-nikoletta
vizsgaremek_gyak/Views/Pages/ProgramInfo.xaml.cs
1,444
C#
namespace Genocs.MicroserviceLight.Template.WebApi.Filters { using Microsoft.OpenApi.Models; using Swashbuckle.AspNetCore.SwaggerGen; using System; using System.Collections.Generic; using System.Linq; public class SwaggerDocumentFilter : IDocumentFilter { private readonly List<OpenApiTag> _tags = new List<OpenApiTag> { new OpenApiTag { Name = "RoutingApi", Description = "This is a description for the api routes" } }; public void Apply(OpenApiDocument swaggerDoc, DocumentFilterContext context) { if (swaggerDoc == null) { throw new ArgumentNullException(nameof(swaggerDoc)); } swaggerDoc.Tags = GetFilteredTagDefinitions(context); swaggerDoc.Paths = GetSortedPaths(swaggerDoc); } private List<OpenApiTag> GetFilteredTagDefinitions(DocumentFilterContext context) { //Filtering ensures route for tag is present var currentGroupNames = context.ApiDescriptions .Select(description => description.GroupName); return _tags.Where(tag => currentGroupNames.Contains(tag.Name)) .ToList(); } private OpenApiPaths GetSortedPaths( OpenApiDocument swaggerDoc) { IDictionary<string, OpenApiPathItem> dic = swaggerDoc.Paths.OrderBy(pair => pair.Key) .ToDictionary(pair => pair.Key, pair => pair.Value); return null; } } }
32.16
97
0.604478
[ "MIT" ]
Genocs/clean-architecture-template
src/template/src/Genocs.MicroserviceLight.Template.WebApi/Filters/SwaggerDocumentFilter.cs
1,608
C#
using Substrate.Nbt; using System; using System.IO; namespace NBTModel.Interop { public class NbtClipboardData { public NbtClipboardData(string name, TagNode node) { Name = name; Node = node; } public string Name { get; set; } public TagNode Node { get; set; } public static byte[] SerializeNode(TagNode node) { var root = new TagNodeCompound(); root.Add("root", node); var tree = new NbtTree(root); using (var ms = new MemoryStream()) { tree.WriteTo(ms); var data = new byte[ms.Length]; Array.Copy(ms.GetBuffer(), data, ms.Length); return data; } } public static TagNode DeserializeNode(byte[] data) { var tree = new NbtTree(); using (var ms = new MemoryStream(data)) { tree.ReadFrom(ms); } var root = tree.Root; if (root == null || !root.ContainsKey("root")) return null; return root["root"]; } } }
23.72
60
0.479764
[ "MIT" ]
DalekCraft2/NBTExplorer
NBTModel/Interop/NbtClipboardData.cs
1,188
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace MvcSolution { public interface ISimpleEntity { Guid Id { get; set; } string Name { get; set; } } public class SimpleEntity : ISimpleEntity { public Guid Id { get; set; } public string Name { get; set; } public SimpleEntity() { } public SimpleEntity(Guid id, string name) { this.Id = id; this.Name = name; } } }
18.21875
49
0.54717
[ "MIT" ]
Davivd659/mvcsolution
MvcSolution.Infrastructure/Core/SimpleEntity.cs
585
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Xpto.Domain.DTO; using Xpto.Domain.Interfaces.Service; namespace Xpto.Application.Controllers { [Route("api/[controller]")] public class KnownRoutesController : ControllerBase { private IKnownRouteService _knownRouteService; public KnownRoutesController(IKnownRouteService knownRouteService) { _knownRouteService = knownRouteService; } // GET api/route [HttpGet] /// <summary> /// Fetch all map points from the database /// </summary> /// <returns>List of routes</returns> public async Task<ActionResult<List<KnownRouteDTO>>> Get() { var routes = await _knownRouteService.GetAllFullAsync(); if (routes.Count() == 0) return NoContent(); var routesDTO = new List<KnownRouteDTO>(); foreach (var route in routes) routesDTO.Add(new KnownRouteDTO(route)); return Ok(routesDTO); } // api/mappoints/000000000-0000-0000-0000-000000000000 [HttpGet("{routeId}")] public async Task<ActionResult<RouteDTO>> Get(Guid routeId) { var route = await _knownRouteService.GetByIdAsync(routeId); if (route == null) return NotFound("MapPoint not found."); return Ok(new KnownRouteDTO(route)); } [HttpGet("{mapPoint1Id}/{mapPoint2Id}")] public async Task<ActionResult<KnownRouteDTO>> CalculateRoute(Guid mapPoint1Id, Guid mapPoint2Id) { var knownRoute = await _knownRouteService.FindBestRouteAsync(mapPoint1Id, mapPoint2Id); if (knownRoute == null) return NotFound("There's no possible route using the provided points."); return new KnownRouteDTO(knownRoute); } } }
30.6
105
0.621418
[ "MIT" ]
nGoline/xpto-delivery
Xpto.Application/Controllers/KnownRoutesController.cs
1,989
C#
using System.Threading.Tasks; using Kentico.Kontent.Management.Models.Shared; using Kentico.Kontent.Management.Models.Types.Elements; using Kentico.Kontent.Management.Models.Types; using Kentico.Kontent.Boilerplate.Sample.Boilerplate.Migrations; namespace Kentico.Kontent.Management.Sample.Boilerplate.Migrations { public class SampleCreateAuthorType : IMigrationModule { public int Order => 3; public async Task RunAsync(ManagementClient client) { var contentGroupExternalId = "personal_details"; var response = await client.CreateContentTypeAsync(new ContentTypeCreateModel { Name = "Author", Codename = Constants.AUTHOR_TYPE_CODENAME, Elements = new[] { new TextElementMetadataModel { Name = "Name", Codename = "name", ContentGroup = Reference.ByExternalId(contentGroupExternalId) }, new TextElementMetadataModel { Name = "Twitter handle", Codename = "twitter_handle", ContentGroup = Reference.ByExternalId(contentGroupExternalId) } }, ContentGroups = new[] { new ContentGroupModel { Name = "Personal details", ExternalId = contentGroupExternalId } } }); System.Console.Out.WriteLine($"Contenty type with {response.Id} was created"); } } }
35.2
90
0.522159
[ "MIT" ]
Simply007/kontent-migrations-boilerplate-net
Migrations/03_SampleCreateAuthorType.cs
1,760
C#
// Copyright Bastian Eicher // Licensed under the MIT License using System.Runtime.CompilerServices; using System.Runtime.Versioning; using Mono.Unix; using Mono.Unix.Native; using NanoByte.Common.Streams; #if !NET20 && !NET40 && !NET using System.Runtime.InteropServices; #endif namespace NanoByte.Common.Native { /// <summary> /// Provides helper methods for Unix-specific features of the Mono library. /// </summary> /// <remarks> /// This class has a dependency on <c>Mono.Posix</c>. /// Make sure to check <see cref="IsUnix"/> before calling any methods in this class to avoid exceptions. /// </remarks> [SupportedOSPlatform("linux"), SupportedOSPlatform("freebsd"), SupportedOSPlatform("macos")] public static class UnixUtils { #region OS /// <summary> /// <c>true</c> if the current operating system is a Unixoid system (e.g. Linux or MacOS X). /// </summary> [SupportedOSPlatformGuard("linux"), SupportedOSPlatformGuard("freebsd"), SupportedOSPlatformGuard("macos")] public static bool IsUnix #if NET => OperatingSystem.IsLinux() || OperatingSystem.IsFreeBSD() || OperatingSystem.IsMacOS(); #elif NET20 || NET40 => Environment.OSVersion.Platform is PlatformID.Unix or PlatformID.MacOSX or (PlatformID)128; #else => RuntimeInformation.IsOSPlatform(OSPlatform.Linux) || RuntimeInformation.IsOSPlatform(OSPlatform.OSX); #endif /// <summary> /// <c>true</c> if the current operating system is MacOS X. /// </summary> [SupportedOSPlatformGuard("macos")] public static bool IsMacOSX #if NET => OperatingSystem.IsMacOS(); #elif NET20 || NET40 => IsUnix && OSName == "Darwin"; #else => RuntimeInformation.IsOSPlatform(OSPlatform.OSX); #endif /// <summary> /// <c>true</c> if there is an X Server running or the current operating system is MacOS X. /// </summary> [SupportedOSPlatformGuard("linux"), SupportedOSPlatformGuard("freebsd"), SupportedOSPlatformGuard("macos")] public static bool HasGui => IsUnix && !string.IsNullOrEmpty(Environment.GetEnvironmentVariable("DISPLAY")) || IsMacOSX; /// <summary> /// The operating system name as reported by the "uname" system call. /// </summary> public static string OSName { [MethodImpl(MethodImplOptions.NoInlining)] get { Syscall.uname(out var buffer); return buffer.sysname; } } /// <summary> /// The CPU type as reported by the "uname" system call (after applying some normalization). /// </summary> public static string CpuType { [MethodImpl(MethodImplOptions.NoInlining)] get { Syscall.uname(out var buffer); string cpuType = buffer.machine; // Normalize names return cpuType switch { "x86" => "i386", "amd64" => "x86_64", "Power Macintosh" => "ppc", "i86pc" => "i686", _ => cpuType }; } } #endregion #region Links /// <summary> /// Creates a new Unix symbolic link to a file or directory. /// </summary> /// <param name="sourcePath">The path of the link to create.</param> /// <param name="targetPath">The path of the existing file or directory to point to (relative to <paramref name="sourcePath"/>).</param> /// <exception cref="InvalidOperationException">The underlying Unix subsystem failed to process the request (e.g. because of insufficient rights).</exception> /// <exception cref="UnixIOException">The underlying Unix subsystem failed to process the request (e.g. because of insufficient rights).</exception> [MethodImpl(MethodImplOptions.NoInlining)] public static void CreateSymlink([Localizable(false)] string sourcePath, [Localizable(false)] string targetPath) => new UnixSymbolicLinkInfo(sourcePath ?? throw new ArgumentNullException(nameof(sourcePath))) .CreateSymbolicLinkTo(targetPath ?? throw new ArgumentNullException(nameof(targetPath))); /// <summary> /// Creates a new Unix hard link between two files. /// </summary> /// <param name="sourcePath">The path of the link to create.</param> /// <param name="targetPath">The absolute path of the existing file to point to.</param> /// <exception cref="InvalidOperationException">The underlying Unix subsystem failed to process the request (e.g. because of insufficient rights).</exception> /// <exception cref="UnixIOException">The underlying Unix subsystem failed to process the request (e.g. because of insufficient rights).</exception> [MethodImpl(MethodImplOptions.NoInlining)] public static void CreateHardlink([Localizable(false)] string sourcePath, [Localizable(false)] string targetPath) => new UnixFileInfo(targetPath ?? throw new ArgumentNullException(nameof(targetPath))) .CreateLink(sourcePath ?? throw new ArgumentNullException(nameof(sourcePath))); /// <summary> /// Returns the Inode ID of a file. /// </summary> /// <param name="path">The path of the file.</param> /// <exception cref="InvalidOperationException">The underlying Unix subsystem failed to process the request (e.g. because of insufficient rights).</exception> /// <exception cref="UnixIOException">The underlying Unix subsystem failed to process the request (e.g. because of insufficient rights).</exception> [MethodImpl(MethodImplOptions.NoInlining)] public static long GetInode([Localizable(false)] string path) => UnixFileSystemInfo.GetFileSystemEntry(path ?? throw new ArgumentNullException(nameof(path))).Inode; /// <summary> /// Renames a file. Atomically replaces the destination if present. /// </summary> /// <param name="source">The path of the file to rename.</param> /// <param name="destination">The new path of the file. Must reside on the same file system as <paramref name="source"/>.</param> /// <exception cref="UnixIOException">The underlying Unix subsystem failed to process the request (e.g. because of insufficient rights).</exception> [MethodImpl(MethodImplOptions.NoInlining)] public static void Rename([Localizable(false)] string source, [Localizable(false)] string destination) { if (Stdlib.rename( source ?? throw new ArgumentNullException(nameof(source)), destination ?? throw new ArgumentNullException(nameof(destination))) != 0) throw new UnixIOException(Stdlib.GetLastError()); } #endregion #region File type /// <summary> /// Checks whether a file is a regular file (i.e. not a device file, symbolic link, etc.). /// </summary> /// <returns><c>true</c> if <paramref name="path"/> points to a regular file; <c>false</c> otherwise.</returns> /// <remarks>Will return <c>false</c> for non-existing files.</remarks> /// <exception cref="InvalidOperationException">The underlying Unix subsystem failed to process the request (e.g. because of insufficient rights).</exception> /// <exception cref="UnixIOException">The underlying Unix subsystem failed to process the request (e.g. because of insufficient rights).</exception> public static bool IsRegularFile([Localizable(false)] string path) => UnixFileSystemInfo.GetFileSystemEntry(path ?? throw new ArgumentNullException(nameof(path))).IsRegularFile; /// <summary> /// Checks whether a file is a Unix symbolic link. /// </summary> /// <param name="path">The path of the file to check.</param> /// <returns><c>true</c> if <paramref name="path"/> points to a symbolic link; <c>false</c> otherwise.</returns> /// <remarks>Will return <c>false</c> for non-existing files.</remarks> /// <exception cref="InvalidOperationException">The underlying Unix subsystem failed to process the request (e.g. because of insufficient rights).</exception> /// <exception cref="UnixIOException">The underlying Unix subsystem failed to process the request (e.g. because of insufficient rights).</exception> public static bool IsSymlink([Localizable(false)] string path) => UnixFileSystemInfo.GetFileSystemEntry(path ?? throw new ArgumentNullException(nameof(path))).IsSymbolicLink; /// <summary> /// Checks whether a file is a Unix symbolic link. /// </summary> /// <param name="path">The path of the file to check.</param> /// <param name="target">Returns the target the symbolic link points to if it exists.</param> /// <returns><c>true</c> if <paramref name="path"/> points to a symbolic link; <c>false</c> otherwise.</returns> /// <exception cref="InvalidOperationException">The underlying Unix subsystem failed to process the request (e.g. because of insufficient rights).</exception> /// <exception cref="UnixIOException">The underlying Unix subsystem failed to process the request (e.g. because of insufficient rights).</exception> public static bool IsSymlink( [Localizable(false)] string path, [MaybeNullWhen(false)] out string target) { if (IsSymlink(path ?? throw new ArgumentNullException(nameof(path)))) { var symlinkInfo = new UnixSymbolicLinkInfo(path); target = symlinkInfo.ContentsPath; return true; } else { target = null; return false; } } #endregion #region Permissions /// <summary>A combination of bit flags to grant everyone writing permissions.</summary> private const FileAccessPermissions AllWritePermission = FileAccessPermissions.UserWrite | FileAccessPermissions.GroupWrite | FileAccessPermissions.OtherWrite; /// <summary> /// Removes write permissions for everyone on a filesystem object (file or directory). /// </summary> /// <param name="path">The filesystem object (file or directory) to make read-only.</param> /// <exception cref="InvalidOperationException">The underlying Unix subsystem failed to process the request (e.g. because of insufficient rights).</exception> /// <exception cref="UnixIOException">The underlying Unix subsystem failed to process the request (e.g. because of insufficient rights).</exception> public static void MakeReadOnly([Localizable(false)] string path) { var fileSysInfo = UnixFileSystemInfo.GetFileSystemEntry(path ?? throw new ArgumentNullException(nameof(path))); fileSysInfo.FileAccessPermissions &= ~AllWritePermission; } /// <summary> /// Sets write permissions for the owner on a filesystem object (file or directory). /// </summary> /// <param name="path">The filesystem object (file or directory) to make writable by the owner.</param> /// <exception cref="InvalidOperationException">The underlying Unix subsystem failed to process the request (e.g. because of insufficient rights).</exception> /// <exception cref="UnixIOException">The underlying Unix subsystem failed to process the request (e.g. because of insufficient rights).</exception> public static void MakeWritable([Localizable(false)] string path) { var fileSysInfo = UnixFileSystemInfo.GetFileSystemEntry(path ?? throw new ArgumentNullException(nameof(path))); fileSysInfo.FileAccessPermissions |= FileAccessPermissions.UserWrite; } /// <summary>A combination of bit flags to grant everyone executing permissions.</summary> private const FileAccessPermissions AllExecutePermission = FileAccessPermissions.UserExecute | FileAccessPermissions.GroupExecute | FileAccessPermissions.OtherExecute; /// <summary> /// Checks whether a file is marked as Unix-executable. /// </summary> /// <param name="path">The file to check for executable rights.</param> /// <returns><c>true</c> if <paramref name="path"/> points to an executable; <c>false</c> otherwise.</returns> /// <exception cref="InvalidOperationException">The underlying Unix subsystem failed to process the request (e.g. because of insufficient rights).</exception> /// <exception cref="UnixIOException">The underlying Unix subsystem failed to process the request (e.g. because of insufficient rights).</exception> /// <remarks>Will return <c>false</c> for non-existing files.</remarks> public static bool IsExecutable([Localizable(false)] string path) { // Check if any execution rights are set var fileInfo = UnixFileSystemInfo.GetFileSystemEntry(path ?? throw new ArgumentNullException(nameof(path))); return (fileInfo.FileAccessPermissions & AllExecutePermission) > 0; } /// <summary> /// Marks a file as Unix-executable or not Unix-executable. /// </summary> /// <param name="path">The file to mark as executable or not executable.</param> /// <param name="executable"><c>true</c> to mark the file as executable, <c>true</c> to mark it as not executable.</param> /// <exception cref="InvalidOperationException">The underlying Unix subsystem failed to process the request (e.g. because of insufficient rights).</exception> /// <exception cref="UnixIOException">The underlying Unix subsystem failed to process the request (e.g. because of insufficient rights).</exception> public static void SetExecutable([Localizable(false)] string path, bool executable) { var fileInfo = UnixFileSystemInfo.GetFileSystemEntry(path ?? throw new ArgumentNullException(nameof(path))); if (executable) fileInfo.FileAccessPermissions |= AllExecutePermission; // Set all execution rights else fileInfo.FileAccessPermissions &= ~AllExecutePermission; // Unset all execution rights } #endregion #region Extended file attributes /// <summary> /// Gets an extended file attribute. /// </summary> /// <param name="path">The path of the file to read the attribute from.</param> /// <param name="name">The name of the attribute to read.</param> /// <returns>The contents of the attribute as a byte array; <c>null</c> if there was a problem reading the file.</returns> [MethodImpl(MethodImplOptions.NoInlining)] public static byte[]? GetXattr([Localizable(false)] string path, [Localizable(false)] string name) => Syscall.getxattr( path ?? throw new ArgumentNullException(nameof(path)), name ?? throw new ArgumentNullException(nameof(name)), out var data) == -1 ? null : data; /// <summary> /// Sets an extended file attribute. /// </summary> /// <param name="path">The path of the file to set the attribute for.</param> /// <param name="name">The name of the attribute to set.</param> /// <param name="data">The data to write to the attribute.</param> /// <exception cref="UnixIOException">The underlying Unix subsystem failed to process the request (e.g. because of insufficient rights).</exception> [MethodImpl(MethodImplOptions.NoInlining)] public static void SetXattr([Localizable(false)] string path, [Localizable(false)] string name, byte[] data) { if (Syscall.setxattr( path ?? throw new ArgumentNullException(nameof(path)), name ?? throw new ArgumentNullException(nameof(name)), data) == -1) throw new UnixIOException(Stdlib.GetLastError()); } #endregion #region Mount point private static readonly SubProcess _stat = new("stat"); /// <summary> /// Determines the file system type a file or directory is stored on. /// </summary> /// <param name="path">The path of the file.</param> /// <returns>The name of the file system in fstab format (e.g. ext3 or ntfs-3g).</returns> /// <remarks>Only works on Linux, not on other Unixes (e.g. MacOS X).</remarks> /// <exception cref="IOException">The underlying Unix subsystem failed to process the request (e.g. because of insufficient rights).</exception> [MethodImpl(MethodImplOptions.NoInlining)] public static string GetFileSystem([Localizable(false)] string path) { string fileSystem = _stat.Run("--file-system", "--printf", "%T", path).TrimEnd('\n'); if (fileSystem == "fuseblk") { // FUSE mounts need to be looked up in /etc/fstab to determine actual file system var fstabData = Syscall.getfsfile(_stat.Run("--printf", "%m", path).TrimEnd('\n')); if (fstabData != null) return fstabData.fs_vfstype; } return fileSystem; } #endregion } }
56.886076
176
0.631787
[ "MIT" ]
nano-byte/common
src/Common/Native/UnixUtils.cs
17,976
C#
using System; using Microsoft.EntityFrameworkCore.Migrations; #nullable disable namespace Migrators.MySQL.Migrations.Tenant; public partial class Initial : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.EnsureSchema( name: "MultiTenancy"); migrationBuilder.AlterDatabase() .Annotation("MySql:CharSet", "utf8mb4"); migrationBuilder.CreateTable( name: "Tenants", schema: "MultiTenancy", columns: table => new { Id = table.Column<string>(type: "varchar(64)", maxLength: 64, nullable: false) .Annotation("MySql:CharSet", "utf8mb4"), Identifier = table.Column<string>(type: "varchar(255)", nullable: false) .Annotation("MySql:CharSet", "utf8mb4"), Name = table.Column<string>(type: "longtext", nullable: false) .Annotation("MySql:CharSet", "utf8mb4"), ConnectionString = table.Column<string>(type: "longtext", nullable: false) .Annotation("MySql:CharSet", "utf8mb4"), AdminEmail = table.Column<string>(type: "longtext", nullable: false) .Annotation("MySql:CharSet", "utf8mb4"), IsActive = table.Column<bool>(type: "tinyint(1)", nullable: false), ValidUpto = table.Column<DateTime>(type: "datetime(6)", nullable: false), Issuer = table.Column<string>(type: "longtext", nullable: true) .Annotation("MySql:CharSet", "utf8mb4") }, constraints: table => { table.PrimaryKey("PK_Tenants", x => x.Id); }) .Annotation("MySql:CharSet", "utf8mb4"); migrationBuilder.CreateIndex( name: "IX_Tenants_Identifier", schema: "MultiTenancy", table: "Tenants", column: "Identifier", unique: true); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropTable( name: "Tenants", schema: "MultiTenancy"); } }
37.508475
94
0.565748
[ "MIT" ]
towseef85/asp.netcore-boilerplate
src/Migrators/Migrators.MySQL/Migrations/Tenant/20220115093549_Initial.cs
2,215
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Cakemanny.FIQL { public class Lexer { private readonly string characters; private int pos = 0; private bool canBeIdent = true; public event Action<String> trace = msg => { }; public Lexer(string characters) { this.characters = characters; } public List<Token> lex() { var result = new List<Token>(); while (!eof()) { var token = readToken(); trace(token.ToString()); result.Add(token); var s = token.symbol; canBeIdent = (s == Symbol.comma || s == Symbol.semicolon || s == Symbol.lparen); } return result; } private bool eof() { return pos >= characters.Length; } private char peekChar() { return !eof() ? characters[pos] : '\0'; } private char readChar() { return !eof() ? characters[pos++] : '\0'; } private char next() { ++pos; return (pos < characters.Length) ? characters[pos] : '\0'; } private LexException error(string message) { return new LexException(message, characters, pos); } private bool isDigit(char c) { return c >= '0' && c <= '9'; } private bool isAlpha(char c) { return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_' || c == '$'; } private bool isAlphaNum(char c) { return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '_' || c == '$'; } private bool isString(char c) { return !(c == '=' || c == '*' || c == '(' || c == ')' || c == '!' || c == ',' || c == ';' || c =='\'' || c == '\0'); } private bool isWild(char c) { return c == '*' || isString(c); } private Token readToken() { StringBuilder data = new StringBuilder(""); int start = pos; char c = peekChar(); switch (c) { case ';': readChar(); return new Token(Symbol.semicolon, ";"); case ',': readChar(); return new Token(Symbol.comma, ","); case '(': readChar(); return new Token(Symbol.lparen, "("); case ')': readChar(); return new Token(Symbol.rparen, ")"); case '!': c = next(); if (c == '=') { readChar(); return new Token(Symbol.notequal, "!="); } throw error("Expected = after !"); case '=': { c = next(); switch (c) { case '=': readChar(); return new Token(Symbol.equal, "=="); case 'g': c = next(); switch (c) { case 'e': if ('=' == next()) { readChar(); return new Token(Symbol.greaterequal, "=ge="); } break; case 't': if ('=' == next()) { readChar(); return new Token(Symbol.greaterthan, "=gt="); } break; } break; case 'l': c = next(); switch (c) { case 'e': if ('=' == next()) { readChar(); return new Token(Symbol.lessequal, "=le="); } break; case 't': if ('=' == next()) { readChar(); return new Token(Symbol.lessthan, "=lt="); } break; } break; } throw error("Expected comparison ==,=ge=,=gt=,=le=,=lt= given first ="); } default: { if (canBeIdent) { // process identifier if (isAlpha(c)) { // identifier or string while (isAlphaNum(c)) { data.Append(c); c = next(); } return new Token(Symbol.ident, data.ToString()); } else { throw error("Expected identifier here"); } } else { return readValue(data, start, c); } } } } private Token readValue(StringBuilder data, int start, char c) { if (isDigit(c)) { // process date // process number while (isDigit(c)) { data.Append(c); c = next(); } if (c == '-' && (pos - start) == 4) { // date data.Append(c); c = next(); if (isDigit(c) && isDigit(next()) && '-' == next() && isDigit(next()) && isDigit(next())) { readChar(); return new Token(Symbol.date, characters.Substring(start, pos - start)); } throw error("Incorrectly formatted date, expected yyyy-mm-dd"); } else if (!isWild(c)) { return new Token(Symbol.number, data.ToString()); } else { return readWild(data, start, c); } } else if (isWild(c)) { return readWild(data, start, c); } else { throw error("Unexpected character!"); } } private Token readWild(StringBuilder data, int start, char c) { bool boolean = true, stringtype = true; // process bool // process string // process wild int x = 0; char[] tru = {'t','r','u','e'}; char[] fals = {'f','a','l','s','e'}; if (c == 't') while (x < 4 && c == tru[x++]) { data.Append(c); c = next(); } else if (c == 'f') while (x < 5 && c == fals[x++]) { data.Append(c); c = next(); } while (isWild(c)) { boolean = false; stringtype = stringtype && (c != '*'); data.Append(c); c = next(); } return boolean ? new Token(Symbol.boolean, data.ToString()) : stringtype ? new Token(Symbol.stringtype, data.ToString()) : new Token(Symbol.wildstring, data.ToString()); } } }
35.233766
96
0.322153
[ "Apache-2.0" ]
cakemanny/fiql-parser-cs
Cakemanny.FIQL/Lexer.cs
8,139
C#
/* * Copyright (c) 2014 Behrooz Amoozad * 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 bd2 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 Behrooz Amoozad BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ using System; namespace BD2.Daemon.Buses { [AttributeUsage (AttributeTargets.Class)] public sealed class ObjectBusMessageDeserializerAttribute : Attribute { System.Reflection.MethodInfo func; public ObjectBusMessage Deserialize (byte[] message) { return (ObjectBusMessage)func.Invoke (null, new object[] { message }); } public ObjectBusMessageDeserializerAttribute (Type type, string funcName) { if (funcName == null) throw new ArgumentNullException ("funcName"); func = type.GetMethod (funcName, System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Public); if (func == null) { Console.Write ("ObjectBusMessageDeserializerAttribute is going into failsafe mode, "); func = type.GetMethod (funcName, System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.NonPublic); if (func == null) Console.WriteLine ("failed."); else Console.WriteLine ("succeeded."); } } } }
43.603448
119
0.74654
[ "BSD-3-Clause" ]
jamesaxl/BD2
BD2.Daemon/Buses/ObjectBusMessageDeserializerAttribute.cs
2,529
C#
using MessagePackLib.MessagePack; using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Net.Security; using System.Net.Sockets; using System.Security.Authentication; using System.Security.Cryptography.X509Certificates; using System.Text; using System.Threading; namespace Plugin { public static class Connection { public static Socket TcpClient { get; set; } public static SslStream SslClient { get; set; } public static X509Certificate2 ServerCertificate { get; set; } private static byte[] Buffer { get; set; } private static long HeaderSize { get; set; } private static long Offset { get; set; } private static Timer Tick { get; set; } public static bool IsConnected { get; set; } private static object SendSync { get; } = new object(); public static string Hwid { get; set; } public static void InitializeClient() { try { TcpClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp) { ReceiveBufferSize = 50 * 1024, SendBufferSize = 50 * 1024, }; TcpClient.Connect(Plugin.Socket.RemoteEndPoint.ToString().Split(':')[0], Convert.ToInt32(Plugin.Socket.RemoteEndPoint.ToString().Split(':')[1])); if (TcpClient.Connected) { Debug.WriteLine("Plugin Connected!"); IsConnected = true; SslClient = new SslStream(new NetworkStream(TcpClient, true), false, ValidateServerCertificate); SslClient.AuthenticateAsClient(TcpClient.RemoteEndPoint.ToString().Split(':')[0], null, SslProtocols.Tls, false); HeaderSize = 4; Buffer = new byte[HeaderSize]; Offset = 0; Tick = new Timer(new TimerCallback(CheckServer), null, new Random().Next(15 * 1000, 30 * 1000), new Random().Next(15 * 1000, 30 * 1000)); SslClient.BeginRead(Buffer, 0, Buffer.Length, ReadServertData, null); new Thread(() => { new HandleProcessManager().ProcessList(); }).Start(); } else { IsConnected = false; return; } } catch { Debug.WriteLine("Disconnected!"); IsConnected = false; return; } } private static bool ValidateServerCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { #if DEBUG return true; #endif return ServerCertificate.Equals(certificate); } public static void Disconnected() { try { IsConnected = false; Tick?.Dispose(); SslClient?.Dispose(); TcpClient?.Dispose(); GC.Collect(); } catch { } } public static void ReadServertData(IAsyncResult ar) //Socket read/recevie { try { if (!TcpClient.Connected || !IsConnected) { IsConnected = false; return; } int recevied = SslClient.EndRead(ar); if (recevied > 0) { Offset += recevied; HeaderSize -= recevied; if (HeaderSize == 0) { HeaderSize = BitConverter.ToInt32(Buffer, 0); Debug.WriteLine("/// Plugin Buffersize " + HeaderSize.ToString() + " Bytes ///"); if (HeaderSize > 0) { Offset = 0; Buffer = new byte[HeaderSize]; while (HeaderSize > 0) { int rc = SslClient.Read(Buffer, (int)Offset, (int)HeaderSize); if (rc <= 0) { IsConnected = false; return; } Offset += rc; HeaderSize -= rc; if (HeaderSize < 0) { IsConnected = false; return; } } Thread thread = new Thread(new ParameterizedThreadStart(Packet.Read)); thread.Start(Buffer); Offset = 0; HeaderSize = 4; Buffer = new byte[HeaderSize]; } else { HeaderSize = 4; Buffer = new byte[HeaderSize]; Offset = 0; } } else if (HeaderSize < 0) { IsConnected = false; return; } SslClient.BeginRead(Buffer, (int)Offset, (int)HeaderSize, ReadServertData, null); } else { IsConnected = false; return; } } catch { IsConnected = false; return; } } public static void Send(byte[] msg) { lock (SendSync) { try { if (!IsConnected || msg == null) { return; } byte[] buffersize = BitConverter.GetBytes(msg.Length); TcpClient.Poll(-1, SelectMode.SelectWrite); SslClient.Write(buffersize, 0, buffersize.Length); if (msg.Length > 1000000) //1mb { Debug.WriteLine("send chunks"); using (MemoryStream memoryStream = new MemoryStream(msg)) { int read = 0; memoryStream.Position = 0; byte[] chunk = new byte[50 * 1000]; while ((read = memoryStream.Read(chunk, 0, chunk.Length)) > 0) { TcpClient.Poll(-1, SelectMode.SelectWrite); SslClient.Write(chunk, 0, read); SslClient.Flush(); } } } else { TcpClient.Poll(-1, SelectMode.SelectWrite); SslClient.Write(msg, 0, msg.Length); SslClient.Flush(); } Debug.WriteLine("Plugin Packet Sent"); } catch { IsConnected = false; return; } } } public static void CheckServer(object obj) { MsgPack msgpack = new MsgPack(); msgpack.ForcePathObject("Packet").AsString = "Ping!)"; Send(msgpack.Encode2Bytes()); GC.Collect(); } } }
35.825112
161
0.409813
[ "MIT" ]
0xyg3n/AsyncRAT-C-Sharp
AsyncRAT-C#/Plugin/ProcessManager/ProcessManager/Connection.cs
7,991
C#
// This code was generated by Hypar. // Edits to this code will be overwritten the next time you run 'hypar init'. // DO NOT EDIT THIS FILE. using Xunit; using System.IO; using System.Reflection; using System.Threading.Tasks; using Xunit.Abstractions; using System; using System.Collections.Generic; namespace DefineProgramRequirements.Tests { public class FunctionTests { private readonly ITestOutputHelper output; public FunctionTests(ITestOutputHelper output) { this.output = output; } } }
22.958333
77
0.711434
[ "MIT" ]
ehtick/HyparSpace
WorkplaceStrategy/DefineProgramRequirements/test/FunctionTest.g.cs
551
C#
using System; using System.Collections.Generic; using System.Data; using System.Data.Entity; using System.Linq; using System.Net; using System.Web; using System.Web.Mvc; using project.Models; namespace project.Controllers { public class passengersController : Controller { private Database1Entities db = new Database1Entities(); // GET: passengers public ActionResult Index() { return View(db.passengers.ToList()); } // GET: passengers/Details/5 public ActionResult Details(int? id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } passenger passenger = db.passengers.Find(id); if (passenger == null) { return HttpNotFound(); } return View(passenger); } // GET: passengers/Create public ActionResult Create() { return View(); } // POST: passengers/Create // To protect from overposting attacks, enable the specific properties you want to bind to, for // more details see https://go.microsoft.com/fwlink/?LinkId=317598. [HttpPost] [ValidateAntiForgeryToken] public ActionResult Create([Bind(Include = "profile_id,password,f_name,l_name,address,e_mail_id,tel_num")] passenger passenger) { if (ModelState.IsValid) { db.passengers.Add(passenger); db.SaveChanges(); return RedirectToAction("Index"); } return View(passenger); } // GET: passengers/Edit/5 public ActionResult Edit(int? id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } passenger passenger = db.passengers.Find(id); if (passenger == null) { return HttpNotFound(); } return View(passenger); } // POST: passengers/Edit/5 // To protect from overposting attacks, enable the specific properties you want to bind to, for // more details see https://go.microsoft.com/fwlink/?LinkId=317598. [HttpPost] [ValidateAntiForgeryToken] public ActionResult Edit([Bind(Include = "profile_id,password,f_name,l_name,address,e_mail_id,tel_num")] passenger passenger) { if (ModelState.IsValid) { db.Entry(passenger).State = EntityState.Modified; db.SaveChanges(); return RedirectToAction("Index"); } return View(passenger); } // GET: passengers/Delete/5 public ActionResult Delete(int? id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } passenger passenger = db.passengers.Find(id); if (passenger == null) { return HttpNotFound(); } return View(passenger); } // POST: passengers/Delete/5 [HttpPost, ActionName("Delete")] [ValidateAntiForgeryToken] public ActionResult DeleteConfirmed(int id) { passenger passenger = db.passengers.Find(id); db.passengers.Remove(passenger); db.SaveChanges(); return RedirectToAction("Index"); } protected override void Dispose(bool disposing) { if (disposing) { db.Dispose(); } base.Dispose(disposing); } } }
29.601563
135
0.542359
[ "MIT" ]
rafay99-epic/University-Projects
Votting Website/Other Projects/Different Projects/Project 1/project/project/project/Controllers/passengersController.cs
3,791
C#
 namespace MyTool_SpriteSheetTool { partial class Form1 { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(Form1)); this.panel1 = new System.Windows.Forms.Panel(); this.pnlLeft = new System.Windows.Forms.Panel(); this.panel3 = new System.Windows.Forms.Panel(); this.label10 = new System.Windows.Forms.Label(); this.panel2 = new System.Windows.Forms.Panel(); this.lblPicSize = new System.Windows.Forms.Label(); this.lblPicNumber = new System.Windows.Forms.Label(); this.label7 = new System.Windows.Forms.Label(); this.label6 = new System.Windows.Forms.Label(); this.btnOK = new System.Windows.Forms.Button(); this.rbBMP = new System.Windows.Forms.RadioButton(); this.rbTIFF = new System.Windows.Forms.RadioButton(); this.rbPNG = new System.Windows.Forms.RadioButton(); this.pbDraw = new System.Windows.Forms.PictureBox(); this.groupBox2 = new System.Windows.Forms.GroupBox(); this.tbSplitH = new System.Windows.Forms.TextBox(); this.label5 = new System.Windows.Forms.Label(); this.tbSplitW = new System.Windows.Forms.TextBox(); this.label3 = new System.Windows.Forms.Label(); this.groupBox1 = new System.Windows.Forms.GroupBox(); this.tbLayoutW = new System.Windows.Forms.TextBox(); this.label2 = new System.Windows.Forms.Label(); this.panel1.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.pbDraw)).BeginInit(); this.groupBox2.SuspendLayout(); this.groupBox1.SuspendLayout(); this.SuspendLayout(); // // panel1 // this.panel1.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(250)))), ((int)(((byte)(245)))), ((int)(((byte)(235))))); this.panel1.Controls.Add(this.pnlLeft); this.panel1.Controls.Add(this.panel3); this.panel1.Controls.Add(this.label10); this.panel1.Controls.Add(this.panel2); this.panel1.Controls.Add(this.lblPicSize); this.panel1.Controls.Add(this.lblPicNumber); this.panel1.Controls.Add(this.label7); this.panel1.Controls.Add(this.label6); this.panel1.Controls.Add(this.btnOK); this.panel1.Controls.Add(this.rbBMP); this.panel1.Controls.Add(this.rbTIFF); this.panel1.Controls.Add(this.rbPNG); this.panel1.Controls.Add(this.pbDraw); this.panel1.Controls.Add(this.groupBox2); this.panel1.Controls.Add(this.groupBox1); this.panel1.Dock = System.Windows.Forms.DockStyle.Fill; this.panel1.Location = new System.Drawing.Point(0, 0); this.panel1.Name = "panel1"; this.panel1.Size = new System.Drawing.Size(581, 387); this.panel1.TabIndex = 18; // // pnlLeft // this.pnlLeft.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(191)))), ((int)(((byte)(92)))), ((int)(((byte)(55))))); this.pnlLeft.Dock = System.Windows.Forms.DockStyle.Left; this.pnlLeft.Location = new System.Drawing.Point(0, 12); this.pnlLeft.Name = "pnlLeft"; this.pnlLeft.Size = new System.Drawing.Size(8, 363); this.pnlLeft.TabIndex = 16; // // panel3 // this.panel3.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(60)))), ((int)(((byte)(58)))), ((int)(((byte)(59))))); this.panel3.Dock = System.Windows.Forms.DockStyle.Bottom; this.panel3.Location = new System.Drawing.Point(0, 375); this.panel3.Name = "panel3"; this.panel3.Size = new System.Drawing.Size(581, 12); this.panel3.TabIndex = 15; // // label10 // this.label10.AutoSize = true; this.label10.Font = new System.Drawing.Font("Meiryo", 10F); this.label10.ForeColor = System.Drawing.SystemColors.ControlText; this.label10.Location = new System.Drawing.Point(22, 19); this.label10.Name = "label10"; this.label10.Size = new System.Drawing.Size(262, 21); this.label10.TabIndex = 12; this.label10.Text = "画像をドラッグ&ドロップしてください"; // // panel2 // this.panel2.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(60)))), ((int)(((byte)(58)))), ((int)(((byte)(59))))); this.panel2.Dock = System.Windows.Forms.DockStyle.Top; this.panel2.Location = new System.Drawing.Point(0, 0); this.panel2.Name = "panel2"; this.panel2.Size = new System.Drawing.Size(581, 12); this.panel2.TabIndex = 0; // // lblPicSize // this.lblPicSize.AutoSize = true; this.lblPicSize.Font = new System.Drawing.Font("Meiryo", 9F); this.lblPicSize.Location = new System.Drawing.Point(205, 348); this.lblPicSize.Name = "lblPicSize"; this.lblPicSize.Size = new System.Drawing.Size(79, 18); this.lblPicSize.TabIndex = 10; this.lblPicSize.Text = "1024 x 1024"; // // lblPicNumber // this.lblPicNumber.AutoSize = true; this.lblPicNumber.Font = new System.Drawing.Font("Meiryo", 9F); this.lblPicNumber.Location = new System.Drawing.Point(85, 348); this.lblPicNumber.Name = "lblPicNumber"; this.lblPicNumber.Size = new System.Drawing.Size(22, 18); this.lblPicNumber.TabIndex = 9; this.lblPicNumber.Text = "64"; // // label7 // this.label7.AutoSize = true; this.label7.Font = new System.Drawing.Font("Meiryo", 9F); this.label7.Location = new System.Drawing.Point(164, 348); this.label7.Name = "label7"; this.label7.Size = new System.Drawing.Size(44, 18); this.label7.TabIndex = 0; this.label7.Text = "Size:"; // // label6 // this.label6.AutoSize = true; this.label6.Font = new System.Drawing.Font("Meiryo", 9F); this.label6.Location = new System.Drawing.Point(22, 348); this.label6.Name = "label6"; this.label6.Size = new System.Drawing.Size(67, 18); this.label6.TabIndex = 0; this.label6.Text = "Number:"; // // btnOK // this.btnOK.Font = new System.Drawing.Font("Meiryo", 9.75F); this.btnOK.Location = new System.Drawing.Point(373, 313); this.btnOK.Name = "btnOK"; this.btnOK.Size = new System.Drawing.Size(159, 32); this.btnOK.TabIndex = 9; this.btnOK.Text = "出力する"; this.btnOK.UseVisualStyleBackColor = true; this.btnOK.Click += new System.EventHandler(this.btnOK_Click); // // rbBMP // this.rbBMP.AutoSize = true; this.rbBMP.Font = new System.Drawing.Font("Meiryo", 9.75F); this.rbBMP.Location = new System.Drawing.Point(491, 283); this.rbBMP.Name = "rbBMP"; this.rbBMP.Size = new System.Drawing.Size(55, 24); this.rbBMP.TabIndex = 8; this.rbBMP.Text = "BMP"; this.rbBMP.UseVisualStyleBackColor = true; // // rbTIFF // this.rbTIFF.AutoSize = true; this.rbTIFF.Font = new System.Drawing.Font("Meiryo", 9.75F); this.rbTIFF.Location = new System.Drawing.Point(425, 283); this.rbTIFF.Name = "rbTIFF"; this.rbTIFF.Size = new System.Drawing.Size(54, 24); this.rbTIFF.TabIndex = 7; this.rbTIFF.Text = "TIFF"; this.rbTIFF.UseVisualStyleBackColor = true; // // rbPNG // this.rbPNG.AutoSize = true; this.rbPNG.Checked = true; this.rbPNG.Font = new System.Drawing.Font("Meiryo", 9.75F); this.rbPNG.Location = new System.Drawing.Point(359, 283); this.rbPNG.Name = "rbPNG"; this.rbPNG.Size = new System.Drawing.Size(54, 24); this.rbPNG.TabIndex = 6; this.rbPNG.TabStop = true; this.rbPNG.Text = "PNG"; this.rbPNG.UseVisualStyleBackColor = true; // // pbDraw // this.pbDraw.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(182)))), ((int)(((byte)(178)))), ((int)(((byte)(172))))); this.pbDraw.Location = new System.Drawing.Point(26, 45); this.pbDraw.Name = "pbDraw"; this.pbDraw.Size = new System.Drawing.Size(300, 300); this.pbDraw.SizeMode = System.Windows.Forms.PictureBoxSizeMode.Zoom; this.pbDraw.TabIndex = 8; this.pbDraw.TabStop = false; this.pbDraw.DragDrop += new System.Windows.Forms.DragEventHandler(this.pbDraw_DragDrop); this.pbDraw.DragEnter += new System.Windows.Forms.DragEventHandler(this.pbDraw_DragEnter); // // groupBox2 // this.groupBox2.Controls.Add(this.tbSplitH); this.groupBox2.Controls.Add(this.label5); this.groupBox2.Controls.Add(this.tbSplitW); this.groupBox2.Controls.Add(this.label3); this.groupBox2.Font = new System.Drawing.Font("Meiryo", 10F); this.groupBox2.Location = new System.Drawing.Point(343, 140); this.groupBox2.Name = "groupBox2"; this.groupBox2.Size = new System.Drawing.Size(218, 127); this.groupBox2.TabIndex = 3; this.groupBox2.TabStop = false; this.groupBox2.Text = "1枚の画像を複数に分割する"; // // tbSplitH // this.tbSplitH.Font = new System.Drawing.Font("Meiryo", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(128))); this.tbSplitH.ImeMode = System.Windows.Forms.ImeMode.Disable; this.tbSplitH.Location = new System.Drawing.Point(135, 75); this.tbSplitH.MaxLength = 2; this.tbSplitH.Name = "tbSplitH"; this.tbSplitH.Size = new System.Drawing.Size(60, 27); this.tbSplitH.TabIndex = 5; this.tbSplitH.Text = "8"; this.tbSplitH.TextAlign = System.Windows.Forms.HorizontalAlignment.Center; this.tbSplitH.Enter += new System.EventHandler(this.tbSplitH_Enter); this.tbSplitH.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.tbSplitH_KeyPress); // // label5 // this.label5.AutoSize = true; this.label5.Font = new System.Drawing.Font("Meiryo", 10F); this.label5.Location = new System.Drawing.Point(20, 78); this.label5.Name = "label5"; this.label5.Size = new System.Drawing.Size(94, 21); this.label5.TabIndex = 0; this.label5.Text = "タテの分割数"; // // tbSplitW // this.tbSplitW.Font = new System.Drawing.Font("Meiryo", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(128))); this.tbSplitW.ImeMode = System.Windows.Forms.ImeMode.Disable; this.tbSplitW.Location = new System.Drawing.Point(135, 37); this.tbSplitW.MaxLength = 2; this.tbSplitW.Name = "tbSplitW"; this.tbSplitW.Size = new System.Drawing.Size(60, 27); this.tbSplitW.TabIndex = 4; this.tbSplitW.Text = "8"; this.tbSplitW.TextAlign = System.Windows.Forms.HorizontalAlignment.Center; this.tbSplitW.Enter += new System.EventHandler(this.tbSplitW_Enter); this.tbSplitW.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.tbSplitW_KeyPress); // // label3 // this.label3.AutoSize = true; this.label3.Font = new System.Drawing.Font("Meiryo", 10F); this.label3.Location = new System.Drawing.Point(20, 40); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(94, 21); this.label3.TabIndex = 0; this.label3.Text = "ヨコの分割数"; // // groupBox1 // this.groupBox1.Controls.Add(this.tbLayoutW); this.groupBox1.Controls.Add(this.label2); this.groupBox1.Font = new System.Drawing.Font("Meiryo", 10F); this.groupBox1.Location = new System.Drawing.Point(343, 39); this.groupBox1.Name = "groupBox1"; this.groupBox1.Size = new System.Drawing.Size(218, 86); this.groupBox1.TabIndex = 1; this.groupBox1.TabStop = false; this.groupBox1.Text = "複数の画像を1枚に結合する"; // // tbLayoutW // this.tbLayoutW.Font = new System.Drawing.Font("Meiryo", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(128))); this.tbLayoutW.ImeMode = System.Windows.Forms.ImeMode.Disable; this.tbLayoutW.Location = new System.Drawing.Point(135, 36); this.tbLayoutW.MaxLength = 2; this.tbLayoutW.Name = "tbLayoutW"; this.tbLayoutW.Size = new System.Drawing.Size(60, 27); this.tbLayoutW.TabIndex = 2; this.tbLayoutW.Text = "8"; this.tbLayoutW.TextAlign = System.Windows.Forms.HorizontalAlignment.Center; this.tbLayoutW.Enter += new System.EventHandler(this.tbLayoutW_Enter); this.tbLayoutW.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.tbLayoutW_KeyPress); // // label2 // this.label2.AutoSize = true; this.label2.Font = new System.Drawing.Font("Meiryo", 10F); this.label2.Location = new System.Drawing.Point(20, 39); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(108, 21); this.label2.TabIndex = 0; this.label2.Text = "ヨコに並べる数"; // // Form1 // this.AllowDrop = true; this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(581, 387); this.Controls.Add(this.panel1); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle; this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); this.Name = "Form1"; this.Text = "Sprite Sheet Tool v.1.00"; this.Load += new System.EventHandler(this.Form1_Load); this.panel1.ResumeLayout(false); this.panel1.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.pbDraw)).EndInit(); this.groupBox2.ResumeLayout(false); this.groupBox2.PerformLayout(); this.groupBox1.ResumeLayout(false); this.groupBox1.PerformLayout(); this.ResumeLayout(false); } #endregion private System.Windows.Forms.Panel panel1; private System.Windows.Forms.PictureBox pbDraw; private System.Windows.Forms.GroupBox groupBox2; public System.Windows.Forms.TextBox tbSplitH; private System.Windows.Forms.Label label5; public System.Windows.Forms.TextBox tbSplitW; private System.Windows.Forms.Label label3; private System.Windows.Forms.GroupBox groupBox1; public System.Windows.Forms.TextBox tbLayoutW; private System.Windows.Forms.Label label2; private System.Windows.Forms.Button btnOK; private System.Windows.Forms.Label label7; private System.Windows.Forms.Label label6; private System.Windows.Forms.RadioButton rbBMP; private System.Windows.Forms.RadioButton rbTIFF; private System.Windows.Forms.RadioButton rbPNG; private System.Windows.Forms.Label lblPicSize; private System.Windows.Forms.Label lblPicNumber; private System.Windows.Forms.Panel panel2; private System.Windows.Forms.Label label10; private System.Windows.Forms.Panel panel3; private System.Windows.Forms.Panel pnlLeft; } }
39.845528
150
0.697409
[ "MIT" ]
moko-vfx/SpriteSheetTool
source/Form1.Designer.cs
14,843
C#
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; using System.Net.Http; using System.Net.Http.Formatting; using System.Net.Http.Headers; using System.Web.Http.Description; using System.Xml.Linq; using Newtonsoft.Json; namespace CarRentalSystem.Areas.HelpPage { /// <summary> /// This class will generate the samples for the help page. /// </summary> public class HelpPageSampleGenerator { /// <summary> /// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class. /// </summary> public HelpPageSampleGenerator() { ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>(); ActionSamples = new Dictionary<HelpPageSampleKey, object>(); SampleObjects = new Dictionary<Type, object>(); } /// <summary> /// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>. /// </summary> public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; } /// <summary> /// Gets the objects that are used directly as samples for certain actions. /// </summary> public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; } /// <summary> /// Gets the objects that are serialized as samples by the supported formatters. /// </summary> public IDictionary<Type, object> SampleObjects { get; internal set; } /// <summary> /// Gets the request body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api) { return GetSample(api, SampleDirection.Request); } /// <summary> /// Gets the response body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api) { return GetSample(api, SampleDirection.Response); } /// <summary> /// Gets the request or response body samples. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The samples keyed by media type.</returns> public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection) { if (api == null) { throw new ArgumentNullException("api"); } string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters); var samples = new Dictionary<MediaTypeHeaderValue, object>(); // Use the samples provided directly for actions var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection); foreach (var actionSample in actionSamples) { samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value)); } // Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage. // Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters. if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type)) { object sampleObject = GetSampleObject(type); foreach (var formatter in formatters) { foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes) { if (!samples.ContainsKey(mediaType)) { object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection); // If no sample found, try generate sample using formatter and sample object if (sample == null && sampleObject != null) { sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType); } samples.Add(mediaType, WrapSampleIfString(sample)); } } } } return samples; } /// <summary> /// Search for samples that are provided directly through <see cref="ActionSamples"/>. /// </summary> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="type">The CLR type.</param> /// <param name="formatter">The formatter.</param> /// <param name="mediaType">The media type.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The sample that matches the parameters.</returns> public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection) { object sample; // First, try get sample provided for a specific mediaType, controllerName, actionName and parameterNames. // If not found, try get the sample provided for a specific mediaType, controllerName and actionName regardless of the parameterNames // If still not found, try get the sample provided for a specific type and mediaType if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample)) { return sample; } return null; } /// <summary> /// Gets the sample object that will be serialized by the formatters. /// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create one using <see cref="ObjectGenerator"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>The sample object.</returns> public virtual object GetSampleObject(Type type) { object sampleObject; if (!SampleObjects.TryGetValue(type, out sampleObject)) { // Try create a default sample object ObjectGenerator objectGenerator = new ObjectGenerator(); sampleObject = objectGenerator.GenerateObject(type); } return sampleObject; } /// <summary> /// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param> /// <param name="formatters">The formatters.</param> [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")] public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters) { if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection)) { throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection)); } if (api == null) { throw new ArgumentNullException("api"); } Type type; if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) || ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type)) { // Re-compute the supported formatters based on type Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>(); foreach (var formatter in api.ActionDescriptor.Configuration.Formatters) { if (IsFormatSupported(sampleDirection, formatter, type)) { newFormatters.Add(formatter); } } formatters = newFormatters; } else { switch (sampleDirection) { case SampleDirection.Request: ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody); type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType; formatters = api.SupportedRequestBodyFormatters; break; case SampleDirection.Response: default: type = api.ActionDescriptor.ReturnType; formatters = api.SupportedResponseFormatters; break; } } return type; } /// <summary> /// Writes the sample object using formatter. /// </summary> /// <param name="formatter">The formatter.</param> /// <param name="value">The value.</param> /// <param name="type">The type.</param> /// <param name="mediaType">Type of the media.</param> /// <returns></returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")] public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType) { if (formatter == null) { throw new ArgumentNullException("formatter"); } if (mediaType == null) { throw new ArgumentNullException("mediaType"); } object sample = String.Empty; MemoryStream ms = null; HttpContent content = null; try { if (formatter.CanWriteType(type)) { ms = new MemoryStream(); content = new ObjectContent(type, value, formatter, mediaType); formatter.WriteToStreamAsync(type, value, ms, content, null).Wait(); ms.Position = 0; StreamReader reader = new StreamReader(ms); string serializedSampleString = reader.ReadToEnd(); if (mediaType.MediaType.ToUpperInvariant().Contains("XML")) { serializedSampleString = TryFormatXml(serializedSampleString); } else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON")) { serializedSampleString = TryFormatJson(serializedSampleString); } sample = new TextSample(serializedSampleString); } else { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.", mediaType, formatter.GetType().Name, type.Name)); } } catch (Exception e) { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}", formatter.GetType().Name, mediaType.MediaType, e.Message)); } finally { if (ms != null) { ms.Dispose(); } if (content != null) { content.Dispose(); } } return sample; } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatJson(string str) { try { object parsedJson = JsonConvert.DeserializeObject(str); return JsonConvert.SerializeObject(parsedJson, Formatting.Indented); } catch { // can't parse JSON, return the original string return str; } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatXml(string str) { try { XDocument xml = XDocument.Parse(str); return xml.ToString(); } catch { // can't parse XML, return the original string return str; } } private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type) { switch (sampleDirection) { case SampleDirection.Request: return formatter.CanReadType(type); case SampleDirection.Response: return formatter.CanWriteType(type); } return false; } private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection) { HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase); foreach (var sample in ActionSamples) { HelpPageSampleKey sampleKey = sample.Key; if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) && String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) && (sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) && sampleDirection == sampleKey.SampleDirection) { yield return sample; } } } private static object WrapSampleIfString(object sample) { string stringSample = sample as string; if (stringSample != null) { return new TextSample(stringSample); } return sample; } } }
46.172043
229
0.582615
[ "MIT" ]
vladislav-karamfilov/TelerikAcademy
JavaScript Frameworks Projects/ExamPreparation/CarRentalSystem/CarRentalSystem/Areas/HelpPage/SampleGeneration/HelpPageSampleGenerator.cs
17,176
C#
/** * Utilities.cs * * Thunder Aerospace Corporation's library for the Kerbal Space Program, by Taranis Elsu * * (C) Copyright 2013, Taranis Elsu * * Kerbal Space Program is Copyright (C) 2013 Squad. See http://kerbalspaceprogram.com/. This * project is in no way associated with nor endorsed by Squad. * * This code is licensed under the Attribution-NonCommercial-ShareAlike 3.0 (CC BY-NC-SA 3.0) * creative commons license. See <http://creativecommons.org/licenses/by-nc-sa/3.0/legalcode> * for full details. * * Attribution — You are free to modify this code, so long as you mention that the resulting * work is based upon or adapted from this code. * * Non-commercial - You may not use this work for commercial purposes. * * Share Alike — If you alter, transform, or build upon this work, you may distribute the * resulting work only under the same or similar license to the CC BY-NC-SA 3.0 license. * * Note that Thunder Aerospace Corporation is a ficticious entity created for entertainment * purposes. It is in no way meant to represent a real entity. Any similarity to a real entity * is purely coincidental. */ using KSP.IO; using System; using System.Collections.Generic; using System.Linq; using System.Text; using UnityEngine; namespace KolonyTools { public static class Utilities { const double SECONDS_PER_MINUTE = 60.0; const double MINUTES_PER_HOUR = 60.0; static double HOURS_PER_DAY = (GameSettings.KERBIN_TIME) ? 6.0 : 24.0; public static double SECONDS_PER_DAY = SECONDS_PER_MINUTE*MINUTES_PER_HOUR*HOURS_PER_DAY; public static double ToDegrees(double radians) { return radians * 180.0 / Math.PI; } public static double ToRadians(double degrees) { return degrees * Math.PI / 180.0; } public static Rect EnsureVisible(Rect pos, float min = 16.0f) { float xMin = min - pos.width; float xMax = Screen.width - min; float yMin = min - pos.height; float yMax = Screen.height - min; pos.x = Mathf.Clamp(pos.x, xMin, xMax); pos.y = Mathf.Clamp(pos.y, yMin, yMax); return pos; } public static Rect EnsureCompletelyVisible(Rect pos) { float xMin = 0; float xMax = Screen.width - pos.width; float yMin = 0; float yMax = Screen.height - pos.height; pos.x = Mathf.Clamp(pos.x, xMin, xMax); pos.y = Mathf.Clamp(pos.y, yMin, yMax); return pos; } public static Rect ClampToScreenEdge(Rect pos) { float topSeparation = Math.Abs(pos.y); float bottomSeparation = Math.Abs(Screen.height - pos.y - pos.height); float leftSeparation = Math.Abs(pos.x); float rightSeparation = Math.Abs(Screen.width - pos.x - pos.width); if (topSeparation <= bottomSeparation && topSeparation <= leftSeparation && topSeparation <= rightSeparation) { pos.y = 0; } else if (leftSeparation <= topSeparation && leftSeparation <= bottomSeparation && leftSeparation <= rightSeparation) { pos.x = 0; } else if (bottomSeparation <= topSeparation && bottomSeparation <= leftSeparation && bottomSeparation <= rightSeparation) { pos.y = Screen.height - pos.height; } else if (rightSeparation <= topSeparation && rightSeparation <= bottomSeparation && rightSeparation <= leftSeparation) { pos.x = Screen.width - pos.width; } return pos; } public static Texture2D LoadImage<T>(string filename) { if (File.Exists<T>(filename)) { var bytes = File.ReadAllBytes<T>(filename); Texture2D texture = new Texture2D(16, 16, TextureFormat.ARGB32, false); texture.LoadImage(bytes); return texture; } else { return null; } } public static bool GetValue(ConfigNode config, string name, bool currentValue) { bool newValue; if (config.HasValue(name) && bool.TryParse(config.GetValue(name), out newValue)) { return newValue; } else { return currentValue; } } public static int GetValue(ConfigNode config, string name, int currentValue) { int newValue; if (config.HasValue(name) && int.TryParse(config.GetValue(name), out newValue)) { return newValue; } else { return currentValue; } } public static float GetValue(ConfigNode config, string name, float currentValue) { float newValue; if (config.HasValue(name) && float.TryParse(config.GetValue(name), out newValue)) { return newValue; } else { return currentValue; } } public static double GetValue(ConfigNode config, string name, double currentValue) { double newValue; if (config.HasValue(name) && double.TryParse(config.GetValue(name), out newValue)) { return newValue; } else { return currentValue; } } public static string GetValue(ConfigNode config, string name, string currentValue) { if (config.HasValue(name)) { return config.GetValue(name); } else { return currentValue; } } public static T GetValue<T>(ConfigNode config, string name, T currentValue) where T : IComparable, IFormattable, IConvertible { if (config.HasValue(name)) { string stringValue = config.GetValue(name); if (Enum.IsDefined(typeof(T), stringValue)) { return (T)Enum.Parse(typeof(T), stringValue); } } return currentValue; } public static double ShowTextField(string label, GUIStyle labelStyle, double currentValue, int maxLength, GUIStyle editStyle, params GUILayoutOption[] options) { GUILayout.BeginHorizontal(); GUILayout.Label(label, labelStyle); GUILayout.FlexibleSpace(); string result = GUILayout.TextField(currentValue.ToString(), maxLength, editStyle, options); GUILayout.EndHorizontal(); double newValue; if (double.TryParse(result, out newValue)) { return newValue; } else { return currentValue; } } public static double ShowTextField(double currentValue, int maxLength, GUIStyle style, params GUILayoutOption[] options) { double newValue; string result = GUILayout.TextField(currentValue.ToString(), maxLength, style, options); if (double.TryParse(result, out newValue)) { return newValue; } else { return currentValue; } } public static float ShowTextField(float currentValue, int maxLength, GUIStyle style, params GUILayoutOption[] options) { float newValue; string result = GUILayout.TextField(currentValue.ToString(), maxLength, style, options); if (float.TryParse(result, out newValue)) { return newValue; } else { return currentValue; } } public static bool ShowToggle(string label, GUIStyle labelStyle, bool currentValue) { GUILayout.BeginHorizontal(); GUILayout.Label(label, labelStyle); GUILayout.FlexibleSpace(); bool result = GUILayout.Toggle(currentValue, ""); GUILayout.EndHorizontal(); return result; } public static string FormatTime(double value, int numDecimals = 0) { string sign = ""; if (value < 0.0) { sign = "-"; value = -value; } double seconds = value; long minutes = (long)(seconds / SECONDS_PER_MINUTE); seconds -= (long)(minutes * SECONDS_PER_MINUTE); long hours = (long)(minutes / MINUTES_PER_HOUR); minutes -= (long)(hours * MINUTES_PER_HOUR); long days = (long)(hours / HOURS_PER_DAY); hours -= (long)(days * HOURS_PER_DAY); if (days > 0) { return sign + days.ToString("#0") + "d " + hours.ToString("00") + ":" + minutes.ToString("00") + ":" + seconds.ToString("00"); } else if (hours > 0) { return sign + hours.ToString("#0") + ":" + minutes.ToString("00") + ":" + seconds.ToString("00"); } else { string format = "00"; if (numDecimals > 0) { format += "." + new String('0', numDecimals); } return sign + minutes.ToString("#0") + ":" + seconds.ToString(format); } } public static string FormatValue(double value, int numDecimals = 2) { string sign = ""; if (value < 0.0) { sign = "-"; value = -value; } string format = "0"; if (numDecimals > 0) { format += "." + new String('0', numDecimals); } if (value > 1000000000.0) { return sign + (value / 1000000000.0).ToString(format) + " G"; } else if (value > 1000000.0) { return sign + (value / 1000000.0).ToString(format) + " M"; } else if (value > 1000.0) { return sign + (value / 1000.0).ToString(format) + " k"; } else if (value < 0.000000001) { return sign + (value * 1000000000.0).ToString(format) + " n"; } else if (value < 0.000001) { return sign + (value * 1000000.0).ToString(format) + " µ"; } else if (value < 0.001) { return sign + (value * 1000.0).ToString(format) + " m"; } else { return sign + value.ToString(format) + " "; } } public static string GetDllVersion<T>(T t) { System.Reflection.Assembly assembly = t.GetType().Assembly; System.Diagnostics.FileVersionInfo fvi = System.Diagnostics.FileVersionInfo.GetVersionInfo(assembly.Location); return fvi.FileVersion; } public static GUIStyle GetVersionStyle() { GUIStyle versionStyle = new GUIStyle(GUI.skin.label); versionStyle.alignment = TextAnchor.MiddleLeft; versionStyle.fontSize = 10; versionStyle.fontStyle = FontStyle.Normal; versionStyle.normal.textColor = Color.white; versionStyle.margin.top = 0; versionStyle.margin.bottom = 0; versionStyle.padding.top = 0; versionStyle.padding.bottom = 0; versionStyle.wordWrap = false; return versionStyle; } //return a day-hour-minute-seconds-time format for the delivery time public static string DeliveryTimeString(double deliveryTime, double currentTime) { int days; int hours; int minutes; int seconds; double time; if (deliveryTime > currentTime) time = deliveryTime - currentTime; else time = currentTime - deliveryTime; days = (int)Math.Floor(time / 21600); time = time - (days * 21600); hours = (int)Math.Floor(time / 3600); time = time - (hours * 3600); minutes = (int)Math.Floor(time / 60); time = time - (minutes * 60); seconds = (int)Math.Floor(time); if (deliveryTime > currentTime) return (days + "d" + hours + "h" + minutes + "m" + seconds + "s"); else return ("-" + days + "d" + hours + "h" + minutes + "m" + seconds + "s"); } } }
32.540541
167
0.517668
[ "BSD-3-Clause" ]
mhoram-kerbin/MKS
Source/KolonyTools/KolonyTools/Utilities.cs
13,251
C#
using System.Threading; using System.Threading.Tasks; using Amazon.SimpleNotificationService.Model; namespace MhLabs.PubSubExtensions.Producer { public interface IAmazonStepFunctionsClientAdapter { Task<PublishResponse> PublishAsync(PublishRequest request, string stateMachineArn, CancellationToken cancellationToken); } }
31.272727
128
0.813953
[ "MIT" ]
calledude/MhLabs.PubSubExtensions
MhLabs.PubSubExtensions/Producer/IAmazonStepFunctionsClientAdapter.cs
346
C#
using System; using RtspClientSharp.Codecs; using RtspClientSharp.Codecs.Audio; using RtspClientSharp.Codecs.Video; using RtspClientSharp.RawFrames; namespace RtspClientSharp.MediaParsers { abstract class MediaPayloadParser : IMediaPayloadParser { private DateTime _baseTime = DateTime.MinValue; public Action<RawFrame> FrameGenerated { get; set; } public abstract void Parse(TimeSpan timeOffset, ArraySegment<byte> byteSegment, bool markerBit); public abstract void ResetState(); protected DateTime GetFrameTimestamp(TimeSpan timeOffset) { if (timeOffset == TimeSpan.MinValue) return DateTime.UtcNow; if (_baseTime == DateTime.MinValue) _baseTime = DateTime.UtcNow; return _baseTime + timeOffset; } protected virtual void OnFrameGenerated(RawFrame e) { FrameGenerated?.Invoke(e); } public static IMediaPayloadParser CreateFrom(CodecInfo codecInfo) { switch (codecInfo) { case H264CodecInfo h264CodecInfo: return new H264VideoPayloadParser(h264CodecInfo); case MJPEGCodecInfo _: return new MJPEGVideoPayloadParser(); case AACCodecInfo aacCodecInfo: return new AACAudioPayloadParser(aacCodecInfo); case G711CodecInfo g711CodecInfo: return new G711AudioPayloadParser(g711CodecInfo); case G726CodecInfo g726CodecInfo: return new G726AudioPayloadParser(g726CodecInfo); case PCMCodecInfo pcmCodecInfo: return new PCMAudioPayloadParser(pcmCodecInfo); default: throw new ArgumentOutOfRangeException(nameof(codecInfo), $"Unsupported codec: {codecInfo.GetType().Name}"); } } } }
34.859649
104
0.616004
[ "MIT" ]
AntonelloSemeraro98/RtspClientSharp
RtspClientSharp/MediaParsers/MediaPayloadParser.cs
1,989
C#
using Alarmy.Common; using Microsoft.VisualStudio.TestTools.UnitTesting; using NSubstitute; using System; namespace Alarmy.Tests { [TestClass] public class AlarmTests { private readonly static DateTime SAMPLE_DATETIME = new DateTime(2014, 10, 10, 13, 05, 0); private IDateTimeProvider dateTimeProvider; private Alarm alarm; [TestInitialize] public void Setup() { this.dateTimeProvider = Substitute.For<IDateTimeProvider>(); this.alarm = new Alarm(this.dateTimeProvider); } #region Set status tests [TestMethod] public void Alarm_WhenSet_CanBeCancelled() { alarm.Status = AlarmStatus.Set; alarm.Cancel(); Assert.AreEqual(AlarmStatus.Canceled, alarm.Status); } [TestMethod] public void Alarm_WhenSet_CanBeRinging() { alarm.Status = AlarmStatus.Set; alarm.SetStatus(AlarmStatus.Ringing); Assert.AreEqual(AlarmStatus.Ringing, alarm.Status); } [TestMethod] [ExpectedException(typeof(InvalidStateException))] public void Alarm_WhenSet_CannotBeCompleted() { alarm.Status = AlarmStatus.Set; alarm.SetStatus(AlarmStatus.Completed); } [TestMethod] public void Alarm_WhenSet_CanBeMissed() { alarm.Status = AlarmStatus.Set; alarm.SetStatus(AlarmStatus.Missed); Assert.AreEqual(AlarmStatus.Missed, alarm.Status); } #endregion #region Ringing status tests [TestMethod] public void Alarm_WhenRinging_CanBeCompleted() { alarm.Status = AlarmStatus.Ringing; alarm.SetStatus(AlarmStatus.Completed); Assert.AreEqual(AlarmStatus.Completed, alarm.Status); } [TestMethod] public void Alarm_WhenRinging_CanBeMissed() { alarm.Status = AlarmStatus.Ringing; alarm.SetStatus(AlarmStatus.Missed); Assert.AreEqual(AlarmStatus.Missed, alarm.Status); } [TestMethod] public void Alarm_WhenRinging_CanBeCancelled() { alarm.Status = AlarmStatus.Ringing; alarm.SetStatus(AlarmStatus.Canceled); Assert.AreEqual(AlarmStatus.Canceled, alarm.Status); } [TestMethod] public void Alarm_WhenRinging_CanBeSet() { alarm.Status = AlarmStatus.Ringing; alarm.SetStatus(AlarmStatus.Set); Assert.AreEqual(AlarmStatus.Set, alarm.Status); } #endregion #region Cancelled state tests [TestMethod] [ExpectedException(typeof(InvalidStateException))] public void Alarm_WhenCancelled_CannotBeCompleted() { alarm.Status = AlarmStatus.Canceled; alarm.SetStatus(AlarmStatus.Completed); } [TestMethod] [ExpectedException(typeof(InvalidStateException))] public void Alarm_WhenCancelled_CannotBeRinging() { alarm.Status = AlarmStatus.Canceled; alarm.SetStatus(AlarmStatus.Ringing); } [TestMethod] public void Alarm_WhenCancelled_CanBeSet() { alarm.Status = AlarmStatus.Canceled; alarm.SetStatus(AlarmStatus.Set); Assert.AreEqual(AlarmStatus.Set, alarm.Status); } [TestMethod] [ExpectedException(typeof(InvalidStateException))] public void Alarm_WhenCancelled_CannotBeMissed() { alarm.Status = AlarmStatus.Canceled; alarm.SetStatus(AlarmStatus.Missed); } #endregion #region Completed state tests [TestMethod] public void Alarm_WhenCompleted_CanBeSet() { alarm.Status = AlarmStatus.Completed; alarm.SetStatus(AlarmStatus.Set); Assert.AreEqual(AlarmStatus.Set, alarm.Status); } [TestMethod] [ExpectedException(typeof(InvalidStateException))] public void Alarm_WhenCompleted_CannotBeRinging() { alarm.Status = AlarmStatus.Completed; alarm.SetStatus(AlarmStatus.Ringing); } [TestMethod] [ExpectedException(typeof(InvalidStateException))] public void Alarm_WhenCompleted_CannotBeCancelled() { alarm.Status = AlarmStatus.Completed; alarm.SetStatus(AlarmStatus.Canceled); } [TestMethod] [ExpectedException(typeof(InvalidStateException))] public void Alarm_WhenCompleted_CannotBeMissed() { alarm.Status = AlarmStatus.Completed; alarm.SetStatus(AlarmStatus.Missed); } #endregion #region Missed status tests [TestMethod] public void Alarm_WhenMissed_CanBeCompleted() { alarm.Status = AlarmStatus.Missed; alarm.SetStatus(AlarmStatus.Completed); Assert.AreEqual(AlarmStatus.Completed, alarm.Status); } [TestMethod] public void Alarm_WhenMissed_CanBeCancelled() { alarm.Status = AlarmStatus.Missed; alarm.SetStatus(AlarmStatus.Canceled); Assert.AreEqual(AlarmStatus.Canceled, alarm.Status); } [TestMethod] public void Alarm_WhenMissed_CanBeSet() { alarm.Status = AlarmStatus.Missed; alarm.SetStatus(AlarmStatus.Set); Assert.AreEqual(AlarmStatus.Set, alarm.Status); } [TestMethod] [ExpectedException(typeof(InvalidStateException))] public void Alarm_WhenMissed_CannotBeRinging() { alarm.Status = AlarmStatus.Missed; alarm.SetStatus(AlarmStatus.Ringing); } #endregion #region TimeTests [TestMethod] public void Time_WhenSet_ChangesRingTime() { this.alarm.SetTime(SAMPLE_DATETIME); Assert.AreEqual(SAMPLE_DATETIME, this.alarm.Time); } [TestMethod] public void Time_WhenSet_ChangesAlarmStatus() { this.alarm.Status = AlarmStatus.Ringing; this.alarm.SetTime(SAMPLE_DATETIME); Assert.AreEqual(AlarmStatus.Set, this.alarm.Status); } [TestMethod] public void Time_WhenSet_ChangesHush() { this.alarm.IsHushed = true; ; this.alarm.SetTime(SAMPLE_DATETIME); Assert.IsFalse(this.alarm.IsHushed); } #endregion #region Snooze tests //[TestMethod] //public void Snooze_WhenCalled_IncreasesRingTime() //{ // this.alarm.Set(SAMPLE_DATETIME); // this.alarm.Snooze(); // Assert.AreEqual(SAMPLE_DATETIME.AddMinutes(TimeAlarm.SNOOZE_INTERVAL), this.alarm.Time); //} //[TestMethod] //public void Snooze_WhenCalled_ChangesAlarmStatus() //{ // this.alarm.Set(SAMPLE_DATETIME); // this.alarm.Status = AlarmStatus.Ringing; // this.alarm.Snooze(); // Assert.AreEqual(AlarmStatus.Set, this.alarm.Status); //} #endregion #region Check tests [TestMethod] public void Check_BeforeAlarm_DoesNothing() { this.alarm.SetTime(SAMPLE_DATETIME); this.dateTimeProvider.Now.Returns(SAMPLE_DATETIME.AddMinutes(-5)); this.alarm.CheckStatusChange(); Assert.AreEqual(AlarmStatus.Set, this.alarm.Status); } [TestMethod] public void Check_DuringAlarm_SetsStatusToRinging() { this.alarm.SetTime(SAMPLE_DATETIME); this.dateTimeProvider.Now.Returns(SAMPLE_DATETIME); this.alarm.CheckStatusChange(); Assert.AreEqual(AlarmStatus.Ringing, this.alarm.Status); } [TestMethod] public void Check_AfterAlarm_SetsStatusToMissed() { this.alarm.SetTime(SAMPLE_DATETIME); this.dateTimeProvider.Now.Returns(SAMPLE_DATETIME.AddMinutes(5)); this.alarm.CheckStatusChange(); Assert.AreEqual(AlarmStatus.Missed, this.alarm.Status); } [TestMethod] public void Check_WhenCompleted_DoesNothing() { this.alarm.SetTime(SAMPLE_DATETIME); this.dateTimeProvider.Now.Returns(SAMPLE_DATETIME.AddMinutes(-5)); this.alarm.Status = AlarmStatus.Completed; this.alarm.CheckStatusChange(); Assert.AreEqual(AlarmStatus.Completed, this.alarm.Status); } #endregion [TestMethod] public void IsRinging_ReturnsFalse_WhenRingingAndNotHushed() { this.alarm.Status = AlarmStatus.Ringing; this.alarm.IsHushed = false; Assert.IsTrue(this.alarm.IsRinging); } [TestMethod] public void IsRinging_ReturnsFalse_WhenRingingButHushed() { this.alarm.Status = AlarmStatus.Ringing; this.alarm.IsHushed = true; Assert.IsFalse(this.alarm.IsRinging); } } }
28.012012
102
0.600021
[ "MIT" ]
finarfin/Alarmy
Alarmy.Tests/Common/AlarmTests.cs
9,330
C#
namespace IsMatch.AbpStudy.Dtos { public class PagedSortedAndFilteredInputDto : PagedAndSortedInputDto { public string FilterText { get; set; } } }
11.9375
72
0.623037
[ "MIT" ]
skyIsland/IsMatch.AbpStudy
src/abpstudy-aspnet-core/src/IsMatch.AbpStudy.Application/Dtos/PagedSortedAndFilteredInputDto.cs
191
C#
using SppdDocs.Core.Domain.Entities; using SppdDocs.DTOs; namespace SppdDocs.MappingProfiles { internal class CardMappingProfile : MappingProfileBase { public CardMappingProfile() { // TODO: Map to correct user language CreateVersionedEntityToDtoMap<Card, CardFullDto>() .ForMember(dest => dest.Name, opt => opt.MapFrom(src => src.Name.En)) .ForMember(dest => dest.DescriptionMarkdown, opt => opt.MapFrom(src => src.DescriptionMarkdown.En)) .ForMember(dest => dest.DescriptionOnCard, opt => opt.MapFrom(src => src.DescriptionOnCard.En)) .ForMember(dest => dest.EnergyCost, opt => opt.MapFrom(src => src.EnergyCost)) .ForMember(dest => dest.UnlockedAtRank, opt => opt.MapFrom(src => src.UnlockedAtRank)) .ForMember(dest => dest.Range, opt => opt.MapFrom(src => src.Range)) .ForMember(dest => dest.ThemeName, opt => opt.MapFrom(src => src.Theme.Name.En)) .ForMember(dest => dest.RarityName, opt => opt.MapFrom(src => src.Rarity.Name.En)) .ForMember(dest => dest.ClassName, opt => opt.MapFrom(src => src.Class.Name.En)) .ForMember(dest => dest.EffectName, opt => opt.MapFrom(src => src.EffectId.HasValue ? src.Effect.Name.En : null)) .ForMember(dest => dest.StatusEffectName, opt => opt.MapFrom(src => src.StatusEffectId.HasValue ? src.StatusEffect.Name.En : null)) .ForMember(dest => dest.CastAreaName, opt => opt.MapFrom(src => src.CastArea.Name.En)) .ForMember(dest => dest.MaxVelocity, opt => opt.MapFrom(src => src.MaxVelocity)) .ForMember(dest => dest.TimeToReachMaxVelocitySec, opt => opt.MapFrom(src => src.TimeToReachMaxVelocitySec)) .ForMember(dest => dest.AgroRangeMultiplier, opt => opt.MapFrom(src => src.AgroRangeMultiplier)) .ForMember(dest => dest.AttackRange, opt => opt.MapFrom(src => src.AttackRange)) .ForMember(dest => dest.PreAttackDelay, opt => opt.MapFrom(src => src.PreAttackDelay)) .ForMember(dest => dest.TimeInBetweenAttacksSec, opt => opt.MapFrom(src => src.TimeInBetweenAttacksSec)) .ForMember(dest => dest.CardUpgrades, opt => opt.MapFrom(src => src.GetUpgradeLevels())) .ForMember(dest => dest.CardAttributes, opt => opt.MapFrom(src => src.GetCardAttributes())); } } }
72.911765
147
0.625252
[ "MIT" ]
taconaut/sppdDocs
Backend/src/SppdDocs/MappingProfiles/CardMappingprofile.cs
2,481
C#
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. namespace BrightChain.EntityFrameworkCore.Storage.Internal { /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public class SqlParameter { /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public SqlParameter(string name, object? value) { Name = name; Value = value; } /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public virtual string Name { get; } /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public virtual object? Value { get; } } }
57.139535
113
0.671958
[ "Apache-2.0" ]
MaxMood96/BrightChain
src/BrightChain.EntityFrameworkCore/Storage/Internal/SqlParameter.cs
2,457
C#
using Microsoft.EntityFrameworkCore.Migrations; namespace IdentityDemo.Migrations.UsersDb { public partial class TestUserSeeding : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.UpdateData( table: "AspNetRoles", keyColumn: "Id", keyValue: "admin", column: "ConcurrencyStamp", value: "17722115-21fd-4451-8db4-e99f5c602421"); migrationBuilder.UpdateData( table: "AspNetRoles", keyColumn: "Id", keyValue: "moderator", column: "ConcurrencyStamp", value: "77ab348b-69d4-4e9a-9515-0a5c60bbf840"); migrationBuilder.UpdateData( table: "AspNetUsers", keyColumn: "Id", keyValue: "dbfcc1a5-fe40-4539-9e3c-ae5d75c09e19", columns: new[] { "ConcurrencyStamp", "PasswordHash", "SecurityStamp" }, values: new object[] { "d6021be4-a1fb-4265-9a99-69353b243cee", "AQAAAAEAACcQAAAAEJcltf7DARNNFfCIS4Uz9uf6vjNJW9HqoFtUiIpymvzqxov24vihIVTVbBmJHkgqvw==", "dee200a6-c80a-4328-9f32-8be7c268f114" }); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.UpdateData( table: "AspNetRoles", keyColumn: "Id", keyValue: "admin", column: "ConcurrencyStamp", value: "7264fdfd-5422-4cad-a12c-356a4694ef01"); migrationBuilder.UpdateData( table: "AspNetRoles", keyColumn: "Id", keyValue: "moderator", column: "ConcurrencyStamp", value: "79b16ad0-71fc-4d45-851a-c8c0544adf1d"); migrationBuilder.UpdateData( table: "AspNetUsers", keyColumn: "Id", keyValue: "dbfcc1a5-fe40-4539-9e3c-ae5d75c09e19", columns: new[] { "ConcurrencyStamp", "PasswordHash", "SecurityStamp" }, values: new object[] { "8d4b7189-803f-4c62-a5e9-bbbce2f08c36", "AQAAAAEAACcQAAAAEMfJn2xgswkLTOY0V861KjTNPhVPpD6+y9Q5NdMpFsZhNEM6kDdZFQUSCT39p+u4AA==", "7a67ae14-e7dc-403a-9556-ba3ae5859429" }); } } }
41.571429
209
0.580326
[ "MIT" ]
TheAgileMCB/cr-dotnet-401d1
Class27/Demo/IdentityDemo/Migrations/UsersDb/20200609152839_TestUserSeeding.cs
2,330
C#
using Domain.Base; namespace Domain.Events { public class UserEmailChangedEvent : DomainEvent { public string ApplicationUserEmail { get; } public string ApplicationUserNewEmail { get; } public UserEmailChangedEvent(string applicationUserEmail, string applicationUserNewEmail) { ApplicationUserEmail = applicationUserEmail; ApplicationUserNewEmail = applicationUserNewEmail; } } }
28.6875
97
0.697168
[ "MIT" ]
GoToWinThat/ProjectManagementApi
ProjectManagement/Domain/Events/UserEmailChangedEvent.cs
461
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using System.Xml.XPath; using StackNav = MS.Internal.Xml.XPath.ClonableStack<System.Xml.XPath.XPathNavigator>; namespace MS.Internal.Xml.XPath { // Algorithm: // Input assumption: qyInput is in DocOrder. // Preceding of a sequence of nodes will be preceding of last node in DocOrder in that sequence. // Because qyInput is in DO last input is last node in DO. -- "last" // If last node is attribute or namespace move last to it element. // Push this last node and all its ancestors into the ancestorStk. The root node will be the top-most element on the stack. // Create descendent iterator from the root. -- "workIterator" // Advancing workIterator we meet all nodes from the ancestorStk in stack order. Nodes in ancestorStk do no belong to the // the 'preceding' axis and must be ignored. // Last node in ancestorStk is a sentinel node; when we pop it from ancestorStk, we should stop iterations. internal sealed class PrecedingQuery : BaseAxisQuery { private XPathNodeIterator _workIterator; private StackNav _ancestorStk; public PrecedingQuery(Query qyInput, string name, string prefix, XPathNodeType typeTest) : base(qyInput, name, prefix, typeTest) { _ancestorStk = new StackNav(); } private PrecedingQuery(PrecedingQuery other) : base(other) { _workIterator = Clone(other._workIterator); _ancestorStk = other._ancestorStk.Clone(); } public override void Reset() { _workIterator = null; _ancestorStk.Clear(); base.Reset(); } public override XPathNavigator Advance() { if (_workIterator == null) { XPathNavigator last; { XPathNavigator input = qyInput.Advance(); if (input == null) { return null; } last = input.Clone(); do { last.MoveTo(input); } while ((input = qyInput.Advance()) != null); if (last.NodeType == XPathNodeType.Attribute || last.NodeType == XPathNodeType.Namespace) { last.MoveToParent(); } } // Fill ancestorStk : do { _ancestorStk.Push(last.Clone()); } while (last.MoveToParent()); // Create workIterator : // last.MoveToRoot(); We are on root already _workIterator = last.SelectDescendants(XPathNodeType.All, true); } while (_workIterator.MoveNext()) { currentNode = _workIterator.Current; if (currentNode.IsSamePosition(_ancestorStk.Peek())) { _ancestorStk.Pop(); if (_ancestorStk.Count == 0) { currentNode = null; _workIterator = null; Debug.Assert(qyInput.Advance() == null, "we read all qyInput.Advance() already"); return null; } continue; } if (matches(currentNode)) { position++; return currentNode; } } Debug.Fail("Algorithm error: we missed the sentinel node"); return null; } public override XPathNodeIterator Clone() { return new PrecedingQuery(this); } public override QueryProps Properties { get { return base.Properties | QueryProps.Reverse; } } } }
38.641509
136
0.540039
[ "MIT" ]
2E0PGS/corefx
src/System.Private.Xml/src/System/Xml/XPath/Internal/PrecedingQuery.cs
4,096
C#
using BizHawk.Common; using BizHawk.BizInvoke; using BizHawk.Emulation.Common; using System; using System.Runtime.InteropServices; namespace BizHawk.Emulation.Cores.Waterbox { public abstract class LibWaterboxCore { public const CallingConvention CC = CallingConvention.Cdecl; [StructLayout(LayoutKind.Sequential)] public class FrameInfo { /// <summary> /// pointer to the video buffer; set by frontend, filled by backend /// </summary> public IntPtr VideoBuffer; /// <summary> /// pointer to the sound buffer; set by frontend, filled by backend /// </summary> public IntPtr SoundBuffer; /// <summary> /// total number of cycles emulated this frame; set by backend /// </summary> public long Cycles; /// <summary> /// width of the output image; set by backend /// </summary> public int Width; /// <summary> /// height of the output image; set by backend /// </summary> public int Height; /// <summary> /// total number of sample pairs produced; set by backend /// </summary> public int Samples; /// <summary> /// true if controllers were not read; set by backend /// </summary> public int Lagged; } [Flags] public enum MemoryDomainFlags : long { None = 0, /// <summary> /// if false, the domain MUST NOT be written to. /// in some cases, a segmentation violation might occur /// </summary> Writable = 1, /// <summary> /// if true, this memory domain should be used in saveram. /// can be ignored if the core provides its own saveram implementation /// </summary> Saverammable = 2, /// <summary> /// if true, domain is filled with ones (FF) by default, instead of zeros. /// used in calculating SaveRamModified /// </summary> OneFilled = 4, /// <summary> /// desginates the default memory domain /// </summary> Primary = 8, /// <summary> /// if true, the most significant bytes are first in multibyte words /// </summary> YugeEndian = 16, /// <summary> /// native wordsize. only a hint /// </summary> WordSize1 = 32, /// <summary> /// native wordsize. only a hint /// </summary> WordSize2 = 64, /// <summary> /// native wordsize. only a hint /// </summary> WordSize4 = 128, /// <summary> /// native wordsize. only a hint /// </summary> WordSize8 = 256, /// <summary> /// for a yuge endian domain, if true, bytes are stored word-swapped from their native ordering /// </summary> Swapped = 512, /// <summary> /// If true, Data is a function to call and not a pointer /// </summary> FunctionHook = 1024, } [StructLayout(LayoutKind.Sequential)] public struct MemoryArea { /// <summary> /// pointer to the data in memory, or a function hook to call /// </summary> public IntPtr Data; /// <summary> /// null terminated strnig naming the memory domain /// </summary> public IntPtr Name; /// <summary> /// size of the domain /// </summary> public long Size; public MemoryDomainFlags Flags; } [UnmanagedFunctionPointer(CC)] public delegate void MemoryFunctionHook(IntPtr buffer, long address, long count, bool write); [UnmanagedFunctionPointer(CC)] public delegate void EmptyCallback(); [BizImport(CC)] public abstract void FrameAdvance([In, Out] FrameInfo frame); [BizImport(CC)] public abstract void GetMemoryAreas([In, Out] MemoryArea[] areas); [BizImport(CC)] public abstract void SetInputCallback(EmptyCallback callback); } }
27.691729
99
0.624219
[ "MIT" ]
NarryG/bizhawk-vanguard
src/BizHawk.Emulation.Cores/Waterbox/LibWaterboxCore.cs
3,685
C#
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using System.Text; namespace AntYecai.Models { [DataContract] public class UserLoginInfo { [DataMember(Name = "loginName")] public String LoginName { get; set; } [DataMember(Name = "password")] public String Password { get; set; } [DataMember(Name = "sign")] public String Sign { get; set; } } }
22.181818
46
0.610656
[ "MIT" ]
HungryAnt/AntYecaiLauncher
AntYecai/Models/UserLoginInfo.cs
490
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Classes { public class DepartamentoBLL { private int id; private string nome; public int Id { get { return id; } set { id = value; } } public string Nome { get { return nome; } set { nome = value; } } } }
17
33
0.520697
[ "MIT" ]
Nivaldeir/Hotelaria-Excellence-Csharp
Classes/BLLs/DepartamentoBLL.cs
461
C#
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; namespace MeshiRoulette.Data { /// <summary>いわゆるルーレット</summary> public class PlaceCollection { public string Id { get; set; } [Required] public string Name { get; set; } [Required] public string CreatorId { get; set; } public ApplicationUser Creator { get; set; } [Required] public string Description { get; set; } public PlaceCollectionAccessibility Accessibility { get; set; } public DateTimeOffset CreatedAt { get; set; } public List<Place> Places { get; set; } public PlaceCollection() { } public PlaceCollection(string name, string creatorId, string description, PlaceCollectionAccessibility accessibility, DateTimeOffset createdAt) { this.Id = Guid.NewGuid().ToString("N"); this.Name = name; this.CreatorId = creatorId; this.Description = description; this.Accessibility = accessibility; this.CreatedAt = createdAt; } } }
27.780488
151
0.62511
[ "Apache-2.0" ]
azyobuzin/meshi
MeshiRoulette/Data/PlaceCollection.cs
1,159
C#
using System; using System.Diagnostics; using System.Drawing; using System.Globalization; using System.IO; using System.Linq; using System.Runtime.InteropServices; using NuGetPackageExplorer.Types; using NuGetPe; namespace PackageExplorerViewModel { internal static class FileHelper { private static readonly string[] ExecutableScriptsExtensions = new[] { ".BAS", ".BAT", ".CHM", ".COM", ".EXE", ".HTA", ".INF", ".JS", ".LNK", ".MSI", ".OCX", ".PPT", ".REG", ".SCT", ".SHS", ".SYS", ".URL", ".VB", ".VBS", ".WSH", ".WSF" }; private static readonly string[] BinaryFileExtensions = new[] { ".DLL", ".EXE", ".WINMD", ".CHM", ".PDF", ".DOCX", ".DOC", ".JPG", ".PNG", ".GIF", ".RTF", ".PDB", ".ZIP", ".RAR", ".XAP", ".VSIX", ".NUPKG", ".SNUPKG", ".SNK", ".PFX", ".ICO" }; public static bool IsBinaryFile(string path) { // TODO: check for content type of the file here var extension = Path.GetExtension(path); return !string.IsNullOrEmpty(extension) && BinaryFileExtensions.Any(p => p.Equals(extension, StringComparison.InvariantCultureIgnoreCase)); } public static void OpenFileInShell(PackageFile file, IUIServices uiServices) { if (IsExecutableScript(file.Name)) { var confirm = uiServices.Confirm( string.Format(CultureInfo.CurrentCulture, Resources.OpenExecutableScriptWarning_Title, file.Name), Resources.OpenExecutableScriptWarning, isWarning: true); if (!confirm) { return; } } // copy to temporary file // create package in the temprary file first in case the operation fails which would // override existing file with a 0-byte file. var tempFileName = Path.Combine(GetTempFilePath(), file.Name); using (Stream tempFileStream = File.Create(tempFileName)) using (var packageStream = file.GetStream()) { packageStream.CopyTo(tempFileStream); } if (File.Exists(tempFileName)) { try { Process.Start("explorer.exe", tempFileName); } catch // Possible Win32 exception, nothing we can do { } } } private static bool IsExecutableScript(string fileName) { var extension = Path.GetExtension(fileName)?.ToUpperInvariant(); return Array.IndexOf(ExecutableScriptsExtensions, extension) > -1; } public static void OpenFileInShellWith(PackageFile file) { DiagnosticsClient.TrackEvent("FileHelper_OpenFileInShellWith"); // copy to temporary file // create package in the temprary file first in case the operation fails which would // override existing file with a 0-byte file. var tempFileName = Path.Combine(GetTempFilePath(), file.Name); using (Stream tempFileStream = File.Create(tempFileName)) using (var packageStream = file.GetStream()) { packageStream.CopyTo(tempFileStream); } if (File.Exists(tempFileName)) { var info = new ProcessStartInfo("rundll32.exe") { ErrorDialog = true, UseShellExecute = false, Arguments = "shell32.dll,OpenAs_RunDLL " + tempFileName }; try { Process.Start(info); } catch // Possible Win32 exception, nothing we can do { } } } public static string GuessFolderNameFromFile(string file) { var extension = Path.GetExtension(file)?.ToUpperInvariant(); if (extension == ".DLL" || extension == ".PDB") { return "lib"; } else if (extension == ".PS1" || extension == ".PSM1" || extension == ".PSD1") { return "tools"; } else { return "content"; } } public static string GetTempFilePath() { var tempPath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); if (!Directory.Exists(tempPath)) { Directory.CreateDirectory(tempPath); } return tempPath; } public static string CreateTempFile(string fileName, string content = "") { if (string.IsNullOrEmpty(fileName)) { throw new ArgumentException("Argument is null or empty", nameof(fileName)); } var filePath = Path.Combine(GetTempFilePath(), fileName); File.WriteAllText(filePath, content); return filePath; } public static string CreateTempFile(string fileName, Stream content) { if (string.IsNullOrEmpty(fileName)) { throw new ArgumentException("Argument is null or empty", nameof(fileName)); } var filePath = Path.Combine(GetTempFilePath(), fileName); using (Stream targetStream = File.Create(filePath)) { content.CopyTo(targetStream); } return filePath; } public static bool IsAssembly(string path) { return path.EndsWith(".dll", StringComparison.OrdinalIgnoreCase) || path.EndsWith(".winmd", StringComparison.OrdinalIgnoreCase) || path.EndsWith(".exe", StringComparison.OrdinalIgnoreCase); } [Flags] private enum SHGFI { /// <summary> /// Get icon /// </summary> Icon = 0x000000100, /// <summary> /// get display name /// </summary> DisplayName = 0x000000200, /// <summary> /// Get type name /// </summary> TypeName = 0x000000400, /// <summary> /// Get attributes /// </summary> Attributes = 0x000000800, /// <summary> /// Get icon location /// </summary> IconLocatin = 0x000001000, /// <summary> /// Return exe type /// </summary> ExeType = 0x000002000, /// <summary> /// Get system icon index /// </summary> SysIconIndex = 0x000004000, /// <summary> /// Put a link overlay on icon /// </summary> LinkOverlay = 0x000008000, /// <summary> /// Show icon in selected state /// </summary> Selected = 0x000010000, /// <summary> /// Get only specified attributes /// </summary> Attr_Specified = 0x000020000, /// <summary> /// Get large icon /// </summary> LargeIcon = 0x000000000, /// <summary> /// Get small icon /// </summary> SmallIcon = 0x000000001, /// <summary> /// Get open icon /// </summary> OpenIcon = 0x000000002, /// <summary> /// Get shell size icon /// </summary> ShellIconize = 0x000000004, /// <summary> /// pszPath is a pidl /// </summary> PIDL = 0x000000008, /// <summary> /// Use passed dwFileAttribute /// </summary> UseFileAttributes = 0x000000010, /// <summary> /// Apply the appropriate overlays /// </summary> AddOverlays = 0x000000020, /// <summary> /// Get the index of the overlay in the upper 8 bits of the iIcon /// </summary> OverlayIndex = 0x000000040, /// <summary> /// The handle that identifies a directory. /// </summary> FILE_ATTRIBUTE_DIRECTORY = 0x10, } /// <summary> /// Maximal Length of unmanaged Windows-Path-strings /// </summary> private const int MAX_PATH = 260; /// <summary> /// Maximal Length of unmanaged Typename /// </summary> private const int MAX_TYPE = 80; private const int FILE_ATTRIBUTE_NORMAL = 0x80; [DllImport("shell32.dll", CharSet = CharSet.Auto, SetLastError = true)] private static extern int SHGetFileInfo(string pszPath, int dwFileAttributes, out SHFILEINFO psfi, uint cbfileInfo, SHGFI uFlags); [DllImport("user32.dll")] private static extern int DestroyIcon(IntPtr hIcon); #pragma warning disable IDE1006 // Naming Styles [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)] private struct SHFILEINFO { public IntPtr hIcon; public int iIcon; public uint dwAttributes; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = MAX_PATH)] public string szDisplayName; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = MAX_TYPE)] public string szTypeName; } #pragma warning restore IDE1006 // Naming Styles [System.Diagnostics.CodeAnalysis.SuppressMessage("Performance", "CA1806:Do not ignore method results", Justification = "<Pending>")] public static Icon ExtractAssociatedIcon(string fileName) { var info = new SHFILEINFO(); var infoSize = (uint)Marshal.SizeOf(info); SHGetFileInfo( fileName, FILE_ATTRIBUTE_NORMAL, out info, infoSize, SHGFI.Icon | SHGFI.SmallIcon | SHGFI.UseFileAttributes); var icon = (Icon)Icon.FromHandle(info.hIcon).Clone(); DestroyIcon(info.hIcon); return icon; } } }
33.92515
151
0.473568
[ "MIT" ]
Frogman7/NuGetPackageExplorer
PackageViewModel/Utilities/FileHelper.cs
11,333
C#
// Copyright © Joerg Battermann 2014, Matt Hunt 2017 using System; using System.Collections.Generic; using System.Globalization; namespace GeoJSON.Net.Geometry; /// <summary> /// A position is the fundamental geometry construct, consisting of <see cref="Latitude" />, /// <see cref="Longitude" /> and (optionally) <see cref="Altitude" />. /// </summary> public class Position : IPosition, IEqualityComparer<Position>, IEquatable<Position> { private static readonly DoubleTenDecimalPlaceComparer DoubleComparer = new(); /// <summary> /// Initializes a new instance of the <see cref="Position" /> class. /// </summary> /// <param name="latitude">The latitude, or Y coordinate.</param> /// <param name="longitude">The longitude or X coordinate.</param> public Position(double latitude, double longitude) { // TODO Coordinate range validation should be performed only when CRS is supplied Latitude = latitude; Longitude = longitude; } /// <summary> /// Initializes a new instance of the <see cref="Position" /> class. /// </summary> /// <param name="latitude">The latitude, or Y coordinate e.g. '38.889722'.</param> /// <param name="longitude">The longitude, or X coordinate e.g. '-77.008889'.</param> public Position(string latitude, string longitude) { // TODO Coordinate range validation should be performed only when CRS is supplied if (string.IsNullOrEmpty(latitude)) { throw new ArgumentOutOfRangeException(nameof(latitude), "May not be empty."); } if (string.IsNullOrEmpty(longitude)) { throw new ArgumentOutOfRangeException(nameof(longitude), "May not be empty."); } if (!double.TryParse(latitude, NumberStyles.Float, CultureInfo.InvariantCulture, out double lat)) { throw new ArgumentOutOfRangeException(nameof(latitude), "Latitude representation must be a numeric."); } if (!double.TryParse(longitude, NumberStyles.Float, CultureInfo.InvariantCulture, out double lon)) { throw new ArgumentOutOfRangeException(nameof(longitude), "Longitude representation must be a numeric."); } Latitude = lat; Longitude = lon; } /// <summary> /// Gets the latitude or Y coordinate /// </summary> public double Latitude { get; } /// <summary> /// Gets the longitude or X coordinate /// </summary> public double Longitude { get; } public static readonly Position Zero = new(0.0d, 0.0d); /// <summary> /// Returns a <see cref="string" /> that represents this instance. /// </summary> /// <returns> /// A <see cref="string" /> that represents this instance. /// </returns> public override string ToString() { return string.Format(CultureInfo.InvariantCulture, "Latitude: {0}, Longitude: {1}", Latitude, Longitude); } #region IEqualityComparer, IEquatable /// <summary> /// Determines whether the specified object is equal to the current object /// </summary> public override bool Equals(object obj) { return this == (obj as Position); } /// <summary> /// Determines whether the specified object is equal to the current object /// </summary> public bool Equals(Position other) { return this == other; } /// <summary> /// Determines whether the specified object instances are considered equal /// </summary> public bool Equals(Position left, Position right) { return left == right; } /// <summary> /// Determines whether the specified object instances are considered equal /// </summary> public static bool operator ==(Position left, Position right) { if (ReferenceEquals(left, right)) { return true; } if (right is null || left is null) { return false; } if (!DoubleComparer.Equals(left.Latitude, right.Latitude) || !DoubleComparer.Equals(left.Longitude, right.Longitude)) { return false; } return true; } /// <summary> /// Determines whether the specified object instances are considered equal /// </summary> public static bool operator !=(Position left, Position right) { return !(left == right); } /// <summary> /// Returns the hash code for this instance /// </summary> public override int GetHashCode() { return HashCode.Combine(Latitude, Longitude); } /// <summary> /// Returns the hash code for the specified object /// </summary> public int GetHashCode(Position other) { return other.GetHashCode(); } #endregion }
30.738854
116
0.624119
[ "MIT" ]
DmitryNizhebovsky/GeoJSON.Net
src/GeoJSON.Net/Geometry/Position.cs
4,829
C#
using System.Threading.Tasks; using HeroesReplay.Core.Models; namespace HeroesReplay.Core.Services.Twitch.Rewards { public interface IRequestQueue { Task<RewardQueueItem> DequeueItemAsync(); Task<RewardResponse> EnqueueItemAsync(RewardRequest request); Task<int> GetItemsInQueue(); Task<RewardQueueItem> FindByIndexAsync(int index); Task<(RewardQueueItem Item, int Position)?> RemoveItemAsync(string login); Task<(RewardQueueItem Item, int Position)?> FindNextByLoginAsync(string login); } }
34.625
87
0.731047
[ "MIT" ]
HeroesReplay/HeroesReplay
src/HeroesReplay.Core/Services/Queue/IRequestQueue.cs
556
C#
// <auto-generated /> using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Migrations; using Microsoft.EntityFrameworkCore.Storage.ValueConversion; using RadioConsole.Web.Database; namespace RadioConsole.Web.Migrations { [DbContext(typeof(RadioDBContext))] [Migration("20210218220305_IncidentListMigration")] partial class IncidentListMigration { protected override void BuildTargetModel(ModelBuilder modelBuilder) { #pragma warning disable 612, 618 modelBuilder .HasAnnotation("ProductVersion", "3.1.0") .HasAnnotation("Relational:MaxIdentifierLength", 128) .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); modelBuilder.Entity("RadioConsole.Web.Entities.IncidentEntity", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("Description") .HasColumnType("nvarchar(max)"); b.Property<decimal>("Latitude") .HasColumnType("decimal(18,2)"); b.Property<decimal>("Longitude") .HasColumnType("decimal(18,2)"); b.HasKey("Id"); b.ToTable("Incidents"); }); modelBuilder.Entity("RadioConsole.Web.Entities.RadioEntity", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<int>("BatteryLevel") .HasColumnType("int"); b.Property<int>("Mode") .HasColumnType("int"); b.Property<string>("Name") .HasColumnType("nvarchar(max)"); b.Property<string>("SerialNumber") .HasColumnType("nvarchar(max)"); b.Property<int>("SignalStrength") .HasColumnType("int"); b.Property<int>("Type") .HasColumnType("int"); b.Property<int>("Unit") .HasColumnType("int"); b.HasKey("Id"); b.ToTable("Radios"); }); modelBuilder.Entity("RadioConsole.Web.Entities.UsersEntity", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("Email") .HasColumnType("nvarchar(max)"); b.Property<string>("Name") .HasColumnType("nvarchar(max)"); b.Property<string>("Password") .HasColumnType("nvarchar(max)"); b.Property<string>("Role") .HasColumnType("nvarchar(max)"); b.Property<string>("Username") .HasColumnType("nvarchar(max)"); b.HasKey("Id"); b.ToTable("Users"); }); #pragma warning restore 612, 618 } } }
36.102804
125
0.514108
[ "MIT" ]
SebastianTyr/RadioSimulator
RadioSimulator/RadioConsole.Web/Migrations/20210218220305_IncidentListMigration.Designer.cs
3,865
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.Outputs { [OutputType] public sealed class WebAclRuleStatementAndStatementStatementAndStatementStatementSqliMatchStatement { /// <summary> /// Part of a web request that you want AWS WAF to inspect. See Field to Match below for details. /// </summary> public readonly Outputs.WebAclRuleStatementAndStatementStatementAndStatementStatementSqliMatchStatementFieldToMatch? FieldToMatch; /// <summary> /// Text transformations eliminate some of the unusual formatting that attackers use in web requests in an effort to bypass detection. See Text Transformation below for details. /// </summary> public readonly ImmutableArray<Outputs.WebAclRuleStatementAndStatementStatementAndStatementStatementSqliMatchStatementTextTransformation> TextTransformations; [OutputConstructor] private WebAclRuleStatementAndStatementStatementAndStatementStatementSqliMatchStatement( Outputs.WebAclRuleStatementAndStatementStatementAndStatementStatementSqliMatchStatementFieldToMatch? fieldToMatch, ImmutableArray<Outputs.WebAclRuleStatementAndStatementStatementAndStatementStatementSqliMatchStatementTextTransformation> textTransformations) { FieldToMatch = fieldToMatch; TextTransformations = textTransformations; } } }
47.25
185
0.768372
[ "ECL-2.0", "Apache-2.0" ]
chivandikwa/pulumi-aws
sdk/dotnet/WafV2/Outputs/WebAclRuleStatementAndStatementStatementAndStatementStatementSqliMatchStatement.cs
1,701
C#
// // Unit tests for AVAudioPlayer // // Authors: // Sebastien Pouliot <sebastien@xamarin.com> // // Copyright 2013 Xamarin Inc. All rights reserved. // #if !__WATCHOS__ using System; using System.IO; #if XAMCORE_2_0 using Foundation; using AVFoundation; #else using MonoTouch.AVFoundation; using MonoTouch.Foundation; #endif using NUnit.Framework; namespace MonoTouchFixtures.AVFoundation { [TestFixture] [Preserve (AllMembers = true)] public class AudioPlayerTest { [Test] public void FromUrl () { string file = Path.Combine (NSBundle.MainBundle.ResourcePath, "Hand.wav"); Assert.True (File.Exists (file), file); NSError error; using (var url = new NSUrl (file, false)) using (var ap = AVAudioPlayer.FromUrl (url, out error)) { Assert.NotNull (ap, "AVAudioPlayer"); Assert.Null (error, "NSError"); } } } } #endif // !__WATCHOS__
19.444444
77
0.706286
[ "BSD-3-Clause" ]
1975781737/xamarin-macios
tests/monotouch-test/AVFoundation/AudioPlayerTest.cs
875
C#
using System; using System.Collections; using System.Collections.Generic; using System.Linq; namespace Lua.Common { public class EvaluationMachine<TIn, TOut> : IEnumerable<TOut> { protected readonly IEnumerable<Func<Evaluator<TIn, TOut>>> Evaluators; protected IEnumerable<Evaluator<TIn, TOut>> DefaultEvaluators() => Evaluators.Select(e => e()); protected readonly IEnumerable<TIn> Source; public EvaluationMachine(IEnumerable<Func<Evaluator<TIn, TOut>>> evaluators, IEnumerable<TIn> source) { Evaluators = evaluators; Source = source; } protected IEnumerable<TOut> Evaluate() { var evaluators = DefaultEvaluators(); foreach (var character in Source) { var next = StepEvaluators(evaluators, character); if (evaluators.HasSingle() && !next.Any()) { yield return evaluators.Single().Value; evaluators = StepEvaluators(DefaultEvaluators(), character); } else if (!next.Any()) { yield return evaluators.Single(e => e.State == EvaluatorState.Accepted).Value; evaluators = StepEvaluators(DefaultEvaluators(), character); } else { evaluators = next; } } } protected Evaluator<TIn, TOut>[] StepEvaluators(IEnumerable<Evaluator<TIn, TOut>> evaluators, TIn character) { return evaluators.Select(e => { var n = e.Copy(); n.State = n.Evaluate(character); return n; }).Where(e => e.State != EvaluatorState.Failed) .ToArray(); } public IEnumerator<TOut> GetEnumerator() => Evaluate().GetEnumerator(); IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); } }
34.118644
116
0.546945
[ "MIT" ]
KelsonBall/Lua.Core
Lua.Common/EvaluationMachine.cs
2,015
C#
using EInfrastructure.Core.Configuration.Ioc.Plugs.Storage.Config; namespace EInfrastructure.Core.Configuration.Ioc.Plugs.Storage.Params.Storage { /// <summary> /// 文件下载(根据文件地址,可访问,有授权) /// </summary> public class FileDownloadParam { /// <summary> /// /// </summary> /// <param name="url">文件访问地址(有权限可以访问的地址,如果你知道key的话,也可通过获取访问地址先获取到文件访问地址)</param> /// <param name="savePath">保存文件</param> /// <param name="persistentOps">策略</param> public FileDownloadParam(string url, string savePath,BasePersistentOps persistentOps) { Url = url; SavePath = savePath; PersistentOps = persistentOps; } /// <summary> /// 文件绝对地址(可访问,有授权) /// </summary> public string Url { get; } /// <summary> /// 保存文件地址 /// </summary> public string SavePath { get; } /// <summary> /// 策略 /// </summary> public BasePersistentOps PersistentOps { get; } } /// <summary> /// 文件下载(根据文件key) /// </summary> public class FileDownloadByKeyParam { /// <summary> /// /// </summary> /// <param name="key">文件key,非访问地址</param> /// <param name="savePath">保存文件</param> /// <param name="persistentOps">策略</param> public FileDownloadByKeyParam(string key, string savePath,BasePersistentOps persistentOps) { Key = key; SavePath = savePath; PersistentOps = persistentOps; } /// <summary> /// 文件key,非访问地址 /// </summary> public string Key { get; } /// <summary> /// 保存文件地址 /// </summary> public string SavePath { get; } /// <summary> /// 策略 /// </summary> public BasePersistentOps PersistentOps { get; } } }
26.246575
98
0.525052
[ "MIT" ]
Hunfnfmvkvllv26/System.Extension.Core
src/Configuration/src/EInfrastructure.Core.Configuration/Ioc/Plugs/Storage/Params/Storage/FileDownloadParam.cs
2,190
C#
// // CyclicDeque.cs // // Author: // Jérémie "Garuma" Laval <jeremie.laval@gmail.com> // // Copyright (c) 2009 Jérémie "Garuma" Laval // // 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. #if NET_4_0 || MOBILE using System; using System.Collections.Generic; using System.Threading; #if INSIDE_MONO_PARALLEL namespace Mono.Threading.Tasks #else namespace System.Threading.Tasks #endif { #if INSIDE_MONO_PARALLEL public #endif class CyclicDeque<T> : IConcurrentDeque<T> { const int BaseSize = 11; long bottom; long top; long upperBound; CircularArray<T> array = new CircularArray<T> (BaseSize); public void PushBottom (T obj) { /* Read is implemented as a simple load operation on 64bits * so no need to make the distinction ourselves */ long b = Interlocked.Read (ref bottom); var a = array; // Take care of growing if (b - upperBound >= a.Size - 1) { upperBound = Interlocked.Read (ref top); a = a.Grow (b, upperBound); array = a; } // Register the new value a.segment[b % a.size] = obj; Interlocked.Increment (ref bottom); } public PopResult PopBottom (out T obj) { obj = default (T); long b = Interlocked.Decrement (ref bottom); var a = array; long t = Interlocked.Read (ref top); long size = b - t; if (size < 0) { // Set bottom to t Interlocked.Add (ref bottom, t - b); return PopResult.Empty; } obj = a.segment[b % a.size]; if (size > 0) return PopResult.Succeed; Interlocked.Add (ref bottom, t + 1 - b); if (Interlocked.CompareExchange (ref top, t + 1, t) != t) return PopResult.Empty; return PopResult.Succeed; } public PopResult PopTop (out T obj) { obj = default (T); long t = Interlocked.Read (ref top); long b = Interlocked.Read (ref bottom); if (b - t <= 0) return PopResult.Empty; if (Interlocked.CompareExchange (ref top, t + 1, t) != t) return PopResult.Abort; var a = array; obj = a.segment[t % a.size]; return PopResult.Succeed; } public IEnumerable<T> GetEnumerable () { var a = array; return a.GetEnumerable (bottom, ref top); } } internal class CircularArray<T> { readonly int baseSize; public readonly int size; public readonly T[] segment; public CircularArray (int baseSize) { this.baseSize = baseSize; this.size = 1 << baseSize; this.segment = new T[size]; } public long Size { get { return size; } } public T this[long index] { get { return segment[index % size]; } set { segment[index % size] = value; } } public CircularArray<T> Grow (long bottom, long top) { var grow = new CircularArray<T> (baseSize + 1); for (long i = top; i < bottom; i++) { grow.segment[i] = segment[i % size]; } return grow; } public IEnumerable<T> GetEnumerable (long bottom, ref long top) { long instantTop = top; T[] slice = new T[bottom - instantTop]; int destIndex = -1; for (long i = instantTop; i < bottom; i++) slice[++destIndex] = segment[i % size]; return RealGetEnumerable (slice, bottom, top, instantTop); } IEnumerable<T> RealGetEnumerable (T[] slice, long bottom, long realTop, long initialTop) { int destIndex = (int)(realTop - initialTop - 1); for (long i = realTop; i < bottom; ++i) yield return slice[++destIndex]; } } } #endif
24.604396
90
0.654757
[ "Apache-2.0" ]
CRivlaldo/mono
mcs/class/corlib/System.Threading.Tasks/CyclicDeque.cs
4,482
C#
using System.Collections.Generic; using Horizon.Payment.Alipay.Response; namespace Horizon.Payment.Alipay.Request { /// <summary> /// koubei.catering.queue.shopqueueinfo.sync /// </summary> public class KoubeiCateringQueueShopqueueinfoSyncRequest : IAlipayRequest<KoubeiCateringQueueShopqueueinfoSyncResponse> { /// <summary> /// 排队队列配置数据回流 /// </summary> public string BizContent { get; set; } #region IAlipayRequest Members private bool needEncrypt = false; private string apiVersion = "1.0"; private string terminalType; private string terminalInfo; private string prodCode; private string notifyUrl; private string returnUrl; private AlipayObject bizModel; public void SetNeedEncrypt(bool needEncrypt) { this.needEncrypt = needEncrypt; } public bool GetNeedEncrypt() { return needEncrypt; } public void SetNotifyUrl(string notifyUrl) { this.notifyUrl = notifyUrl; } public string GetNotifyUrl() { return notifyUrl; } public void SetReturnUrl(string returnUrl) { this.returnUrl = returnUrl; } public string GetReturnUrl() { return returnUrl; } public void SetTerminalType(string terminalType) { this.terminalType = terminalType; } public string GetTerminalType() { return terminalType; } public void SetTerminalInfo(string terminalInfo) { this.terminalInfo = terminalInfo; } public string GetTerminalInfo() { return terminalInfo; } public void SetProdCode(string prodCode) { this.prodCode = prodCode; } public string GetProdCode() { return prodCode; } public string GetApiName() { return "koubei.catering.queue.shopqueueinfo.sync"; } public void SetApiVersion(string apiVersion) { this.apiVersion = apiVersion; } public string GetApiVersion() { return apiVersion; } public IDictionary<string, string> GetParameters() { var parameters = new AlipayDictionary { { "biz_content", BizContent } }; return parameters; } public AlipayObject GetBizModel() { return bizModel; } public void SetBizModel(AlipayObject bizModel) { this.bizModel = bizModel; } #endregion } }
22.758065
123
0.54961
[ "Apache-2.0" ]
bluexray/Horizon.Sample
Horizon.Payment.Alipay/Request/KoubeiCateringQueueShopqueueinfoSyncRequest.cs
2,844
C#
using System.Collections.Generic; using SC2APIProtocol; using SC2Sharp.Agents; namespace SC2Sharp.Tasks { class WorkersAttackLocationTask : Task { public static WorkersAttackLocationTask Task = new WorkersAttackLocationTask(); public Point2D AttackTarget = null; public int Max = 4; public static void Enable() { Task.Stopped = false; Bot.Main.TaskManager.Add(Task); } public WorkersAttackLocationTask() : base(8) {} public override bool DoWant(Agent agent) { return agent.IsWorker; } public override List<UnitDescriptor> GetDescriptors() { List<UnitDescriptor> result = new List<UnitDescriptor>(); if (units.Count < Max && AttackTarget != null) result.Add(new UnitDescriptor() { Count = Max - units.Count, UnitTypes = UnitTypes.WorkerTypes, Pos = AttackTarget }); return result; } public override bool IsNeeded() { return AttackTarget != null; } public override void OnFrame(Bot bot) { if (AttackTarget == null) { Clear(); return; } foreach (Agent agent in units) Attack(agent, AttackTarget); } } }
26.461538
134
0.554506
[ "MIT" ]
SimonPrins/TyrSc2
Tyr/Tasks/WorkersAttackLocationTask.cs
1,378
C#
using System; using System.Collections.Generic; using System.IO; using EntityFrameworkCore.Scaffolding.Handlebars; using EntityFrameworkCore.Scaffolding.Handlebars.Helpers; using HandlebarsDotNet; using Microsoft.EntityFrameworkCore.Design; using Microsoft.EntityFrameworkCore.Scaffolding; using Microsoft.EntityFrameworkCore.Scaffolding.Internal; using Microsoft.EntityFrameworkCore.SqlServer.Design.Internal; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Options; using Scaffolding.Handlebars.Tests.Fakes; using Scaffolding.Handlebars.Tests.Helpers; using Xunit; using Constants = Scaffolding.Handlebars.Tests.Helpers.Constants; namespace Scaffolding.Handlebars.Tests { [Collection("NorthwindDbContext")] public partial class HbsTypeScriptScaffoldingGeneratorTests { private NorthwindDbContextFixture Fixture { get; } private InputFile ContextClassTemplate { get; } private InputFile ContextImportsTemplate { get; } private InputFile ContextCtorTemplate { get; } private InputFile ContextOnConfiguringTemplate { get; } private InputFile ContextDbSetsTemplate { get; } private InputFile EntityClassTemplate { get; } private InputFile EntityImportsTemplate { get; } private InputFile EntityCtorTemplate { get; } private InputFile EntityPropertiesTemplate { get; } public HbsTypeScriptScaffoldingGeneratorTests(NorthwindDbContextFixture fixture) { Fixture = fixture; Fixture.Initialize(useInMemory: false); var projectRootDir = Path.Combine("..", "..", "..", "..", ".."); var contextTemplatesVirtualPath = $"{Constants.Templates.CodeTemplatesFolder}/{Constants.Templates.TypeScriptTemplateDirectories.ContextFolder}"; var contextPartialsVirtualPath = contextTemplatesVirtualPath + $"/{Constants.Templates.PartialsFolder}"; var contextTemplatesPath = Path.Combine(projectRootDir, "src", Constants.Templates.ProjectFolder, Constants.Templates.CodeTemplatesFolder, Constants.Templates.TypeScriptTemplateDirectories.ContextFolder); var contextPartialTemplatesPath = Path.Combine(contextTemplatesPath, Constants.Templates.PartialsFolder); var entityTemplatesVirtualPath = $"{Constants.Templates.CodeTemplatesFolder}/{Constants.Templates.TypeScriptTemplateDirectories.EntityTypeFolder}"; var entityPartialsVirtualPath = entityTemplatesVirtualPath + $"/{Constants.Templates.PartialsFolder}"; var entityTemplatesPath = Path.Combine(projectRootDir, "src", Constants.Templates.ProjectFolder, Constants.Templates.CodeTemplatesFolder, Constants.Templates.TypeScriptTemplateDirectories.EntityTypeFolder); var entityPartialTemplatesPath = Path.Combine(entityTemplatesPath, Constants.Templates.PartialsFolder); ContextClassTemplate = new InputFile { Directory = contextTemplatesVirtualPath, File = Constants.Templates.ContextClassFile, Contents = File.ReadAllText(Path.Combine(contextTemplatesPath, Constants.Templates.ContextClassFile)) }; ContextImportsTemplate = new InputFile { Directory = contextPartialsVirtualPath, File = Constants.Templates.ContextImportsFile, Contents = File.ReadAllText(Path.Combine(contextPartialTemplatesPath, Constants.Templates.ContextImportsFile)) }; ContextCtorTemplate = new InputFile { Directory = contextPartialsVirtualPath, File = Constants.Templates.ContextCtorFile, Contents = File.ReadAllText(Path.Combine(contextPartialTemplatesPath, Constants.Templates.ContextCtorFile)) }; ContextOnConfiguringTemplate = new InputFile { Directory = contextPartialsVirtualPath, File = Constants.Templates.ContextOnConfiguringFile, Contents = File.ReadAllText(Path.Combine(contextPartialTemplatesPath, Constants.Templates.ContextOnConfiguringFile)) }; ContextDbSetsTemplate = new InputFile { Directory = contextPartialsVirtualPath, File = Constants.Templates.ContextDbSetsFile, Contents = File.ReadAllText(Path.Combine(contextPartialTemplatesPath, Constants.Templates.ContextDbSetsFile)) }; EntityClassTemplate = new InputFile { Directory = entityTemplatesVirtualPath, File = Constants.Templates.EntityClassFile, Contents = File.ReadAllText(Path.Combine(entityTemplatesPath, Constants.Templates.EntityClassFile)) }; EntityImportsTemplate = new InputFile { Directory = entityPartialsVirtualPath, File = Constants.Templates.EntityImportsFile, Contents = File.ReadAllText(Path.Combine(entityPartialTemplatesPath, Constants.Templates.EntityImportsFile)) }; EntityCtorTemplate = new InputFile { Directory = entityPartialsVirtualPath, File = Constants.Templates.EntityCtorFile, Contents = File.ReadAllText(Path.Combine(entityPartialTemplatesPath, Constants.Templates.EntityCtorFile)) }; EntityPropertiesTemplate = new InputFile { Directory = entityPartialsVirtualPath, File = Constants.Templates.EntityPropertiesFile, Contents = File.ReadAllText(Path.Combine(entityPartialTemplatesPath, Constants.Templates.EntityPropertiesFile)) }; } [Fact] public void WriteCode_Should_Generate_Context_File() { // Arrange var options = ReverseEngineerOptions.DbContextOnly; var scaffolder = CreateScaffolder(options); // Act var model = scaffolder.ScaffoldModel( connectionString: Constants.Connections.SqlServerConnection, databaseOptions: new DatabaseModelFactoryOptions(), modelOptions: new ModelReverseEngineerOptions(), codeOptions: new ModelCodeGenerationOptions { ContextNamespace = Constants.Parameters.RootNamespace, ModelNamespace = Constants.Parameters.RootNamespace, ContextName = Constants.Parameters.ContextName, ContextDir = Constants.Parameters.ProjectPath, UseDataAnnotations = false, Language = "C#", }); // Assert var files = GetGeneratedFiles(model, options); object expectedContext = ExpectedContexts.ContextClass; var context = files[Constants.Files.TypeScriptFiles.DbContextFile]; Assert.Equal(expectedContext, context); } [Fact] public void WriteCode_Should_Generate_Entity_Files() { // Arrange var options = ReverseEngineerOptions.EntitiesOnly; var scaffolder = CreateScaffolder(options); // Act var model = scaffolder.ScaffoldModel( connectionString: Constants.Connections.SqlServerConnection, databaseOptions: new DatabaseModelFactoryOptions(), modelOptions: new ModelReverseEngineerOptions(), codeOptions: new ModelCodeGenerationOptions { ContextNamespace = Constants.Parameters.RootNamespace, ModelNamespace = Constants.Parameters.RootNamespace, ContextName = Constants.Parameters.ContextName, ContextDir = Constants.Parameters.ProjectPath, UseDataAnnotations = false, Language = "C#", }); // Assert var files = GetGeneratedFiles(model, options); var category = files[Constants.Files.TypeScriptFiles.CategoryFile]; var product = files[Constants.Files.TypeScriptFiles.ProductFile]; object expectedCategory = ExpectedEntities.CategoryClass; object expectedProduct = ExpectedEntities.ProductClass; Assert.Equal(expectedCategory, category); Assert.Equal(expectedProduct, product); } [Fact] public void WriteCode_Should_Generate_Context_and_Entity_Files() { // Arrange var options = ReverseEngineerOptions.DbContextAndEntities; var scaffolder = CreateScaffolder(options); // Act var model = scaffolder.ScaffoldModel( connectionString: Constants.Connections.SqlServerConnection, databaseOptions: new DatabaseModelFactoryOptions(), modelOptions: new ModelReverseEngineerOptions(), codeOptions: new ModelCodeGenerationOptions { ContextNamespace = Constants.Parameters.RootNamespace, ModelNamespace = Constants.Parameters.RootNamespace, ContextName = Constants.Parameters.ContextName, ContextDir = Constants.Parameters.ProjectPath, UseDataAnnotations = false, Language = "C#", }); // Act Dictionary<string, string> files = GetGeneratedFiles(model, options); // Assert object expectedContext = ExpectedContexts.ContextClass; object expectedCategory = ExpectedEntities.CategoryClass; object expectedProduct = ExpectedEntities.ProductClass; var context = files[Constants.Files.TypeScriptFiles.DbContextFile]; var category = files[Constants.Files.TypeScriptFiles.CategoryFile]; var product = files[Constants.Files.TypeScriptFiles.ProductFile]; Assert.Equal(expectedContext, context); Assert.Equal(expectedCategory, category); Assert.Equal(expectedProduct, product); } [Fact] public void Save_Should_Write_Context_File() { using (var directory = new TempDirectory()) { // Arrange var scaffolder = CreateScaffolder(ReverseEngineerOptions.DbContextOnly); var model = scaffolder.ScaffoldModel( connectionString: Constants.Connections.SqlServerConnection, databaseOptions: new DatabaseModelFactoryOptions(), modelOptions: new ModelReverseEngineerOptions(), codeOptions: new ModelCodeGenerationOptions { ContextNamespace = Constants.Parameters.RootNamespace, ModelNamespace = Constants.Parameters.RootNamespace, ContextName = Constants.Parameters.ContextName, ContextDir = Path.Combine(directory.Path, "Contexts"), UseDataAnnotations = false, Language = "C#", }); // Act var result = scaffolder.Save(model, Path.Combine(directory.Path, "Models"), overwriteFiles: false); // Assert var expectedContextPath = Path.Combine(directory.Path, "Contexts", Constants.Files.TypeScriptFiles.DbContextFile); var expectedCategoryPath = Path.Combine(directory.Path, "Models", Constants.Files.TypeScriptFiles.CategoryFile); var expectedProductPath = Path.Combine(directory.Path, "Models", Constants.Files.TypeScriptFiles.ProductFile); Assert.Equal(expectedContextPath, result.ContextFile); Assert.False(File.Exists(expectedCategoryPath)); Assert.False(File.Exists(expectedProductPath)); } } [Fact] public void Save_Should_Write_Entity_Files() { using (var directory = new TempDirectory()) { // Arrange var scaffolder = CreateScaffolder(ReverseEngineerOptions.EntitiesOnly); var model = scaffolder.ScaffoldModel( connectionString: Constants.Connections.SqlServerConnection, databaseOptions: new DatabaseModelFactoryOptions(), modelOptions: new ModelReverseEngineerOptions(), codeOptions: new ModelCodeGenerationOptions { ContextNamespace = Constants.Parameters.RootNamespace, ModelNamespace = Constants.Parameters.RootNamespace, ContextName = Constants.Parameters.ContextName, ContextDir = Path.Combine(directory.Path, "Contexts"), UseDataAnnotations = false, Language = "C#", }); // Act var result = scaffolder.Save(model, Path.Combine(directory.Path, "Models"), overwriteFiles: false); // Assert var expectedContextPath = Path.Combine(directory.Path, "Contexts", Constants.Files.TypeScriptFiles.DbContextFile); var expectedCategoryPath = Path.Combine(directory.Path, "Models", Constants.Files.TypeScriptFiles.CategoryFile); var expectedProductPath = Path.Combine(directory.Path, "Models", Constants.Files.TypeScriptFiles.ProductFile); Assert.Equal(expectedCategoryPath, result.AdditionalFiles[0]); Assert.Equal(expectedProductPath, result.AdditionalFiles[1]); Assert.False(File.Exists(expectedContextPath)); } } [Fact] public void Save_Should_Write_Context_and_Entity_Files() { using (var directory = new TempDirectory()) { // Arrange var scaffolder = CreateScaffolder(ReverseEngineerOptions.DbContextAndEntities); var model = scaffolder.ScaffoldModel( connectionString: Constants.Connections.SqlServerConnection, databaseOptions: new DatabaseModelFactoryOptions(), modelOptions: new ModelReverseEngineerOptions(), codeOptions: new ModelCodeGenerationOptions { ContextNamespace = Constants.Parameters.RootNamespace, ModelNamespace = Constants.Parameters.RootNamespace, ContextName = Constants.Parameters.ContextName, ContextDir = Path.Combine(directory.Path, "Contexts"), UseDataAnnotations = false, Language = "C#", }); // Act var result = scaffolder.Save(model, Path.Combine(directory.Path, "Models"), overwriteFiles: false); // Assert var expectedContextPath = Path.Combine(directory.Path, "Contexts", Constants.Files.TypeScriptFiles.DbContextFile); var expectedCategoryPath = Path.Combine(directory.Path, "Models", Constants.Files.TypeScriptFiles.CategoryFile); var expectedProductPath = Path.Combine(directory.Path, "Models", Constants.Files.TypeScriptFiles.ProductFile); Assert.Equal(expectedContextPath, result.ContextFile); Assert.Equal(expectedCategoryPath, result.AdditionalFiles[0]); Assert.Equal(expectedProductPath, result.AdditionalFiles[1]); } } private IReverseEngineerScaffolder CreateScaffolder(ReverseEngineerOptions options) { var fileService = new InMemoryTemplateFileService(); fileService.InputFiles(ContextClassTemplate, ContextImportsTemplate, ContextCtorTemplate, ContextOnConfiguringTemplate, ContextDbSetsTemplate, EntityClassTemplate, EntityImportsTemplate, EntityCtorTemplate, EntityPropertiesTemplate); var services = new ServiceCollection() .AddEntityFrameworkDesignTimeServices() .AddSingleton<IDbContextTemplateService, FakeHbsDbContextTemplateService>() .AddSingleton<IEntityTypeTemplateService, FakeHbsEntityTypeTemplateService>() .AddSingleton<IEntityTypeTransformationService, HbsEntityTypeTransformationService>() .AddSingleton<ITypeScriptHelper, TypeScriptHelper>() .AddSingleton<ITemplateFileService>(fileService) .AddSingleton<ITemplateLanguageService, FakeTypeScriptTemplateLanguageService>() .AddSingleton<IModelCodeGenerator, HbsTypeScriptModelGenerator>() .AddSingleton(provider => { ICSharpDbContextGenerator contextGenerator = new HbsCSharpDbContextGenerator( provider.GetRequiredService<IProviderConfigurationCodeGenerator>(), provider.GetRequiredService<IAnnotationCodeGenerator>(), provider.GetRequiredService<IDbContextTemplateService>(), provider.GetRequiredService<IEntityTypeTransformationService>(), provider.GetRequiredService<ICSharpHelper>(), provider.GetRequiredService<IOptions<HandlebarsScaffoldingOptions>>()); return options == ReverseEngineerOptions.DbContextOnly || options == ReverseEngineerOptions.DbContextAndEntities ? contextGenerator : new NullCSharpDbContextGenerator(); }) .AddSingleton(provider => { ICSharpEntityTypeGenerator entityGenerator = new HbsTypeScriptEntityTypeGenerator( provider.GetRequiredService<IEntityTypeTemplateService>(), provider.GetRequiredService<IEntityTypeTransformationService>(), provider.GetRequiredService<ICSharpHelper>(), provider.GetRequiredService<ITypeScriptHelper>(), provider.GetRequiredService<IOptions<HandlebarsScaffoldingOptions>>()); return options == ReverseEngineerOptions.EntitiesOnly || options == ReverseEngineerOptions.DbContextAndEntities ? entityGenerator : new NullCSharpEntityTypeGenerator(); }) .AddSingleton<IHbsHelperService>(provider => new HbsHelperService(new Dictionary<string, Action<TextWriter, Dictionary<string, object>, object[]>> { {EntityFrameworkCore.Scaffolding.Handlebars.Helpers.Constants.SpacesHelper, HandlebarsHelpers.SpacesHelper} })) .AddSingleton<IHbsBlockHelperService>(provider => new HbsBlockHelperService(new Dictionary<string, Action<TextWriter, HelperOptions, Dictionary<string, object>, object[]>>())) .AddSingleton<IReverseEngineerScaffolder, HbsReverseEngineerScaffolder>(); new SqlServerDesignTimeServices().ConfigureDesignTimeServices(services); var scaffolder = services .BuildServiceProvider() .GetRequiredService<IReverseEngineerScaffolder>(); return scaffolder; } private Dictionary<string, string> GetGeneratedFiles(ScaffoldedModel model, ReverseEngineerOptions options) { var generatedFiles = new Dictionary<string, string>(); if (options == ReverseEngineerOptions.DbContextOnly || options == ReverseEngineerOptions.DbContextAndEntities) { generatedFiles.Add(Constants.Files.TypeScriptFiles.DbContextFile, model.ContextFile.Code); } if (options == ReverseEngineerOptions.EntitiesOnly || options == ReverseEngineerOptions.DbContextAndEntities) { generatedFiles.Add(Constants.Files.TypeScriptFiles.CategoryFile, model.AdditionalFiles[0].Code); generatedFiles.Add(Constants.Files.TypeScriptFiles.ProductFile, model.AdditionalFiles[1].Code); } return generatedFiles; } } }
51.630273
145
0.627481
[ "MIT" ]
Hedi-s/EntityFrameworkCore.Scaffolding.Handlebars
test/Scaffolding.Handlebars.Tests/HbsTypeScriptScaffoldingGeneratorTests.cs
20,809
C#
// Copyright 2015-2018 The NATS Authors // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System; using System.Linq; using NATS.Client; using Xunit; namespace IntegrationTests { public abstract class TestSuite<TSuiteContext> : IClassFixture<TSuiteContext> where TSuiteContext : class { protected TSuiteContext Context { get; } protected TestSuite(TSuiteContext context) { Context = context; } } /// <summary> /// IANA unassigned port range 11490-11599 has been selected withing the user-ports (1024-49151). /// </summary> public static class TestSeedPorts { public const int DefaultSuiteNormalServers = 4221; //7pc public const int DefaultSuiteNormalClusterServers = 4551; //7pc public const int AuthorizationSuite = 11490; //3pc public const int ReconnectSuite = 11493; //1pc public const int PublishErrorsDuringReconnectSuite = 11494; //1pc public const int ClusterSuite = 11495; //10pc public const int ConnectionSuite = 11505;//2pc public const int ConnectionSecuritySuite = 11507; //1pc public const int ConnectionDrainSuite = 11508; //1pc public const int ConnectionMemoryLeaksSuite = 11509; //3pc public const int EncodingSuite = 11512; //1pc public const int SubscriptionsSuite = 11513; //1pc public const int TlsSuite = 11514; //3pc public const int RxSuite = 11517; //1pc public const int AsyncAwaitDeadlocksSuite = 11518; //1pc public const int ConnectionIpV6Suite = 11519; //1pc public const int JetStreamSuite = 11520; //1pc public const int JetStreamManagementSuite = 11521; //1pc public const int JetStreamPublishSuite = 11522; //1pc public const int JetStreamPushAsyncSuite = 11523; //1pc public const int JetStreamPushSyncSuite = 11524; //1pc public const int JetStreamPullSuite = 11525; //1pc } public abstract class SuiteContext { public ConnectionFactory ConnectionFactory { get; } = new ConnectionFactory(); public Options GetTestOptionsWithDefaultTimeout(int? port = null) { var opts = ConnectionFactory.GetDefaultOptions(); if (port.HasValue) opts.Url = $"nats://localhost:{port.Value}"; return opts; } public Options GetTestOptions(int? port = null) { var opts = GetTestOptionsWithDefaultTimeout(port); opts.Timeout = 10000; return opts; } public IConnection OpenConnection(int? port = null) { var opts = GetTestOptions(port); return ConnectionFactory.CreateConnection(opts); } public IEncodedConnection OpenEncodedConnectionWithDefaultTimeout(int? port = null) { var opts = GetTestOptionsWithDefaultTimeout(port); return ConnectionFactory.CreateEncodedConnection(opts); } public void RunInServer(Action<IConnection> test, TestServerInfo testServerInfo) { using (var s = NATSServer.CreateFastAndVerify(testServerInfo.Port)) { using (var c = OpenConnection(testServerInfo.Port)) { test(c); } } } public void RunInJsServer(Action<IConnection> test, TestServerInfo testServerInfo) { using (var s = NATSServer.CreateJetStreamFastAndVerify(testServerInfo.Port)) { using (var c = OpenConnection(testServerInfo.Port)) { test(c); } } } } public class DefaultSuiteContext : SuiteContext { public const string CollectionKey = "9733f463316047fa9207e0a3aaa3c41a"; private const int SeedPortNormalServers = TestSeedPorts.DefaultSuiteNormalServers; public readonly TestServerInfo DefaultServer = new TestServerInfo(Defaults.Port); public readonly TestServerInfo Server1 = new TestServerInfo(SeedPortNormalServers); public readonly TestServerInfo Server2 = new TestServerInfo(SeedPortNormalServers + 1); public readonly TestServerInfo Server3 = new TestServerInfo(SeedPortNormalServers + 2); public readonly TestServerInfo Server4 = new TestServerInfo(SeedPortNormalServers + 3); public readonly TestServerInfo Server5 = new TestServerInfo(SeedPortNormalServers + 4); public readonly TestServerInfo Server6 = new TestServerInfo(SeedPortNormalServers + 5); public readonly TestServerInfo Server7 = new TestServerInfo(SeedPortNormalServers + 6); private const int SeedPortClusterServers = TestSeedPorts.DefaultSuiteNormalClusterServers; public readonly TestServerInfo ClusterServer1 = new TestServerInfo(SeedPortClusterServers); public readonly TestServerInfo ClusterServer2 = new TestServerInfo(SeedPortClusterServers + 1); public readonly TestServerInfo ClusterServer3 = new TestServerInfo(SeedPortClusterServers + 2); public readonly TestServerInfo ClusterServer4 = new TestServerInfo(SeedPortClusterServers + 3); public readonly TestServerInfo ClusterServer5 = new TestServerInfo(SeedPortClusterServers + 4); public readonly TestServerInfo ClusterServer6 = new TestServerInfo(SeedPortClusterServers + 5); public readonly TestServerInfo ClusterServer7 = new TestServerInfo(SeedPortClusterServers + 6); } public class AuthorizationSuiteContext : SuiteContext { private const int SeedPort = TestSeedPorts.AuthorizationSuite; public readonly TestServerInfo Server1 = new TestServerInfo(SeedPort); public readonly TestServerInfo Server2 = new TestServerInfo(SeedPort + 1); public readonly TestServerInfo Server3 = new TestServerInfo(SeedPort + 2); } public class ConnectionSuiteContext : SuiteContext { private const int SeedPort = TestSeedPorts.ConnectionSuite; public readonly TestServerInfo Server1 = new TestServerInfo(SeedPort); public readonly TestServerInfo Server2 = new TestServerInfo(SeedPort + 1); } public class ConnectionSecuritySuiteContext : SuiteContext { private const int SeedPort = TestSeedPorts.ConnectionSecuritySuite; public readonly TestServerInfo Server1 = new TestServerInfo(SeedPort); } public class ConnectionDrainSuiteContext : SuiteContext { private const int SeedPort = TestSeedPorts.ConnectionDrainSuite; public readonly TestServerInfo Server1 = new TestServerInfo(SeedPort); } public class ConnectionIpV6SuiteContext : SuiteContext { private const int SeedPort = TestSeedPorts.ConnectionIpV6Suite; public readonly TestServerInfo Server1 = new TestServerInfo(SeedPort); } public class ConnectionMemoryLeaksSuiteContext : SuiteContext { private const int SeedPort = TestSeedPorts.ConnectionMemoryLeaksSuite; public readonly TestServerInfo Server1 = new TestServerInfo(SeedPort); public readonly TestServerInfo Server2 = new TestServerInfo(SeedPort + 1); public readonly TestServerInfo Server3 = new TestServerInfo(SeedPort + 2); } public class ClusterSuiteContext : SuiteContext { private const int SeedPort = TestSeedPorts.ClusterSuite; public readonly TestServerInfo ClusterServer1 = new TestServerInfo(SeedPort); public readonly TestServerInfo ClusterServer2 = new TestServerInfo(SeedPort + 1); public readonly TestServerInfo Server1 = new TestServerInfo(SeedPort + 2); public readonly TestServerInfo Server2 = new TestServerInfo(SeedPort + 3); public readonly TestServerInfo Server3 = new TestServerInfo(SeedPort + 4); public readonly TestServerInfo Server4 = new TestServerInfo(SeedPort + 5); public readonly TestServerInfo Server5 = new TestServerInfo(SeedPort + 6); public readonly TestServerInfo Server6 = new TestServerInfo(SeedPort + 7); public readonly TestServerInfo Server7 = new TestServerInfo(SeedPort + 8); public readonly TestServerInfo Server8 = new TestServerInfo(SeedPort + 9); public readonly TestServerInfo[] TestServers; public readonly TestServerInfo[] TestServersShortList; public ClusterSuiteContext() { TestServers = new[] { Server1, Server2, Server3, Server4, Server5, Server6, Server7, Server8 }; TestServersShortList = TestServers.Take(2).ToArray(); } public string[] GetTestServersUrls() => TestServers.Select(s => s.Url).ToArray(); public string[] GetTestServersShortListUrls() => TestServersShortList.Select(s => s.Url).ToArray(); } public class AsyncAwaitDeadlocksSuiteContext : SuiteContext { private const int SeedPort = TestSeedPorts.AsyncAwaitDeadlocksSuite; public readonly TestServerInfo Server1 = new TestServerInfo(SeedPort); } public class EncodingSuiteContext : SuiteContext { private const int SeedPort = TestSeedPorts.EncodingSuite; public readonly TestServerInfo Server1 = new TestServerInfo(SeedPort); } public class ReconnectSuiteContext : SuiteContext { private const int SeedPort = TestSeedPorts.ReconnectSuite; public readonly TestServerInfo Server1 = new TestServerInfo(SeedPort); } public class PublishErrorsDuringReconnectSuiteContext : SuiteContext { private const int SeedPort = TestSeedPorts.PublishErrorsDuringReconnectSuite; public readonly TestServerInfo Server1 = new TestServerInfo(SeedPort); } public class RxSuiteContext : SuiteContext { private const int SeedPort = TestSeedPorts.RxSuite; public readonly TestServerInfo Server1 = new TestServerInfo(SeedPort); } public class SubscriptionsSuiteContext : SuiteContext { private const int SeedPort = TestSeedPorts.SubscriptionsSuite; public readonly TestServerInfo Server1 = new TestServerInfo(SeedPort); } public class TlsSuiteContext : SuiteContext { private const int SeedPort = TestSeedPorts.TlsSuite; public readonly TestServerInfo Server1 = new TestServerInfo(SeedPort); public readonly TestServerInfo Server2 = new TestServerInfo(SeedPort + 1); public readonly TestServerInfo Server3 = new TestServerInfo(SeedPort + 2); } public class JetStreamSuiteContext : OneServerSuiteContext { public JetStreamSuiteContext() : base(TestSeedPorts.JetStreamSuite) {} } public class JetStreamManagementSuiteContext : OneServerSuiteContext { public JetStreamManagementSuiteContext() : base(TestSeedPorts.JetStreamManagementSuite) {} } public class JetStreamPublishSuiteContext : OneServerSuiteContext { public JetStreamPublishSuiteContext() : base(TestSeedPorts.JetStreamPublishSuite) {} } public class JetStreamPushAsyncSuiteContext : OneServerSuiteContext { public JetStreamPushAsyncSuiteContext() : base(TestSeedPorts.JetStreamPushAsyncSuite) {} } public class JetStreamPushSyncSuiteContext : OneServerSuiteContext { public JetStreamPushSyncSuiteContext() : base(TestSeedPorts.JetStreamPushSyncSuite) {} } public class JetStreamPullSuiteContext : OneServerSuiteContext { public JetStreamPullSuiteContext() : base(TestSeedPorts.JetStreamPullSuite) {} } public class OneServerSuiteContext : SuiteContext { public readonly TestServerInfo Server1; public OneServerSuiteContext(int seedPort) { Server1 = new TestServerInfo(seedPort); } public void RunInJsServer(Action<IConnection> test) { base.RunInJsServer(test, Server1); } public void RunInServer(Action<IConnection> test) { base.RunInServer(test, Server1); } } public sealed class SkipPlatformsWithoutSignals : FactAttribute { public SkipPlatformsWithoutSignals() { if (NATSServer.SupportsSignals == false) { Skip = "Ignore environments that do not support signaling."; } } } }
37.731214
109
0.688242
[ "Apache-2.0" ]
rgfaber/nats.net
src/Tests/IntegrationTests/TestSuite.cs
13,057
C#
// -------------------------------------------------------------------------------------------------------------------- // <auto-generated> // Generated using OBeautifulCode.CodeGen.ModelObject (1.0.178.0) // </auto-generated> // -------------------------------------------------------------------------------------------------------------------- namespace Naos.Database.Domain.Test { using global::System; using global::System.CodeDom.Compiler; using global::System.Collections.Concurrent; using global::System.Collections.Generic; using global::System.Collections.ObjectModel; using global::System.Diagnostics.CodeAnalysis; using global::System.Globalization; using global::System.Linq; using global::System.Reflection; using global::FakeItEasy; using global::OBeautifulCode.Assertion.Recipes; using global::OBeautifulCode.AutoFakeItEasy; using global::OBeautifulCode.CodeGen.ModelObject.Recipes; using global::OBeautifulCode.Equality.Recipes; using global::OBeautifulCode.Math.Recipes; using global::OBeautifulCode.Reflection.Recipes; using global::OBeautifulCode.Representation.System; using global::OBeautifulCode.Serialization; using global::OBeautifulCode.Serialization.Recipes; using global::OBeautifulCode.Type; using global::Xunit; using static global::System.FormattableString; public static partial class StandardCreateStreamOpTest { private static readonly StringRepresentationTestScenarios<StandardCreateStreamOp> StringRepresentationTestScenarios = new StringRepresentationTestScenarios<StandardCreateStreamOp>() .AddScenario(() => new StringRepresentationTestScenario<StandardCreateStreamOp> { Name = "Default Code Generated Scenario", SystemUnderTestExpectedStringRepresentationFunc = () => { var systemUnderTest = A.Dummy<StandardCreateStreamOp>(); var result = new SystemUnderTestExpectedStringRepresentation<StandardCreateStreamOp> { SystemUnderTest = systemUnderTest, ExpectedStringRepresentation = Invariant($"Naos.Database.Domain.StandardCreateStreamOp: StreamRepresentation = {systemUnderTest.StreamRepresentation?.ToString() ?? "<null>"}, ExistingStreamStrategy = {systemUnderTest.ExistingStreamStrategy.ToString() ?? "<null>"}."), }; return result; }, }); private static readonly ConstructorArgumentValidationTestScenarios<StandardCreateStreamOp> ConstructorArgumentValidationTestScenarios = new ConstructorArgumentValidationTestScenarios<StandardCreateStreamOp>() .AddScenario(() => new ConstructorArgumentValidationTestScenario<StandardCreateStreamOp> { Name = "constructor should throw ArgumentNullException when parameter 'streamRepresentation' is null scenario", ConstructionFunc = () => { var referenceObject = A.Dummy<StandardCreateStreamOp>(); var result = new StandardCreateStreamOp( null, referenceObject.ExistingStreamStrategy); return result; }, ExpectedExceptionType = typeof(ArgumentNullException), ExpectedExceptionMessageContains = new[] { "streamRepresentation", }, }); private static readonly ConstructorPropertyAssignmentTestScenarios<StandardCreateStreamOp> ConstructorPropertyAssignmentTestScenarios = new ConstructorPropertyAssignmentTestScenarios<StandardCreateStreamOp>() .AddScenario(() => new ConstructorPropertyAssignmentTestScenario<StandardCreateStreamOp> { Name = "StreamRepresentation should return same 'streamRepresentation' parameter passed to constructor when getting", SystemUnderTestExpectedPropertyValueFunc = () => { var referenceObject = A.Dummy<StandardCreateStreamOp>(); var result = new SystemUnderTestExpectedPropertyValue<StandardCreateStreamOp> { SystemUnderTest = new StandardCreateStreamOp( referenceObject.StreamRepresentation, referenceObject.ExistingStreamStrategy), ExpectedPropertyValue = referenceObject.StreamRepresentation, }; return result; }, PropertyName = "StreamRepresentation", }) .AddScenario(() => new ConstructorPropertyAssignmentTestScenario<StandardCreateStreamOp> { Name = "ExistingStreamStrategy should return same 'existingStreamStrategy' parameter passed to constructor when getting", SystemUnderTestExpectedPropertyValueFunc = () => { var referenceObject = A.Dummy<StandardCreateStreamOp>(); var result = new SystemUnderTestExpectedPropertyValue<StandardCreateStreamOp> { SystemUnderTest = new StandardCreateStreamOp( referenceObject.StreamRepresentation, referenceObject.ExistingStreamStrategy), ExpectedPropertyValue = referenceObject.ExistingStreamStrategy, }; return result; }, PropertyName = "ExistingStreamStrategy", }); private static readonly DeepCloneWithTestScenarios<StandardCreateStreamOp> DeepCloneWithTestScenarios = new DeepCloneWithTestScenarios<StandardCreateStreamOp>() .AddScenario(() => new DeepCloneWithTestScenario<StandardCreateStreamOp> { Name = "DeepCloneWithStreamRepresentation should deep clone object and replace StreamRepresentation with the provided streamRepresentation", WithPropertyName = "StreamRepresentation", SystemUnderTestDeepCloneWithValueFunc = () => { var systemUnderTest = A.Dummy<StandardCreateStreamOp>(); var referenceObject = A.Dummy<StandardCreateStreamOp>().ThatIs(_ => !systemUnderTest.StreamRepresentation.IsEqualTo(_.StreamRepresentation)); var result = new SystemUnderTestDeepCloneWithValue<StandardCreateStreamOp> { SystemUnderTest = systemUnderTest, DeepCloneWithValue = referenceObject.StreamRepresentation, }; return result; }, }) .AddScenario(() => new DeepCloneWithTestScenario<StandardCreateStreamOp> { Name = "DeepCloneWithExistingStreamStrategy should deep clone object and replace ExistingStreamStrategy with the provided existingStreamStrategy", WithPropertyName = "ExistingStreamStrategy", SystemUnderTestDeepCloneWithValueFunc = () => { var systemUnderTest = A.Dummy<StandardCreateStreamOp>(); var referenceObject = A.Dummy<StandardCreateStreamOp>().ThatIs(_ => !systemUnderTest.ExistingStreamStrategy.IsEqualTo(_.ExistingStreamStrategy)); var result = new SystemUnderTestDeepCloneWithValue<StandardCreateStreamOp> { SystemUnderTest = systemUnderTest, DeepCloneWithValue = referenceObject.ExistingStreamStrategy, }; return result; }, }); private static readonly StandardCreateStreamOp ReferenceObjectForEquatableTestScenarios = A.Dummy<StandardCreateStreamOp>(); private static readonly EquatableTestScenarios<StandardCreateStreamOp> EquatableTestScenarios = new EquatableTestScenarios<StandardCreateStreamOp>() .AddScenario(() => new EquatableTestScenario<StandardCreateStreamOp> { Name = "Default Code Generated Scenario", ReferenceObject = ReferenceObjectForEquatableTestScenarios, ObjectsThatAreEqualToButNotTheSameAsReferenceObject = new StandardCreateStreamOp[] { new StandardCreateStreamOp( ReferenceObjectForEquatableTestScenarios.StreamRepresentation, ReferenceObjectForEquatableTestScenarios.ExistingStreamStrategy), }, ObjectsThatAreNotEqualToReferenceObject = new StandardCreateStreamOp[] { new StandardCreateStreamOp( A.Dummy<StandardCreateStreamOp>().Whose(_ => !_.StreamRepresentation.IsEqualTo(ReferenceObjectForEquatableTestScenarios.StreamRepresentation)).StreamRepresentation, ReferenceObjectForEquatableTestScenarios.ExistingStreamStrategy), new StandardCreateStreamOp( ReferenceObjectForEquatableTestScenarios.StreamRepresentation, A.Dummy<StandardCreateStreamOp>().Whose(_ => !_.ExistingStreamStrategy.IsEqualTo(ReferenceObjectForEquatableTestScenarios.ExistingStreamStrategy)).ExistingStreamStrategy), }, ObjectsThatAreNotOfTheSameTypeAsReferenceObject = new object[] { A.Dummy<object>(), A.Dummy<string>(), A.Dummy<int>(), A.Dummy<int?>(), A.Dummy<Guid>(), A.Dummy<ArchiveFailureToHandleRecordOp>(), A.Dummy<CancelRunningHandleRecordOp>(), A.Dummy<CompleteRunningHandleRecordOp>(), A.Dummy<CreateDatabaseOp>(), A.Dummy<DeleteDatabaseOp>(), A.Dummy<DisableHandlingForRecordOp>(), A.Dummy<DisableHandlingForStreamOp>(), A.Dummy<DoesAnyExistByIdOp<Version>>(), A.Dummy<EnableHandlingForStreamOp>(), A.Dummy<FailRunningHandleRecordOp>(), A.Dummy<GetAllRecordsByIdOp<Version>>(), A.Dummy<GetAllRecordsMetadataByIdOp<Version>>(), A.Dummy<GetAllResourceLocatorsOp>(), A.Dummy<GetCompositeHandlingStatusByIdsOp>(), A.Dummy<GetCompositeHandlingStatusByIdsOp<Version>>(), A.Dummy<GetCompositeHandlingStatusByTagsOp>(), A.Dummy<GetDistinctIdsOp<Version>>(), A.Dummy<GetHandlingHistoryOp>(), A.Dummy<GetHandlingStatusOp>(), A.Dummy<GetLatestObjectByIdOp<Version, Version>>(), A.Dummy<GetLatestObjectByTagsOp<Version>>(), A.Dummy<GetLatestObjectOp<Version>>(), A.Dummy<GetLatestRecordByIdOp<Version, Version>>(), A.Dummy<GetLatestRecordByIdOp<Version>>(), A.Dummy<GetLatestRecordMetadataByIdOp<Version>>(), A.Dummy<GetLatestRecordOp<Version>>(), A.Dummy<GetLatestStringSerializedObjectByIdOp<Version>>(), A.Dummy<GetNextUniqueLongOp>(), A.Dummy<GetResourceLocatorByIdOp<Version>>(), A.Dummy<GetResourceLocatorForUniqueIdentifierOp>(), A.Dummy<GetStreamFromRepresentationOp>(), A.Dummy<GetStreamFromRepresentationOp<FileStreamRepresentation, MemoryStandardStream>>(), A.Dummy<HandleRecordOp>(), A.Dummy<HandleRecordOp<Version>>(), A.Dummy<HandleRecordWithIdOp<Version, Version>>(), A.Dummy<HandleRecordWithIdOp<Version>>(), A.Dummy<PruneBeforeInternalRecordDateOp>(), A.Dummy<PruneBeforeInternalRecordIdOp>(), A.Dummy<PutAndReturnInternalRecordIdOp<Version>>(), A.Dummy<PutOp<Version>>(), A.Dummy<PutWithIdAndReturnInternalRecordIdOp<Version, Version>>(), A.Dummy<PutWithIdOp<Version, Version>>(), A.Dummy<ResetCompletedHandleRecordOp>(), A.Dummy<ResetFailedHandleRecordOp>(), A.Dummy<SelfCancelRunningHandleRecordOp>(), A.Dummy<StandardDeleteStreamOp>(), A.Dummy<StandardGetDistinctStringSerializedIdsOp>(), A.Dummy<StandardGetHandlingHistoryOp>(), A.Dummy<StandardGetHandlingStatusOp>(), A.Dummy<StandardGetInternalRecordIdsOp>(), A.Dummy<StandardGetLatestRecordOp>(), A.Dummy<StandardGetLatestStringSerializedObjectOp>(), A.Dummy<StandardGetNextUniqueLongOp>(), A.Dummy<StandardPruneStreamOp>(), A.Dummy<StandardPutRecordOp>(), A.Dummy<StandardTryHandleRecordOp>(), A.Dummy<StandardUpdateHandlingStatusForRecordOp>(), A.Dummy<StandardUpdateHandlingStatusForStreamOp>(), A.Dummy<ThrowIfResourceUnavailableOp>(), A.Dummy<TryHandleRecordOp<Version>>(), A.Dummy<TryHandleRecordWithIdOp<Version, Version>>(), A.Dummy<TryHandleRecordWithIdOp<Version>>(), }, }); [SuppressMessage("Microsoft.Design", "CA1034:NestedTypesShouldNotBeVisible")] [SuppressMessage("Microsoft.Naming", "CA1724:TypeNamesShouldNotMatchNamespaces")] public static class Structural { [Fact] [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")] [SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")] [SuppressMessage("Microsoft.Naming", "CA1715:IdentifiersShouldHaveCorrectPrefix")] [SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords")] [SuppressMessage("Microsoft.Naming", "CA1719:ParameterNamesShouldNotMatchMemberNames")] [SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames")] [SuppressMessage("Microsoft.Naming", "CA1722:IdentifiersShouldNotHaveIncorrectPrefix")] [SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration")] [SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms")] [SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly")] public static void StandardCreateStreamOp___Should_implement_IModel_of_StandardCreateStreamOp___When_reflecting() { // Arrange var type = typeof(StandardCreateStreamOp); var expectedModelMethods = typeof(IModel<StandardCreateStreamOp>).GetInterfaceDeclaredAndImplementedMethods(); var expectedModelMethodHashes = expectedModelMethods.Select(_ => _.GetSignatureHash()); // Act var actualInterfaces = type.GetInterfaces(); var actualModelMethods = type.GetMethodsFiltered(MemberRelationships.DeclaredOrInherited, MemberOwners.Instance, MemberAccessModifiers.Public).ToList(); var actualModelMethodHashes = actualModelMethods.Select(_ => _.GetSignatureHash()); // Assert actualInterfaces.AsTest().Must().ContainElement(typeof(IModel<StandardCreateStreamOp>)); expectedModelMethodHashes.Except(actualModelMethodHashes).AsTest().Must().BeEmptyEnumerable(); } [Fact] [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")] [SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")] [SuppressMessage("Microsoft.Naming", "CA1715:IdentifiersShouldHaveCorrectPrefix")] [SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords")] [SuppressMessage("Microsoft.Naming", "CA1719:ParameterNamesShouldNotMatchMemberNames")] [SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames")] [SuppressMessage("Microsoft.Naming", "CA1722:IdentifiersShouldNotHaveIncorrectPrefix")] [SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration")] [SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms")] [SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly")] public static void StandardCreateStreamOp___Should_be_attributed_with_Serializable____When_reflecting() { // Arrange var type = typeof(StandardCreateStreamOp); // Act var actualAttributes = type.GetCustomAttributes(typeof(SerializableAttribute), false); // Assert actualAttributes.AsTest().Must().NotBeEmptyEnumerable(); } } [SuppressMessage("Microsoft.Design", "CA1034:NestedTypesShouldNotBeVisible")] [SuppressMessage("Microsoft.Naming", "CA1724:TypeNamesShouldNotMatchNamespaces")] public static class StringRepresentation { [Fact] [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")] [SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")] [SuppressMessage("Microsoft.Naming", "CA1715:IdentifiersShouldHaveCorrectPrefix")] [SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords")] [SuppressMessage("Microsoft.Naming", "CA1719:ParameterNamesShouldNotMatchMemberNames")] [SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames")] [SuppressMessage("Microsoft.Naming", "CA1722:IdentifiersShouldNotHaveIncorrectPrefix")] [SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration")] [SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms")] [SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly")] public static void ToString___Should_generate_friendly_string_representation_of_object___When_called() { var scenarios = StringRepresentationTestScenarios.ValidateAndPrepareForTesting(); foreach (var scenario in scenarios) { // Arrange, Act var actual = scenario.SystemUnderTest.ToString(); // Assert actual.AsTest().Must().BeEqualTo(scenario.ExpectedStringRepresentation, because: scenario.Id); } } } [SuppressMessage("Microsoft.Design", "CA1034:NestedTypesShouldNotBeVisible")] [SuppressMessage("Microsoft.Naming", "CA1724:TypeNamesShouldNotMatchNamespaces")] public static class Constructing { [Fact] [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")] [SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")] [SuppressMessage("Microsoft.Naming", "CA1715:IdentifiersShouldHaveCorrectPrefix")] [SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords")] [SuppressMessage("Microsoft.Naming", "CA1719:ParameterNamesShouldNotMatchMemberNames")] [SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames")] [SuppressMessage("Microsoft.Naming", "CA1722:IdentifiersShouldNotHaveIncorrectPrefix")] [SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration")] [SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms")] [SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly")] public static void Constructor___Should_throw___When_parameters_are_not_valid() { var scenarios = ConstructorArgumentValidationTestScenarios.ValidateAndPrepareForTesting(); foreach (var scenario in scenarios) { // Arrange, Act var actual = Record.Exception(scenario.ConstructionFunc); // Assert actual.AsTest().Must().BeOfType(scenario.ExpectedExceptionType, because: scenario.Id); foreach(var expected in scenario.ExpectedExceptionMessageContains ?? new List<string>()) { actual.Message.AsTest().Must().ContainString(expected, because: scenario.Id); } if (scenario.ExpectedExceptionMessageEquals != null) { actual.Message.AsTest().Must().BeEqualTo(scenario.ExpectedExceptionMessageEquals, because: scenario.Id); } } } [Fact] [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")] [SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")] [SuppressMessage("Microsoft.Naming", "CA1715:IdentifiersShouldHaveCorrectPrefix")] [SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords")] [SuppressMessage("Microsoft.Naming", "CA1719:ParameterNamesShouldNotMatchMemberNames")] [SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames")] [SuppressMessage("Microsoft.Naming", "CA1722:IdentifiersShouldNotHaveIncorrectPrefix")] [SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration")] [SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms")] [SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly")] [SuppressMessage("Microsoft.Performance", "CA1804:RemoveUnusedLocals", MessageId = "referenceObject")] public static void Properties___Should_be_assigned_by_constructor_to_expected_value___When_getting() { var scenarios = ConstructorPropertyAssignmentTestScenarios.ValidateAndPrepareForTesting(); var asTestMethodInfo = typeof(WorkflowExtensions).GetMethodFiltered(nameof(WorkflowExtensions.AsTest)); var beEqualToMethodInfo = typeof(Verifications).GetMethodFiltered(nameof(Verifications.BeEqualTo)); foreach (var scenario in scenarios) { // Arrange if ((scenario.PropertyName == ConstructorPropertyAssignmentTestScenario.NoPropertiesAssignedInConstructorScenarioPropertyName) || (scenario.PropertyName == ConstructorPropertyAssignmentTestScenario.ForceGeneratedTestsToPassAndWriteMyOwnScenarioPropertyName)) { continue; } // Act var actual = scenario.Property.GetValue(scenario.SystemUnderTest); // Assert // When the scenario specifies CompareActualToExpectedUsing.DefaultStrategy, ValidateAndPrepareForTesting() // will check if ExpectedPropertyValue == null. If so, it sets CompareActualToExpectedUsing = ReferenceEquality. // If not, then it checks the runtime type of ExpectedPropertyValue and if it's a value type, // then it sets CompareActualToExpectedUsing = ValueEquality, otherwise it uses ValueEquality. // So a boxed value type is handled properly (using ValueEquality instead of ReferenceEquality). if (scenario.CompareActualToExpectedUsing == CompareActualToExpectedUsing.ValueEquality) { // The below reflection code is used in lieu of the following single line of code // so that equality is determined based on the property type instead of using // OBeautifulCode.Equality.Recipes.ObjectEqualityComparer, which will return false // when the objects being compared have different runtime types. For example, if // the property type is IReadOnlyCollection<string> and we are comparing an empty array // an empty List, the assertion below would fail inappropriately. // actual.AsTest().Must().BeEqualTo(scenario.ExpectedPropertyValue, because: scenario.Id); var propertyType = scenario.Property.PropertyType; var asTestMethodInfoToInvoke = asTestMethodInfo.MakeGenericMethod(propertyType); var assertionTracker = asTestMethodInfoToInvoke.Invoke(null, new[] { actual, Type.Missing }); assertionTracker.Must(); var mustBeEqualToMethodInfoToInvoke = beEqualToMethodInfo.MakeGenericMethod(propertyType); mustBeEqualToMethodInfoToInvoke.Invoke(null, new[]{ assertionTracker, scenario.ExpectedPropertyValue, scenario.Id, Type.Missing, Type.Missing }); } else if (scenario.CompareActualToExpectedUsing == CompareActualToExpectedUsing.ReferenceEquality) { actual.AsTest().Must().BeSameReferenceAs(scenario.ExpectedPropertyValue, because: scenario.Id); } else { throw new NotSupportedException("This CompareActualToExpectedUsing is not supported: " + scenario.CompareActualToExpectedUsing); } } } } [SuppressMessage("Microsoft.Design", "CA1034:NestedTypesShouldNotBeVisible")] [SuppressMessage("Microsoft.Naming", "CA1724:TypeNamesShouldNotMatchNamespaces")] public static class Cloning { [Fact] [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")] [SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")] [SuppressMessage("Microsoft.Naming", "CA1715:IdentifiersShouldHaveCorrectPrefix")] [SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords")] [SuppressMessage("Microsoft.Naming", "CA1719:ParameterNamesShouldNotMatchMemberNames")] [SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames")] [SuppressMessage("Microsoft.Naming", "CA1722:IdentifiersShouldNotHaveIncorrectPrefix")] [SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration")] [SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms")] [SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly")] public static void Clone___Should_clone_object___When_called() { // Arrange var systemUnderTest = A.Dummy<StandardCreateStreamOp>(); // Act var actual = (StandardCreateStreamOp)systemUnderTest.Clone(); // Assert actual.AsTest().Must().BeEqualTo(systemUnderTest); actual.AsTest().Must().NotBeSameReferenceAs(systemUnderTest); } [Fact] [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")] [SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")] [SuppressMessage("Microsoft.Naming", "CA1715:IdentifiersShouldHaveCorrectPrefix")] [SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords")] [SuppressMessage("Microsoft.Naming", "CA1719:ParameterNamesShouldNotMatchMemberNames")] [SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames")] [SuppressMessage("Microsoft.Naming", "CA1722:IdentifiersShouldNotHaveIncorrectPrefix")] [SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration")] [SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms")] [SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly")] public static void DeepClone___Should_deep_clone_object___When_called() { // Arrange var systemUnderTest = A.Dummy<StandardCreateStreamOp>(); // Act var actual = systemUnderTest.DeepClone(); // Assert actual.AsTest().Must().BeEqualTo(systemUnderTest); actual.AsTest().Must().NotBeSameReferenceAs(systemUnderTest); if (systemUnderTest.StreamRepresentation == null) { actual.StreamRepresentation.AsTest().Must().BeNull(); } else if (!actual.StreamRepresentation.GetType().IsValueType) { // When the declared type is a reference type, we still have to check the runtime type. // The object could be a boxed value type, which will fail this asseration because // a deep clone of a value type object is the same object. actual.StreamRepresentation.AsTest().Must().NotBeSameReferenceAs(systemUnderTest.StreamRepresentation); } } [Fact] [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")] [SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")] [SuppressMessage("Microsoft.Naming", "CA1715:IdentifiersShouldHaveCorrectPrefix")] [SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords")] [SuppressMessage("Microsoft.Naming", "CA1719:ParameterNamesShouldNotMatchMemberNames")] [SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames")] [SuppressMessage("Microsoft.Naming", "CA1722:IdentifiersShouldNotHaveIncorrectPrefix")] [SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration")] [SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms")] [SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly")] public static void DeepCloneWith___Should_deep_clone_object_and_replace_the_associated_property_with_the_provided_value___When_called() { var propertyNames = new string[] { "StreamRepresentation", "ExistingStreamStrategy" }; var scenarios = DeepCloneWithTestScenarios.ValidateAndPrepareForTesting(); foreach (var scenario in scenarios) { // Arrange if (scenario.WithPropertyName == DeepCloneWithTestScenario.ForceGeneratedTestsToPassAndWriteMyOwnScenarioWithPropertyName) { continue; } // Act var actual = (StandardCreateStreamOp)scenario.DeepCloneWithMethod.Invoke(scenario.SystemUnderTest, new[] { scenario.WithValue }); // Assert foreach(var propertyName in propertyNames) { var propertyInfo = typeof(StandardCreateStreamOp).GetPropertyFiltered(propertyName, MemberRelationships.DeclaredOrInherited, MemberOwners.Instance, MemberAccessModifiers.Public); var actualPropertyValue = propertyInfo.GetValue(actual); var comparisonValue = propertyName == scenario.WithPropertyName ? scenario.WithValue : propertyInfo.GetValue(scenario.SystemUnderTest); if (actualPropertyValue == null) { comparisonValue.Must().BeNull(because: scenario.Id); } else { // We use the runtime type here to solve for the case where the object is a boxed value type. var actualPropertyValueRuntimeType = actualPropertyValue.GetType(); if (actualPropertyValueRuntimeType.IsValueType || (actualPropertyValueRuntimeType == typeof(string))) { // actualPropertyValue and comparisonValue are declared as typeof(object), but // BeEqualTo (which uses IsEqualTo), will do the right thing by comparing the // objects using their runtime type. actualPropertyValue.AsTest().Must().BeEqualTo(comparisonValue, because: scenario.Id); } else { if (propertyName == scenario.WithPropertyName) { actualPropertyValue.AsTest().Must().BeSameReferenceAs(comparisonValue, because: scenario.Id); } else { actualPropertyValue.AsTest().Must().NotBeSameReferenceAs(comparisonValue, because: scenario.Id); } } } } } } } [SuppressMessage("Microsoft.Design", "CA1034:NestedTypesShouldNotBeVisible")] [SuppressMessage("Microsoft.Naming", "CA1724:TypeNamesShouldNotMatchNamespaces")] public static class Serialization { [Fact] [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")] [SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")] [SuppressMessage("Microsoft.Naming", "CA1715:IdentifiersShouldHaveCorrectPrefix")] [SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords")] [SuppressMessage("Microsoft.Naming", "CA1719:ParameterNamesShouldNotMatchMemberNames")] [SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames")] [SuppressMessage("Microsoft.Naming", "CA1722:IdentifiersShouldNotHaveIncorrectPrefix")] [SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration")] [SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms")] [SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly")] public static void Deserialize___Should_roundtrip_object___When_serializing_to_and_deserializing_from_string_using_ObcBsonSerializer() { // Arrange var expected = A.Dummy<StandardCreateStreamOp>(); var serializationConfigurationType = SerializationConfigurationTypes.BsonSerializationConfigurationType.ConcreteSerializationConfigurationDerivativeType; var serializationFormats = new[] { SerializationFormat.String }; var appDomainScenarios = AppDomainScenarios.RoundtripInCurrentAppDomain | AppDomainScenarios.SerializeInCurrentAppDomainAndDeserializeInNewAppDomain; // Act, Assert expected.RoundtripSerializeViaBsonWithBeEqualToAssertion(serializationConfigurationType, serializationFormats, appDomainScenarios); } [Fact] [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")] [SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")] [SuppressMessage("Microsoft.Naming", "CA1715:IdentifiersShouldHaveCorrectPrefix")] [SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords")] [SuppressMessage("Microsoft.Naming", "CA1719:ParameterNamesShouldNotMatchMemberNames")] [SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames")] [SuppressMessage("Microsoft.Naming", "CA1722:IdentifiersShouldNotHaveIncorrectPrefix")] [SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration")] [SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms")] [SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly")] public static void Deserialize___Should_roundtrip_object___When_serializing_to_and_deserializing_from_bytes_using_ObcBsonSerializer() { // Arrange var expected = A.Dummy<StandardCreateStreamOp>(); var serializationConfigurationType = SerializationConfigurationTypes.BsonSerializationConfigurationType.ConcreteSerializationConfigurationDerivativeType; var serializationFormats = new[] { SerializationFormat.Binary }; var appDomainScenarios = AppDomainScenarios.RoundtripInCurrentAppDomain | AppDomainScenarios.SerializeInCurrentAppDomainAndDeserializeInNewAppDomain; // Act, Assert expected.RoundtripSerializeViaBsonWithBeEqualToAssertion(serializationConfigurationType, serializationFormats, appDomainScenarios); } [Fact] [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")] [SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")] [SuppressMessage("Microsoft.Naming", "CA1715:IdentifiersShouldHaveCorrectPrefix")] [SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords")] [SuppressMessage("Microsoft.Naming", "CA1719:ParameterNamesShouldNotMatchMemberNames")] [SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames")] [SuppressMessage("Microsoft.Naming", "CA1722:IdentifiersShouldNotHaveIncorrectPrefix")] [SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration")] [SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms")] [SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly")] public static void Deserialize___Should_roundtrip_object___When_serializing_to_and_deserializing_from_string_using_ObcJsonSerializer() { // Arrange var expected = A.Dummy<StandardCreateStreamOp>(); var serializationConfigurationType = SerializationConfigurationTypes.JsonSerializationConfigurationType.ConcreteSerializationConfigurationDerivativeType; var serializationFormats = new[] { SerializationFormat.String }; var appDomainScenarios = AppDomainScenarios.RoundtripInCurrentAppDomain | AppDomainScenarios.SerializeInCurrentAppDomainAndDeserializeInNewAppDomain; // Act, Assert expected.RoundtripSerializeViaJsonWithBeEqualToAssertion(serializationConfigurationType, serializationFormats, appDomainScenarios); } [Fact] [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")] [SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")] [SuppressMessage("Microsoft.Naming", "CA1715:IdentifiersShouldHaveCorrectPrefix")] [SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords")] [SuppressMessage("Microsoft.Naming", "CA1719:ParameterNamesShouldNotMatchMemberNames")] [SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames")] [SuppressMessage("Microsoft.Naming", "CA1722:IdentifiersShouldNotHaveIncorrectPrefix")] [SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration")] [SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms")] [SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly")] public static void Deserialize___Should_roundtrip_object___When_serializing_to_and_deserializing_from_bytes_using_ObcJsonSerializer() { // Arrange var expected = A.Dummy<StandardCreateStreamOp>(); var serializationConfigurationType = SerializationConfigurationTypes.JsonSerializationConfigurationType.ConcreteSerializationConfigurationDerivativeType; var serializationFormats = new[] { SerializationFormat.Binary }; var appDomainScenarios = AppDomainScenarios.RoundtripInCurrentAppDomain | AppDomainScenarios.SerializeInCurrentAppDomainAndDeserializeInNewAppDomain; // Act, Assert expected.RoundtripSerializeViaJsonWithBeEqualToAssertion(serializationConfigurationType, serializationFormats, appDomainScenarios); } } [SuppressMessage("Microsoft.Design", "CA1034:NestedTypesShouldNotBeVisible")] [SuppressMessage("Microsoft.Naming", "CA1724:TypeNamesShouldNotMatchNamespaces")] public static class Equality { [Fact] [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")] [SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")] [SuppressMessage("Microsoft.Naming", "CA1715:IdentifiersShouldHaveCorrectPrefix")] [SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords")] [SuppressMessage("Microsoft.Naming", "CA1719:ParameterNamesShouldNotMatchMemberNames")] [SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames")] [SuppressMessage("Microsoft.Naming", "CA1722:IdentifiersShouldNotHaveIncorrectPrefix")] [SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration")] [SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms")] [SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly")] public static void EqualsOperator___Should_return_true___When_both_sides_of_operator_are_null() { // Arrange StandardCreateStreamOp systemUnderTest1 = null; StandardCreateStreamOp systemUnderTest2 = null; // Act var actual = systemUnderTest1 == systemUnderTest2; // Assert actual.AsTest().Must().BeTrue(); } [Fact] [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")] [SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")] [SuppressMessage("Microsoft.Naming", "CA1715:IdentifiersShouldHaveCorrectPrefix")] [SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords")] [SuppressMessage("Microsoft.Naming", "CA1719:ParameterNamesShouldNotMatchMemberNames")] [SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames")] [SuppressMessage("Microsoft.Naming", "CA1722:IdentifiersShouldNotHaveIncorrectPrefix")] [SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration")] [SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms")] [SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly")] public static void EqualsOperator___Should_return_false___When_one_side_of_operator_is_null_and_the_other_side_is_not_null() { var scenarios = EquatableTestScenarios.ValidateAndPrepareForTesting(); foreach (var scenario in scenarios) { // Arrange StandardCreateStreamOp systemUnderTest = null; // Act var actual1 = systemUnderTest == scenario.ReferenceObject; var actual2 = scenario.ReferenceObject == systemUnderTest; // Assert actual1.AsTest().Must().BeFalse(because: scenario.Id); actual2.AsTest().Must().BeFalse(because: scenario.Id); } } [Fact] [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")] [SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")] [SuppressMessage("Microsoft.Naming", "CA1715:IdentifiersShouldHaveCorrectPrefix")] [SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords")] [SuppressMessage("Microsoft.Naming", "CA1719:ParameterNamesShouldNotMatchMemberNames")] [SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames")] [SuppressMessage("Microsoft.Naming", "CA1722:IdentifiersShouldNotHaveIncorrectPrefix")] [SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration")] [SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms")] [SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly")] public static void EqualsOperator___Should_return_true___When_same_object_is_on_both_sides_of_operator() { var scenarios = EquatableTestScenarios.ValidateAndPrepareForTesting(); foreach (var scenario in scenarios) { // Arrange, Act #pragma warning disable CS1718 // Comparison made to same variable var actual = scenario.ReferenceObject == scenario.ReferenceObject; #pragma warning restore CS1718 // Comparison made to same variable // Assert actual.AsTest().Must().BeTrue(because: scenario.Id); } } [Fact] [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")] [SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")] [SuppressMessage("Microsoft.Naming", "CA1715:IdentifiersShouldHaveCorrectPrefix")] [SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords")] [SuppressMessage("Microsoft.Naming", "CA1719:ParameterNamesShouldNotMatchMemberNames")] [SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames")] [SuppressMessage("Microsoft.Naming", "CA1722:IdentifiersShouldNotHaveIncorrectPrefix")] [SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration")] [SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms")] [SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly")] public static void EqualsOperator___Should_return_false___When_objects_being_compared_derive_from_the_same_type_but_are_not_of_the_same_type() { var scenarios = EquatableTestScenarios.ValidateAndPrepareForTesting(); foreach (var scenario in scenarios) { // Arrange, Act var actuals1 = scenario.ObjectsThatDeriveFromScenarioTypeButAreNotOfTheSameTypeAsReferenceObject.Select(_ => scenario.ReferenceObject == _).ToList(); var actuals2 = scenario.ObjectsThatDeriveFromScenarioTypeButAreNotOfTheSameTypeAsReferenceObject.Select(_ => _ == scenario.ReferenceObject).ToList(); // Assert actuals1.AsTest().Must().Each().BeFalse(because: scenario.Id); actuals2.AsTest().Must().Each().BeFalse(because: scenario.Id); } } [Fact] [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")] [SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")] [SuppressMessage("Microsoft.Naming", "CA1715:IdentifiersShouldHaveCorrectPrefix")] [SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords")] [SuppressMessage("Microsoft.Naming", "CA1719:ParameterNamesShouldNotMatchMemberNames")] [SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames")] [SuppressMessage("Microsoft.Naming", "CA1722:IdentifiersShouldNotHaveIncorrectPrefix")] [SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration")] [SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms")] [SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly")] public static void EqualsOperator___Should_return_false___When_objects_being_compared_have_different_property_values() { var scenarios = EquatableTestScenarios.ValidateAndPrepareForTesting(); foreach (var scenario in scenarios) { // Arrange, Act var actuals1 = scenario.ObjectsThatAreNotEqualToReferenceObject.Select(_ => scenario.ReferenceObject == _).ToList(); var actuals2 = scenario.ObjectsThatAreNotEqualToReferenceObject.Select(_ => _ == scenario.ReferenceObject).ToList(); // Assert actuals1.AsTest().Must().Each().BeFalse(because: scenario.Id); actuals2.AsTest().Must().Each().BeFalse(because: scenario.Id); } } [Fact] [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")] [SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")] [SuppressMessage("Microsoft.Naming", "CA1715:IdentifiersShouldHaveCorrectPrefix")] [SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords")] [SuppressMessage("Microsoft.Naming", "CA1719:ParameterNamesShouldNotMatchMemberNames")] [SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames")] [SuppressMessage("Microsoft.Naming", "CA1722:IdentifiersShouldNotHaveIncorrectPrefix")] [SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration")] [SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms")] [SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly")] public static void EqualsOperator___Should_return_true___When_objects_being_compared_have_same_property_values() { var scenarios = EquatableTestScenarios.ValidateAndPrepareForTesting(); foreach (var scenario in scenarios) { // Arrange, Act var actuals1 = scenario.ObjectsThatAreEqualToButNotTheSameAsReferenceObject.Select(_ => scenario.ReferenceObject == _).ToList(); var actuals2 = scenario.ObjectsThatAreEqualToButNotTheSameAsReferenceObject.Select(_ => _ == scenario.ReferenceObject).ToList(); // Assert actuals1.AsTest().Must().Each().BeTrue(because: scenario.Id); actuals2.AsTest().Must().Each().BeTrue(because: scenario.Id); } } [Fact] [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")] [SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")] [SuppressMessage("Microsoft.Naming", "CA1715:IdentifiersShouldHaveCorrectPrefix")] [SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords")] [SuppressMessage("Microsoft.Naming", "CA1719:ParameterNamesShouldNotMatchMemberNames")] [SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames")] [SuppressMessage("Microsoft.Naming", "CA1722:IdentifiersShouldNotHaveIncorrectPrefix")] [SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration")] [SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms")] [SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly")] public static void NotEqualsOperator___Should_return_false___When_both_sides_of_operator_are_null() { // Arrange StandardCreateStreamOp systemUnderTest1 = null; StandardCreateStreamOp systemUnderTest2 = null; // Act var actual = systemUnderTest1 != systemUnderTest2; // Assert actual.AsTest().Must().BeFalse(); } [Fact] [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")] [SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")] [SuppressMessage("Microsoft.Naming", "CA1715:IdentifiersShouldHaveCorrectPrefix")] [SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords")] [SuppressMessage("Microsoft.Naming", "CA1719:ParameterNamesShouldNotMatchMemberNames")] [SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames")] [SuppressMessage("Microsoft.Naming", "CA1722:IdentifiersShouldNotHaveIncorrectPrefix")] [SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration")] [SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms")] [SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly")] public static void NotEqualsOperator___Should_return_true___When_one_side_of_operator_is_null_and_the_other_side_is_not_null() { var scenarios = EquatableTestScenarios.ValidateAndPrepareForTesting(); foreach (var scenario in scenarios) { // Arrange StandardCreateStreamOp systemUnderTest = null; // Act var actual1 = systemUnderTest != scenario.ReferenceObject; var actual2 = scenario.ReferenceObject != systemUnderTest; // Assert actual1.AsTest().Must().BeTrue(because: scenario.Id); actual2.AsTest().Must().BeTrue(because: scenario.Id); } } [Fact] [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")] [SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")] [SuppressMessage("Microsoft.Naming", "CA1715:IdentifiersShouldHaveCorrectPrefix")] [SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords")] [SuppressMessage("Microsoft.Naming", "CA1719:ParameterNamesShouldNotMatchMemberNames")] [SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames")] [SuppressMessage("Microsoft.Naming", "CA1722:IdentifiersShouldNotHaveIncorrectPrefix")] [SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration")] [SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms")] [SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly")] public static void NotEqualsOperator___Should_return_false___When_same_object_is_on_both_sides_of_operator() { var scenarios = EquatableTestScenarios.ValidateAndPrepareForTesting(); foreach (var scenario in scenarios) { // Arrange, Act #pragma warning disable CS1718 // Comparison made to same variable var actual = scenario.ReferenceObject != scenario.ReferenceObject; #pragma warning restore CS1718 // Comparison made to same variable // Assert actual.AsTest().Must().BeFalse(because: scenario.Id); } } [Fact] [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")] [SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")] [SuppressMessage("Microsoft.Naming", "CA1715:IdentifiersShouldHaveCorrectPrefix")] [SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords")] [SuppressMessage("Microsoft.Naming", "CA1719:ParameterNamesShouldNotMatchMemberNames")] [SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames")] [SuppressMessage("Microsoft.Naming", "CA1722:IdentifiersShouldNotHaveIncorrectPrefix")] [SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration")] [SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms")] [SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly")] public static void NotEqualsOperator___Should_return_true___When_objects_being_compared_derive_from_the_same_type_but_are_not_of_the_same_type() { var scenarios = EquatableTestScenarios.ValidateAndPrepareForTesting(); foreach (var scenario in scenarios) { // Arrange, Act var actuals1 = scenario.ObjectsThatDeriveFromScenarioTypeButAreNotOfTheSameTypeAsReferenceObject.Select(_ => scenario.ReferenceObject != _).ToList(); var actuals2 = scenario.ObjectsThatDeriveFromScenarioTypeButAreNotOfTheSameTypeAsReferenceObject.Select(_ => _ != scenario.ReferenceObject).ToList(); // Assert actuals1.AsTest().Must().Each().BeTrue(because: scenario.Id); actuals2.AsTest().Must().Each().BeTrue(because: scenario.Id); } } [Fact] [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")] [SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")] [SuppressMessage("Microsoft.Naming", "CA1715:IdentifiersShouldHaveCorrectPrefix")] [SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords")] [SuppressMessage("Microsoft.Naming", "CA1719:ParameterNamesShouldNotMatchMemberNames")] [SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames")] [SuppressMessage("Microsoft.Naming", "CA1722:IdentifiersShouldNotHaveIncorrectPrefix")] [SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration")] [SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms")] [SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly")] public static void NotEqualsOperator___Should_return_true___When_objects_being_compared_have_different_property_values() { var scenarios = EquatableTestScenarios.ValidateAndPrepareForTesting(); foreach (var scenario in scenarios) { // Arrange, Act var actuals1 = scenario.ObjectsThatAreNotEqualToReferenceObject.Select(_ => scenario.ReferenceObject != _).ToList(); var actuals2 = scenario.ObjectsThatAreNotEqualToReferenceObject.Select(_ => _ != scenario.ReferenceObject).ToList(); // Assert actuals1.AsTest().Must().Each().BeTrue(because: scenario.Id); actuals2.AsTest().Must().Each().BeTrue(because: scenario.Id); } } [Fact] [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")] [SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")] [SuppressMessage("Microsoft.Naming", "CA1715:IdentifiersShouldHaveCorrectPrefix")] [SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords")] [SuppressMessage("Microsoft.Naming", "CA1719:ParameterNamesShouldNotMatchMemberNames")] [SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames")] [SuppressMessage("Microsoft.Naming", "CA1722:IdentifiersShouldNotHaveIncorrectPrefix")] [SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration")] [SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms")] [SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly")] public static void NotEqualsOperator___Should_return_false___When_objects_being_compared_have_same_property_values() { var scenarios = EquatableTestScenarios.ValidateAndPrepareForTesting(); foreach (var scenario in scenarios) { // Arrange, Act var actuals1 = scenario.ObjectsThatAreEqualToButNotTheSameAsReferenceObject.Select(_ => scenario.ReferenceObject != _).ToList(); var actuals2 = scenario.ObjectsThatAreEqualToButNotTheSameAsReferenceObject.Select(_ => _ != scenario.ReferenceObject).ToList(); // Assert actuals1.AsTest().Must().Each().BeFalse(because: scenario.Id); actuals2.AsTest().Must().Each().BeFalse(because: scenario.Id); } } [Fact] [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")] [SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")] [SuppressMessage("Microsoft.Naming", "CA1715:IdentifiersShouldHaveCorrectPrefix")] [SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords")] [SuppressMessage("Microsoft.Naming", "CA1719:ParameterNamesShouldNotMatchMemberNames")] [SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames")] [SuppressMessage("Microsoft.Naming", "CA1722:IdentifiersShouldNotHaveIncorrectPrefix")] [SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration")] [SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms")] [SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly")] public static void Equals_with_OperationBase___Should_return_false___When_parameter_other_is_null() { var scenarios = EquatableTestScenarios.ValidateAndPrepareForTesting(); foreach (var scenario in scenarios) { // Arrange OperationBase systemUnderTest = null; // Act var actual = scenario.ReferenceObject.Equals((OperationBase)systemUnderTest); // Assert actual.AsTest().Must().BeFalse(because: scenario.Id); } } [Fact] [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")] [SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")] [SuppressMessage("Microsoft.Naming", "CA1715:IdentifiersShouldHaveCorrectPrefix")] [SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords")] [SuppressMessage("Microsoft.Naming", "CA1719:ParameterNamesShouldNotMatchMemberNames")] [SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames")] [SuppressMessage("Microsoft.Naming", "CA1722:IdentifiersShouldNotHaveIncorrectPrefix")] [SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration")] [SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms")] [SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly")] public static void Equals_with_OperationBase___Should_return_true___When_parameter_other_is_same_object() { var scenarios = EquatableTestScenarios.ValidateAndPrepareForTesting(); foreach (var scenario in scenarios) { // Arrange, Act var actual = scenario.ReferenceObject.Equals((OperationBase)scenario.ReferenceObject); // Assert actual.AsTest().Must().BeTrue(because: scenario.Id); } } [Fact] [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")] [SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")] [SuppressMessage("Microsoft.Naming", "CA1715:IdentifiersShouldHaveCorrectPrefix")] [SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords")] [SuppressMessage("Microsoft.Naming", "CA1719:ParameterNamesShouldNotMatchMemberNames")] [SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames")] [SuppressMessage("Microsoft.Naming", "CA1722:IdentifiersShouldNotHaveIncorrectPrefix")] [SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration")] [SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms")] [SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly")] public static void Equals_with_OperationBase___Should_return_false___When_parameter_other_is_derived_from_the_same_type_but_is_not_of_the_same_type_as_this_object() { var scenarios = EquatableTestScenarios.ValidateAndPrepareForTesting(); foreach (var scenario in scenarios) { // Arrange, Act var actuals = scenario.ObjectsThatDeriveFromScenarioTypeButAreNotOfTheSameTypeAsReferenceObject.Select(_ => scenario.ReferenceObject.Equals((OperationBase)_)).ToList(); // Assert actuals.AsTest().Must().Each().BeFalse(because: scenario.Id); } } [Fact] [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")] [SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")] [SuppressMessage("Microsoft.Naming", "CA1715:IdentifiersShouldHaveCorrectPrefix")] [SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords")] [SuppressMessage("Microsoft.Naming", "CA1719:ParameterNamesShouldNotMatchMemberNames")] [SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames")] [SuppressMessage("Microsoft.Naming", "CA1722:IdentifiersShouldNotHaveIncorrectPrefix")] [SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration")] [SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms")] [SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly")] public static void Equals_with_OperationBase___Should_return_false___When_objects_being_compared_have_different_property_values() { var scenarios = EquatableTestScenarios.ValidateAndPrepareForTesting(); foreach (var scenario in scenarios) { // Arrange, Act var actuals = scenario.ObjectsThatAreNotEqualToReferenceObject.Select(_ => scenario.ReferenceObject.Equals((OperationBase)_)).ToList(); // Assert actuals.AsTest().Must().Each().BeFalse(because: scenario.Id); } } [Fact] [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")] [SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")] [SuppressMessage("Microsoft.Naming", "CA1715:IdentifiersShouldHaveCorrectPrefix")] [SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords")] [SuppressMessage("Microsoft.Naming", "CA1719:ParameterNamesShouldNotMatchMemberNames")] [SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames")] [SuppressMessage("Microsoft.Naming", "CA1722:IdentifiersShouldNotHaveIncorrectPrefix")] [SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration")] [SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms")] [SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly")] public static void Equals_with_OperationBase___Should_return_true___When_objects_being_compared_have_same_property_values() { var scenarios = EquatableTestScenarios.ValidateAndPrepareForTesting(); foreach (var scenario in scenarios) { // Arrange, Act var actuals = scenario.ObjectsThatAreEqualToButNotTheSameAsReferenceObject.Select(_ => scenario.ReferenceObject.Equals((OperationBase)_)).ToList(); // Assert actuals.AsTest().Must().Each().BeTrue(because: scenario.Id); } } [Fact] [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")] [SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")] [SuppressMessage("Microsoft.Naming", "CA1715:IdentifiersShouldHaveCorrectPrefix")] [SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords")] [SuppressMessage("Microsoft.Naming", "CA1719:ParameterNamesShouldNotMatchMemberNames")] [SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames")] [SuppressMessage("Microsoft.Naming", "CA1722:IdentifiersShouldNotHaveIncorrectPrefix")] [SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration")] [SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms")] [SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly")] public static void Equals_with_ReturningOperationBase_of_CreateStreamResult___Should_return_false___When_parameter_other_is_null() { var scenarios = EquatableTestScenarios.ValidateAndPrepareForTesting(); foreach (var scenario in scenarios) { // Arrange ReturningOperationBase<CreateStreamResult> systemUnderTest = null; // Act var actual = scenario.ReferenceObject.Equals((ReturningOperationBase<CreateStreamResult>)systemUnderTest); // Assert actual.AsTest().Must().BeFalse(because: scenario.Id); } } [Fact] [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")] [SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")] [SuppressMessage("Microsoft.Naming", "CA1715:IdentifiersShouldHaveCorrectPrefix")] [SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords")] [SuppressMessage("Microsoft.Naming", "CA1719:ParameterNamesShouldNotMatchMemberNames")] [SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames")] [SuppressMessage("Microsoft.Naming", "CA1722:IdentifiersShouldNotHaveIncorrectPrefix")] [SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration")] [SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms")] [SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly")] public static void Equals_with_ReturningOperationBase_of_CreateStreamResult___Should_return_true___When_parameter_other_is_same_object() { var scenarios = EquatableTestScenarios.ValidateAndPrepareForTesting(); foreach (var scenario in scenarios) { // Arrange, Act var actual = scenario.ReferenceObject.Equals((ReturningOperationBase<CreateStreamResult>)scenario.ReferenceObject); // Assert actual.AsTest().Must().BeTrue(because: scenario.Id); } } [Fact] [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")] [SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")] [SuppressMessage("Microsoft.Naming", "CA1715:IdentifiersShouldHaveCorrectPrefix")] [SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords")] [SuppressMessage("Microsoft.Naming", "CA1719:ParameterNamesShouldNotMatchMemberNames")] [SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames")] [SuppressMessage("Microsoft.Naming", "CA1722:IdentifiersShouldNotHaveIncorrectPrefix")] [SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration")] [SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms")] [SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly")] public static void Equals_with_ReturningOperationBase_of_CreateStreamResult___Should_return_false___When_parameter_other_is_derived_from_the_same_type_but_is_not_of_the_same_type_as_this_object() { var scenarios = EquatableTestScenarios.ValidateAndPrepareForTesting(); foreach (var scenario in scenarios) { // Arrange, Act var actuals = scenario.ObjectsThatDeriveFromScenarioTypeButAreNotOfTheSameTypeAsReferenceObject.Select(_ => scenario.ReferenceObject.Equals((ReturningOperationBase<CreateStreamResult>)_)).ToList(); // Assert actuals.AsTest().Must().Each().BeFalse(because: scenario.Id); } } [Fact] [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")] [SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")] [SuppressMessage("Microsoft.Naming", "CA1715:IdentifiersShouldHaveCorrectPrefix")] [SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords")] [SuppressMessage("Microsoft.Naming", "CA1719:ParameterNamesShouldNotMatchMemberNames")] [SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames")] [SuppressMessage("Microsoft.Naming", "CA1722:IdentifiersShouldNotHaveIncorrectPrefix")] [SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration")] [SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms")] [SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly")] public static void Equals_with_ReturningOperationBase_of_CreateStreamResult___Should_return_false___When_objects_being_compared_have_different_property_values() { var scenarios = EquatableTestScenarios.ValidateAndPrepareForTesting(); foreach (var scenario in scenarios) { // Arrange, Act var actuals = scenario.ObjectsThatAreNotEqualToReferenceObject.Select(_ => scenario.ReferenceObject.Equals((ReturningOperationBase<CreateStreamResult>)_)).ToList(); // Assert actuals.AsTest().Must().Each().BeFalse(because: scenario.Id); } } [Fact] [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")] [SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")] [SuppressMessage("Microsoft.Naming", "CA1715:IdentifiersShouldHaveCorrectPrefix")] [SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords")] [SuppressMessage("Microsoft.Naming", "CA1719:ParameterNamesShouldNotMatchMemberNames")] [SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames")] [SuppressMessage("Microsoft.Naming", "CA1722:IdentifiersShouldNotHaveIncorrectPrefix")] [SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration")] [SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms")] [SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly")] public static void Equals_with_ReturningOperationBase_of_CreateStreamResult___Should_return_true___When_objects_being_compared_have_same_property_values() { var scenarios = EquatableTestScenarios.ValidateAndPrepareForTesting(); foreach (var scenario in scenarios) { // Arrange, Act var actuals = scenario.ObjectsThatAreEqualToButNotTheSameAsReferenceObject.Select(_ => scenario.ReferenceObject.Equals((ReturningOperationBase<CreateStreamResult>)_)).ToList(); // Assert actuals.AsTest().Must().Each().BeTrue(because: scenario.Id); } } [Fact] [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")] [SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")] [SuppressMessage("Microsoft.Naming", "CA1715:IdentifiersShouldHaveCorrectPrefix")] [SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords")] [SuppressMessage("Microsoft.Naming", "CA1719:ParameterNamesShouldNotMatchMemberNames")] [SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames")] [SuppressMessage("Microsoft.Naming", "CA1722:IdentifiersShouldNotHaveIncorrectPrefix")] [SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration")] [SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms")] [SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly")] public static void Equals_with_StandardCreateStreamOp___Should_return_false___When_parameter_other_is_null() { var scenarios = EquatableTestScenarios.ValidateAndPrepareForTesting(); foreach (var scenario in scenarios) { // Arrange StandardCreateStreamOp systemUnderTest = null; // Act var actual = scenario.ReferenceObject.Equals(systemUnderTest); // Assert actual.AsTest().Must().BeFalse(because: scenario.Id); } } [Fact] [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")] [SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")] [SuppressMessage("Microsoft.Naming", "CA1715:IdentifiersShouldHaveCorrectPrefix")] [SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords")] [SuppressMessage("Microsoft.Naming", "CA1719:ParameterNamesShouldNotMatchMemberNames")] [SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames")] [SuppressMessage("Microsoft.Naming", "CA1722:IdentifiersShouldNotHaveIncorrectPrefix")] [SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration")] [SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms")] [SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly")] public static void Equals_with_StandardCreateStreamOp___Should_return_true___When_parameter_other_is_same_object() { var scenarios = EquatableTestScenarios.ValidateAndPrepareForTesting(); foreach (var scenario in scenarios) { // Arrange, Act var actual = scenario.ReferenceObject.Equals(scenario.ReferenceObject); // Assert actual.AsTest().Must().BeTrue(because: scenario.Id); } } [Fact] [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")] [SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")] [SuppressMessage("Microsoft.Naming", "CA1715:IdentifiersShouldHaveCorrectPrefix")] [SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords")] [SuppressMessage("Microsoft.Naming", "CA1719:ParameterNamesShouldNotMatchMemberNames")] [SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames")] [SuppressMessage("Microsoft.Naming", "CA1722:IdentifiersShouldNotHaveIncorrectPrefix")] [SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration")] [SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms")] [SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly")] public static void Equals_with_StandardCreateStreamOp___Should_return_false___When_parameter_other_is_derived_from_the_same_type_but_is_not_of_the_same_type_as_this_object() { var scenarios = EquatableTestScenarios.ValidateAndPrepareForTesting(); foreach (var scenario in scenarios) { // Arrange, Act var actuals = scenario.ObjectsThatDeriveFromScenarioTypeButAreNotOfTheSameTypeAsReferenceObject.Select(_ => scenario.ReferenceObject.Equals(_)).ToList(); // Assert actuals.AsTest().Must().Each().BeFalse(because: scenario.Id); } } [Fact] [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")] [SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")] [SuppressMessage("Microsoft.Naming", "CA1715:IdentifiersShouldHaveCorrectPrefix")] [SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords")] [SuppressMessage("Microsoft.Naming", "CA1719:ParameterNamesShouldNotMatchMemberNames")] [SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames")] [SuppressMessage("Microsoft.Naming", "CA1722:IdentifiersShouldNotHaveIncorrectPrefix")] [SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration")] [SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms")] [SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly")] public static void Equals_with_StandardCreateStreamOp___Should_return_false___When_objects_being_compared_have_different_property_values() { var scenarios = EquatableTestScenarios.ValidateAndPrepareForTesting(); foreach (var scenario in scenarios) { // Arrange, Act var actuals = scenario.ObjectsThatAreNotEqualToReferenceObject.Select(_ => scenario.ReferenceObject.Equals(_)).ToList(); // Assert actuals.AsTest().Must().Each().BeFalse(because: scenario.Id); } } [Fact] [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")] [SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")] [SuppressMessage("Microsoft.Naming", "CA1715:IdentifiersShouldHaveCorrectPrefix")] [SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords")] [SuppressMessage("Microsoft.Naming", "CA1719:ParameterNamesShouldNotMatchMemberNames")] [SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames")] [SuppressMessage("Microsoft.Naming", "CA1722:IdentifiersShouldNotHaveIncorrectPrefix")] [SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration")] [SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms")] [SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly")] public static void Equals_with_StandardCreateStreamOp___Should_return_true___When_objects_being_compared_have_same_property_values() { var scenarios = EquatableTestScenarios.ValidateAndPrepareForTesting(); foreach (var scenario in scenarios) { // Arrange, Act var actuals = scenario.ObjectsThatAreEqualToButNotTheSameAsReferenceObject.Select(_ => scenario.ReferenceObject.Equals(_)).ToList(); // Assert actuals.AsTest().Must().Each().BeTrue(because: scenario.Id); } } [Fact] [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")] [SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")] [SuppressMessage("Microsoft.Naming", "CA1715:IdentifiersShouldHaveCorrectPrefix")] [SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords")] [SuppressMessage("Microsoft.Naming", "CA1719:ParameterNamesShouldNotMatchMemberNames")] [SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames")] [SuppressMessage("Microsoft.Naming", "CA1722:IdentifiersShouldNotHaveIncorrectPrefix")] [SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration")] [SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms")] [SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly")] public static void Equals_with_Object___Should_return_false___When_parameter_other_is_null() { var scenarios = EquatableTestScenarios.ValidateAndPrepareForTesting(); foreach (var scenario in scenarios) { // Arrange, Act var actual = scenario.ReferenceObject.Equals((object)null); // Assert actual.AsTest().Must().BeFalse(because: scenario.Id); } } [Fact] [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")] [SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")] [SuppressMessage("Microsoft.Naming", "CA1715:IdentifiersShouldHaveCorrectPrefix")] [SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords")] [SuppressMessage("Microsoft.Naming", "CA1719:ParameterNamesShouldNotMatchMemberNames")] [SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames")] [SuppressMessage("Microsoft.Naming", "CA1722:IdentifiersShouldNotHaveIncorrectPrefix")] [SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration")] [SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms")] [SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly")] public static void Equals_with_Object___Should_return_false___When_parameter_other_is_not_of_the_same_type() { var scenarios = EquatableTestScenarios.ValidateAndPrepareForTesting(); foreach (var scenario in scenarios) { // Arrange, Act var actuals1 = scenario.ObjectsThatDeriveFromScenarioTypeButAreNotOfTheSameTypeAsReferenceObject.Select(_ => scenario.ReferenceObject.Equals((object)_)).ToList(); var actuals2 = scenario.ObjectsThatAreNotOfTheSameTypeAsReferenceObject.Select(_ => scenario.ReferenceObject.Equals((object)_)).ToList(); // Assert actuals1.AsTest().Must().Each().BeFalse(because: scenario.Id); actuals2.AsTest().Must().Each().BeFalse(because: scenario.Id); } } [Fact] [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")] [SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")] [SuppressMessage("Microsoft.Naming", "CA1715:IdentifiersShouldHaveCorrectPrefix")] [SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords")] [SuppressMessage("Microsoft.Naming", "CA1719:ParameterNamesShouldNotMatchMemberNames")] [SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames")] [SuppressMessage("Microsoft.Naming", "CA1722:IdentifiersShouldNotHaveIncorrectPrefix")] [SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration")] [SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms")] [SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly")] public static void Equals_with_Object___Should_return_true___When_parameter_other_is_same_object() { var scenarios = EquatableTestScenarios.ValidateAndPrepareForTesting(); foreach (var scenario in scenarios) { // Arrange, Act var actual = scenario.ReferenceObject.Equals((object)scenario.ReferenceObject); // Assert actual.AsTest().Must().BeTrue(because: scenario.Id); } } [Fact] [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")] [SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")] [SuppressMessage("Microsoft.Naming", "CA1715:IdentifiersShouldHaveCorrectPrefix")] [SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords")] [SuppressMessage("Microsoft.Naming", "CA1719:ParameterNamesShouldNotMatchMemberNames")] [SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames")] [SuppressMessage("Microsoft.Naming", "CA1722:IdentifiersShouldNotHaveIncorrectPrefix")] [SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration")] [SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms")] [SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly")] public static void Equals_with_Object___Should_return_false___When_objects_being_compared_have_different_property_values() { var scenarios = EquatableTestScenarios.ValidateAndPrepareForTesting(); foreach (var scenario in scenarios) { // Arrange, Act var actuals = scenario.ObjectsThatAreNotEqualToReferenceObject.Select(_ => scenario.ReferenceObject.Equals((object)_)).ToList(); // Assert actuals.AsTest().Must().Each().BeFalse(because: scenario.Id); } } [Fact] [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")] [SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")] [SuppressMessage("Microsoft.Naming", "CA1715:IdentifiersShouldHaveCorrectPrefix")] [SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords")] [SuppressMessage("Microsoft.Naming", "CA1719:ParameterNamesShouldNotMatchMemberNames")] [SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames")] [SuppressMessage("Microsoft.Naming", "CA1722:IdentifiersShouldNotHaveIncorrectPrefix")] [SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration")] [SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms")] [SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly")] public static void Equals_with_Object___Should_return_true___When_objects_being_compared_have_same_property_values() { var scenarios = EquatableTestScenarios.ValidateAndPrepareForTesting(); foreach (var scenario in scenarios) { // Arrange, Act var actuals = scenario.ObjectsThatAreEqualToButNotTheSameAsReferenceObject.Select(_ => scenario.ReferenceObject.Equals((object)_)).ToList(); // Assert actuals.AsTest().Must().Each().BeTrue(because: scenario.Id); } } } [SuppressMessage("Microsoft.Design", "CA1034:NestedTypesShouldNotBeVisible")] [SuppressMessage("Microsoft.Naming", "CA1724:TypeNamesShouldNotMatchNamespaces")] public static class Hashing { [Fact] [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")] [SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")] [SuppressMessage("Microsoft.Naming", "CA1715:IdentifiersShouldHaveCorrectPrefix")] [SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords")] [SuppressMessage("Microsoft.Naming", "CA1719:ParameterNamesShouldNotMatchMemberNames")] [SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames")] [SuppressMessage("Microsoft.Naming", "CA1722:IdentifiersShouldNotHaveIncorrectPrefix")] [SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration")] [SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms")] [SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly")] public static void GetHashCode___Should_not_be_equal_for_two_objects___When_objects_have_different_property_values() { var scenarios = EquatableTestScenarios.ValidateAndPrepareForTesting(); foreach (var scenario in scenarios) { // Arrange, Act var unexpected = scenario.ReferenceObject.GetHashCode(); var actuals = scenario.ObjectsThatAreNotEqualToReferenceObject.Select(_ => _.GetHashCode()).ToList(); // Assert actuals.AsTest().Must().NotContainElement(unexpected, because: scenario.Id); } } [Fact] [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly")] [SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")] [SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")] [SuppressMessage("Microsoft.Naming", "CA1715:IdentifiersShouldHaveCorrectPrefix")] [SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords")] [SuppressMessage("Microsoft.Naming", "CA1719:ParameterNamesShouldNotMatchMemberNames")] [SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames")] [SuppressMessage("Microsoft.Naming", "CA1722:IdentifiersShouldNotHaveIncorrectPrefix")] [SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration")] [SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms")] [SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly")] public static void GetHashCode___Should_be_equal_for_two_objects___When_objects_have_the_same_property_values() { var scenarios = EquatableTestScenarios.ValidateAndPrepareForTesting(); foreach (var scenario in scenarios) { // Arrange, Act var expected = scenario.ReferenceObject.GetHashCode(); var actuals = scenario.ObjectsThatAreEqualToButNotTheSameAsReferenceObject.Select(_ => _.GetHashCode()).ToList(); // Assert actuals.AsTest().Must().Each().BeEqualTo(expected, because: scenario.Id); } } } } }
65.580403
295
0.661185
[ "MIT" ]
NaosFramework/Naos.Database
Naos.Database.Domain.Test/Operations/Classes/Stream/Standard/Management/StandardCreateStreamOpTest.designer.cs
113,784
C#
public interface IEmployee { string Name { get; } int WorkHoursPerWeek { get; } }
18
33
0.655556
[ "MIT" ]
sevdalin/Software-University-SoftUni
C-sharp-Web-Developer/C# OOP Advanced/08. Obj Communic and Events/04. WorkForce/Interfaces/IEmployee.cs
92
C#
using System.Collections.Generic; using System.IO; using System.Runtime.Serialization; using WolvenKit.CR2W.Reflection; using static WolvenKit.CR2W.Types.Enums; using FastMember; namespace WolvenKit.CR2W.Types { [REDMeta(EREDMetaInfo.REDStruct)] public class SMaterialGraphParameter : CVariable { [Ordinal(0)] [RED] public CUInt8 Type { get; set; } [Ordinal(1)] [RED] public CUInt8 Offset { get; set; } [Ordinal(2)] [RED] public CName Name { get; set; } public SMaterialGraphParameter(CR2WFile cr2w, CVariable parent, string name) : base(cr2w, parent, name) { } public static CVariable Create(CR2WFile cr2w, CVariable parent, string name) { return new SMaterialGraphParameter(cr2w, parent, name); } public override string ToString() { return ""; } } }
28.4375
116
0.632967
[ "MIT" ]
DerinHalil/CP77Tools
CP77.CR2W/Types/BufferedTypes/BufferStructs/SMaterialGraphParameter.cs
881
C#
namespace GitPulseAnalytics.Models { /// <summary> /// GitHub user account. /// </summary> public class GitHubUser { public long Id { get; set; } public string Login { get; set; } public string Url { get; set; } public string Type { get; set; } } }
20.230769
35
0.638783
[ "MIT" ]
quanyincoder/GitPulseAnalytics
GitPulseAnalytics/Models/GitHubUser.cs
265
C#
// <auto-generated> // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. // </auto-generated> namespace CRM.Interface.Models { using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.Linq; /// <summary> /// Microsoft.Dynamics.CRM.businessunitnewsarticle /// </summary> public partial class MicrosoftDynamicsCRMbusinessunitnewsarticle { /// <summary> /// Initializes a new instance of the /// MicrosoftDynamicsCRMbusinessunitnewsarticle class. /// </summary> public MicrosoftDynamicsCRMbusinessunitnewsarticle() { CustomInit(); } /// <summary> /// Initializes a new instance of the /// MicrosoftDynamicsCRMbusinessunitnewsarticle class. /// </summary> public MicrosoftDynamicsCRMbusinessunitnewsarticle(string newsarticle = default(string), string businessunitnewsarticleid = default(string), string _createdbyValue = default(string), bool? showonhomepage = default(bool?), string _modifiedbyValue = default(string), System.DateTimeOffset? createdon = default(System.DateTimeOffset?), int? timezoneruleversionnumber = default(int?), string _organizationidValue = default(string), string _createdonbehalfbyValue = default(string), string versionnumber = default(string), System.DateTimeOffset? activeuntil = default(System.DateTimeOffset?), int? importsequencenumber = default(int?), int? articletypecode = default(int?), System.DateTimeOffset? overriddencreatedon = default(System.DateTimeOffset?), int? utcconversiontimezonecode = default(int?), string articletitle = default(string), System.DateTimeOffset? modifiedon = default(System.DateTimeOffset?), System.DateTimeOffset? activeon = default(System.DateTimeOffset?), string articleurl = default(string), string _modifiedonbehalfbyValue = default(string), IList<MicrosoftDynamicsCRMbulkdeletefailure> businessUnitNewsArticleBulkDeleteFailures = default(IList<MicrosoftDynamicsCRMbulkdeletefailure>), MicrosoftDynamicsCRMsystemuser createdby = default(MicrosoftDynamicsCRMsystemuser), MicrosoftDynamicsCRMsystemuser modifiedby = default(MicrosoftDynamicsCRMsystemuser), MicrosoftDynamicsCRMorganization organizationid = default(MicrosoftDynamicsCRMorganization), IList<MicrosoftDynamicsCRMasyncoperation> businessUnitNewsArticleAsyncOperations = default(IList<MicrosoftDynamicsCRMasyncoperation>), IList<MicrosoftDynamicsCRMprocesssession> businessUnitNewsArticleProcessSessions = default(IList<MicrosoftDynamicsCRMprocesssession>), MicrosoftDynamicsCRMsystemuser modifiedonbehalfby = default(MicrosoftDynamicsCRMsystemuser), MicrosoftDynamicsCRMsystemuser createdonbehalfby = default(MicrosoftDynamicsCRMsystemuser)) { Newsarticle = newsarticle; Businessunitnewsarticleid = businessunitnewsarticleid; this._createdbyValue = _createdbyValue; Showonhomepage = showonhomepage; this._modifiedbyValue = _modifiedbyValue; Createdon = createdon; Timezoneruleversionnumber = timezoneruleversionnumber; this._organizationidValue = _organizationidValue; this._createdonbehalfbyValue = _createdonbehalfbyValue; Versionnumber = versionnumber; Activeuntil = activeuntil; Importsequencenumber = importsequencenumber; Articletypecode = articletypecode; Overriddencreatedon = overriddencreatedon; Utcconversiontimezonecode = utcconversiontimezonecode; Articletitle = articletitle; Modifiedon = modifiedon; Activeon = activeon; Articleurl = articleurl; this._modifiedonbehalfbyValue = _modifiedonbehalfbyValue; BusinessUnitNewsArticleBulkDeleteFailures = businessUnitNewsArticleBulkDeleteFailures; Createdby = createdby; Modifiedby = modifiedby; Organizationid = organizationid; BusinessUnitNewsArticleAsyncOperations = businessUnitNewsArticleAsyncOperations; BusinessUnitNewsArticleProcessSessions = businessUnitNewsArticleProcessSessions; Modifiedonbehalfby = modifiedonbehalfby; Createdonbehalfby = createdonbehalfby; CustomInit(); } /// <summary> /// An initialization method that performs custom operations like setting defaults /// </summary> partial void CustomInit(); /// <summary> /// </summary> [JsonProperty(PropertyName = "newsarticle")] public string Newsarticle { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "businessunitnewsarticleid")] public string Businessunitnewsarticleid { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "_createdby_value")] public string _createdbyValue { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "showonhomepage")] public bool? Showonhomepage { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "_modifiedby_value")] public string _modifiedbyValue { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "createdon")] public System.DateTimeOffset? Createdon { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "timezoneruleversionnumber")] public int? Timezoneruleversionnumber { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "_organizationid_value")] public string _organizationidValue { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "_createdonbehalfby_value")] public string _createdonbehalfbyValue { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "versionnumber")] public string Versionnumber { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "activeuntil")] public System.DateTimeOffset? Activeuntil { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "importsequencenumber")] public int? Importsequencenumber { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "articletypecode")] public int? Articletypecode { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "overriddencreatedon")] public System.DateTimeOffset? Overriddencreatedon { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "utcconversiontimezonecode")] public int? Utcconversiontimezonecode { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "articletitle")] public string Articletitle { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "modifiedon")] public System.DateTimeOffset? Modifiedon { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "activeon")] public System.DateTimeOffset? Activeon { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "articleurl")] public string Articleurl { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "_modifiedonbehalfby_value")] public string _modifiedonbehalfbyValue { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "BusinessUnitNewsArticle_BulkDeleteFailures")] public IList<MicrosoftDynamicsCRMbulkdeletefailure> BusinessUnitNewsArticleBulkDeleteFailures { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "createdby")] public MicrosoftDynamicsCRMsystemuser Createdby { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "modifiedby")] public MicrosoftDynamicsCRMsystemuser Modifiedby { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "organizationid")] public MicrosoftDynamicsCRMorganization Organizationid { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "BusinessUnitNewsArticle_AsyncOperations")] public IList<MicrosoftDynamicsCRMasyncoperation> BusinessUnitNewsArticleAsyncOperations { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "BusinessUnitNewsArticle_ProcessSessions")] public IList<MicrosoftDynamicsCRMprocesssession> BusinessUnitNewsArticleProcessSessions { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "modifiedonbehalfby")] public MicrosoftDynamicsCRMsystemuser Modifiedonbehalfby { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "createdonbehalfby")] public MicrosoftDynamicsCRMsystemuser Createdonbehalfby { get; set; } } }
44.476415
1,926
0.666985
[ "MIT" ]
msehudi/cms-accelerator
OData.OpenAPI/odata2openapi/Client/Models/MicrosoftDynamicsCRMbusinessunitnewsarticle.cs
9,429
C#