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 CalculatorShell.Expressions.Properties; using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CalculatorShell.Expressions.Internals.Expressions { internal sealed class Variable : IExpression { public IVariables? Variables { get; } public string Name { get; } public string PropertyName { get; } private readonly string _identifier; public Variable(string identifier, IVariables variables) { _identifier = identifier; Variables = variables; if (identifier.Contains('[') && identifier.Contains(']')) { var parts = identifier.Split(new char[] { '[', ']' }, StringSplitOptions.RemoveEmptyEntries); if (parts.Length != 2) throw new ExpressionEngineException(Resources.InvalidToken); Name = parts[0]; PropertyName = parts[1]; } else { Name = identifier.ToLower(); PropertyName = string.Empty; } } public IExpression Differentiate(string byVariable) { if (byVariable == _identifier) { // f(x) = x // d( f(x) ) = 1 * d( x ) // d( x ) = 1 // f'(x) = 1 return new Constant(new NumberImplementation(1.0d)); } // f(x) = c // d( f(x) ) = c * d( c ) // d( c ) = 0 // f'(x) = 0 return new Constant(new NumberImplementation(0.0d)); } public INumber Evaluate() { if (Variables == null) throw new ExpressionEngineException(Resources.NoVariableValues); if (!string.IsNullOrEmpty(PropertyName)) { return Variables[Name, PropertyName]; } return Variables[Name]; } public IExpression Simplify() { if (Variables == null) throw new ExpressionEngineException(Resources.NoVariableValues); if (Variables.IsConstant(Name) && string.IsNullOrEmpty(PropertyName)) { return new Constant((NumberImplementation)Variables[Name]); } return new Variable(_identifier, Variables); } public string ToString(IFormatProvider formatProvider) { return Name.ToString(formatProvider); } public override string ToString() { return ToString(CultureInfo.InvariantCulture); } } }
28.833333
109
0.523121
[ "MIT" ]
webmaster442/CalculatorShell
CalculatorShell.Expressions/Internals/Expressions/Variable.cs
2,770
C#
using NUnit.Framework; /// <summary> /// A collection of unit tests for the DisjointSet class. /// </summary> public class DisjointSetTest { #region Find Tests [Test] public void Find_ParentOfXisX_ReturnsX() { CellGrid grid = new CellGrid(2, 2); Cell subject = grid.Cells[0]; DisjointSet dSet = new DisjointSet(grid.Cells); // When a DisjointSet is initialized, each element of the passed list is // its own parent. Assert.AreEqual(subject, dSet.Find(subject)); } [Test] public void Find_ParentOfXisY_ReturnsY() { CellGrid grid = new CellGrid(2, 2); Cell subjectX = grid.Cells[0]; Cell subjectY = grid.Cells[1]; DisjointSet dSet = new DisjointSet(grid.Cells); dSet.Union(subjectY, subjectX); Assert.AreEqual(subjectY, dSet.Find(subjectX)); } #endregion #region Union Tests [Test] public void Union_ParentOfXisXBeforeAndYAfter_ReturnsXBeforeAndYAfter() { CellGrid grid = new CellGrid(2, 2); Cell subjectX = grid.Cells[0]; Cell subjectY = grid.Cells[1]; DisjointSet dSet = new DisjointSet(grid.Cells); // When a DisjointSet is initialized, each element of the passed list is // its own parent. Assert.AreEqual(subjectX, dSet.Find(subjectX)); dSet.Union(subjectY, subjectX); Assert.AreEqual(subjectY, dSet.Find(subjectX)); } #endregion }
30.020408
80
0.638341
[ "MIT" ]
blyman94/maze-pathfinding-game
PrototypeApplicationProject/Assets/Scripts/Editor/DisjointSetTest.cs
1,471
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 ec2-2016-11-15.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.EC2.Model { /// <summary> /// This is the response object from the ImportInstance operation. /// </summary> public partial class ImportInstanceResponse : AmazonWebServiceResponse { private ConversionTask _conversionTask; /// <summary> /// Gets and sets the property ConversionTask. /// <para> /// Information about the conversion task. /// </para> /// </summary> public ConversionTask ConversionTask { get { return this._conversionTask; } set { this._conversionTask = value; } } // Check to see if ConversionTask property is set internal bool IsSetConversionTask() { return this._conversionTask != null; } } }
29.631579
101
0.668443
[ "Apache-2.0" ]
DetlefGolze/aws-sdk-net
sdk/src/Services/EC2/Generated/Model/ImportInstanceResponse.cs
1,689
C#
using System; namespace Application.Orders.Projections { public class OrderProjection { public Guid OrderId { get; set; } public decimal Value { get; set; } } }
18.9
42
0.640212
[ "MIT" ]
marcinlovescode/CQRS.SingleDatabase
Application/Orders/Projections/Order.cs
189
C#
// This file was generated by TemplateEngine from template source 'Quad' // using template 'Quad2d. Do not modify this file directly, modify it from template source. // This file constitutes a part of the SharpMedia project, (c) 2007 by the SharpMedia team // and is licensed for your use under the conditions of the NDA or other legally binding contract // that you or a legal entity you represent has signed with the SharpMedia team. // In an event that you have received or obtained this file without such legally binding contract // in place, you MUST destroy all files and other content to which this lincese applies and // contact the SharpMedia team for further instructions at the internet mail address: // // legal@sharpmedia.com // using System; using System.Collections.Generic; using System.Text; using SharpMedia.Testing; using SharpMedia.Math.Shapes.Volumes; namespace SharpMedia.Math.Shapes { /// <summary> /// A quad in 2D space. /// </summary> [Serializable] public class Quad2d : IArea2d, IOutline2d, IControlPoints2d, IContainsPoint2d, ITransformable2d, IEquatable<Quad2d>, IComparable<Quad2d>, IEnumerable<Vector2d>, ICloneable<Quad2d> { #region Public Members /// <summary> /// The first control point. /// </summary> public Vector2d A; /// <summary> /// The second control point. /// </summary> public Vector2d B; /// <summary> /// The third control point. /// </summary> public Vector2d C; /// <summary> /// The forth control point. /// </summary> public Vector2d D; #endregion #region Constructors /// <summary> /// Empty constructor. /// </summary> public Quad2d() { } /// <summary> /// Constructor with all four points. /// </summary> /// <param name="p0">The first point.</param> /// <param name="p1">The second point.</param> /// <param name="p2">The third point.</param> /// <param name="p3">The forth point.</param> public Quad2d(Vector2d p0, Vector2d p1, Vector2d p2, Vector2d p3) { A = p0; B = p1; C = p2; D = p3; } #endregion #region Properties /// <summary> /// The alpha, angle at A. /// </summary> public double Alpha { get { Vector2d v1 = B - A; Vector2d v2 = D - A; return MathHelper.ACos((v1 * v2) / (v1.Length * v2.Length)); } } /// <summary> /// Alpha in degrees. /// </summary> public double AlphaDegrees { get { return MathHelper.ToDegrees(Alpha); } } /// <summary> /// Beta angle, angle at B. /// </summary> public double Beta { get { Vector2d v1 = A - B; Vector2d v2 = C - B; return MathHelper.ACos((v1 * v2) / (v1.Length * v2.Length)); } } /// <summary> /// Beta angle in degrees. /// </summary> public double BetaDegrees { get { return MathHelper.ToDegrees(Beta); } } /// <summary> /// Gamma angle, angle at C. /// </summary> public double Gamma { get { Vector2d v1 = B - C; Vector2d v2 = D - C; return MathHelper.ACos((v1 * v2) / (v1.Length * v2.Length)); } } /// <summary> /// Gamma angle in degrees. /// </summary> public double GammaDegrees { get { return MathHelper.ToDegrees(Gamma); } } /// <summary> /// Delta angle, the angle at D. /// </summary> public double Delta { get { Vector2d v1 = A - D; Vector2d v2 = C - D; return MathHelper.ACos((v1 * v2) / (v1.Length * v2.Length)); } } /// <summary> /// Delta angle in degrees. /// </summary> public double DeltaDegrees { get { return MathHelper.ToDegrees(Delta); } } /// <summary> /// The side a, between vertices A and B. /// </summary> public double SideA { get { return (B - A).Length; } } /// <summary> /// The side a, between vertices C and B. /// </summary> public double SideB { get { return (B - C).Length; } } /// <summary> /// The side a, between vertices C and D. /// </summary> public double SideC { get { return (D - C).Length; } } /// <summary> /// The side a, between vertices A and D. /// </summary> public double SideD { get { return (D - A).Length; } } /// <summary> /// The center of quad. /// </summary> public Vector2d Center { get { return (A + B + C + D) / (double)4.0; } } /// <summary> /// Is the quad square. /// </summary> public bool IsSquare { get { if (!IsRectangle) return false; // We check that all sides are the same length. return MathHelper.NearEqual((D - A).Length2, (B - A).Length2); } } /// <summary> /// Is the shape a rectangle. /// </summary> public bool IsRectangle { get { // We require all angles to be 90 degress. if (!MathHelper.NearEqual((B - A) * (D - A), 0.0)) return false; if (!MathHelper.NearEqual((A - B) * (C - B), 0.0)) return false; if (!MathHelper.NearEqual((D - C) * (B - C), 0.0)) return false; // The other is automatically. return true; } } #endregion #region Overrides public override string ToString() { StringBuilder builder = new StringBuilder(100); builder.Append("Quad : {"); builder.Append(A.ToString()); builder.Append(", "); builder.Append(B.ToString()); builder.Append(", "); builder.Append(C.ToString()); builder.Append(", "); builder.Append(D.ToString()); builder.Append("}"); return builder.ToString(); } public override bool Equals(object obj) { if (obj is Quad2d) return this.Equals((Quad2d)obj); return false; } public override int GetHashCode() { return base.GetHashCode(); } #endregion #region Public Members /// <summary> /// Always prefer this split over the tesellation because it is faster and there is /// no need to allocate collection. This only works for quads/rectanges. /// </summary> /// <param name="t1">The first triangle.</param> /// <param name="t2">The second triangle.</param> public void Split(out Triangle2d t1, out Triangle2d t2) { t1 = new Triangle2d(A, B, C); t2 = new Triangle2d(A, C, D); } #endregion #region IArea2d Members public double Area { get { // We sum two triangles. return (double)0.5 * (A.X * (B.Y - C.Y) + B.X * (C.Y - A.Y) + C.X * (A.Y - B.Y)) + (double)0.5 * (A.X * (C.Y - D.Y) + C.X * (D.Y - A.Y) + D.X * (A.Y - C.Y)); } } public void Tesselate(double resolution, Storage.Builders.ITriangleBuilder2d builder) { if (resolution < 0.0 || (resolution > SideA && resolution > SideB && resolution > SideC && resolution > SideD)) { if (builder.IsIndexed) { // We simply append vertices and proceed. uint indexBase = builder.AddControlPoints(A, B, C, D); // Add vertices if indexed builder.AddIndexedTriangles( new uint[] { indexBase, indexBase + 1, indexBase + 2, indexBase, indexBase + 2, indexBase + 3 } ); } else { // We need to pust 2 triangles. builder.AddControlPoints(A, B, C, A, C, D); } } else { throw new NotImplementedException(); } } #endregion #region IOutline2d Members public Vector2d Sample(double t) { if (t >= (double)0.0 && t <= (1.0 / (double).25)) { double inter = (double)4 * t; return A * (1.0 - inter) + B * inter; } else if (t <= ((double)2 / (double)4)) { double inter = (double)4 * t - 1.0; return B * (1.0 - inter) + C * inter; } else if (t <= ((double)3 / (double)4)) { double inter = (double)4 * t - (double)2; return C * (1.0 - inter) + D * inter; } else { double inter = (double)4 * t - (double)3; return D * (1.0 - inter) + A * inter; } } public void Sample(double resolution, Storage.Builders.ILineBuilder2d builder) { if (resolution < 0.0) { builder.AddLineStrip(true, A, B, C, D); } else { throw new NotImplementedException(); } } #endregion #region IOutlined Members public double OutlineLength { get { return SideA + SideB + SideC + SideD; } } #endregion #region IControlPoints2d Members public Vector2d[] ControlPoints { get { return new Vector2d[] { A, B, C, D }; } set { if (value.Length != 4) throw new ArgumentException("Three control points expected."); A = value[0]; B = value[1]; C = value[2]; D = value[3]; } } public void SetControlPoints(uint index, Vector2d cp) { switch (index) { case 0: A = cp; break; case 1: B = cp; break; case 2: C = cp; break; case 3: D = cp; break; default: throw new ArgumentException("Index out of range, must be 0-3 for quad."); } } public Vector2d GetControlPoint(uint index) { switch (index) { case 0: return A; case 1: return B; case 2: return C; case 3: return D; default: throw new ArgumentException("Index out of range, must be 0-3 for quad."); } } #endregion #region IControlPointsd Members public uint ControlPointCount { get { return 4; } } #endregion #region IContainsPoint2d Members public bool ContainsPoint(Vector2d point) { throw new Exception("The method or operation is not implemented."); } #endregion #region ITransformable2d public void Transform(Matrix.Matrix3x3d matrix) { A = matrix * A; B = matrix * B; C = matrix * C; D = matrix * D; } #endregion #region IEquatable<Quad2d> Members public bool Equals(Quad2d other) { return Vector2d.NearEqual(A, other.A) && Vector2d.NearEqual(B, other.B) && Vector2d.NearEqual(C, other.C) && Vector2d.NearEqual(D, other.D); } #endregion #region IEnumerable<Vector2d> Members public IEnumerator<Vector2d> GetEnumerator() { yield return A; yield return B; yield return C; yield return D; } #endregion #region IEnumerable Members System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { yield return A; yield return B; yield return C; yield return D; } #endregion #region ICloneable<Quad2d> Members public Quad2d Clone() { return new Quad2d(A, B, C, D); } #endregion #region IComparable<Triangled> Members public int CompareTo(Quad2d other) { double a1 = Area, a2 = other.Area; if (a1 < a2) return -1; else if (a1 == a2) return 0; return 1; } #endregion } #if SHARPMEDIA_TESTSUITE [TestSuite] internal class Quad2d_Test { /* [CorrectnessTest] public void Construction() { Quad2d q = new Quad2d(new Vector2d(0, 0, 0), new Vector2d(1, 0, 0), new Vector2d(1, 1, 0), new Vector2d(0, 1, 0)); Assert.AreEqual(q.A, new Vector2d(0, 0, 0)); Assert.AreEqual(q.B, new Vector2d(1, 0, 0)); Assert.AreEqual(q.C, new Vector2d(1, 1, 0)); Assert.AreEqual(q.D, new Vector2d(0, 1, 0)); Assert.AreEqual(q.AlphaDegrees, 90.0); } [CorrectnessTest] public void Intersection() { } [CorrectnessTest] public void Tesselation() { }*/ } #endif }
25.370184
103
0.441569
[ "Apache-2.0" ]
zigaosolin/SharpMedia
SharpMedia/Math/Shapes/Quad2d.cs
15,146
C#
using System.IO; using System.Runtime.Serialization; using WolvenKit.CR2W.Reflection; using FastMember; using static WolvenKit.CR2W.Types.Enums; namespace WolvenKit.CR2W.Types { [DataContract(Namespace = "")] [REDMeta] public class CSpawnTreeCurrentlySpawnedCounterMonitorInitializer : ISpawnTreeSpawnMonitorInitializer { public CSpawnTreeCurrentlySpawnedCounterMonitorInitializer(CR2WFile cr2w, CVariable parent, string name) : base(cr2w, parent, name){ } public static new CVariable Create(CR2WFile cr2w, CVariable parent, string name) => new CSpawnTreeCurrentlySpawnedCounterMonitorInitializer(cr2w, parent, name); public override void Read(BinaryReader file, uint size) => base.Read(file, size); public override void Write(BinaryWriter file) => base.Write(file); } }
35.26087
163
0.779285
[ "MIT" ]
DerinHalil/CP77Tools
CP77.CR2W/Types/W3/RTTIConvert/CSpawnTreeCurrentlySpawnedCounterMonitorInitializer.cs
789
C#
using System.Collections.Generic; namespace Bev.IO.NmmReader.scan_mode { /// <summary> /// A convienient container for some methods used to evaluate NMM scan files. /// </summary> public static class Scan { #region Public methods /// <summary> /// Interpretes the provided data mask for the number of columns in the data file. /// </summary> /// <param name="dataMask">The data mask.</param> /// <returns>The expected number of columns in the data file.</returns> public static int NumberOfColumnsFor(long dataMask) { return ColumnPredicatesFor(dataMask).Length; } /// <summary> /// Interpretes the provided data mask for short and long titles of columns in the data file. /// </summary> /// <param name="dataMask">The data mask.</param> /// <returns>The array of <c>ScanColumnPredicate</c>.</returns> public static ScanColumnPredicate[] ColumnPredicatesFor(long dataMask) { // create a list of the predicates List<ScanColumnPredicate> columnsPredicates = new List<ScanColumnPredicate>(); // some bools to implement logic not inside the data mask bool columnLX = false; bool columnLY = false; bool columnLZ = false; bool columnAZ = false; // split the data mask // the order of the if cases is essential! // The data files columnes are (hopefully) in the same order. if ((dataMask & 0x1) != 0) { columnsPredicates.Add(new ScanColumnPredicate("LX", "X length", "m")); columnLX = true; } if ((dataMask & 0x2) != 0) { columnsPredicates.Add(new ScanColumnPredicate("LY", "Y length", "m")); columnLY = true; } if ((dataMask & 0x4) != 0) { columnsPredicates.Add(new ScanColumnPredicate("LZ", "Z length", "m")); columnLZ = true; } if ((dataMask & 0x8) != 0) columnsPredicates.Add(new ScanColumnPredicate("WX", "X angle", "n")); if ((dataMask & 0x10) != 0) columnsPredicates.Add(new ScanColumnPredicate("WY", "Y angle", "n")); if ((dataMask & 0x20) != 0) columnsPredicates.Add(new ScanColumnPredicate("WZ", "Z angle", "n")); if ((dataMask & 0x40) != 0) columnsPredicates.Add(new ScanColumnPredicate("AX", "Auxiliary input 1", "n")); if ((dataMask & 0x80) != 0) { // The *.dsc file sometimes masks the AY channel // columnsPredicates.Add(new ScanColumnPredicate("AY", "Auxiliary input 2", "n")); } if ((dataMask & 0x100) != 0) { columnsPredicates.Add(new ScanColumnPredicate("AZ", "Probe values", "m")); columnAZ = true; } if ((dataMask & 0x200) != 0) columnsPredicates.Add(new ScanColumnPredicate("TX", "Air temperature X", "oC")); if ((dataMask & 0x400) != 0) columnsPredicates.Add(new ScanColumnPredicate("TY", "Air temperature Y", "oC")); if ((dataMask & 0x800) != 0) columnsPredicates.Add(new ScanColumnPredicate("TZ", "Air temperature Z", "oC")); if ((dataMask & 0x1000) != 0) columnsPredicates.Add(new ScanColumnPredicate("LD", "Air pressure", "Pa")); if ((dataMask & 0x2000) != 0) columnsPredicates.Add(new ScanColumnPredicate("LF", "Relative humidity", "%")); if ((dataMask & 0x4000) != 0) columnsPredicates.Add(new ScanColumnPredicate("?0", "??? 0", "n")); if ((dataMask & 0x8000) != 0) columnsPredicates.Add(new ScanColumnPredicate("?1", "??? 1", "n")); if ((dataMask & 0x10000) != 0) columnsPredicates.Add(new ScanColumnPredicate("?2", "??? 2", "n")); if ((dataMask & 0x20000) != 0) columnsPredicates.Add(new ScanColumnPredicate("F0", "Interferometer signal XS", "n")); if ((dataMask & 0x40000) != 0) columnsPredicates.Add(new ScanColumnPredicate("F1", "Interferometer signal XC", "n")); if ((dataMask & 0x80000) != 0) columnsPredicates.Add(new ScanColumnPredicate("F2", "Interferometer signal YS", "n")); if ((dataMask & 0x100000) != 0) columnsPredicates.Add(new ScanColumnPredicate("F3", "Interferometer signal YC", "n")); if ((dataMask & 0x200000) != 0) columnsPredicates.Add(new ScanColumnPredicate("F4", "Interferometer signal ZS", "n")); if ((dataMask & 0x400000) != 0) columnsPredicates.Add(new ScanColumnPredicate("F5", "Interferometer signal ZC", "n")); if ((dataMask & 0x800000) != 0) columnsPredicates.Add(new ScanColumnPredicate("AZ0", "Probe input 1", "n")); if ((dataMask & 0x1000000) != 0) columnsPredicates.Add(new ScanColumnPredicate("AZ1", "Probe input 2", "n")); // the following columns are not mapped by the data mask // but anyway present in the *.dat file if (columnLZ && columnAZ) columnsPredicates.Add(new ScanColumnPredicate("-LZ+AZ", "Surface height", "m")); if (columnLX && columnLY) columnsPredicates.Add(new ScanColumnPredicate("XYvec", "XY motion vector", "m")); // return as array return columnsPredicates.ToArray(); } #endregion } }
48.92437
102
0.543971
[ "MIT" ]
matusm/Bev.IO.NmmReader
Bev.IO.NmmReader/scan_mode/Scan.cs
5,824
C#
using Protogame; [Asset("ai.Test")] public class TestAI : AIAsset { public override void Update(IEntity entity, IGameContext gameContext, IUpdateContext updateContext) { } public override void Render(IEntity entity, IGameContext gameContext, IRenderContext renderContext) { } public override void Update(IServerEntity entity, IServerContext serverContext, IUpdateContext updateContext) { } }
25.294118
113
0.744186
[ "Unlicense", "MIT" ]
RedpointGames/Protogame
Protogame.Docs/core_arch/snippet/ai_logic.cs
430
C#
using System.IO; using System.Net.Security; using System.Threading.Tasks; namespace WinWeelay.Core { /// <summary> /// Secure TCP connection with SSL. /// </summary> public class SslRelayTransport : TcpRelayTransport { /// <summary> /// Initialize the network stream and vrify the SSL connection. /// </summary> /// <returns>Async task.</returns> protected override async Task InitializeStream() { _networkStream = new SslStream(_tcpClient.GetStream()); SslStream sslStream = _networkStream as SslStream; await Task.WhenAny(sslStream.AuthenticateAsClientAsync(_configuration.Hostname), Task.Delay(5000)); if (!sslStream.IsAuthenticated) throw new IOException("SSL authentication timed out."); } } }
31.333333
111
0.637116
[ "MIT" ]
Heufneutje/WinWeeRelay
WinWeelay.Core/Transport/SslRelayTransport.cs
848
C#
namespace ClearHl7.Codes.V290 { /// <summary> /// HL7 Version 2 Table 0653 - Date Format. /// </summary> /// <remarks>https://www.hl7.org/fhir/v2/0653</remarks> public enum CodeDateFormat { /// <summary> /// 1 - mm/dd/yy. /// </summary> MmDdYyWithSlashes, /// <summary> /// 2 - yy.mm.dd. /// </summary> YyMmDdWithPeriods, /// <summary> /// 3 - dd/mm/yy. /// </summary> DdMmYyWithSlashes, /// <summary> /// 4 - dd.mm.yy. /// </summary> DdMmYyWithPeriods, /// <summary> /// 5 - yy/mm/dd. /// </summary> YyMmDdWithSlashes, /// <summary> /// 6 - Yymmdd. /// </summary> Yymmdd } }
22.538462
60
0.397042
[ "MIT" ]
davebronson/clear-hl7-net
src/ClearHl7.Codes/V290/CodeDateFormat.cs
881
C#
// Generated class v2.19.0.0, don't modify using System; using System.Collections.Generic; using System.Collections.Specialized; using System.Linq; using System.Text; namespace NHtmlUnit.Javascript.Host.Svg { public partial class SVGGElement : NHtmlUnit.Javascript.Host.Svg.SVGGraphicsElement { static SVGGElement() { ObjectWrapper.RegisterWrapperCreator((com.gargoylesoftware.htmlunit.javascript.host.svg.SVGGElement o) => new SVGGElement(o)); } public SVGGElement(com.gargoylesoftware.htmlunit.javascript.host.svg.SVGGElement wrappedObject) : base(wrappedObject) {} public new com.gargoylesoftware.htmlunit.javascript.host.svg.SVGGElement WObj { get { return (com.gargoylesoftware.htmlunit.javascript.host.svg.SVGGElement)WrappedObject; } } public SVGGElement() : this(new com.gargoylesoftware.htmlunit.javascript.host.svg.SVGGElement()) {} } }
29.787879
127
0.701933
[ "Apache-2.0" ]
JonAnders/NHtmlUnit
app/NHtmlUnit/Generated/Javascript/Host/Svg/SVGGElement.cs
983
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.Azure.Management.Automation.Models; namespace Microsoft.Azure.Management.Automation { /// <summary> /// Service operation for node reports. (see /// http://aka.ms/azureautomationsdk/dscnodereportoperations for more /// information) /// </summary> public partial interface IDscNodeReportsOperations { /// <summary> /// Retrieve the Dsc node report data by node id and report id. (see /// http://aka.ms/azureautomationsdk/dscnodereportoperations for more /// information) /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group /// </param> /// <param name='automationAccount'> /// The automation account name. /// </param> /// <param name='nodeId'> /// The Dsc node id. /// </param> /// <param name='reportId'> /// The report id. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response model for the get dsc node report operation. /// </returns> Task<DscNodeReportGetResponse> GetAsync(string resourceGroupName, string automationAccount, Guid nodeId, Guid reportId, CancellationToken cancellationToken); /// <summary> /// Retrieve the Dsc node reports by node id and report id. (see /// http://aka.ms/azureautomationsdk/dscnodereportoperations for more /// information) /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group /// </param> /// <param name='automationAccount'> /// The automation account name. /// </param> /// <param name='nodeId'> /// The Dsc node id. /// </param> /// <param name='reportId'> /// The report id. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response model for the get node report content operation. /// </returns> Task<DscNodeReportGetContentResponse> GetContentAsync(string resourceGroupName, string automationAccount, Guid nodeId, Guid reportId, CancellationToken cancellationToken); /// <summary> /// Retrieve the Dsc node report list by node id and report id. (see /// http://aka.ms/azureautomationsdk/dscnodereportoperations for more /// information) /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group /// </param> /// <param name='automationAccount'> /// The automation account name. /// </param> /// <param name='parameters'> /// The parameters supplied to the list operation. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response model for the list dsc nodes operation. /// </returns> Task<DscNodeReportListResponse> ListAsync(string resourceGroupName, string automationAccount, DscNodeReportListParameters parameters, CancellationToken cancellationToken); /// <summary> /// Retrieve the Dsc node report list by node id and report id. (see /// http://aka.ms/azureautomationsdk/dscnodereportoperations for more /// information) /// </summary> /// <param name='nextLink'> /// The link to retrieve next set of items. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response model for the list dsc nodes operation. /// </returns> Task<DscNodeReportListResponse> ListNextAsync(string nextLink, CancellationToken cancellationToken); } }
38.681416
179
0.600778
[ "MIT" ]
DiogenesPolanco/azure-sdk-for-net
src/ResourceManagement/Automation/AutomationManagement/Generated/IDscNodeReportsOperations.cs
4,371
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. #pragma warning disable 1591 namespace IdentityServer4.Admin.Api.Entities { public class ClientClaim { public virtual int Id { get; set; } public virtual string Type { get; set; } public virtual string Value { get; set; } public virtual int ClientId { get; set; } public virtual Client Client { get; set; } } }
30.166667
107
0.672192
[ "MIT" ]
DORAdreamless/IdentityServer4.AdminUI
src/IdentityServer4.Admin/IdentityServer4.Admin.Api/Entities/ClientClaim.cs
545
C#
/************************************************************************************ Copyright : Copyright 2014 Oculus VR, LLC. All Rights reserved. Licensed under the Oculus VR Rift SDK License Version 3.3 (the "License"); you may not use the Oculus VR Rift SDK except in compliance with the License, which is provided at the time of installation or download, or which otherwise accompanies this software in either electronic or hard copy form. You may obtain a copy of the License at http://www.oculus.com/licenses/LICENSE-3.3 Unless required by applicable law or agreed to in writing, the Oculus VR SDK 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.Collections; using System.Collections.Generic; using System.Runtime.InteropServices; using UnityEngine; /// <summary> /// Provides a unified input system for Oculus controllers and gamepads. /// </summary> public static class OVRInput { [Flags] /// Virtual button mappings that allow the same input bindings to work across different controllers. public enum Button { None = 0, ///< Maps to RawButton: [Gamepad, Touch, LTouch, RTouch, LTrackedRemote, RTrackedRemote, Touchpad, Remote: None] One = 0x00000001, ///< Maps to RawButton: [Gamepad, Touch, RTouch: A], [LTouch: X], [LTrackedRemote: LTouchpad], [RTrackedRemote: RTouchpad], [Touchpad, Remote: Start] Two = 0x00000002, ///< Maps to RawButton: [Gamepad, Touch, RTouch: B], [LTouch: Y], [LTrackedRemote, RTrackedRemote, Touchpad, Remote: Back] Three = 0x00000004, ///< Maps to RawButton: [Gamepad, Touch: X], [LTouch, RTouch, LTrackedRemote, RTrackedRemote, Touchpad, Remote: None] Four = 0x00000008, ///< Maps to RawButton: [Gamepad, Touch: Y], [LTouch, RTouch, LTrackedRemote, RTrackedRemote, Touchpad, Remote: None] Start = 0x00000100, ///< Maps to RawButton: [Gamepad: Start], [Touch, LTouch, LTrackedRemote, RTrackedRemote, Touchpad, Remote: Start], [RTouch: None] Back = 0x00000200, ///< Maps to RawButton: [Gamepad, LTrackedRemote, RTrackedRemote, Touchpad, Remote: Back], [Touch, LTouch, RTouch: None] PrimaryShoulder = 0x00001000, ///< Maps to RawButton: [Gamepad: LShoulder], [Touch, LTouch, RTouch, LTrackedRemote, RTrackedRemote, Touchpad, Remote: None] PrimaryIndexTrigger = 0x00002000, ///< Maps to RawButton: [Gamepad, Touch, LTouch, LTrackedRemote: LIndexTrigger], [RTouch, RTrackedRemote: RIndexTrigger], [Touchpad, Remote: None] PrimaryHandTrigger = 0x00004000, ///< Maps to RawButton: [Touch, LTouch: LHandTrigger], [RTouch: RHandTrigger], [Gamepad, LTrackedRemote, RTrackedRemote, Touchpad, Remote: None] PrimaryThumbstick = 0x00008000, ///< Maps to RawButton: [Gamepad, Touch, LTouch: LThumbstick], [RTouch: RThumbstick], [LTrackedRemote, RTrackedRemote, Touchpad, Remote: None] PrimaryThumbstickUp = 0x00010000, ///< Maps to RawButton: [Gamepad, Touch, LTouch: LThumbstickUp], [RTouch: RThumbstickUp], [LTrackedRemote, RTrackedRemote, Touchpad, Remote: None] PrimaryThumbstickDown = 0x00020000, ///< Maps to RawButton: [Gamepad, Touch, LTouch: LThumbstickDown], [RTouch: RThumbstickDown], [LTrackedRemote, RTrackedRemote, Touchpad, Remote: None] PrimaryThumbstickLeft = 0x00040000, ///< Maps to RawButton: [Gamepad, Touch, LTouch: LThumbstickLeft], [RTouch: RThumbstickLeft], [LTrackedRemote, RTrackedRemote, Touchpad, Remote: None] PrimaryThumbstickRight = 0x00080000, ///< Maps to RawButton: [Gamepad, Touch, LTouch: LThumbstickRight], [RTouch: RThumbstickRight], [LTrackedRemote, RTrackedRemote, Touchpad, Remote: None] PrimaryTouchpad = 0x00000400, ///< Maps to RawButton: [LTrackedRemote, Touchpad: LTouchpad], [RTrackedRemote: RTouchpad], [Gamepad, Touch, LTouch, RTouch, Remote: None] SecondaryShoulder = 0x00100000, ///< Maps to RawButton: [Gamepad: RShoulder], [Touch, LTouch, RTouch, LTrackedRemote, RTrackedRemote, Touchpad, Remote: None] SecondaryIndexTrigger = 0x00200000, ///< Maps to RawButton: [Gamepad, Touch: RIndexTrigger], [LTouch, RTouch, LTrackedRemote, RTrackedRemote, Touchpad, Remote: None] SecondaryHandTrigger = 0x00400000, ///< Maps to RawButton: [Touch: RHandTrigger], [Gamepad, LTouch, RTouch, LTrackedRemote, RTrackedRemote, Touchpad, Remote: None] SecondaryThumbstick = 0x00800000, ///< Maps to RawButton: [Gamepad, Touch: RThumbstick], [LTouch, RTouch, LTrackedRemote, RTrackedRemote, Touchpad, Remote: None] SecondaryThumbstickUp = 0x01000000, ///< Maps to RawButton: [Gamepad, Touch: RThumbstickUp], [LTouch, RTouch, LTrackedRemote, RTrackedRemote, Touchpad, Remote: None] SecondaryThumbstickDown = 0x02000000, ///< Maps to RawButton: [Gamepad, Touch: RThumbstickDown], [LTouch, RTouch, LTrackedRemote, RTrackedRemote, Touchpad, Remote: None] SecondaryThumbstickLeft = 0x04000000, ///< Maps to RawButton: [Gamepad, Touch: RThumbstickLeft], [LTouch, RTouch, LTrackedRemote, RTrackedRemote, Touchpad, Remote: None] SecondaryThumbstickRight = 0x08000000, ///< Maps to RawButton: [Gamepad, Touch: RThumbstickRight], [LTouch, RTouch, LTrackedRemote, RTrackedRemote, Touchpad, Remote: None] SecondaryTouchpad = 0x00000800, ///< Maps to RawButton: [Gamepad, Touch, LTouch, RTouch, LTrackedRemote, RTrackedRemote, Touchpad, Remote: None] DpadUp = 0x00000010, ///< Maps to RawButton: [Gamepad, LTrackedRemote, RTrackedRemote, Touchpad, Remote: DpadUp], [Touch, LTouch, RTouch: None] DpadDown = 0x00000020, ///< Maps to RawButton: [Gamepad, LTrackedRemote, RTrackedRemote, Touchpad, Remote: DpadDown], [Touch, LTouch, RTouch: None] DpadLeft = 0x00000040, ///< Maps to RawButton: [Gamepad, LTrackedRemote, RTrackedRemote, Touchpad, Remote: DpadLeft], [Touch, LTouch, RTouch: None] DpadRight = 0x00000080, ///< Maps to RawButton: [Gamepad, LTrackedRemote, RTrackedRemote, Touchpad, Remote: DpadRight], [Touch, LTouch, RTouch: None] Up = 0x10000000, ///< Maps to RawButton: [Gamepad, Touch, LTouch: LThumbstickUp], [RTouch: RThumbstickUp], [LTrackedRemote, RTrackedRemote, Touchpad, Remote: DpadUp] Down = 0x20000000, ///< Maps to RawButton: [Gamepad, Touch, LTouch: LThumbstickDown], [RTouch: RThumbstickDown], [LTrackedRemote, RTrackedRemote, Touchpad, Remote: DpadDown] Left = 0x40000000, ///< Maps to RawButton: [Gamepad, Touch, LTouch: LThumbstickLeft], [RTouch: RThumbstickLeft], [LTrackedRemote, RTrackedRemote, Touchpad, Remote: DpadLeft] Right = unchecked((int)0x80000000),///< Maps to RawButton: [Gamepad, Touch, LTouch: LThumbstickRight], [RTouch: RThumbstickRight], [LTrackedRemote, RTrackedRemote, Touchpad, Remote: DpadRight] Any = ~None, ///< Maps to RawButton: [Gamepad, Touch, LTouch, RTouch: Any] } [Flags] /// Raw button mappings that can be used to directly query the state of a controller. public enum RawButton { None = 0, ///< Maps to Physical Button: [Gamepad, Touch, LTouch, RTouch, LTrackedRemote, RTrackedRemote, Touchpad, Remote: None] A = 0x00000001, ///< Maps to Physical Button: [Gamepad, Touch, RTouch: A], [LTrackedRemote: LIndexTrigger], [RTrackedRemote: RIndexTrigger], [LTouch, Touchpad, Remote: None] B = 0x00000002, ///< Maps to Physical Button: [Gamepad, Touch, RTouch: B], [LTouch, LTrackedRemote, RTrackedRemote, Touchpad, Remote: None] X = 0x00000100, ///< Maps to Physical Button: [Gamepad, Touch, LTouch: X], [RTouch, LTrackedRemote, RTrackedRemote, Touchpad, Remote: None] Y = 0x00000200, ///< Maps to Physical Button: [Gamepad, Touch, LTouch: Y], [RTouch, LTrackedRemote, RTrackedRemote, Touchpad, Remote: None] Start = 0x00100000, ///< Maps to Physical Button: [Gamepad, Touch, LTouch, LTrackedRemote, RTrackedRemote, Touchpad, Remote: Start], [RTouch: None] Back = 0x00200000, ///< Maps to Physical Button: [Gamepad, LTrackedRemote, RTrackedRemote, Touchpad, Remote: Back], [Touch, LTouch, RTouch: None] LShoulder = 0x00000800, ///< Maps to Physical Button: [Gamepad: LShoulder], [Touch, LTouch, RTouch, LTrackedRemote, RTrackedRemote, Touchpad, Remote: None] LIndexTrigger = 0x10000000, ///< Maps to Physical Button: [Gamepad, Touch, LTouch, LTrackedRemote: LIndexTrigger], [RTouch, RTrackedRemote, Touchpad, Remote: None] LHandTrigger = 0x20000000, ///< Maps to Physical Button: [Touch, LTouch: LHandTrigger], [Gamepad, RTouch, LTrackedRemote, RTrackedRemote, Touchpad, Remote: None] LThumbstick = 0x00000400, ///< Maps to Physical Button: [Gamepad, Touch, LTouch: LThumbstick], [RTouch, LTrackedRemote, RTrackedRemote, Touchpad, Remote: None] LThumbstickUp = 0x00000010, ///< Maps to Physical Button: [Gamepad, Touch, LTouch: LThumbstickUp], [RTouch, LTrackedRemote, RTrackedRemote, Touchpad, Remote: None] LThumbstickDown = 0x00000020, ///< Maps to Physical Button: [Gamepad, Touch, LTouch: LThumbstickDown], [RTouch, LTrackedRemote, RTrackedRemote, Touchpad, Remote: None] LThumbstickLeft = 0x00000040, ///< Maps to Physical Button: [Gamepad, Touch, LTouch: LThumbstickLeft], [RTouch, LTrackedRemote, RTrackedRemote, Touchpad, Remote: None] LThumbstickRight = 0x00000080, ///< Maps to Physical Button: [Gamepad, Touch, LTouch: LThumbstickRight], [RTouch, LTrackedRemote, RTrackedRemote, Touchpad, Remote: None] LTouchpad = 0x40000000, ///< Maps to Physical Button: [LTrackedRemote: LTouchpad], [Gamepad, Touch, LTouch, RTouch, RTrackedRemote, Touchpad, Remote: None] RShoulder = 0x00000008, ///< Maps to Physical Button: [Gamepad: RShoulder], [Touch, LTouch, RTouch, LTrackedRemote, RTrackedRemote, Touchpad, Remote: None] RIndexTrigger = 0x04000000, ///< Maps to Physical Button: [Gamepad, Touch, RTouch, RTrackedRemote: RIndexTrigger], [LTouch, LTrackedRemote, Touchpad, Remote: None] RHandTrigger = 0x08000000, ///< Maps to Physical Button: [Touch, RTouch: RHandTrigger], [Gamepad, LTouch, LTrackedRemote, RTrackedRemote, Touchpad, Remote: None] RThumbstick = 0x00000004, ///< Maps to Physical Button: [Gamepad, Touch, RTouch: RThumbstick], [LTouch, LTrackedRemote, RTrackedRemote, Touchpad, Remote: None] RThumbstickUp = 0x00001000, ///< Maps to Physical Button: [Gamepad, Touch, RTouch: RThumbstickUp], [LTouch, LTrackedRemote, RTrackedRemote, Touchpad, Remote: None] RThumbstickDown = 0x00002000, ///< Maps to Physical Button: [Gamepad, Touch, RTouch: RThumbstickDown], [LTouch, LTrackedRemote, RTrackedRemote, Touchpad, Remote: None] RThumbstickLeft = 0x00004000, ///< Maps to Physical Button: [Gamepad, Touch, RTouch: RThumbstickLeft], [LTouch, LTrackedRemote, RTrackedRemote, Touchpad, Remote: None] RThumbstickRight = 0x00008000, ///< Maps to Physical Button: [Gamepad, Touch, RTouch: RThumbstickRight], [LTouch, LTrackedRemote, RTrackedRemote, Touchpad, Remote: None] RTouchpad = unchecked((int)0x80000000),///< Maps to Physical Button: [Gamepad, Touch, LTouch, RTouch, LTrackedRemote, RTrackedRemote, Touchpad, Remote: None] DpadUp = 0x00010000, ///< Maps to Physical Button: [Gamepad, LTrackedRemote, RTrackedRemote, Touchpad, Remote: DpadUp], [Touch, LTouch, RTouch: None] DpadDown = 0x00020000, ///< Maps to Physical Button: [Gamepad, LTrackedRemote, RTrackedRemote, Touchpad, Remote: DpadDown], [Touch, LTouch, RTouch: None] DpadLeft = 0x00040000, ///< Maps to Physical Button: [Gamepad, LTrackedRemote, RTrackedRemote, Touchpad, Remote: DpadLeft], [Touch, LTouch, RTouch: None] DpadRight = 0x00080000, ///< Maps to Physical Button: [Gamepad, LTrackedRemote, RTrackedRemote, Touchpad, Remote: DpadRight], [Touch, LTouch, RTouch: None] Any = ~None, ///< Maps to Physical Button: [Gamepad, Touch, LTouch, RTouch, LTrackedRemote, RTrackedRemote, Touchpad, Remote: Any] } [Flags] /// Virtual capacitive touch mappings that allow the same input bindings to work across different controllers with capacitive touch support. public enum Touch { None = 0, ///< Maps to RawTouch: [Gamepad, Touch, LTouch, RTouch, LTrackedRemote, RTrackedRemote, Touchpad, Remote: None] One = Button.One, ///< Maps to RawTouch: [Touch, RTouch: A], [LTouch: X], [Gamepad, LTrackedRemote, RTrackedRemote, Touchpad, Remote: None] Two = Button.Two, ///< Maps to RawTouch: [Touch, RTouch: B], [LTouch: Y], [Gamepad, LTrackedRemote, RTrackedRemote, Touchpad, Remote: None] Three = Button.Three, ///< Maps to RawTouch: [Touch: X], [Gamepad, LTouch, RTouch, LTrackedRemote, RTrackedRemote, Touchpad, Remote: None] Four = Button.Four, ///< Maps to RawTouch: [Touch: Y], [Gamepad, LTouch, RTouch, LTrackedRemote, RTrackedRemote, Touchpad, Remote: None] PrimaryIndexTrigger = Button.PrimaryIndexTrigger, ///< Maps to RawTouch: [Touch, LTouch: LIndexTrigger], [RTouch: RIndexTrigger], [Gamepad, LTrackedRemote, RTrackedRemote, Touchpad, Remote: None] PrimaryThumbstick = Button.PrimaryThumbstick, ///< Maps to RawTouch: [Touch, LTouch: LThumbstick], [RTouch: RThumbstick], [Gamepad, LTrackedRemote, RTrackedRemote, Touchpad, Remote: None] PrimaryThumbRest = 0x00001000, ///< Maps to RawTouch: [Touch, LTouch: LThumbRest], [RTouch: RThumbRest], [Gamepad, LTrackedRemote, RTrackedRemote, Touchpad, Remote: None] PrimaryTouchpad = Button.PrimaryTouchpad, ///< Maps to RawTouch: [LTrackedRemote, Touchpad: LTouchpad], [RTrackedRemote: RTouchpad], [Gamepad, Touch, LTouch, RTouch, Remote: None] SecondaryIndexTrigger = Button.SecondaryIndexTrigger, ///< Maps to RawTouch: [Touch: RIndexTrigger], [Gamepad, LTouch, RTouch, LTrackedRemote, RTrackedRemote, Touchpad, Remote: None] SecondaryThumbstick = Button.SecondaryThumbstick, ///< Maps to RawTouch: [Touch: RThumbstick], [Gamepad, LTouch, RTouch, LTrackedRemote, RTrackedRemote, Touchpad, Remote: None] SecondaryThumbRest = 0x00100000, ///< Maps to RawTouch: [Touch: RThumbRest], [Gamepad, LTouch, RTouch, LTrackedRemote, RTrackedRemote, Touchpad, Remote: None] SecondaryTouchpad = Button.SecondaryTouchpad, ///< Maps to RawTouch: [Gamepad, Touch, LTouch, RTouch, LTrackedRemote, RTrackedRemote, Touchpad, Remote: None] Any = ~None, ///< Maps to RawTouch: [Touch, LTouch, RTouch, LTrackedRemote, RTrackedRemote, Touchpad: Any], [Gamepad, Remote: None] } [Flags] /// Raw capacitive touch mappings that can be used to directly query the state of a controller. public enum RawTouch { None = 0, ///< Maps to Physical Touch: [Gamepad, Touch, LTouch, RTouch, LTrackedRemote, RTrackedRemote, Touchpad, Remote: None] A = RawButton.A, ///< Maps to Physical Touch: [Touch, RTouch: A], [Gamepad, LTouch, LTrackedRemote, RTrackedRemote, Touchpad, Remote: None] B = RawButton.B, ///< Maps to Physical Touch: [Touch, RTouch: B], [Gamepad, LTouch, LTrackedRemote, RTrackedRemote, Touchpad, Remote: None] X = RawButton.X, ///< Maps to Physical Touch: [Touch, LTouch: X], [Gamepad, RTouch, LTrackedRemote, RTrackedRemote, Touchpad, Remote: None] Y = RawButton.Y, ///< Maps to Physical Touch: [Touch, LTouch: Y], [Gamepad, RTouch, LTrackedRemote, RTrackedRemote, Touchpad, Remote: None] LIndexTrigger = 0x00001000, ///< Maps to Physical Touch: [Touch, LTouch: LIndexTrigger], [Gamepad, RTouch, LTrackedRemote, RTrackedRemote, Touchpad, Remote: None] LThumbstick = RawButton.LThumbstick, ///< Maps to Physical Touch: [Touch, LTouch: LThumbstick], [Gamepad, RTouch, LTrackedRemote, RTrackedRemote, Touchpad, Remote: None] LThumbRest = 0x00000800, ///< Maps to Physical Touch: [Touch, LTouch: LThumbRest], [Gamepad, RTouch, LTrackedRemote, RTrackedRemote, Touchpad, Remote: None] LTouchpad = RawButton.LTouchpad, ///< Maps to Physical Touch: [LTrackedRemote, Touchpad: LTouchpad], [Gamepad, Touch, LTouch, RTouch, RTrackedRemote, Remote: None] RIndexTrigger = 0x00000010, ///< Maps to Physical Touch: [Touch, RTouch: RIndexTrigger], [Gamepad, LTouch, LTrackedRemote, RTrackedRemote, Touchpad, Remote: None] RThumbstick = RawButton.RThumbstick, ///< Maps to Physical Touch: [Touch, RTouch: RThumbstick], [Gamepad, LTouch, LTrackedRemote, RTrackedRemote, Touchpad, Remote: None] RThumbRest = 0x00000008, ///< Maps to Physical Touch: [Touch, RTouch: RThumbRest], [Gamepad, LTouch, LTrackedRemote, RTrackedRemote, Touchpad, Remote: None] RTouchpad = RawButton.RTouchpad, ///< Maps to Physical Touch: [RTrackedRemote: RTouchpad], [Gamepad, Touch, LTouch, RTouch, LTrackedRemote, Touchpad, Remote: None] Any = ~None, ///< Maps to Physical Touch: [Touch, LTouch, RTouch, LTrackedRemote, RTrackedRemote, Touchpad: Any], [Gamepad, Remote: None] } [Flags] /// Virtual near touch mappings that allow the same input bindings to work across different controllers with near touch support. /// A near touch uses the capacitive touch sensors of a controller to detect approximate finger proximity prior to a full touch being reported. public enum NearTouch { None = 0, ///< Maps to RawNearTouch: [Gamepad, Touch, LTouch, RTouch, LTrackedRemote, RTrackedRemote, Touchpad, Remote: None] PrimaryIndexTrigger = 0x00000001, ///< Maps to RawNearTouch: [Touch, LTouch: LIndexTrigger], [RTouch: RIndexTrigger], [Gamepad, LTrackedRemote, RTrackedRemote, Touchpad, Remote: None] PrimaryThumbButtons = 0x00000002, ///< Maps to RawNearTouch: [Touch, LTouch: LThumbButtons], [RTouch: RThumbButtons], [Gamepad, LTrackedRemote, RTrackedRemote, Touchpad, Remote: None] SecondaryIndexTrigger = 0x00000004, ///< Maps to RawNearTouch: [Touch: RIndexTrigger], [Gamepad, LTouch, RTouch, LTrackedRemote, RTrackedRemote, Touchpad, Remote: None] SecondaryThumbButtons = 0x00000008, ///< Maps to RawNearTouch: [Touch: RThumbButtons], [Gamepad, LTouch, RTouch, LTrackedRemote, RTrackedRemote, Touchpad, Remote: None] Any = ~None, ///< Maps to RawNearTouch: [Touch, LTouch, RTouch: Any], [Gamepad, LTrackedRemote, RTrackedRemote, Touchpad, Remote: None] } [Flags] /// Raw near touch mappings that can be used to directly query the state of a controller. public enum RawNearTouch { None = 0, ///< Maps to Physical NearTouch: [Gamepad, Touch, LTouch, RTouch, LTrackedRemote, RTrackedRemote, Touchpad, Remote: None] LIndexTrigger = 0x00000001, ///< Maps to Physical NearTouch: [Touch, LTouch: Implies finger is in close proximity to LIndexTrigger.], [Gamepad, RTouch, LTrackedRemote, RTrackedRemote, Touchpad, Remote: None] LThumbButtons = 0x00000002, ///< Maps to Physical NearTouch: [Touch, LTouch: Implies thumb is in close proximity to LThumbstick OR X/Y buttons.], [Gamepad, RTouch, LTrackedRemote, RTrackedRemote, Touchpad, Remote: None] RIndexTrigger = 0x00000004, ///< Maps to Physical NearTouch: [Touch, RTouch: Implies finger is in close proximity to RIndexTrigger.], [Gamepad, LTouch, LTrackedRemote, RTrackedRemote, Touchpad, Remote: None] RThumbButtons = 0x00000008, ///< Maps to Physical NearTouch: [Touch, RTouch: Implies thumb is in close proximity to RThumbstick OR A/B buttons.], [Gamepad, LTouch, LTrackedRemote, RTrackedRemote, Touchpad, Remote: None] Any = ~None, ///< Maps to Physical NearTouch: [Touch, LTouch, RTouch: Any], [Gamepad, LTrackedRemote, RTrackedRemote, Touchpad, Remote: None] } [Flags] /// Virtual 1-dimensional axis (float) mappings that allow the same input bindings to work across different controllers. public enum Axis1D { None = 0, ///< Maps to RawAxis1D: [Gamepad, Touch, LTouch, RTouch, LTrackedRemote, RTrackedRemote, Touchpad, Remote: None] PrimaryIndexTrigger = 0x01, ///< Maps to RawAxis1D: [Gamepad, Touch, LTouch: LIndexTrigger], [RTouch: RIndexTrigger], [LTrackedRemote, RTrackedRemote, Touchpad, Remote: None] PrimaryHandTrigger = 0x04, ///< Maps to RawAxis1D: [Touch, LTouch: LHandTrigger], [RTouch: RHandTrigger], [Gamepad, LTrackedRemote, RTrackedRemote, Touchpad, Remote: None] SecondaryIndexTrigger = 0x02, ///< Maps to RawAxis1D: [Gamepad, Touch: RIndexTrigger], [LTouch, RTouch, LTrackedRemote, RTrackedRemote, Touchpad, Remote: None] SecondaryHandTrigger = 0x08, ///< Maps to RawAxis1D: [Touch: RHandTrigger], [Gamepad, LTouch, RTouch, LTrackedRemote, RTrackedRemote, Touchpad, Remote: None] Any = ~None, ///< Maps to RawAxis1D: [Gamepad, Touch, LTouch, RTouch: Any], [LTrackedRemote, RTrackedRemote, Touchpad, Remote: None] } [Flags] /// Raw 1-dimensional axis (float) mappings that can be used to directly query the state of a controller. public enum RawAxis1D { None = 0, ///< Maps to Physical Axis1D: [Gamepad, Touch, LTouch, RTouch, LTrackedRemote, RTrackedRemote, Touchpad, Remote: None] LIndexTrigger = 0x01, ///< Maps to Physical Axis1D: [Gamepad, Touch, LTouch: LIndexTrigger], [RTouch, LTrackedRemote, RTrackedRemote, Touchpad, Remote: None] LHandTrigger = 0x04, ///< Maps to Physical Axis1D: [Touch, LTouch: LHandTrigger], [Gamepad, RTouch, LTrackedRemote, RTrackedRemote, Touchpad, Remote: None] RIndexTrigger = 0x02, ///< Maps to Physical Axis1D: [Gamepad, Touch, RTouch: RIndexTrigger], [LTouch, LTrackedRemote, RTrackedRemote, Touchpad, Remote: None] RHandTrigger = 0x08, ///< Maps to Physical Axis1D: [Touch, RTouch: RHandTrigger], [Gamepad, LTouch, LTrackedRemote, RTrackedRemote, Touchpad, Remote: None] Any = ~None, ///< Maps to Physical Axis1D: [Gamepad, Touch, LTouch, RTouch: Any], [LTrackedRemote, RTrackedRemote, Touchpad, Remote: None] } [Flags] /// Virtual 2-dimensional axis (Vector2) mappings that allow the same input bindings to work across different controllers. public enum Axis2D { None = 0, ///< Maps to RawAxis2D: [Gamepad, Touch, LTouch, RTouch, LTrackedRemote, RTrackedRemote, Touchpad, Remote: None] PrimaryThumbstick = 0x01, ///< Maps to RawAxis2D: [Gamepad, Touch, LTouch: LThumbstick], [RTouch: RThumbstick], [LTrackedRemote, RTrackedRemote, Touchpad, Remote: None] PrimaryTouchpad = 0x04, ///< Maps to RawAxis2D: [LTrackedRemote, Touchpad: LTouchpad], RTrackedRemote: RTouchpad], [Gamepad, Touch, LTouch, RTouch, Remote: None] SecondaryThumbstick = 0x02, ///< Maps to RawAxis2D: [Gamepad, Touch: RThumbstick], [LTouch, RTouch, LTrackedRemote, RTrackedRemote, Touchpad, Remote: None] SecondaryTouchpad = 0x08, ///< Maps to RawAxis2D: [Gamepad, Touch, LTouch, RTouch, LTrackedRemote, RTrackedRemote, Touchpad, Remote: None] Any = ~None, ///< Maps to RawAxis2D: [Gamepad, Touch, LTouch, RTouch, LTrackedRemote, RTrackedRemote, Touchpad: Any], [Remote: None] } [Flags] /// Raw 2-dimensional axis (Vector2) mappings that can be used to directly query the state of a controller. public enum RawAxis2D { None = 0, ///< Maps to Physical Axis2D: [Gamepad, Touch, LTouch, RTouch, LTrackedRemote, RTrackedRemote, Touchpad, Remote: None] LThumbstick = 0x01, ///< Maps to Physical Axis2D: [Gamepad, Touch, LTouch: LThumbstick], [RTouch, LTrackedRemote, RTrackedRemote, Touchpad, Remote: None] LTouchpad = 0x04, ///< Maps to Physical Axis2D: [LTrackedRemote, Touchpad: LTouchpad], [Gamepad, Touch, LTouch, RTouch, RTrackedRemote, Remote: None] RThumbstick = 0x02, ///< Maps to Physical Axis2D: [Gamepad, Touch, RTouch: RThumbstick], [LTouch, LTrackedRemote, RTrackedRemote, Touchpad, Remote: None] RTouchpad = 0x08, ///< Maps to Physical Axis2D: [RTrackedRemote: RTouchpad], [Gamepad, Touch, LTouch, RTouch, LTrackedRemote, Touchpad, Remote: None] Any = ~None, ///< Maps to Physical Axis2D: [Gamepad, Touch, LTouch, RTouch, LTrackedRemote, RTrackedRemote: Any], [Touchpad, Remote: None] } [Flags] /// Identifies a controller which can be used to query the virtual or raw input state. public enum Controller { None = OVRPlugin.Controller.None, ///< Null controller. LTouch = OVRPlugin.Controller.LTouch, ///< Left Oculus Touch controller. Virtual input mapping differs from the combined L/R Touch mapping. RTouch = OVRPlugin.Controller.RTouch, ///< Right Oculus Touch controller. Virtual input mapping differs from the combined L/R Touch mapping. Touch = OVRPlugin.Controller.Touch, ///< Combined Left/Right pair of Oculus Touch controllers. Remote = OVRPlugin.Controller.Remote, ///< Oculus Remote controller. Gamepad = OVRPlugin.Controller.Gamepad, ///< Xbox 360 or Xbox One gamepad on PC. Generic gamepad on Android. Touchpad = OVRPlugin.Controller.Touchpad, ///< GearVR touchpad on Android. LTrackedRemote = OVRPlugin.Controller.LTrackedRemote, ///< Left GearVR tracked remote on Android. RTrackedRemote = OVRPlugin.Controller.RTrackedRemote, ///< Right GearVR tracked remote on Android. Active = OVRPlugin.Controller.Active, ///< Default controller. Represents the controller that most recently registered a button press from the user. All = OVRPlugin.Controller.All, ///< Represents the logical OR of all controllers. } private static readonly float AXIS_AS_BUTTON_THRESHOLD = 0.5f; private static readonly float AXIS_DEADZONE_THRESHOLD = 0.2f; private static List<OVRControllerBase> controllers; private static Controller activeControllerType = Controller.None; private static Controller connectedControllerTypes = Controller.None; private static OVRPlugin.Step stepType = OVRPlugin.Step.Render; private static int fixedUpdateCount = 0; private static bool _pluginSupportsActiveController = false; private static bool _pluginSupportsActiveControllerCached = false; private static System.Version _pluginSupportsActiveControllerMinVersion = new System.Version(1, 9, 0); private static bool pluginSupportsActiveController { get { if (!_pluginSupportsActiveControllerCached) { bool isSupportedPlatform = true; #if (UNITY_ANDROID && !UNITY_EDITOR) || UNITY_STANDALONE_OSX || UNITY_EDITOR_OSX isSupportedPlatform = false; #endif _pluginSupportsActiveController = isSupportedPlatform && (OVRPlugin.version >= _pluginSupportsActiveControllerMinVersion); _pluginSupportsActiveControllerCached = true; } return _pluginSupportsActiveController; } } /// <summary> /// Creates an instance of OVRInput. /// </summary> static OVRInput() { controllers = new List<OVRControllerBase> { #if UNITY_ANDROID && !UNITY_EDITOR new OVRControllerGamepadAndroid(), new OVRControllerTouchpad(), new OVRControllerLTrackedRemote(), new OVRControllerRTrackedRemote(), #elif UNITY_STANDALONE_OSX || UNITY_EDITOR_OSX new OVRControllerGamepadMac(), #else new OVRControllerGamepadPC(), new OVRControllerTouch(), new OVRControllerLTouch(), new OVRControllerRTouch(), new OVRControllerRemote(), #endif }; } /// <summary> /// Updates the internal state of OVRInput. Must be called manually if used independently from OVRManager. /// </summary> public static void Update() { connectedControllerTypes = Controller.None; stepType = OVRPlugin.Step.Render; fixedUpdateCount = 0; for (int i = 0; i < controllers.Count; i++) { OVRControllerBase controller = controllers[i]; connectedControllerTypes |= controller.Update(); if ((connectedControllerTypes & controller.controllerType) != 0) { if (Get(RawButton.Any, controller.controllerType) || Get(RawTouch.Any, controller.controllerType)) { activeControllerType = controller.controllerType; } } } if ((activeControllerType == Controller.LTouch) || (activeControllerType == Controller.RTouch)) { // If either Touch controller is Active, set both to Active. activeControllerType = Controller.Touch; } if ((connectedControllerTypes & activeControllerType) == 0) { activeControllerType = Controller.None; } // Promote TrackedRemote to Active if one is connected and no other controller is active if (activeControllerType == Controller.None) { if ((connectedControllerTypes & Controller.RTrackedRemote) != 0) { activeControllerType = Controller.RTrackedRemote; } else if ((connectedControllerTypes & Controller.LTrackedRemote) != 0) { activeControllerType = Controller.LTrackedRemote; } } if (pluginSupportsActiveController) { // override locally derived active and connected controllers if plugin provides more accurate data connectedControllerTypes = (OVRInput.Controller)OVRPlugin.GetConnectedControllers(); activeControllerType = (OVRInput.Controller)OVRPlugin.GetActiveController(); } } /// <summary> /// Updates the internal physics state of OVRInput. Must be called manually if used independently from OVRManager. /// </summary> public static void FixedUpdate() { stepType = OVRPlugin.Step.Physics; double predictionSeconds = (double)fixedUpdateCount * Time.fixedDeltaTime / Mathf.Max(Time.timeScale, 1e-6f); fixedUpdateCount++; OVRPlugin.UpdateNodePhysicsPoses(0, predictionSeconds); } /// <summary> /// Returns true if the given Controller's orientation is currently tracked. /// Only supported for Oculus LTouch and RTouch controllers. Non-tracked controllers will return false. /// </summary> public static bool GetControllerOrientationTracked(OVRInput.Controller controllerType) { switch (controllerType) { case Controller.LTouch: case Controller.LTrackedRemote: return OVRPlugin.GetNodeOrientationTracked(OVRPlugin.Node.HandLeft); case Controller.RTouch: case Controller.RTrackedRemote: return OVRPlugin.GetNodeOrientationTracked(OVRPlugin.Node.HandRight); default: return false; } } /// <summary> /// Returns true if the given Controller's position is currently tracked. /// Only supported for Oculus LTouch and RTouch controllers. Non-tracked controllers will return false. /// </summary> public static bool GetControllerPositionTracked(OVRInput.Controller controllerType) { switch (controllerType) { case Controller.LTouch: case Controller.LTrackedRemote: return OVRPlugin.GetNodePositionTracked(OVRPlugin.Node.HandLeft); case Controller.RTouch: case Controller.RTrackedRemote: return OVRPlugin.GetNodePositionTracked(OVRPlugin.Node.HandRight); default: return false; } } /// <summary> /// Gets the position of the given Controller local to its tracking space. /// Only supported for Oculus LTouch and RTouch controllers. Non-tracked controllers will return Vector3.zero. /// </summary> public static Vector3 GetLocalControllerPosition(OVRInput.Controller controllerType) { switch (controllerType) { case Controller.LTouch: case Controller.LTrackedRemote: return OVRPlugin.GetNodePose(OVRPlugin.Node.HandLeft, stepType).ToOVRPose().position; case Controller.RTouch: case Controller.RTrackedRemote: return OVRPlugin.GetNodePose(OVRPlugin.Node.HandRight, stepType).ToOVRPose().position; default: return Vector3.zero; } } /// <summary> /// Gets the linear velocity of the given Controller local to its tracking space. /// Only supported for Oculus LTouch and RTouch controllers. Non-tracked controllers will return Vector3.zero. /// </summary> public static Vector3 GetLocalControllerVelocity(OVRInput.Controller controllerType) { switch (controllerType) { case Controller.LTouch: case Controller.LTrackedRemote: return OVRPlugin.GetNodeVelocity(OVRPlugin.Node.HandLeft, stepType).FromFlippedZVector3f(); case Controller.RTouch: case Controller.RTrackedRemote: return OVRPlugin.GetNodeVelocity(OVRPlugin.Node.HandRight, stepType).FromFlippedZVector3f(); default: return Vector3.zero; } } /// <summary> /// Gets the linear acceleration of the given Controller local to its tracking space. /// Only supported for Oculus LTouch and RTouch controllers. Non-tracked controllers will return Vector3.zero. /// </summary> public static Vector3 GetLocalControllerAcceleration(OVRInput.Controller controllerType) { switch (controllerType) { case Controller.LTouch: case Controller.LTrackedRemote: return OVRPlugin.GetNodeAcceleration(OVRPlugin.Node.HandLeft, stepType).FromFlippedZVector3f(); case Controller.RTouch: case Controller.RTrackedRemote: return OVRPlugin.GetNodeAcceleration(OVRPlugin.Node.HandRight, stepType).FromFlippedZVector3f(); default: return Vector3.zero; } } /// <summary> /// Gets the rotation of the given Controller local to its tracking space. /// Only supported for Oculus LTouch and RTouch controllers. Non-tracked controllers will return Quaternion.identity. /// </summary> public static Quaternion GetLocalControllerRotation(OVRInput.Controller controllerType) { switch (controllerType) { case Controller.LTouch: case Controller.LTrackedRemote: return OVRPlugin.GetNodePose(OVRPlugin.Node.HandLeft, stepType).ToOVRPose().orientation; case Controller.RTouch: case Controller.RTrackedRemote: return OVRPlugin.GetNodePose(OVRPlugin.Node.HandRight, stepType).ToOVRPose().orientation; default: return Quaternion.identity; } } /// <summary> /// Gets the angular velocity of the given Controller local to its tracking space in radians per second around each axis. /// Only supported for Oculus LTouch and RTouch controllers. Non-tracked controllers will return Quaternion.identity. /// </summary> public static Vector3 GetLocalControllerAngularVelocity(OVRInput.Controller controllerType) { switch (controllerType) { case Controller.LTouch: case Controller.LTrackedRemote: return OVRPlugin.GetNodeAngularVelocity(OVRPlugin.Node.HandLeft, stepType).FromFlippedZVector3f(); case Controller.RTouch: case Controller.RTrackedRemote: return OVRPlugin.GetNodeAngularVelocity(OVRPlugin.Node.HandRight, stepType).FromFlippedZVector3f(); default: return Vector3.zero; } } /// <summary> /// Gets the angular acceleration of the given Controller local to its tracking space in radians per second per second around each axis. /// Only supported for Oculus LTouch and RTouch controllers. Non-tracked controllers will return Quaternion.identity. /// </summary> public static Vector3 GetLocalControllerAngularAcceleration(OVRInput.Controller controllerType) { switch (controllerType) { case Controller.LTouch: case Controller.LTrackedRemote: return OVRPlugin.GetNodeAngularAcceleration(OVRPlugin.Node.HandLeft, stepType).FromFlippedZVector3f(); case Controller.RTouch: case Controller.RTrackedRemote: return OVRPlugin.GetNodeAngularAcceleration(OVRPlugin.Node.HandRight, stepType).FromFlippedZVector3f(); default: return Vector3.zero; } } /// <summary> /// Gets the current state of the given virtual button mask with the given controller mask. /// Returns true if any masked button is down on any masked controller. /// </summary> public static bool Get(Button virtualMask, Controller controllerMask = Controller.Active) { return GetResolvedButton(virtualMask, RawButton.None, controllerMask); } /// <summary> /// Gets the current state of the given raw button mask with the given controller mask. /// Returns true if any masked button is down on any masked controllers. /// </summary> public static bool Get(RawButton rawMask, Controller controllerMask = Controller.Active) { return GetResolvedButton(Button.None, rawMask, controllerMask); } private static bool GetResolvedButton(Button virtualMask, RawButton rawMask, Controller controllerMask) { if ((controllerMask & Controller.Active) != 0) controllerMask |= activeControllerType; for (int i = 0; i < controllers.Count; i++) { OVRControllerBase controller = controllers[i]; if (ShouldResolveController(controller.controllerType, controllerMask)) { RawButton resolvedMask = rawMask | controller.ResolveToRawMask(virtualMask); if (((RawButton)controller.currentState.Buttons & resolvedMask) != 0) { return true; } } } return false; } /// <summary> /// Gets the current down state of the given virtual button mask with the given controller mask. /// Returns true if any masked button was pressed this frame on any masked controller and no masked button was previously down last frame. /// </summary> public static bool GetDown(Button virtualMask, Controller controllerMask = Controller.Active) { return GetResolvedButtonDown(virtualMask, RawButton.None, controllerMask); } /// <summary> /// Gets the current down state of the given raw button mask with the given controller mask. /// Returns true if any masked button was pressed this frame on any masked controller and no masked button was previously down last frame. /// </summary> public static bool GetDown(RawButton rawMask, Controller controllerMask = Controller.Active) { return GetResolvedButtonDown(Button.None, rawMask, controllerMask); } private static bool GetResolvedButtonDown(Button virtualMask, RawButton rawMask, Controller controllerMask) { bool down = false; if ((controllerMask & Controller.Active) != 0) controllerMask |= activeControllerType; for (int i = 0; i < controllers.Count; i++) { OVRControllerBase controller = controllers[i]; if (ShouldResolveController(controller.controllerType, controllerMask)) { RawButton resolvedMask = rawMask | controller.ResolveToRawMask(virtualMask); if (((RawButton)controller.previousState.Buttons & resolvedMask) != 0) { return false; } if ((((RawButton)controller.currentState.Buttons & resolvedMask) != 0) && (((RawButton)controller.previousState.Buttons & resolvedMask) == 0)) { down = true; } } } return down; } /// <summary> /// Gets the current up state of the given virtual button mask with the given controller mask. /// Returns true if any masked button was released this frame on any masked controller and no other masked button is still down this frame. /// </summary> public static bool GetUp(Button virtualMask, Controller controllerMask = Controller.Active) { return GetResolvedButtonUp(virtualMask, RawButton.None, controllerMask); } /// <summary> /// Gets the current up state of the given raw button mask with the given controller mask. /// Returns true if any masked button was released this frame on any masked controller and no other masked button is still down this frame. /// </summary> public static bool GetUp(RawButton rawMask, Controller controllerMask = Controller.Active) { return GetResolvedButtonUp(Button.None, rawMask, controllerMask); } private static bool GetResolvedButtonUp(Button virtualMask, RawButton rawMask, Controller controllerMask) { bool up = false; if ((controllerMask & Controller.Active) != 0) controllerMask |= activeControllerType; for (int i = 0; i < controllers.Count; i++) { OVRControllerBase controller = controllers[i]; if (ShouldResolveController(controller.controllerType, controllerMask)) { RawButton resolvedMask = rawMask | controller.ResolveToRawMask(virtualMask); if (((RawButton)controller.currentState.Buttons & resolvedMask) != 0) { return false; } if ((((RawButton)controller.currentState.Buttons & resolvedMask) == 0) && (((RawButton)controller.previousState.Buttons & resolvedMask) != 0)) { up = true; } } } return up; } /// <summary> /// Gets the current state of the given virtual touch mask with the given controller mask. /// Returns true if any masked touch is down on any masked controller. /// </summary> public static bool Get(Touch virtualMask, Controller controllerMask = Controller.Active) { return GetResolvedTouch(virtualMask, RawTouch.None, controllerMask); } /// <summary> /// Gets the current state of the given raw touch mask with the given controller mask. /// Returns true if any masked touch is down on any masked controllers. /// </summary> public static bool Get(RawTouch rawMask, Controller controllerMask = Controller.Active) { return GetResolvedTouch(Touch.None, rawMask, controllerMask); } private static bool GetResolvedTouch(Touch virtualMask, RawTouch rawMask, Controller controllerMask) { if ((controllerMask & Controller.Active) != 0) controllerMask |= activeControllerType; for (int i = 0; i < controllers.Count; i++) { OVRControllerBase controller = controllers[i]; if (ShouldResolveController(controller.controllerType, controllerMask)) { RawTouch resolvedMask = rawMask | controller.ResolveToRawMask(virtualMask); if (((RawTouch)controller.currentState.Touches & resolvedMask) != 0) { return true; } } } return false; } /// <summary> /// Gets the current down state of the given virtual touch mask with the given controller mask. /// Returns true if any masked touch was pressed this frame on any masked controller and no masked touch was previously down last frame. /// </summary> public static bool GetDown(Touch virtualMask, Controller controllerMask = Controller.Active) { return GetResolvedTouchDown(virtualMask, RawTouch.None, controllerMask); } /// <summary> /// Gets the current down state of the given raw touch mask with the given controller mask. /// Returns true if any masked touch was pressed this frame on any masked controller and no masked touch was previously down last frame. /// </summary> public static bool GetDown(RawTouch rawMask, Controller controllerMask = Controller.Active) { return GetResolvedTouchDown(Touch.None, rawMask, controllerMask); } private static bool GetResolvedTouchDown(Touch virtualMask, RawTouch rawMask, Controller controllerMask) { bool down = false; if ((controllerMask & Controller.Active) != 0) controllerMask |= activeControllerType; for (int i = 0; i < controllers.Count; i++) { OVRControllerBase controller = controllers[i]; if (ShouldResolveController(controller.controllerType, controllerMask)) { RawTouch resolvedMask = rawMask | controller.ResolveToRawMask(virtualMask); if (((RawTouch)controller.previousState.Touches & resolvedMask) != 0) { return false; } if ((((RawTouch)controller.currentState.Touches & resolvedMask) != 0) && (((RawTouch)controller.previousState.Touches & resolvedMask) == 0)) { down = true; } } } return down; } /// <summary> /// Gets the current up state of the given virtual touch mask with the given controller mask. /// Returns true if any masked touch was released this frame on any masked controller and no other masked touch is still down this frame. /// </summary> public static bool GetUp(Touch virtualMask, Controller controllerMask = Controller.Active) { return GetResolvedTouchUp(virtualMask, RawTouch.None, controllerMask); } /// <summary> /// Gets the current up state of the given raw touch mask with the given controller mask. /// Returns true if any masked touch was released this frame on any masked controller and no other masked touch is still down this frame. /// </summary> public static bool GetUp(RawTouch rawMask, Controller controllerMask = Controller.Active) { return GetResolvedTouchUp(Touch.None, rawMask, controllerMask); } private static bool GetResolvedTouchUp(Touch virtualMask, RawTouch rawMask, Controller controllerMask) { bool up = false; if ((controllerMask & Controller.Active) != 0) controllerMask |= activeControllerType; for (int i = 0; i < controllers.Count; i++) { OVRControllerBase controller = controllers[i]; if (ShouldResolveController(controller.controllerType, controllerMask)) { RawTouch resolvedMask = rawMask | controller.ResolveToRawMask(virtualMask); if (((RawTouch)controller.currentState.Touches & resolvedMask) != 0) { return false; } if ((((RawTouch)controller.currentState.Touches & resolvedMask) == 0) && (((RawTouch)controller.previousState.Touches & resolvedMask) != 0)) { up = true; } } } return up; } /// <summary> /// Gets the current state of the given virtual near touch mask with the given controller mask. /// Returns true if any masked near touch is down on any masked controller. /// </summary> public static bool Get(NearTouch virtualMask, Controller controllerMask = Controller.Active) { return GetResolvedNearTouch(virtualMask, RawNearTouch.None, controllerMask); } /// <summary> /// Gets the current state of the given raw near touch mask with the given controller mask. /// Returns true if any masked near touch is down on any masked controllers. /// </summary> public static bool Get(RawNearTouch rawMask, Controller controllerMask = Controller.Active) { return GetResolvedNearTouch(NearTouch.None, rawMask, controllerMask); } private static bool GetResolvedNearTouch(NearTouch virtualMask, RawNearTouch rawMask, Controller controllerMask) { if ((controllerMask & Controller.Active) != 0) controllerMask |= activeControllerType; for (int i = 0; i < controllers.Count; i++) { OVRControllerBase controller = controllers[i]; if (ShouldResolveController(controller.controllerType, controllerMask)) { RawNearTouch resolvedMask = rawMask | controller.ResolveToRawMask(virtualMask); if (((RawNearTouch)controller.currentState.NearTouches & resolvedMask) != 0) { return true; } } } return false; } /// <summary> /// Gets the current down state of the given virtual near touch mask with the given controller mask. /// Returns true if any masked near touch was pressed this frame on any masked controller and no masked near touch was previously down last frame. /// </summary> public static bool GetDown(NearTouch virtualMask, Controller controllerMask = Controller.Active) { return GetResolvedNearTouchDown(virtualMask, RawNearTouch.None, controllerMask); } /// <summary> /// Gets the current down state of the given raw near touch mask with the given controller mask. /// Returns true if any masked near touch was pressed this frame on any masked controller and no masked near touch was previously down last frame. /// </summary> public static bool GetDown(RawNearTouch rawMask, Controller controllerMask = Controller.Active) { return GetResolvedNearTouchDown(NearTouch.None, rawMask, controllerMask); } private static bool GetResolvedNearTouchDown(NearTouch virtualMask, RawNearTouch rawMask, Controller controllerMask) { bool down = false; if ((controllerMask & Controller.Active) != 0) controllerMask |= activeControllerType; for (int i = 0; i < controllers.Count; i++) { OVRControllerBase controller = controllers[i]; if (ShouldResolveController(controller.controllerType, controllerMask)) { RawNearTouch resolvedMask = rawMask | controller.ResolveToRawMask(virtualMask); if (((RawNearTouch)controller.previousState.NearTouches & resolvedMask) != 0) { return false; } if ((((RawNearTouch)controller.currentState.NearTouches & resolvedMask) != 0) && (((RawNearTouch)controller.previousState.NearTouches & resolvedMask) == 0)) { down = true; } } } return down; } /// <summary> /// Gets the current up state of the given virtual near touch mask with the given controller mask. /// Returns true if any masked near touch was released this frame on any masked controller and no other masked near touch is still down this frame. /// </summary> public static bool GetUp(NearTouch virtualMask, Controller controllerMask = Controller.Active) { return GetResolvedNearTouchUp(virtualMask, RawNearTouch.None, controllerMask); } /// <summary> /// Gets the current up state of the given raw near touch mask with the given controller mask. /// Returns true if any masked near touch was released this frame on any masked controller and no other masked near touch is still down this frame. /// </summary> public static bool GetUp(RawNearTouch rawMask, Controller controllerMask = Controller.Active) { return GetResolvedNearTouchUp(NearTouch.None, rawMask, controllerMask); } private static bool GetResolvedNearTouchUp(NearTouch virtualMask, RawNearTouch rawMask, Controller controllerMask) { bool up = false; if ((controllerMask & Controller.Active) != 0) controllerMask |= activeControllerType; for (int i = 0; i < controllers.Count; i++) { OVRControllerBase controller = controllers[i]; if (ShouldResolveController(controller.controllerType, controllerMask)) { RawNearTouch resolvedMask = rawMask | controller.ResolveToRawMask(virtualMask); if (((RawNearTouch)controller.currentState.NearTouches & resolvedMask) != 0) { return false; } if ((((RawNearTouch)controller.currentState.NearTouches & resolvedMask) == 0) && (((RawNearTouch)controller.previousState.NearTouches & resolvedMask) != 0)) { up = true; } } } return up; } /// <summary> /// Gets the current state of the given virtual 1-dimensional axis mask on the given controller mask. /// Returns the value of the largest masked axis across all masked controllers. Values range from 0 to 1. /// </summary> public static float Get(Axis1D virtualMask, Controller controllerMask = Controller.Active) { return GetResolvedAxis1D(virtualMask, RawAxis1D.None, controllerMask); } /// <summary> /// Gets the current state of the given raw 1-dimensional axis mask on the given controller mask. /// Returns the value of the largest masked axis across all masked controllers. Values range from 0 to 1. /// </summary> public static float Get(RawAxis1D rawMask, Controller controllerMask = Controller.Active) { return GetResolvedAxis1D(Axis1D.None, rawMask, controllerMask); } private static float GetResolvedAxis1D(Axis1D virtualMask, RawAxis1D rawMask, Controller controllerMask) { float maxAxis = 0.0f; if ((controllerMask & Controller.Active) != 0) controllerMask |= activeControllerType; for (int i = 0; i < controllers.Count; i++) { OVRControllerBase controller = controllers[i]; if (ShouldResolveController(controller.controllerType, controllerMask)) { RawAxis1D resolvedMask = rawMask | controller.ResolveToRawMask(virtualMask); if ((RawAxis1D.LIndexTrigger & resolvedMask) != 0) { float axis = controller.currentState.LIndexTrigger; if (controller.shouldApplyDeadzone) axis = CalculateDeadzone(axis, AXIS_DEADZONE_THRESHOLD); maxAxis = CalculateAbsMax(maxAxis, axis); } if ((RawAxis1D.RIndexTrigger & resolvedMask) != 0) { float axis = controller.currentState.RIndexTrigger; if (controller.shouldApplyDeadzone) axis = CalculateDeadzone(axis, AXIS_DEADZONE_THRESHOLD); maxAxis = CalculateAbsMax(maxAxis, axis); } if ((RawAxis1D.LHandTrigger & resolvedMask) != 0) { float axis = controller.currentState.LHandTrigger; if (controller.shouldApplyDeadzone) axis = CalculateDeadzone(axis, AXIS_DEADZONE_THRESHOLD); maxAxis = CalculateAbsMax(maxAxis, axis); } if ((RawAxis1D.RHandTrigger & resolvedMask) != 0) { float axis = controller.currentState.RHandTrigger; if (controller.shouldApplyDeadzone) axis = CalculateDeadzone(axis, AXIS_DEADZONE_THRESHOLD); maxAxis = CalculateAbsMax(maxAxis, axis); } } } return maxAxis; } /// <summary> /// Gets the current state of the given virtual 2-dimensional axis mask on the given controller mask. /// Returns the vector of the largest masked axis across all masked controllers. Values range from -1 to 1. /// </summary> public static Vector2 Get(Axis2D virtualMask, Controller controllerMask = Controller.Active) { return GetResolvedAxis2D(virtualMask, RawAxis2D.None, controllerMask); } /// <summary> /// Gets the current state of the given raw 2-dimensional axis mask on the given controller mask. /// Returns the vector of the largest masked axis across all masked controllers. Values range from -1 to 1. /// </summary> public static Vector2 Get(RawAxis2D rawMask, Controller controllerMask = Controller.Active) { return GetResolvedAxis2D(Axis2D.None, rawMask, controllerMask); } private static Vector2 GetResolvedAxis2D(Axis2D virtualMask, RawAxis2D rawMask, Controller controllerMask) { Vector2 maxAxis = Vector2.zero; if ((controllerMask & Controller.Active) != 0) controllerMask |= activeControllerType; for (int i = 0; i < controllers.Count; i++) { OVRControllerBase controller = controllers[i]; if (ShouldResolveController(controller.controllerType, controllerMask)) { RawAxis2D resolvedMask = rawMask | controller.ResolveToRawMask(virtualMask); if ((RawAxis2D.LThumbstick & resolvedMask) != 0) { Vector2 axis = new Vector2( controller.currentState.LThumbstick.x, controller.currentState.LThumbstick.y); if (controller.shouldApplyDeadzone) axis = CalculateDeadzone(axis, AXIS_DEADZONE_THRESHOLD); maxAxis = CalculateAbsMax(maxAxis, axis); } if ((RawAxis2D.LTouchpad & resolvedMask) != 0) { Vector2 axis = new Vector2( controller.currentState.LTouchpad.x, controller.currentState.LTouchpad.y); //if (controller.shouldApplyDeadzone) // axis = CalculateDeadzone(axis, AXIS_DEADZONE_THRESHOLD); maxAxis = CalculateAbsMax(maxAxis, axis); } if ((RawAxis2D.RThumbstick & resolvedMask) != 0) { Vector2 axis = new Vector2( controller.currentState.RThumbstick.x, controller.currentState.RThumbstick.y); if (controller.shouldApplyDeadzone) axis = CalculateDeadzone(axis, AXIS_DEADZONE_THRESHOLD); maxAxis = CalculateAbsMax(maxAxis, axis); } if ((RawAxis2D.RTouchpad & resolvedMask) != 0) { Vector2 axis = new Vector2( controller.currentState.RTouchpad.x, controller.currentState.RTouchpad.y); //if (controller.shouldApplyDeadzone) // axis = CalculateDeadzone(axis, AXIS_DEADZONE_THRESHOLD); maxAxis = CalculateAbsMax(maxAxis, axis); } } } return maxAxis; } /// <summary> /// Returns a mask of all currently connected controller types. /// </summary> public static Controller GetConnectedControllers() { return connectedControllerTypes; } /// <summary> /// Returns true if the specified controller type is currently connected. /// </summary> public static bool IsControllerConnected(Controller controller) { return (connectedControllerTypes & controller) == controller; } /// <summary> /// Returns the current active controller type. /// </summary> public static Controller GetActiveController() { return activeControllerType; } /// <summary> /// Activates vibration with the given frequency and amplitude with the given controller mask. /// Ignored on controllers that do not support vibration. Expected values range from 0 to 1. /// </summary> public static void SetControllerVibration(float frequency, float amplitude, Controller controllerMask = Controller.Active) { if ((controllerMask & Controller.Active) != 0) controllerMask |= activeControllerType; for (int i = 0; i < controllers.Count; i++) { OVRControllerBase controller = controllers[i]; if (ShouldResolveController(controller.controllerType, controllerMask)) { controller.SetControllerVibration(frequency, amplitude); } } } private static Vector2 CalculateAbsMax(Vector2 a, Vector2 b) { float absA = a.sqrMagnitude; float absB = b.sqrMagnitude; if (absA >= absB) return a; return b; } private static float CalculateAbsMax(float a, float b) { float absA = (a >= 0) ? a : -a; float absB = (b >= 0) ? b : -b; if (absA >= absB) return a; return b; } private static Vector2 CalculateDeadzone(Vector2 a, float deadzone) { if (a.sqrMagnitude <= (deadzone * deadzone)) return Vector2.zero; a *= ((a.magnitude - deadzone) / (1.0f - deadzone)); if (a.sqrMagnitude > 1.0f) return a.normalized; return a; } private static float CalculateDeadzone(float a, float deadzone) { float mag = (a >= 0) ? a : -a; if (mag <= deadzone) return 0.0f; a *= (mag - deadzone) / (1.0f - deadzone); if ((a * a) > 1.0f) return (a >= 0) ? 1.0f : -1.0f; return a; } private static bool ShouldResolveController(Controller controllerType, Controller controllerMask) { bool isValid = false; if ((controllerType & controllerMask) == controllerType) { isValid = true; } // If the mask requests both Touch controllers, reject the individual touch controllers. if (((controllerMask & Controller.Touch) == Controller.Touch) && ((controllerType & Controller.Touch) != 0) && ((controllerType & Controller.Touch) != Controller.Touch)) { isValid = false; } return isValid; } private abstract class OVRControllerBase { public class VirtualButtonMap { public RawButton None = RawButton.None; public RawButton One = RawButton.None; public RawButton Two = RawButton.None; public RawButton Three = RawButton.None; public RawButton Four = RawButton.None; public RawButton Start = RawButton.None; public RawButton Back = RawButton.None; public RawButton PrimaryShoulder = RawButton.None; public RawButton PrimaryIndexTrigger = RawButton.None; public RawButton PrimaryHandTrigger = RawButton.None; public RawButton PrimaryThumbstick = RawButton.None; public RawButton PrimaryThumbstickUp = RawButton.None; public RawButton PrimaryThumbstickDown = RawButton.None; public RawButton PrimaryThumbstickLeft = RawButton.None; public RawButton PrimaryThumbstickRight = RawButton.None; public RawButton PrimaryTouchpad = RawButton.None; public RawButton SecondaryShoulder = RawButton.None; public RawButton SecondaryIndexTrigger = RawButton.None; public RawButton SecondaryHandTrigger = RawButton.None; public RawButton SecondaryThumbstick = RawButton.None; public RawButton SecondaryThumbstickUp = RawButton.None; public RawButton SecondaryThumbstickDown = RawButton.None; public RawButton SecondaryThumbstickLeft = RawButton.None; public RawButton SecondaryThumbstickRight = RawButton.None; public RawButton SecondaryTouchpad = RawButton.None; public RawButton DpadUp = RawButton.None; public RawButton DpadDown = RawButton.None; public RawButton DpadLeft = RawButton.None; public RawButton DpadRight = RawButton.None; public RawButton Up = RawButton.None; public RawButton Down = RawButton.None; public RawButton Left = RawButton.None; public RawButton Right = RawButton.None; public RawButton ToRawMask(Button virtualMask) { RawButton rawMask = 0; if (virtualMask == Button.None) return RawButton.None; if ((virtualMask & Button.One) != 0) rawMask |= One; if ((virtualMask & Button.Two) != 0) rawMask |= Two; if ((virtualMask & Button.Three) != 0) rawMask |= Three; if ((virtualMask & Button.Four) != 0) rawMask |= Four; if ((virtualMask & Button.Start) != 0) rawMask |= Start; if ((virtualMask & Button.Back) != 0) rawMask |= Back; if ((virtualMask & Button.PrimaryShoulder) != 0) rawMask |= PrimaryShoulder; if ((virtualMask & Button.PrimaryIndexTrigger) != 0) rawMask |= PrimaryIndexTrigger; if ((virtualMask & Button.PrimaryHandTrigger) != 0) rawMask |= PrimaryHandTrigger; if ((virtualMask & Button.PrimaryThumbstick) != 0) rawMask |= PrimaryThumbstick; if ((virtualMask & Button.PrimaryThumbstickUp) != 0) rawMask |= PrimaryThumbstickUp; if ((virtualMask & Button.PrimaryThumbstickDown) != 0) rawMask |= PrimaryThumbstickDown; if ((virtualMask & Button.PrimaryThumbstickLeft) != 0) rawMask |= PrimaryThumbstickLeft; if ((virtualMask & Button.PrimaryThumbstickRight) != 0) rawMask |= PrimaryThumbstickRight; if ((virtualMask & Button.PrimaryTouchpad) != 0) rawMask |= PrimaryTouchpad; if ((virtualMask & Button.SecondaryShoulder) != 0) rawMask |= SecondaryShoulder; if ((virtualMask & Button.SecondaryIndexTrigger) != 0) rawMask |= SecondaryIndexTrigger; if ((virtualMask & Button.SecondaryHandTrigger) != 0) rawMask |= SecondaryHandTrigger; if ((virtualMask & Button.SecondaryThumbstick) != 0) rawMask |= SecondaryThumbstick; if ((virtualMask & Button.SecondaryThumbstickUp) != 0) rawMask |= SecondaryThumbstickUp; if ((virtualMask & Button.SecondaryThumbstickDown) != 0) rawMask |= SecondaryThumbstickDown; if ((virtualMask & Button.SecondaryThumbstickLeft) != 0) rawMask |= SecondaryThumbstickLeft; if ((virtualMask & Button.SecondaryThumbstickRight) != 0) rawMask |= SecondaryThumbstickRight; if ((virtualMask & Button.SecondaryTouchpad) != 0) rawMask |= SecondaryTouchpad; if ((virtualMask & Button.DpadUp) != 0) rawMask |= DpadUp; if ((virtualMask & Button.DpadDown) != 0) rawMask |= DpadDown; if ((virtualMask & Button.DpadLeft) != 0) rawMask |= DpadLeft; if ((virtualMask & Button.DpadRight) != 0) rawMask |= DpadRight; if ((virtualMask & Button.Up) != 0) rawMask |= Up; if ((virtualMask & Button.Down) != 0) rawMask |= Down; if ((virtualMask & Button.Left) != 0) rawMask |= Left; if ((virtualMask & Button.Right) != 0) rawMask |= Right; return rawMask; } } public class VirtualTouchMap { public RawTouch None = RawTouch.None; public RawTouch One = RawTouch.None; public RawTouch Two = RawTouch.None; public RawTouch Three = RawTouch.None; public RawTouch Four = RawTouch.None; public RawTouch PrimaryIndexTrigger = RawTouch.None; public RawTouch PrimaryThumbstick = RawTouch.None; public RawTouch PrimaryThumbRest = RawTouch.None; public RawTouch PrimaryTouchpad = RawTouch.None; public RawTouch SecondaryIndexTrigger = RawTouch.None; public RawTouch SecondaryThumbstick = RawTouch.None; public RawTouch SecondaryThumbRest = RawTouch.None; public RawTouch SecondaryTouchpad = RawTouch.None; public RawTouch ToRawMask(Touch virtualMask) { RawTouch rawMask = 0; if (virtualMask == Touch.None) return RawTouch.None; if ((virtualMask & Touch.One) != 0) rawMask |= One; if ((virtualMask & Touch.Two) != 0) rawMask |= Two; if ((virtualMask & Touch.Three) != 0) rawMask |= Three; if ((virtualMask & Touch.Four) != 0) rawMask |= Four; if ((virtualMask & Touch.PrimaryIndexTrigger) != 0) rawMask |= PrimaryIndexTrigger; if ((virtualMask & Touch.PrimaryThumbstick) != 0) rawMask |= PrimaryThumbstick; if ((virtualMask & Touch.PrimaryThumbRest) != 0) rawMask |= PrimaryThumbRest; if ((virtualMask & Touch.PrimaryTouchpad) != 0) rawMask |= PrimaryTouchpad; if ((virtualMask & Touch.SecondaryIndexTrigger) != 0) rawMask |= SecondaryIndexTrigger; if ((virtualMask & Touch.SecondaryThumbstick) != 0) rawMask |= SecondaryThumbstick; if ((virtualMask & Touch.SecondaryThumbRest) != 0) rawMask |= SecondaryThumbRest; if ((virtualMask & Touch.SecondaryTouchpad) != 0) rawMask |= SecondaryTouchpad; return rawMask; } } public class VirtualNearTouchMap { public RawNearTouch None = RawNearTouch.None; public RawNearTouch PrimaryIndexTrigger = RawNearTouch.None; public RawNearTouch PrimaryThumbButtons = RawNearTouch.None; public RawNearTouch SecondaryIndexTrigger = RawNearTouch.None; public RawNearTouch SecondaryThumbButtons = RawNearTouch.None; public RawNearTouch ToRawMask(NearTouch virtualMask) { RawNearTouch rawMask = 0; if (virtualMask == NearTouch.None) return RawNearTouch.None; if ((virtualMask & NearTouch.PrimaryIndexTrigger) != 0) rawMask |= PrimaryIndexTrigger; if ((virtualMask & NearTouch.PrimaryThumbButtons) != 0) rawMask |= PrimaryThumbButtons; if ((virtualMask & NearTouch.SecondaryIndexTrigger) != 0) rawMask |= SecondaryIndexTrigger; if ((virtualMask & NearTouch.SecondaryThumbButtons) != 0) rawMask |= SecondaryThumbButtons; return rawMask; } } public class VirtualAxis1DMap { public RawAxis1D None = RawAxis1D.None; public RawAxis1D PrimaryIndexTrigger = RawAxis1D.None; public RawAxis1D PrimaryHandTrigger = RawAxis1D.None; public RawAxis1D SecondaryIndexTrigger = RawAxis1D.None; public RawAxis1D SecondaryHandTrigger = RawAxis1D.None; public RawAxis1D ToRawMask(Axis1D virtualMask) { RawAxis1D rawMask = 0; if (virtualMask == Axis1D.None) return RawAxis1D.None; if ((virtualMask & Axis1D.PrimaryIndexTrigger) != 0) rawMask |= PrimaryIndexTrigger; if ((virtualMask & Axis1D.PrimaryHandTrigger) != 0) rawMask |= PrimaryHandTrigger; if ((virtualMask & Axis1D.SecondaryIndexTrigger) != 0) rawMask |= SecondaryIndexTrigger; if ((virtualMask & Axis1D.SecondaryHandTrigger) != 0) rawMask |= SecondaryHandTrigger; return rawMask; } } public class VirtualAxis2DMap { public RawAxis2D None = RawAxis2D.None; public RawAxis2D PrimaryThumbstick = RawAxis2D.None; public RawAxis2D PrimaryTouchpad = RawAxis2D.None; public RawAxis2D SecondaryThumbstick = RawAxis2D.None; public RawAxis2D SecondaryTouchpad = RawAxis2D.None; public RawAxis2D ToRawMask(Axis2D virtualMask) { RawAxis2D rawMask = 0; if (virtualMask == Axis2D.None) return RawAxis2D.None; if ((virtualMask & Axis2D.PrimaryThumbstick) != 0) rawMask |= PrimaryThumbstick; if ((virtualMask & Axis2D.PrimaryTouchpad) != 0) rawMask |= PrimaryTouchpad; if ((virtualMask & Axis2D.SecondaryThumbstick) != 0) rawMask |= SecondaryThumbstick; if ((virtualMask & Axis2D.SecondaryTouchpad) != 0) rawMask |= SecondaryTouchpad; return rawMask; } } public Controller controllerType = Controller.None; public VirtualButtonMap buttonMap = new VirtualButtonMap(); public VirtualTouchMap touchMap = new VirtualTouchMap(); public VirtualNearTouchMap nearTouchMap = new VirtualNearTouchMap(); public VirtualAxis1DMap axis1DMap = new VirtualAxis1DMap(); public VirtualAxis2DMap axis2DMap = new VirtualAxis2DMap(); public OVRPlugin.ControllerState2 previousState = new OVRPlugin.ControllerState2(); public OVRPlugin.ControllerState2 currentState = new OVRPlugin.ControllerState2(); public bool shouldApplyDeadzone = true; public OVRControllerBase() { ConfigureButtonMap(); ConfigureTouchMap(); ConfigureNearTouchMap(); ConfigureAxis1DMap(); ConfigureAxis2DMap(); } public virtual Controller Update() { OVRPlugin.ControllerState2 state = OVRPlugin.GetControllerState2((uint)controllerType); //Debug.Log("MalibuManaged - " + (state.Touches & (uint)RawTouch.LTouchpad) + " " + state.LTouchpad.x + " " + state.LTouchpad.y + " " + state.RTouchpad.x + " " + state.RTouchpad.y); if (state.LIndexTrigger >= AXIS_AS_BUTTON_THRESHOLD) state.Buttons |= (uint)RawButton.LIndexTrigger; if (state.LHandTrigger >= AXIS_AS_BUTTON_THRESHOLD) state.Buttons |= (uint)RawButton.LHandTrigger; if (state.LThumbstick.y >= AXIS_AS_BUTTON_THRESHOLD) state.Buttons |= (uint)RawButton.LThumbstickUp; if (state.LThumbstick.y <= -AXIS_AS_BUTTON_THRESHOLD) state.Buttons |= (uint)RawButton.LThumbstickDown; if (state.LThumbstick.x <= -AXIS_AS_BUTTON_THRESHOLD) state.Buttons |= (uint)RawButton.LThumbstickLeft; if (state.LThumbstick.x >= AXIS_AS_BUTTON_THRESHOLD) state.Buttons |= (uint)RawButton.LThumbstickRight; if (state.RIndexTrigger >= AXIS_AS_BUTTON_THRESHOLD) state.Buttons |= (uint)RawButton.RIndexTrigger; if (state.RHandTrigger >= AXIS_AS_BUTTON_THRESHOLD) state.Buttons |= (uint)RawButton.RHandTrigger; if (state.RThumbstick.y >= AXIS_AS_BUTTON_THRESHOLD) state.Buttons |= (uint)RawButton.RThumbstickUp; if (state.RThumbstick.y <= -AXIS_AS_BUTTON_THRESHOLD) state.Buttons |= (uint)RawButton.RThumbstickDown; if (state.RThumbstick.x <= -AXIS_AS_BUTTON_THRESHOLD) state.Buttons |= (uint)RawButton.RThumbstickLeft; if (state.RThumbstick.x >= AXIS_AS_BUTTON_THRESHOLD) state.Buttons |= (uint)RawButton.RThumbstickRight; previousState = currentState; currentState = state; return ((Controller)currentState.ConnectedControllers & controllerType); } public virtual void SetControllerVibration(float frequency, float amplitude) { OVRPlugin.SetControllerVibration((uint)controllerType, frequency, amplitude); } public abstract void ConfigureButtonMap(); public abstract void ConfigureTouchMap(); public abstract void ConfigureNearTouchMap(); public abstract void ConfigureAxis1DMap(); public abstract void ConfigureAxis2DMap(); public RawButton ResolveToRawMask(Button virtualMask) { return buttonMap.ToRawMask(virtualMask); } public RawTouch ResolveToRawMask(Touch virtualMask) { return touchMap.ToRawMask(virtualMask); } public RawNearTouch ResolveToRawMask(NearTouch virtualMask) { return nearTouchMap.ToRawMask(virtualMask); } public RawAxis1D ResolveToRawMask(Axis1D virtualMask) { return axis1DMap.ToRawMask(virtualMask); } public RawAxis2D ResolveToRawMask(Axis2D virtualMask) { return axis2DMap.ToRawMask(virtualMask); } } private class OVRControllerTouch : OVRControllerBase { public OVRControllerTouch() { controllerType = Controller.Touch; } public override void ConfigureButtonMap() { buttonMap.None = RawButton.None; buttonMap.One = RawButton.A; buttonMap.Two = RawButton.B; buttonMap.Three = RawButton.X; buttonMap.Four = RawButton.Y; buttonMap.Start = RawButton.Start; buttonMap.Back = RawButton.None; buttonMap.PrimaryShoulder = RawButton.None; buttonMap.PrimaryIndexTrigger = RawButton.LIndexTrigger; buttonMap.PrimaryHandTrigger = RawButton.LHandTrigger; buttonMap.PrimaryThumbstick = RawButton.LThumbstick; buttonMap.PrimaryThumbstickUp = RawButton.LThumbstickUp; buttonMap.PrimaryThumbstickDown = RawButton.LThumbstickDown; buttonMap.PrimaryThumbstickLeft = RawButton.LThumbstickLeft; buttonMap.PrimaryThumbstickRight = RawButton.LThumbstickRight; buttonMap.PrimaryTouchpad = RawButton.None; buttonMap.SecondaryShoulder = RawButton.None; buttonMap.SecondaryIndexTrigger = RawButton.RIndexTrigger; buttonMap.SecondaryHandTrigger = RawButton.RHandTrigger; buttonMap.SecondaryThumbstick = RawButton.RThumbstick; buttonMap.SecondaryThumbstickUp = RawButton.RThumbstickUp; buttonMap.SecondaryThumbstickDown = RawButton.RThumbstickDown; buttonMap.SecondaryThumbstickLeft = RawButton.RThumbstickLeft; buttonMap.SecondaryThumbstickRight = RawButton.RThumbstickRight; buttonMap.SecondaryTouchpad = RawButton.None; buttonMap.DpadUp = RawButton.None; buttonMap.DpadDown = RawButton.None; buttonMap.DpadLeft = RawButton.None; buttonMap.DpadRight = RawButton.None; buttonMap.Up = RawButton.LThumbstickUp; buttonMap.Down = RawButton.LThumbstickDown; buttonMap.Left = RawButton.LThumbstickLeft; buttonMap.Right = RawButton.LThumbstickRight; } public override void ConfigureTouchMap() { touchMap.None = RawTouch.None; touchMap.One = RawTouch.A; touchMap.Two = RawTouch.B; touchMap.Three = RawTouch.X; touchMap.Four = RawTouch.Y; touchMap.PrimaryIndexTrigger = RawTouch.LIndexTrigger; touchMap.PrimaryThumbstick = RawTouch.LThumbstick; touchMap.PrimaryThumbRest = RawTouch.LThumbRest; touchMap.PrimaryTouchpad = RawTouch.None; touchMap.SecondaryIndexTrigger = RawTouch.RIndexTrigger; touchMap.SecondaryThumbstick = RawTouch.RThumbstick; touchMap.SecondaryThumbRest = RawTouch.RThumbRest; touchMap.SecondaryTouchpad = RawTouch.None; } public override void ConfigureNearTouchMap() { nearTouchMap.None = RawNearTouch.None; nearTouchMap.PrimaryIndexTrigger = RawNearTouch.LIndexTrigger; nearTouchMap.PrimaryThumbButtons = RawNearTouch.LThumbButtons; nearTouchMap.SecondaryIndexTrigger = RawNearTouch.RIndexTrigger; nearTouchMap.SecondaryThumbButtons = RawNearTouch.RThumbButtons; } public override void ConfigureAxis1DMap() { axis1DMap.None = RawAxis1D.None; axis1DMap.PrimaryIndexTrigger = RawAxis1D.LIndexTrigger; axis1DMap.PrimaryHandTrigger = RawAxis1D.LHandTrigger; axis1DMap.SecondaryIndexTrigger = RawAxis1D.RIndexTrigger; axis1DMap.SecondaryHandTrigger = RawAxis1D.RHandTrigger; } public override void ConfigureAxis2DMap() { axis2DMap.None = RawAxis2D.None; axis2DMap.PrimaryThumbstick = RawAxis2D.LThumbstick; axis2DMap.PrimaryTouchpad = RawAxis2D.None; axis2DMap.SecondaryThumbstick = RawAxis2D.RThumbstick; axis2DMap.SecondaryTouchpad = RawAxis2D.None; } } private class OVRControllerLTouch : OVRControllerBase { public OVRControllerLTouch() { controllerType = Controller.LTouch; } public override void ConfigureButtonMap() { buttonMap.None = RawButton.None; buttonMap.One = RawButton.X; buttonMap.Two = RawButton.Y; buttonMap.Three = RawButton.None; buttonMap.Four = RawButton.None; buttonMap.Start = RawButton.Start; buttonMap.Back = RawButton.None; buttonMap.PrimaryShoulder = RawButton.None; buttonMap.PrimaryIndexTrigger = RawButton.LIndexTrigger; buttonMap.PrimaryHandTrigger = RawButton.LHandTrigger; buttonMap.PrimaryThumbstick = RawButton.LThumbstick; buttonMap.PrimaryThumbstickUp = RawButton.LThumbstickUp; buttonMap.PrimaryThumbstickDown = RawButton.LThumbstickDown; buttonMap.PrimaryThumbstickLeft = RawButton.LThumbstickLeft; buttonMap.PrimaryThumbstickRight = RawButton.LThumbstickRight; buttonMap.PrimaryTouchpad = RawButton.None; buttonMap.SecondaryShoulder = RawButton.None; buttonMap.SecondaryIndexTrigger = RawButton.None; buttonMap.SecondaryHandTrigger = RawButton.None; buttonMap.SecondaryThumbstick = RawButton.None; buttonMap.SecondaryThumbstickUp = RawButton.None; buttonMap.SecondaryThumbstickDown = RawButton.None; buttonMap.SecondaryThumbstickLeft = RawButton.None; buttonMap.SecondaryThumbstickRight = RawButton.None; buttonMap.SecondaryTouchpad = RawButton.None; buttonMap.DpadUp = RawButton.None; buttonMap.DpadDown = RawButton.None; buttonMap.DpadLeft = RawButton.None; buttonMap.DpadRight = RawButton.None; buttonMap.Up = RawButton.LThumbstickUp; buttonMap.Down = RawButton.LThumbstickDown; buttonMap.Left = RawButton.LThumbstickLeft; buttonMap.Right = RawButton.LThumbstickRight; } public override void ConfigureTouchMap() { touchMap.None = RawTouch.None; touchMap.One = RawTouch.X; touchMap.Two = RawTouch.Y; touchMap.Three = RawTouch.None; touchMap.Four = RawTouch.None; touchMap.PrimaryIndexTrigger = RawTouch.LIndexTrigger; touchMap.PrimaryThumbstick = RawTouch.LThumbstick; touchMap.PrimaryThumbRest = RawTouch.LThumbRest; touchMap.PrimaryTouchpad = RawTouch.None; touchMap.SecondaryIndexTrigger = RawTouch.None; touchMap.SecondaryThumbstick = RawTouch.None; touchMap.SecondaryThumbRest = RawTouch.None; touchMap.SecondaryTouchpad = RawTouch.None; } public override void ConfigureNearTouchMap() { nearTouchMap.None = RawNearTouch.None; nearTouchMap.PrimaryIndexTrigger = RawNearTouch.LIndexTrigger; nearTouchMap.PrimaryThumbButtons = RawNearTouch.LThumbButtons; nearTouchMap.SecondaryIndexTrigger = RawNearTouch.None; nearTouchMap.SecondaryThumbButtons = RawNearTouch.None; } public override void ConfigureAxis1DMap() { axis1DMap.None = RawAxis1D.None; axis1DMap.PrimaryIndexTrigger = RawAxis1D.LIndexTrigger; axis1DMap.PrimaryHandTrigger = RawAxis1D.LHandTrigger; axis1DMap.SecondaryIndexTrigger = RawAxis1D.None; axis1DMap.SecondaryHandTrigger = RawAxis1D.None; } public override void ConfigureAxis2DMap() { axis2DMap.None = RawAxis2D.None; axis2DMap.PrimaryThumbstick = RawAxis2D.LThumbstick; axis2DMap.PrimaryTouchpad = RawAxis2D.None; axis2DMap.SecondaryThumbstick = RawAxis2D.None; axis2DMap.SecondaryTouchpad = RawAxis2D.None; } } private class OVRControllerRTouch : OVRControllerBase { public OVRControllerRTouch() { controllerType = Controller.RTouch; } public override void ConfigureButtonMap() { buttonMap.None = RawButton.None; buttonMap.One = RawButton.A; buttonMap.Two = RawButton.B; buttonMap.Three = RawButton.None; buttonMap.Four = RawButton.None; buttonMap.Start = RawButton.None; buttonMap.Back = RawButton.None; buttonMap.PrimaryShoulder = RawButton.None; buttonMap.PrimaryIndexTrigger = RawButton.RIndexTrigger; buttonMap.PrimaryHandTrigger = RawButton.RHandTrigger; buttonMap.PrimaryThumbstick = RawButton.RThumbstick; buttonMap.PrimaryThumbstickUp = RawButton.RThumbstickUp; buttonMap.PrimaryThumbstickDown = RawButton.RThumbstickDown; buttonMap.PrimaryThumbstickLeft = RawButton.RThumbstickLeft; buttonMap.PrimaryThumbstickRight = RawButton.RThumbstickRight; buttonMap.PrimaryTouchpad = RawButton.None; buttonMap.SecondaryShoulder = RawButton.None; buttonMap.SecondaryIndexTrigger = RawButton.None; buttonMap.SecondaryHandTrigger = RawButton.None; buttonMap.SecondaryThumbstick = RawButton.None; buttonMap.SecondaryThumbstickUp = RawButton.None; buttonMap.SecondaryThumbstickDown = RawButton.None; buttonMap.SecondaryThumbstickLeft = RawButton.None; buttonMap.SecondaryThumbstickRight = RawButton.None; buttonMap.SecondaryTouchpad = RawButton.None; buttonMap.DpadUp = RawButton.None; buttonMap.DpadDown = RawButton.None; buttonMap.DpadLeft = RawButton.None; buttonMap.DpadRight = RawButton.None; buttonMap.Up = RawButton.RThumbstickUp; buttonMap.Down = RawButton.RThumbstickDown; buttonMap.Left = RawButton.RThumbstickLeft; buttonMap.Right = RawButton.RThumbstickRight; } public override void ConfigureTouchMap() { touchMap.None = RawTouch.None; touchMap.One = RawTouch.A; touchMap.Two = RawTouch.B; touchMap.Three = RawTouch.None; touchMap.Four = RawTouch.None; touchMap.PrimaryIndexTrigger = RawTouch.RIndexTrigger; touchMap.PrimaryThumbstick = RawTouch.RThumbstick; touchMap.PrimaryThumbRest = RawTouch.RThumbRest; touchMap.PrimaryTouchpad = RawTouch.None; touchMap.SecondaryIndexTrigger = RawTouch.None; touchMap.SecondaryThumbstick = RawTouch.None; touchMap.SecondaryThumbRest = RawTouch.None; touchMap.SecondaryTouchpad = RawTouch.None; } public override void ConfigureNearTouchMap() { nearTouchMap.None = RawNearTouch.None; nearTouchMap.PrimaryIndexTrigger = RawNearTouch.RIndexTrigger; nearTouchMap.PrimaryThumbButtons = RawNearTouch.RThumbButtons; nearTouchMap.SecondaryIndexTrigger = RawNearTouch.None; nearTouchMap.SecondaryThumbButtons = RawNearTouch.None; } public override void ConfigureAxis1DMap() { axis1DMap.None = RawAxis1D.None; axis1DMap.PrimaryIndexTrigger = RawAxis1D.RIndexTrigger; axis1DMap.PrimaryHandTrigger = RawAxis1D.RHandTrigger; axis1DMap.SecondaryIndexTrigger = RawAxis1D.None; axis1DMap.SecondaryHandTrigger = RawAxis1D.None; } public override void ConfigureAxis2DMap() { axis2DMap.None = RawAxis2D.None; axis2DMap.PrimaryThumbstick = RawAxis2D.RThumbstick; axis2DMap.PrimaryTouchpad = RawAxis2D.None; axis2DMap.SecondaryThumbstick = RawAxis2D.None; axis2DMap.SecondaryTouchpad = RawAxis2D.None; } } private class OVRControllerRemote : OVRControllerBase { public OVRControllerRemote() { controllerType = Controller.Remote; } public override void ConfigureButtonMap() { buttonMap.None = RawButton.None; buttonMap.One = RawButton.Start; buttonMap.Two = RawButton.Back; buttonMap.Three = RawButton.None; buttonMap.Four = RawButton.None; buttonMap.Start = RawButton.Start; buttonMap.Back = RawButton.Back; buttonMap.PrimaryShoulder = RawButton.None; buttonMap.PrimaryIndexTrigger = RawButton.None; buttonMap.PrimaryHandTrigger = RawButton.None; buttonMap.PrimaryThumbstick = RawButton.None; buttonMap.PrimaryThumbstickUp = RawButton.None; buttonMap.PrimaryThumbstickDown = RawButton.None; buttonMap.PrimaryThumbstickLeft = RawButton.None; buttonMap.PrimaryThumbstickRight = RawButton.None; buttonMap.PrimaryTouchpad = RawButton.None; buttonMap.SecondaryShoulder = RawButton.None; buttonMap.SecondaryIndexTrigger = RawButton.None; buttonMap.SecondaryHandTrigger = RawButton.None; buttonMap.SecondaryThumbstick = RawButton.None; buttonMap.SecondaryThumbstickUp = RawButton.None; buttonMap.SecondaryThumbstickDown = RawButton.None; buttonMap.SecondaryThumbstickLeft = RawButton.None; buttonMap.SecondaryThumbstickRight = RawButton.None; buttonMap.SecondaryTouchpad = RawButton.None; buttonMap.DpadUp = RawButton.DpadUp; buttonMap.DpadDown = RawButton.DpadDown; buttonMap.DpadLeft = RawButton.DpadLeft; buttonMap.DpadRight = RawButton.DpadRight; buttonMap.Up = RawButton.DpadUp; buttonMap.Down = RawButton.DpadDown; buttonMap.Left = RawButton.DpadLeft; buttonMap.Right = RawButton.DpadRight; } public override void ConfigureTouchMap() { touchMap.None = RawTouch.None; touchMap.One = RawTouch.None; touchMap.Two = RawTouch.None; touchMap.Three = RawTouch.None; touchMap.Four = RawTouch.None; touchMap.PrimaryIndexTrigger = RawTouch.None; touchMap.PrimaryThumbstick = RawTouch.None; touchMap.PrimaryThumbRest = RawTouch.None; touchMap.PrimaryTouchpad = RawTouch.None; touchMap.SecondaryIndexTrigger = RawTouch.None; touchMap.SecondaryThumbstick = RawTouch.None; touchMap.SecondaryThumbRest = RawTouch.None; touchMap.SecondaryTouchpad = RawTouch.None; } public override void ConfigureNearTouchMap() { nearTouchMap.None = RawNearTouch.None; nearTouchMap.PrimaryIndexTrigger = RawNearTouch.None; nearTouchMap.PrimaryThumbButtons = RawNearTouch.None; nearTouchMap.SecondaryIndexTrigger = RawNearTouch.None; nearTouchMap.SecondaryThumbButtons = RawNearTouch.None; } public override void ConfigureAxis1DMap() { axis1DMap.None = RawAxis1D.None; axis1DMap.PrimaryIndexTrigger = RawAxis1D.None; axis1DMap.PrimaryHandTrigger = RawAxis1D.None; axis1DMap.SecondaryIndexTrigger = RawAxis1D.None; axis1DMap.SecondaryHandTrigger = RawAxis1D.None; } public override void ConfigureAxis2DMap() { axis2DMap.None = RawAxis2D.None; axis2DMap.PrimaryThumbstick = RawAxis2D.None; axis2DMap.PrimaryTouchpad = RawAxis2D.None; axis2DMap.SecondaryThumbstick = RawAxis2D.None; axis2DMap.SecondaryTouchpad = RawAxis2D.None; } } private class OVRControllerGamepadPC : OVRControllerBase { public OVRControllerGamepadPC() { controllerType = Controller.Gamepad; } public override void ConfigureButtonMap() { buttonMap.None = RawButton.None; buttonMap.One = RawButton.A; buttonMap.Two = RawButton.B; buttonMap.Three = RawButton.X; buttonMap.Four = RawButton.Y; buttonMap.Start = RawButton.Start; buttonMap.Back = RawButton.Back; buttonMap.PrimaryShoulder = RawButton.LShoulder; buttonMap.PrimaryIndexTrigger = RawButton.LIndexTrigger; buttonMap.PrimaryHandTrigger = RawButton.None; buttonMap.PrimaryThumbstick = RawButton.LThumbstick; buttonMap.PrimaryThumbstickUp = RawButton.LThumbstickUp; buttonMap.PrimaryThumbstickDown = RawButton.LThumbstickDown; buttonMap.PrimaryThumbstickLeft = RawButton.LThumbstickLeft; buttonMap.PrimaryThumbstickRight = RawButton.LThumbstickRight; buttonMap.PrimaryTouchpad = RawButton.None; buttonMap.SecondaryShoulder = RawButton.RShoulder; buttonMap.SecondaryIndexTrigger = RawButton.RIndexTrigger; buttonMap.SecondaryHandTrigger = RawButton.None; buttonMap.SecondaryThumbstick = RawButton.RThumbstick; buttonMap.SecondaryThumbstickUp = RawButton.RThumbstickUp; buttonMap.SecondaryThumbstickDown = RawButton.RThumbstickDown; buttonMap.SecondaryThumbstickLeft = RawButton.RThumbstickLeft; buttonMap.SecondaryThumbstickRight = RawButton.RThumbstickRight; buttonMap.SecondaryTouchpad = RawButton.None; buttonMap.DpadUp = RawButton.DpadUp; buttonMap.DpadDown = RawButton.DpadDown; buttonMap.DpadLeft = RawButton.DpadLeft; buttonMap.DpadRight = RawButton.DpadRight; buttonMap.Up = RawButton.LThumbstickUp; buttonMap.Down = RawButton.LThumbstickDown; buttonMap.Left = RawButton.LThumbstickLeft; buttonMap.Right = RawButton.LThumbstickRight; } public override void ConfigureTouchMap() { touchMap.None = RawTouch.None; touchMap.One = RawTouch.None; touchMap.Two = RawTouch.None; touchMap.Three = RawTouch.None; touchMap.Four = RawTouch.None; touchMap.PrimaryIndexTrigger = RawTouch.None; touchMap.PrimaryThumbstick = RawTouch.None; touchMap.PrimaryThumbRest = RawTouch.None; touchMap.PrimaryTouchpad = RawTouch.None; touchMap.SecondaryIndexTrigger = RawTouch.None; touchMap.SecondaryThumbstick = RawTouch.None; touchMap.SecondaryThumbRest = RawTouch.None; touchMap.SecondaryTouchpad = RawTouch.None; } public override void ConfigureNearTouchMap() { nearTouchMap.None = RawNearTouch.None; nearTouchMap.PrimaryIndexTrigger = RawNearTouch.None; nearTouchMap.PrimaryThumbButtons = RawNearTouch.None; nearTouchMap.SecondaryIndexTrigger = RawNearTouch.None; nearTouchMap.SecondaryThumbButtons = RawNearTouch.None; } public override void ConfigureAxis1DMap() { axis1DMap.None = RawAxis1D.None; axis1DMap.PrimaryIndexTrigger = RawAxis1D.LIndexTrigger; axis1DMap.PrimaryHandTrigger = RawAxis1D.None; axis1DMap.SecondaryIndexTrigger = RawAxis1D.RIndexTrigger; axis1DMap.SecondaryHandTrigger = RawAxis1D.None; } public override void ConfigureAxis2DMap() { axis2DMap.None = RawAxis2D.None; axis2DMap.PrimaryThumbstick = RawAxis2D.LThumbstick; axis2DMap.PrimaryTouchpad = RawAxis2D.None; axis2DMap.SecondaryThumbstick = RawAxis2D.RThumbstick; axis2DMap.SecondaryTouchpad = RawAxis2D.None; } } private class OVRControllerGamepadMac : OVRControllerBase { /// <summary> An axis on the gamepad. </summary> private enum AxisGPC { None = -1, LeftXAxis = 0, LeftYAxis, RightXAxis, RightYAxis, LeftTrigger, RightTrigger, DPad_X_Axis, DPad_Y_Axis, Max, }; /// <summary> A button on the gamepad. </summary> public enum ButtonGPC { None = -1, A = 0, B, X, Y, Up, Down, Left, Right, Start, Back, LStick, RStick, LeftShoulder, RightShoulder, Max }; private bool initialized = false; public OVRControllerGamepadMac() { controllerType = Controller.Gamepad; initialized = OVR_GamepadController_Initialize(); } ~OVRControllerGamepadMac() { if (!initialized) return; OVR_GamepadController_Destroy(); } public override Controller Update() { if (!initialized) { return Controller.None; } OVRPlugin.ControllerState2 state = new OVRPlugin.ControllerState2(); bool result = OVR_GamepadController_Update(); if (result) state.ConnectedControllers = (uint)Controller.Gamepad; if (OVR_GamepadController_GetButton((int)ButtonGPC.A)) state.Buttons |= (uint)RawButton.A; if (OVR_GamepadController_GetButton((int)ButtonGPC.B)) state.Buttons |= (uint)RawButton.B; if (OVR_GamepadController_GetButton((int)ButtonGPC.X)) state.Buttons |= (uint)RawButton.X; if (OVR_GamepadController_GetButton((int)ButtonGPC.Y)) state.Buttons |= (uint)RawButton.Y; if (OVR_GamepadController_GetButton((int)ButtonGPC.Up)) state.Buttons |= (uint)RawButton.DpadUp; if (OVR_GamepadController_GetButton((int)ButtonGPC.Down)) state.Buttons |= (uint)RawButton.DpadDown; if (OVR_GamepadController_GetButton((int)ButtonGPC.Left)) state.Buttons |= (uint)RawButton.DpadLeft; if (OVR_GamepadController_GetButton((int)ButtonGPC.Right)) state.Buttons |= (uint)RawButton.DpadRight; if (OVR_GamepadController_GetButton((int)ButtonGPC.Start)) state.Buttons |= (uint)RawButton.Start; if (OVR_GamepadController_GetButton((int)ButtonGPC.Back)) state.Buttons |= (uint)RawButton.Back; if (OVR_GamepadController_GetButton((int)ButtonGPC.LStick)) state.Buttons |= (uint)RawButton.LThumbstick; if (OVR_GamepadController_GetButton((int)ButtonGPC.RStick)) state.Buttons |= (uint)RawButton.RThumbstick; if (OVR_GamepadController_GetButton((int)ButtonGPC.LeftShoulder)) state.Buttons |= (uint)RawButton.LShoulder; if (OVR_GamepadController_GetButton((int)ButtonGPC.RightShoulder)) state.Buttons |= (uint)RawButton.RShoulder; state.LThumbstick.x = OVR_GamepadController_GetAxis((int)AxisGPC.LeftXAxis); state.LThumbstick.y = OVR_GamepadController_GetAxis((int)AxisGPC.LeftYAxis); state.RThumbstick.x = OVR_GamepadController_GetAxis((int)AxisGPC.RightXAxis); state.RThumbstick.y = OVR_GamepadController_GetAxis((int)AxisGPC.RightYAxis); state.LIndexTrigger = OVR_GamepadController_GetAxis((int)AxisGPC.LeftTrigger); state.RIndexTrigger = OVR_GamepadController_GetAxis((int)AxisGPC.RightTrigger); if (state.LIndexTrigger >= AXIS_AS_BUTTON_THRESHOLD) state.Buttons |= (uint)RawButton.LIndexTrigger; if (state.LHandTrigger >= AXIS_AS_BUTTON_THRESHOLD) state.Buttons |= (uint)RawButton.LHandTrigger; if (state.LThumbstick.y >= AXIS_AS_BUTTON_THRESHOLD) state.Buttons |= (uint)RawButton.LThumbstickUp; if (state.LThumbstick.y <= -AXIS_AS_BUTTON_THRESHOLD) state.Buttons |= (uint)RawButton.LThumbstickDown; if (state.LThumbstick.x <= -AXIS_AS_BUTTON_THRESHOLD) state.Buttons |= (uint)RawButton.LThumbstickLeft; if (state.LThumbstick.x >= AXIS_AS_BUTTON_THRESHOLD) state.Buttons |= (uint)RawButton.LThumbstickRight; if (state.RIndexTrigger >= AXIS_AS_BUTTON_THRESHOLD) state.Buttons |= (uint)RawButton.RIndexTrigger; if (state.RHandTrigger >= AXIS_AS_BUTTON_THRESHOLD) state.Buttons |= (uint)RawButton.RHandTrigger; if (state.RThumbstick.y >= AXIS_AS_BUTTON_THRESHOLD) state.Buttons |= (uint)RawButton.RThumbstickUp; if (state.RThumbstick.y <= -AXIS_AS_BUTTON_THRESHOLD) state.Buttons |= (uint)RawButton.RThumbstickDown; if (state.RThumbstick.x <= -AXIS_AS_BUTTON_THRESHOLD) state.Buttons |= (uint)RawButton.RThumbstickLeft; if (state.RThumbstick.x >= AXIS_AS_BUTTON_THRESHOLD) state.Buttons |= (uint)RawButton.RThumbstickRight; previousState = currentState; currentState = state; return ((Controller)currentState.ConnectedControllers & controllerType); } public override void ConfigureButtonMap() { buttonMap.None = RawButton.None; buttonMap.One = RawButton.A; buttonMap.Two = RawButton.B; buttonMap.Three = RawButton.X; buttonMap.Four = RawButton.Y; buttonMap.Start = RawButton.Start; buttonMap.Back = RawButton.Back; buttonMap.PrimaryShoulder = RawButton.LShoulder; buttonMap.PrimaryIndexTrigger = RawButton.LIndexTrigger; buttonMap.PrimaryHandTrigger = RawButton.None; buttonMap.PrimaryThumbstick = RawButton.LThumbstick; buttonMap.PrimaryThumbstickUp = RawButton.LThumbstickUp; buttonMap.PrimaryThumbstickDown = RawButton.LThumbstickDown; buttonMap.PrimaryThumbstickLeft = RawButton.LThumbstickLeft; buttonMap.PrimaryThumbstickRight = RawButton.LThumbstickRight; buttonMap.PrimaryTouchpad = RawButton.None; buttonMap.SecondaryShoulder = RawButton.RShoulder; buttonMap.SecondaryIndexTrigger = RawButton.RIndexTrigger; buttonMap.SecondaryHandTrigger = RawButton.None; buttonMap.SecondaryThumbstick = RawButton.RThumbstick; buttonMap.SecondaryThumbstickUp = RawButton.RThumbstickUp; buttonMap.SecondaryThumbstickDown = RawButton.RThumbstickDown; buttonMap.SecondaryThumbstickLeft = RawButton.RThumbstickLeft; buttonMap.SecondaryThumbstickRight = RawButton.RThumbstickRight; buttonMap.SecondaryTouchpad = RawButton.None; buttonMap.DpadUp = RawButton.DpadUp; buttonMap.DpadDown = RawButton.DpadDown; buttonMap.DpadLeft = RawButton.DpadLeft; buttonMap.DpadRight = RawButton.DpadRight; buttonMap.Up = RawButton.LThumbstickUp; buttonMap.Down = RawButton.LThumbstickDown; buttonMap.Left = RawButton.LThumbstickLeft; buttonMap.Right = RawButton.LThumbstickRight; } public override void ConfigureTouchMap() { touchMap.None = RawTouch.None; touchMap.One = RawTouch.None; touchMap.Two = RawTouch.None; touchMap.Three = RawTouch.None; touchMap.Four = RawTouch.None; touchMap.PrimaryIndexTrigger = RawTouch.None; touchMap.PrimaryThumbstick = RawTouch.None; touchMap.PrimaryThumbRest = RawTouch.None; touchMap.PrimaryTouchpad = RawTouch.None; touchMap.SecondaryIndexTrigger = RawTouch.None; touchMap.SecondaryThumbstick = RawTouch.None; touchMap.SecondaryThumbRest = RawTouch.None; touchMap.SecondaryTouchpad = RawTouch.None; } public override void ConfigureNearTouchMap() { nearTouchMap.None = RawNearTouch.None; nearTouchMap.PrimaryIndexTrigger = RawNearTouch.None; nearTouchMap.PrimaryThumbButtons = RawNearTouch.None; nearTouchMap.SecondaryIndexTrigger = RawNearTouch.None; nearTouchMap.SecondaryThumbButtons = RawNearTouch.None; } public override void ConfigureAxis1DMap() { axis1DMap.None = RawAxis1D.None; axis1DMap.PrimaryIndexTrigger = RawAxis1D.LIndexTrigger; axis1DMap.PrimaryHandTrigger = RawAxis1D.None; axis1DMap.SecondaryIndexTrigger = RawAxis1D.RIndexTrigger; axis1DMap.SecondaryHandTrigger = RawAxis1D.None; } public override void ConfigureAxis2DMap() { axis2DMap.None = RawAxis2D.None; axis2DMap.PrimaryThumbstick = RawAxis2D.LThumbstick; axis2DMap.PrimaryTouchpad = RawAxis2D.None; axis2DMap.SecondaryThumbstick = RawAxis2D.RThumbstick; axis2DMap.SecondaryTouchpad = RawAxis2D.None; } public override void SetControllerVibration(float frequency, float amplitude) { int gpcNode = 0; float gpcFrequency = frequency * 200.0f; //Map frequency from 0-1 CAPI range to 0-200 GPC range float gpcStrength = amplitude; OVR_GamepadController_SetVibration(gpcNode, gpcStrength, gpcFrequency); } private const string DllName = "OVRGamepad"; [DllImport(DllName, CallingConvention = CallingConvention.Cdecl)] private static extern bool OVR_GamepadController_Initialize(); [DllImport(DllName, CallingConvention = CallingConvention.Cdecl)] private static extern bool OVR_GamepadController_Destroy(); [DllImport(DllName, CallingConvention = CallingConvention.Cdecl)] private static extern bool OVR_GamepadController_Update(); [DllImport(DllName, CallingConvention = CallingConvention.Cdecl)] private static extern float OVR_GamepadController_GetAxis(int axis); [DllImport(DllName, CallingConvention = CallingConvention.Cdecl)] private static extern bool OVR_GamepadController_GetButton(int button); [DllImport(DllName, CallingConvention = CallingConvention.Cdecl)] private static extern bool OVR_GamepadController_SetVibration(int node, float strength, float frequency); } private class OVRControllerGamepadAndroid : OVRControllerBase { private static class AndroidButtonNames { public static readonly KeyCode A = KeyCode.JoystickButton0; public static readonly KeyCode B = KeyCode.JoystickButton1; public static readonly KeyCode X = KeyCode.JoystickButton2; public static readonly KeyCode Y = KeyCode.JoystickButton3; public static readonly KeyCode Start = KeyCode.JoystickButton10; public static readonly KeyCode Back = KeyCode.JoystickButton11; public static readonly KeyCode LThumbstick = KeyCode.JoystickButton8; public static readonly KeyCode RThumbstick = KeyCode.JoystickButton9; public static readonly KeyCode LShoulder = KeyCode.JoystickButton4; public static readonly KeyCode RShoulder = KeyCode.JoystickButton5; } private static class AndroidAxisNames { public static readonly string LThumbstickX = "Oculus_GearVR_LThumbstickX"; public static readonly string LThumbstickY = "Oculus_GearVR_LThumbstickY"; public static readonly string RThumbstickX = "Oculus_GearVR_RThumbstickX"; public static readonly string RThumbstickY = "Oculus_GearVR_RThumbstickY"; public static readonly string LIndexTrigger = "Oculus_GearVR_LIndexTrigger"; public static readonly string RIndexTrigger = "Oculus_GearVR_RIndexTrigger"; public static readonly string DpadX = "Oculus_GearVR_DpadX"; public static readonly string DpadY = "Oculus_GearVR_DpadY"; } private bool joystickDetected = false; private float joystickCheckInterval = 1.0f; private float joystickCheckTime = 0.0f; public OVRControllerGamepadAndroid() { controllerType = Controller.Gamepad; } private bool ShouldUpdate() { // Use Unity's joystick detection as a quick way to determine joystick availability. if ((Time.realtimeSinceStartup - joystickCheckTime) > joystickCheckInterval) { joystickCheckTime = Time.realtimeSinceStartup; joystickDetected = false; var joystickNames = UnityEngine.Input.GetJoystickNames(); for (int i = 0; i < joystickNames.Length; i++) { if (joystickNames[i] != String.Empty) { joystickDetected = true; break; } } } return joystickDetected; } public override Controller Update() { if (!ShouldUpdate()) { return Controller.None; } OVRPlugin.ControllerState2 state = new OVRPlugin.ControllerState2(); state.ConnectedControllers = (uint)Controller.Gamepad; if (Input.GetKey(AndroidButtonNames.A)) state.Buttons |= (uint)RawButton.A; if (Input.GetKey(AndroidButtonNames.B)) state.Buttons |= (uint)RawButton.B; if (Input.GetKey(AndroidButtonNames.X)) state.Buttons |= (uint)RawButton.X; if (Input.GetKey(AndroidButtonNames.Y)) state.Buttons |= (uint)RawButton.Y; if (Input.GetKey(AndroidButtonNames.Start)) state.Buttons |= (uint)RawButton.Start; if (Input.GetKey(AndroidButtonNames.Back) || Input.GetKey(KeyCode.Escape)) state.Buttons |= (uint)RawButton.Back; if (Input.GetKey(AndroidButtonNames.LThumbstick)) state.Buttons |= (uint)RawButton.LThumbstick; if (Input.GetKey(AndroidButtonNames.RThumbstick)) state.Buttons |= (uint)RawButton.RThumbstick; if (Input.GetKey(AndroidButtonNames.LShoulder)) state.Buttons |= (uint)RawButton.LShoulder; if (Input.GetKey(AndroidButtonNames.RShoulder)) state.Buttons |= (uint)RawButton.RShoulder; state.LThumbstick.x = Input.GetAxisRaw(AndroidAxisNames.LThumbstickX); state.LThumbstick.y = Input.GetAxisRaw(AndroidAxisNames.LThumbstickY); state.RThumbstick.x = Input.GetAxisRaw(AndroidAxisNames.RThumbstickX); state.RThumbstick.y = Input.GetAxisRaw(AndroidAxisNames.RThumbstickY); state.LIndexTrigger = Input.GetAxisRaw(AndroidAxisNames.LIndexTrigger); state.RIndexTrigger = Input.GetAxisRaw(AndroidAxisNames.RIndexTrigger); if (state.LIndexTrigger >= AXIS_AS_BUTTON_THRESHOLD) state.Buttons |= (uint)RawButton.LIndexTrigger; if (state.LHandTrigger >= AXIS_AS_BUTTON_THRESHOLD) state.Buttons |= (uint)RawButton.LHandTrigger; if (state.LThumbstick.y >= AXIS_AS_BUTTON_THRESHOLD) state.Buttons |= (uint)RawButton.LThumbstickUp; if (state.LThumbstick.y <= -AXIS_AS_BUTTON_THRESHOLD) state.Buttons |= (uint)RawButton.LThumbstickDown; if (state.LThumbstick.x <= -AXIS_AS_BUTTON_THRESHOLD) state.Buttons |= (uint)RawButton.LThumbstickLeft; if (state.LThumbstick.x >= AXIS_AS_BUTTON_THRESHOLD) state.Buttons |= (uint)RawButton.LThumbstickRight; if (state.RIndexTrigger >= AXIS_AS_BUTTON_THRESHOLD) state.Buttons |= (uint)RawButton.RIndexTrigger; if (state.RHandTrigger >= AXIS_AS_BUTTON_THRESHOLD) state.Buttons |= (uint)RawButton.RHandTrigger; if (state.RThumbstick.y >= AXIS_AS_BUTTON_THRESHOLD) state.Buttons |= (uint)RawButton.RThumbstickUp; if (state.RThumbstick.y <= -AXIS_AS_BUTTON_THRESHOLD) state.Buttons |= (uint)RawButton.RThumbstickDown; if (state.RThumbstick.x <= -AXIS_AS_BUTTON_THRESHOLD) state.Buttons |= (uint)RawButton.RThumbstickLeft; if (state.RThumbstick.x >= AXIS_AS_BUTTON_THRESHOLD) state.Buttons |= (uint)RawButton.RThumbstickRight; float dpadX = Input.GetAxisRaw(AndroidAxisNames.DpadX); float dpadY = Input.GetAxisRaw(AndroidAxisNames.DpadY); if (dpadX <= -AXIS_AS_BUTTON_THRESHOLD) state.Buttons |= (uint)RawButton.DpadLeft; if (dpadX >= AXIS_AS_BUTTON_THRESHOLD) state.Buttons |= (uint)RawButton.DpadRight; if (dpadY <= -AXIS_AS_BUTTON_THRESHOLD) state.Buttons |= (uint)RawButton.DpadDown; if (dpadY >= AXIS_AS_BUTTON_THRESHOLD) state.Buttons |= (uint)RawButton.DpadUp; previousState = currentState; currentState = state; return ((Controller)currentState.ConnectedControllers & controllerType); } public override void ConfigureButtonMap() { buttonMap.None = RawButton.None; buttonMap.One = RawButton.A; buttonMap.Two = RawButton.B; buttonMap.Three = RawButton.X; buttonMap.Four = RawButton.Y; buttonMap.Start = RawButton.Start; buttonMap.Back = RawButton.Back; buttonMap.PrimaryShoulder = RawButton.LShoulder; buttonMap.PrimaryIndexTrigger = RawButton.LIndexTrigger; buttonMap.PrimaryHandTrigger = RawButton.None; buttonMap.PrimaryThumbstick = RawButton.LThumbstick; buttonMap.PrimaryThumbstickUp = RawButton.LThumbstickUp; buttonMap.PrimaryThumbstickDown = RawButton.LThumbstickDown; buttonMap.PrimaryThumbstickLeft = RawButton.LThumbstickLeft; buttonMap.PrimaryThumbstickRight = RawButton.LThumbstickRight; buttonMap.PrimaryTouchpad = RawButton.None; buttonMap.SecondaryShoulder = RawButton.RShoulder; buttonMap.SecondaryIndexTrigger = RawButton.RIndexTrigger; buttonMap.SecondaryHandTrigger = RawButton.None; buttonMap.SecondaryThumbstick = RawButton.RThumbstick; buttonMap.SecondaryThumbstickUp = RawButton.RThumbstickUp; buttonMap.SecondaryThumbstickDown = RawButton.RThumbstickDown; buttonMap.SecondaryThumbstickLeft = RawButton.RThumbstickLeft; buttonMap.SecondaryThumbstickRight = RawButton.RThumbstickRight; buttonMap.SecondaryTouchpad = RawButton.None; buttonMap.DpadUp = RawButton.DpadUp; buttonMap.DpadDown = RawButton.DpadDown; buttonMap.DpadLeft = RawButton.DpadLeft; buttonMap.DpadRight = RawButton.DpadRight; buttonMap.Up = RawButton.LThumbstickUp; buttonMap.Down = RawButton.LThumbstickDown; buttonMap.Left = RawButton.LThumbstickLeft; buttonMap.Right = RawButton.LThumbstickRight; } public override void ConfigureTouchMap() { touchMap.None = RawTouch.None; touchMap.One = RawTouch.None; touchMap.Two = RawTouch.None; touchMap.Three = RawTouch.None; touchMap.Four = RawTouch.None; touchMap.PrimaryIndexTrigger = RawTouch.None; touchMap.PrimaryThumbstick = RawTouch.None; touchMap.PrimaryThumbRest = RawTouch.None; touchMap.PrimaryTouchpad = RawTouch.None; touchMap.SecondaryIndexTrigger = RawTouch.None; touchMap.SecondaryThumbstick = RawTouch.None; touchMap.SecondaryThumbRest = RawTouch.None; touchMap.SecondaryTouchpad = RawTouch.None; } public override void ConfigureNearTouchMap() { nearTouchMap.None = RawNearTouch.None; nearTouchMap.PrimaryIndexTrigger = RawNearTouch.None; nearTouchMap.PrimaryThumbButtons = RawNearTouch.None; nearTouchMap.SecondaryIndexTrigger = RawNearTouch.None; nearTouchMap.SecondaryThumbButtons = RawNearTouch.None; } public override void ConfigureAxis1DMap() { axis1DMap.None = RawAxis1D.None; axis1DMap.PrimaryIndexTrigger = RawAxis1D.LIndexTrigger; axis1DMap.PrimaryHandTrigger = RawAxis1D.None; axis1DMap.SecondaryIndexTrigger = RawAxis1D.RIndexTrigger; axis1DMap.SecondaryHandTrigger = RawAxis1D.None; } public override void ConfigureAxis2DMap() { axis2DMap.None = RawAxis2D.None; axis2DMap.PrimaryThumbstick = RawAxis2D.LThumbstick; axis2DMap.PrimaryTouchpad = RawAxis2D.None; axis2DMap.SecondaryThumbstick = RawAxis2D.RThumbstick; axis2DMap.SecondaryTouchpad = RawAxis2D.None; } public override void SetControllerVibration(float frequency, float amplitude) { } } private class OVRControllerTouchpad : OVRControllerBase { private OVRPlugin.Vector2f moveAmount; private float maxTapMagnitude = 0.1f; private float minMoveMagnitude = 0.15f; public OVRControllerTouchpad() { controllerType = Controller.Touchpad; } public override Controller Update() { Controller res = base.Update(); if (GetDown(RawTouch.LTouchpad, OVRInput.Controller.Touchpad)) { moveAmount = currentState.LTouchpad; } if (GetUp(RawTouch.LTouchpad, OVRInput.Controller.Touchpad)) { moveAmount.x = previousState.LTouchpad.x - moveAmount.x; moveAmount.y = previousState.LTouchpad.y - moveAmount.y; Vector2 move = new Vector2(moveAmount.x, moveAmount.y); float moveMag = move.magnitude; if (moveMag < maxTapMagnitude) { // Emit Touchpad Tap currentState.Buttons |= (uint)RawButton.Start; currentState.Buttons |= (uint)RawButton.LTouchpad; } else if (moveMag >= minMoveMagnitude) { move.Normalize(); // Left/Right if (Mathf.Abs(move.x) > Mathf.Abs(move.y)) { if (move.x < 0.0f) { currentState.Buttons |= (uint)RawButton.DpadLeft; } else { currentState.Buttons |= (uint)RawButton.DpadRight; } } // Up/Down else { if (move.y < 0.0f) { currentState.Buttons |= (uint)RawButton.DpadDown; } else { currentState.Buttons |= (uint)RawButton.DpadUp; } } } } return res; } public override void ConfigureButtonMap() { buttonMap.None = RawButton.None; buttonMap.One = RawButton.Start; buttonMap.Two = RawButton.Back; buttonMap.Three = RawButton.None; buttonMap.Four = RawButton.None; buttonMap.Start = RawButton.Start; buttonMap.Back = RawButton.Back; buttonMap.PrimaryShoulder = RawButton.None; buttonMap.PrimaryIndexTrigger = RawButton.None; buttonMap.PrimaryHandTrigger = RawButton.None; buttonMap.PrimaryThumbstick = RawButton.None; buttonMap.PrimaryThumbstickUp = RawButton.None; buttonMap.PrimaryThumbstickDown = RawButton.None; buttonMap.PrimaryThumbstickLeft = RawButton.None; buttonMap.PrimaryThumbstickRight = RawButton.None; buttonMap.PrimaryTouchpad = RawButton.LTouchpad; buttonMap.SecondaryShoulder = RawButton.None; buttonMap.SecondaryIndexTrigger = RawButton.None; buttonMap.SecondaryHandTrigger = RawButton.None; buttonMap.SecondaryThumbstick = RawButton.None; buttonMap.SecondaryThumbstickUp = RawButton.None; buttonMap.SecondaryThumbstickDown = RawButton.None; buttonMap.SecondaryThumbstickLeft = RawButton.None; buttonMap.SecondaryThumbstickRight = RawButton.None; buttonMap.SecondaryTouchpad = RawButton.None; buttonMap.DpadUp = RawButton.DpadUp; buttonMap.DpadDown = RawButton.DpadDown; buttonMap.DpadLeft = RawButton.DpadLeft; buttonMap.DpadRight = RawButton.DpadRight; buttonMap.Up = RawButton.DpadUp; buttonMap.Down = RawButton.DpadDown; buttonMap.Left = RawButton.DpadLeft; buttonMap.Right = RawButton.DpadRight; } public override void ConfigureTouchMap() { touchMap.None = RawTouch.None; touchMap.One = RawTouch.None; touchMap.Two = RawTouch.None; touchMap.Three = RawTouch.None; touchMap.Four = RawTouch.None; touchMap.PrimaryIndexTrigger = RawTouch.None; touchMap.PrimaryThumbstick = RawTouch.None; touchMap.PrimaryThumbRest = RawTouch.None; touchMap.PrimaryTouchpad = RawTouch.LTouchpad; touchMap.SecondaryIndexTrigger = RawTouch.None; touchMap.SecondaryThumbstick = RawTouch.None; touchMap.SecondaryThumbRest = RawTouch.None; touchMap.SecondaryTouchpad = RawTouch.None; } public override void ConfigureNearTouchMap() { nearTouchMap.None = RawNearTouch.None; nearTouchMap.PrimaryIndexTrigger = RawNearTouch.None; nearTouchMap.PrimaryThumbButtons = RawNearTouch.None; nearTouchMap.SecondaryIndexTrigger = RawNearTouch.None; nearTouchMap.SecondaryThumbButtons = RawNearTouch.None; } public override void ConfigureAxis1DMap() { axis1DMap.None = RawAxis1D.None; axis1DMap.PrimaryIndexTrigger = RawAxis1D.None; axis1DMap.PrimaryHandTrigger = RawAxis1D.None; axis1DMap.SecondaryIndexTrigger = RawAxis1D.None; axis1DMap.SecondaryHandTrigger = RawAxis1D.None; } public override void ConfigureAxis2DMap() { axis2DMap.None = RawAxis2D.None; axis2DMap.PrimaryThumbstick = RawAxis2D.None; axis2DMap.PrimaryTouchpad = RawAxis2D.LTouchpad; axis2DMap.SecondaryThumbstick = RawAxis2D.None; axis2DMap.SecondaryTouchpad = RawAxis2D.None; } } private class OVRControllerLTrackedRemote : OVRControllerBase { private bool emitSwipe; private OVRPlugin.Vector2f moveAmount; private float minMoveMagnitude = 0.3f; public OVRControllerLTrackedRemote() { controllerType = Controller.LTrackedRemote; } public override void ConfigureButtonMap() { buttonMap.None = RawButton.None; buttonMap.One = RawButton.LTouchpad; buttonMap.Two = RawButton.Back; buttonMap.Three = RawButton.None; buttonMap.Four = RawButton.None; buttonMap.Start = RawButton.Start; buttonMap.Back = RawButton.Back; buttonMap.PrimaryShoulder = RawButton.None; buttonMap.PrimaryIndexTrigger = RawButton.LIndexTrigger; buttonMap.PrimaryHandTrigger = RawButton.None; buttonMap.PrimaryThumbstick = RawButton.None; buttonMap.PrimaryThumbstickUp = RawButton.None; buttonMap.PrimaryThumbstickDown = RawButton.None; buttonMap.PrimaryThumbstickLeft = RawButton.None; buttonMap.PrimaryThumbstickRight = RawButton.None; buttonMap.PrimaryTouchpad = RawButton.LTouchpad; buttonMap.SecondaryShoulder = RawButton.None; buttonMap.SecondaryIndexTrigger = RawButton.None; buttonMap.SecondaryHandTrigger = RawButton.None; buttonMap.SecondaryThumbstick = RawButton.None; buttonMap.SecondaryThumbstickUp = RawButton.None; buttonMap.SecondaryThumbstickDown = RawButton.None; buttonMap.SecondaryThumbstickLeft = RawButton.None; buttonMap.SecondaryThumbstickRight = RawButton.None; buttonMap.SecondaryTouchpad = RawButton.None; buttonMap.DpadUp = RawButton.DpadUp; buttonMap.DpadDown = RawButton.DpadDown; buttonMap.DpadLeft = RawButton.DpadLeft; buttonMap.DpadRight = RawButton.DpadRight; buttonMap.Up = RawButton.DpadUp; buttonMap.Down = RawButton.DpadDown; buttonMap.Left = RawButton.DpadLeft; buttonMap.Right = RawButton.DpadRight; } public override void ConfigureTouchMap() { touchMap.None = RawTouch.None; touchMap.One = RawTouch.None; touchMap.Two = RawTouch.None; touchMap.Three = RawTouch.None; touchMap.Four = RawTouch.None; touchMap.PrimaryIndexTrigger = RawTouch.None; touchMap.PrimaryThumbstick = RawTouch.None; touchMap.PrimaryThumbRest = RawTouch.None; touchMap.PrimaryTouchpad = RawTouch.LTouchpad; touchMap.SecondaryIndexTrigger = RawTouch.None; touchMap.SecondaryThumbstick = RawTouch.None; touchMap.SecondaryThumbRest = RawTouch.None; touchMap.SecondaryTouchpad = RawTouch.None; } public override void ConfigureNearTouchMap() { nearTouchMap.None = RawNearTouch.None; nearTouchMap.PrimaryIndexTrigger = RawNearTouch.None; nearTouchMap.PrimaryThumbButtons = RawNearTouch.None; nearTouchMap.SecondaryIndexTrigger = RawNearTouch.None; nearTouchMap.SecondaryThumbButtons = RawNearTouch.None; } public override void ConfigureAxis1DMap() { axis1DMap.None = RawAxis1D.None; axis1DMap.PrimaryIndexTrigger = RawAxis1D.None; axis1DMap.PrimaryHandTrigger = RawAxis1D.None; axis1DMap.SecondaryIndexTrigger = RawAxis1D.None; axis1DMap.SecondaryHandTrigger = RawAxis1D.None; } public override void ConfigureAxis2DMap() { axis2DMap.None = RawAxis2D.None; axis2DMap.PrimaryThumbstick = RawAxis2D.None; axis2DMap.PrimaryTouchpad = RawAxis2D.LTouchpad; axis2DMap.SecondaryThumbstick = RawAxis2D.None; axis2DMap.SecondaryTouchpad = RawAxis2D.None; } public override Controller Update() { Controller res = base.Update(); if (GetDown(RawTouch.LTouchpad, OVRInput.Controller.LTrackedRemote)) { emitSwipe = true; moveAmount = currentState.LTouchpad; } if (GetDown(RawButton.LTouchpad, OVRInput.Controller.LTrackedRemote)) { emitSwipe = false; } if (GetUp(RawTouch.LTouchpad, OVRInput.Controller.LTrackedRemote) && emitSwipe) { emitSwipe = false; moveAmount.x = previousState.LTouchpad.x - moveAmount.x; moveAmount.y = previousState.LTouchpad.y - moveAmount.y; Vector2 move = new Vector2(moveAmount.x, moveAmount.y); if (move.magnitude >= minMoveMagnitude) { move.Normalize(); // Left/Right if (Mathf.Abs(move.x) > Mathf.Abs(move.y)) { if (move.x < 0.0f) { currentState.Buttons |= (uint)RawButton.DpadLeft; } else { currentState.Buttons |= (uint)RawButton.DpadRight; } } // Up/Down else { if (move.y < 0.0f) { currentState.Buttons |= (uint)RawButton.DpadDown; } else { currentState.Buttons |= (uint)RawButton.DpadUp; } } } } return res; } } private class OVRControllerRTrackedRemote : OVRControllerBase { private bool emitSwipe; private OVRPlugin.Vector2f moveAmount; private float minMoveMagnitude = 0.3f; public OVRControllerRTrackedRemote() { controllerType = Controller.RTrackedRemote; } public override void ConfigureButtonMap() { buttonMap.None = RawButton.None; buttonMap.One = RawButton.RTouchpad; buttonMap.Two = RawButton.Back; buttonMap.Three = RawButton.None; buttonMap.Four = RawButton.None; buttonMap.Start = RawButton.Start; buttonMap.Back = RawButton.Back; buttonMap.PrimaryShoulder = RawButton.None; buttonMap.PrimaryIndexTrigger = RawButton.RIndexTrigger; buttonMap.PrimaryHandTrigger = RawButton.None; buttonMap.PrimaryThumbstick = RawButton.None; buttonMap.PrimaryThumbstickUp = RawButton.None; buttonMap.PrimaryThumbstickDown = RawButton.None; buttonMap.PrimaryThumbstickLeft = RawButton.None; buttonMap.PrimaryThumbstickRight = RawButton.None; buttonMap.PrimaryTouchpad = RawButton.RTouchpad; buttonMap.SecondaryShoulder = RawButton.None; buttonMap.SecondaryIndexTrigger = RawButton.None; buttonMap.SecondaryHandTrigger = RawButton.None; buttonMap.SecondaryThumbstick = RawButton.None; buttonMap.SecondaryThumbstickUp = RawButton.None; buttonMap.SecondaryThumbstickDown = RawButton.None; buttonMap.SecondaryThumbstickLeft = RawButton.None; buttonMap.SecondaryThumbstickRight = RawButton.None; buttonMap.SecondaryTouchpad = RawButton.None; buttonMap.DpadUp = RawButton.DpadUp; buttonMap.DpadDown = RawButton.DpadDown; buttonMap.DpadLeft = RawButton.DpadLeft; buttonMap.DpadRight = RawButton.DpadRight; buttonMap.Up = RawButton.DpadUp; buttonMap.Down = RawButton.DpadDown; buttonMap.Left = RawButton.DpadLeft; buttonMap.Right = RawButton.DpadRight; } public override void ConfigureTouchMap() { touchMap.None = RawTouch.None; touchMap.One = RawTouch.None; touchMap.Two = RawTouch.None; touchMap.Three = RawTouch.None; touchMap.Four = RawTouch.None; touchMap.PrimaryIndexTrigger = RawTouch.None; touchMap.PrimaryThumbstick = RawTouch.None; touchMap.PrimaryThumbRest = RawTouch.None; touchMap.PrimaryTouchpad = RawTouch.RTouchpad; touchMap.SecondaryIndexTrigger = RawTouch.None; touchMap.SecondaryThumbstick = RawTouch.None; touchMap.SecondaryThumbRest = RawTouch.None; touchMap.SecondaryTouchpad = RawTouch.None; } public override void ConfigureNearTouchMap() { nearTouchMap.None = RawNearTouch.None; nearTouchMap.PrimaryIndexTrigger = RawNearTouch.None; nearTouchMap.PrimaryThumbButtons = RawNearTouch.None; nearTouchMap.SecondaryIndexTrigger = RawNearTouch.None; nearTouchMap.SecondaryThumbButtons = RawNearTouch.None; } public override void ConfigureAxis1DMap() { axis1DMap.None = RawAxis1D.None; axis1DMap.PrimaryIndexTrigger = RawAxis1D.None; axis1DMap.PrimaryHandTrigger = RawAxis1D.None; axis1DMap.SecondaryIndexTrigger = RawAxis1D.None; axis1DMap.SecondaryHandTrigger = RawAxis1D.None; } public override void ConfigureAxis2DMap() { axis2DMap.None = RawAxis2D.None; axis2DMap.PrimaryThumbstick = RawAxis2D.None; axis2DMap.PrimaryTouchpad = RawAxis2D.RTouchpad; axis2DMap.SecondaryThumbstick = RawAxis2D.None; axis2DMap.SecondaryTouchpad = RawAxis2D.None; } public override Controller Update() { Controller res = base.Update(); if (GetDown(RawTouch.RTouchpad, OVRInput.Controller.RTrackedRemote)) { emitSwipe = true; moveAmount = currentState.RTouchpad; } if (GetDown(RawButton.RTouchpad, OVRInput.Controller.RTrackedRemote)) { emitSwipe = false; } if (GetUp(RawTouch.RTouchpad, OVRInput.Controller.RTrackedRemote) && emitSwipe) { emitSwipe = false; moveAmount.x = previousState.RTouchpad.x - moveAmount.x; moveAmount.y = previousState.RTouchpad.y - moveAmount.y; Vector2 move = new Vector2(moveAmount.x, moveAmount.y); if (move.magnitude >= minMoveMagnitude) { move.Normalize(); // Left/Right if (Mathf.Abs(move.x) > Mathf.Abs(move.y)) { if (move.x < 0.0f) { currentState.Buttons |= (uint)RawButton.DpadLeft; } else { currentState.Buttons |= (uint)RawButton.DpadRight; } } // Up/Down else { if (move.y < 0.0f) { currentState.Buttons |= (uint)RawButton.DpadDown; } else { currentState.Buttons |= (uint)RawButton.DpadUp; } } } } return res; } } }
44.025069
233
0.68377
[ "MIT" ]
GRArgo/VR-Test-Base
Assets/OVR/Scripts/OVRInput.cs
128,201
C#
namespace Machete.Benchmarking.Configuration { using BenchmarkDotNet.Configs; using BenchmarkDotNet.Diagnosers; using BenchmarkDotNet.Engines; using BenchmarkDotNet.Environments; using BenchmarkDotNet.Exporters; using BenchmarkDotNet.Exporters.Csv; using BenchmarkDotNet.Jobs; public class DotNetCoreBenchmarkConfig : ManualConfig { const int Iteration = 300; public DotNetCoreBenchmarkConfig() { Add(MemoryDiagnoser.Default); // Add(RPlotExporter.Default); Add(new CsvExporter(CsvSeparator.CurrentCulture, new BenchmarkDotNet.Reports.SummaryStyle { PrintUnitsInHeader = true, PrintUnitsInContent = false, TimeUnit = BenchmarkDotNet.Horology.TimeUnit.Microsecond, SizeUnit = BenchmarkDotNet.Columns.SizeUnit.KB })); Add(new Job { Env = {Runtime = Runtime.Core}, Run = { TargetCount = Iteration, RunStrategy = RunStrategy.Throughput, WarmupCount = 5, LaunchCount = 1, UnrollFactor = 1, InvocationCount = Iteration } }); } } }
31.418605
101
0.555885
[ "Apache-2.0" ]
AreebaAroosh/Machete
src/Machete.Benchmarking/Configuration/DotNetCoreBenchmarkConfig.cs
1,353
C#
namespace Box.V2 { /// <summary> /// Interface that defines a Box form part /// </summary> public interface IBoxFormPart { /// <summary> /// The name of the form part /// </summary> string Name { get; } } /// <summary> /// Interface that takes different types of Form parts /// </summary> /// <typeparam name="T"></typeparam> public interface IBoxFormPart<T> : IBoxFormPart { /// <summary> /// The value of the form part /// </summary> T Value { get; } } }
22.259259
59
0.49584
[ "Apache-2.0" ]
box/box-windows-sdk-v2
Box.V2/Wrappers/Contracts/IBoxFormPart.cs
601
C#
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using CoreAnimation; using CoreGraphics; using Foundation; using Microsoft.Extensions.Logging; using UIKit; using Uno.Extensions; using Uno.UI; using Uno.UI.Controls; using Uno.UI.Extensions; using Windows.Devices.Input; using Windows.Foundation; using Windows.UI.Input; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Controls.Primitives; using Windows.UI.Xaml.Input; using Windows.UI.Xaml.Media; using UIViewExtensions = UIKit.UIViewExtensions; namespace Windows.UI.Xaml { public partial class UIElement : BindableUIView { public UIElement() { InitializePointers(); } internal bool ClippingIsSetByCornerRadius { get; set; } = false; partial void ApplyNativeClip(Rect rect) { if (rect.IsEmpty || double.IsPositiveInfinity(rect.X) || double.IsPositiveInfinity(rect.Y) || double.IsPositiveInfinity(rect.Width) || double.IsPositiveInfinity(rect.Height) ) { if (!ClippingIsSetByCornerRadius) { this.Layer.Mask = null; } return; } this.Layer.Mask = new CAShapeLayer { Path = CGPath.FromRect(rect.ToCGRect()) }; } partial void OnOpacityChanged(DependencyPropertyChangedEventArgs args) { // Don't update the internal value if the value is being animated. // The value is being animated by the platform itself. if (!(args.NewPrecedence == DependencyPropertyValuePrecedences.Animations && args.BypassesPropagation)) { Alpha = IsRenderingSuspended ? 0 : (nfloat)Opacity; } } protected virtual void OnVisibilityChanged(Visibility oldValue, Visibility newValue) { var newVisibility = (Visibility)newValue; if (base.Hidden != newVisibility.IsHidden()) { base.Hidden = newVisibility.IsHidden(); InvalidateMeasure(); if (newVisibility == Visibility.Visible) { // This recursively invalidates the layout of all subviews // to ensure LayoutSubviews is called and views get updated. // Failing to do this can cause some views to remain collapsed. SetSubviewsNeedLayout(); } } } public override bool Hidden { get { return base.Hidden; } set { // Only set the Visility property, the Hidden property is updated // in the property changed handler as there are actions associated with // the change. Visibility = value ? Visibility.Collapsed : Visibility.Visible; } } public void SetSubviewsNeedLayout() { base.SetNeedsLayout(); if (this is Controls.Panel p) { // This section is here because of the enumerator type returned by Children, // to avoid allocating during the enumeration. foreach (var view in p.Children) { (view as IFrameworkElement)?.SetSubviewsNeedLayout(); } } else { foreach (var view in this.GetChildren()) { (view as IFrameworkElement)?.SetSubviewsNeedLayout(); } } } internal Windows.Foundation.Point GetPosition(Point position, global::Windows.UI.Xaml.UIElement relativeTo) { return ConvertPointToCoordinateSpace(position, relativeTo); } /// <summary> /// Note: Offsets are only an approximation which does not take in consideration possible transformations /// applied by a 'UIView' between this element and its parent UIElement. /// </summary> private bool TryGetParentUIElementForTransformToVisual(out UIElement parentElement, ref double offsetX, ref double offsetY) { var parent = this.GetParent(); switch (parent) { // First we try the direct parent, if it's from the known type we won't even have to adjust offsets case UIElement elt: parentElement = elt; return true; case null: parentElement = null; return false; case UIView view: do { parent = parent.GetParent(); switch (parent) { case UIElement eltParent: // We found a UIElement in the parent hierarchy, we compute the X/Y offset between the // first parent 'view' and this 'elt', and return it. if (view is UICollectionView) { // The UICollectionView (ListView) will include the scroll offset when converting point to coordinates // space of the parent, but the same scroll offset will be applied by the parent ScrollViewer. // So as it's not expected to have any transform/margins/etc., we compute offset directly from its parent. view = view.Superview; } var offset = view?.ConvertPointToCoordinateSpace(default, eltParent) ?? default; parentElement = eltParent; offsetX += offset.X; offsetY += offset.Y; return true; case null: // We reached the top of the window without any UIElement in the hierarchy, // so we adjust offsets using the X/Y position of the original 'view' in the window. offset = view.ConvertRectToView(default, null).Location; parentElement = null; offsetX += offset.X; offsetY += offset.Y; return false; } } while (true); default: Application.Current.RaiseRecoverableUnhandledException(new InvalidOperationException("Found a parent which is NOT a UIView.")); parentElement = null; return false; } } #if DEBUG public static Predicate<UIView> ViewOfInterestSelector { get; set; } = v => (v as FrameworkElement)?.Name == "TargetView"; public bool IsViewOfInterest => ViewOfInterestSelector(this); /// <summary> /// Returns all views matching <see cref="ViewOfInterestSelector"/> anywhere in the visual tree. Handy when debugging Uno. /// </summary> /// <remarks>This property is intended as a shortcut to inspect the properties of a specific view at runtime. Suggested usage: /// 1. Be debugging Uno. 2. Flag the view you want in xaml with 'Name = "TargetView", or set <see cref="ViewOfInterestSelector"/> /// to select the view you want. 3. Put a breakpoint in the <see cref="FrameworkElement.HitTest(CGPoint, UIEvent)"/> method. 4. Tap anywhere in the app. /// 5. Inspect this property, or one of the typed versions below.</remarks> public UIView[] ViewsOfInterest { get { UIView topLevel = this; while (topLevel.Superview is UIView newTopLevel) { topLevel = newTopLevel; } return GetMatchesInChildren(topLevel).ToArray(); IEnumerable<UIView> GetMatchesInChildren(UIView parent) { foreach (var subview in parent.Subviews) { if (ViewOfInterestSelector(subview)) { yield return subview; } foreach (var match in GetMatchesInChildren(subview)) { yield return match; } } } } } /// <summary> /// Convenience method to find all views with the given name. /// </summary> public FrameworkElement[] FindViewsByName(string name) => FindViewsByName(name, searchDescendantsOnly: false); /// <summary> /// Convenience method to find all views with the given name. /// </summary> /// <param name="searchDescendantsOnly">If true, only look in descendants of the current view; otherwise search the entire visual tree.</param> public FrameworkElement[] FindViewsByName(string name, bool searchDescendantsOnly) { UIView topLevel = this; if (!searchDescendantsOnly) { while (topLevel.Superview is UIView newTopLevel) { topLevel = newTopLevel; } } return GetMatchesInChildren(topLevel).ToArray(); IEnumerable<FrameworkElement> GetMatchesInChildren(UIView parent) { foreach (var subview in parent.Subviews) { if (subview is FrameworkElement fe && fe.Name == name) { yield return fe; } foreach (var match in GetMatchesInChildren(subview)) { yield return match; } } } } public FrameworkElement[] FrameworkElementsOfInterest => ViewsOfInterest.OfType<FrameworkElement>().ToArray(); public Controls.ContentControl[] ContentControlsOfInterest => ViewsOfInterest.OfType<Controls.ContentControl>().ToArray(); public Controls.Panel[] PanelsOfInterest => ViewsOfInterest.OfType<Controls.Panel>().ToArray(); /// <summary> /// Strongly-typed superview, purely a debugger convenience. /// </summary> public FrameworkElement FrameworkElementSuperview => Superview as FrameworkElement; public string ShowDescendants() => UIViewExtensions.ShowDescendants(this); public string ShowLocalVisualTree(int fromHeight) => UIViewExtensions.ShowLocalVisualTree(this, fromHeight); public IList<VisualStateGroup> VisualStateGroups => VisualStateManager.GetVisualStateGroups((this as Controls.Control).GetTemplateRoot()); #endif } }
29.060201
155
0.694096
[ "Apache-2.0" ]
SuperJMN/uno
src/Uno.UI/UI/Xaml/UIElement.iOS.cs
8,691
C#
#region License // Copyright(c) Workshell Ltd // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. #endregion using System; using System.Collections.Generic; using System.Text; namespace Workshell.PE.Resources.Dialogs.Styles { [Flags] public enum WindowStyle : uint { WS_OVERLAPPED = 0x00000000, WS_POPUP = 0x80000000, WS_CHILD = 0x40000000, WS_MINIMIZE = 0x20000000, WS_VISIBLE = 0x10000000, WS_DISABLED = 0x08000000, WS_CLIPSIBLINGS = 0x04000000, WS_CLIPCHILDREN = 0x02000000, WS_MAXIMIZE = 0x01000000, WS_CAPTION = 0x00C00000, // WS_BORDER | WS_DLGFRAME WS_BORDER = 0x00800000, WS_DLGFRAME = 0x00400000, WS_VSCROLL = 0x00200000, WS_HSCROLL = 0x00100000, WS_SYSMENU = 0x00080000, WS_THICKFRAME = 0x00040000, WS_GROUP = 0x00020000, WS_TABSTOP = 0x00010000, WS_MINIMIZEBOX = 0x00020000, WS_MAXIMIZEBOX = 0x00010000, WS_TILED = WS_OVERLAPPED, WS_ICONIC = WS_MINIMIZE, WS_SIZEBOX = WS_THICKFRAME, WS_TILEDWINDOW = WS_OVERLAPPEDWINDOW, WS_OVERLAPPEDWINDOW = (WS_OVERLAPPED | WS_CAPTION | WS_SYSMENU | WS_THICKFRAME | WS_MINIMIZEBOX | WS_MAXIMIZEBOX), WS_POPUPWINDOW = (WS_POPUP | WS_BORDER | WS_SYSMENU), WS_CHILDWINDOW = WS_CHILD } }
37.625
122
0.702243
[ "MIT" ]
Workshell/pe
src/Workshell.PE.Resources/Dialogs/Styles/WindowStyle.cs
2,410
C#
using System; using Microsoft.VisualStudio.TestTools.UnitTesting; using System.ServiceModel; using TimeSpent.Business.Contracts; namespace TimeSpent.ServiceHost.Tests { [TestClass] public class ServiceAccessTest { [TestMethod] public void test_time_entry_manager_as_service() { ChannelFactory<ITimeEntryService> channelFactory = new ChannelFactory<ITimeEntryService>(""); ITimeEntryService proxy = channelFactory.CreateChannel(); (proxy as ICommunicationObject).Open(); channelFactory.Close(); } } }
25.041667
105
0.688852
[ "MIT" ]
saeidehv/TimeSpent
TimeSpent.ServiceHost.Tests/ServiceAccessTest.cs
603
C#
using System.Collections.Generic; using Search.Index; using Search.Text; namespace Search.Query { public interface IQueryComponent { /// <summary> /// Get Postings /// </summary> /// <param name="index">Index</param> /// <param name="processor">Tokene processor</param> /// <returns></returns> IList<Posting> GetPostings(IIndex index, ITokenProcessor processor); } }
24.277778
76
0.615561
[ "MIT" ]
sotheanith/CECS-529-SearchEngine
Models/Search.Query/IQueryComponent.cs
439
C#
using System; using System.Collections.Generic; using System.Text; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using ZombieSmashers.map; using ZombieSmashers.quake; using ZombieSmashers.audio; using Microsoft.Xna.Framework.Net; namespace ZombieSmashers.Particles { /// <summary> /// ParticleManager manages all of our game particles, such as smoke, fire, /// missiles, melee attacks, etc. /// /// ParticleManager is covered in chapter 6. /// </summary> public class ParticleManager { Particle[] particle = new Particle[1024]; SpriteBatch sprite; public void Reset() { for (int i = 0; i < particle.Length; i++) particle[i] = null; } /// <summary> /// Make a bullet with muzzle flash. /// </summary> /// <param name="loc">Location to create the bullet from.</param> /// <param name="traj">Bullet trajectory</param> /// <param name="face">Facing of owner</param> /// <param name="owner">Owner of bullet</param> public void MakeBullet(Vector2 loc, Vector2 traj, CharDir face, int owner) { if (face == CharDir.Left) { AddParticle(new Bullet(loc, new Vector2(-traj.X, traj.Y) + Rand.GetRandomVector2(-90f, 90f, -90f, 90f), owner)); MakeMuzzleFlash(loc, new Vector2(-traj.X, traj.Y)); } else { AddParticle(new Bullet(loc, traj + Rand.GetRandomVector2(-90f, 90f, -90f, 90f), owner)); MakeMuzzleFlash(loc, traj); } } /// <summary> /// Make muzzle flash. A muzzle flash is comprised of heat haze, muzzleflash sprites, /// and smoke. /// </summary> /// <param name="loc">Location to make muzzle flash from</param> /// <param name="traj">Trajectory of bullet making muzzle flash</param> public void MakeMuzzleFlash(Vector2 loc, Vector2 traj) { for (int i = 0; i < 16; i++) { AddParticle(new MuzzleFlash( loc + (traj * (float)i) * 0.001f + Rand.GetRandomVector2(-5f, 5f, -5f, 5f), traj / 5f, (20f - (float)i) * 0.06f)); } for (int i = 0; i < 4; i++) AddParticle(new Smoke( loc, Rand.GetRandomVector2(-30f, 30f, -100f, 0f), 0f, 0f, 0f, 0.25f, Rand.GetRandomFloat(0.25f, 1.0f), Rand.GetRandomInt(0, 4))); for (int i = 4; i < 12; i++) AddParticle(new Heat( loc + (traj * (float)i) * 0.001f + Rand.GetRandomVector2(-30f, 30f, -30f, 30f), Rand.GetRandomVector2(-30f, 30f, -100f, 0f), Rand.GetRandomFloat(.5f, 1.1f))); } /// <summary> /// Makes a good looking exit wound. /// </summary> /// <param name="loc">Location of bullet impact.</param> /// <param name="traj">Bullet trajectory.</param> public void MakeBulletBlood(Vector2 loc, Vector2 traj) { for (int t = 0; t < 32; t++) AddParticle( new Blood(loc, traj * -1f * Rand.GetRandomFloat(0.01f, 0.2f) + Rand.GetRandomVector2(-50f, 50f, -50f, 50f), 1f, 0f, 0f, 1f, Rand.GetRandomFloat(0.1f, 0.3f), Rand.GetRandomInt(0, 4))); } /// <summary> /// Make wraith missle explosion, using smoke, fire, and a shockwave refraction effect. /// </summary> /// <param name="loc">Explosion location</param> /// <param name="mag">Explosion magnitude--affects particle size</param> public void MakeExplosion(Vector2 loc, float mag) { for (int i = 0; i < 8; i++) AddParticle(new Smoke(loc, Rand.GetRandomVector2(-100f, 100f, -100f, 100f), 1f, .8f, .6f, 1f, Rand.GetRandomFloat(1f, 1.5f), Rand.GetRandomInt(0, 4))); for (int i = 0; i < 8; i++) AddParticle(new Fire(loc, Rand.GetRandomVector2(-80f, 80f, -80f, 80f), 1f, Rand.GetRandomInt(0, 4))); AddParticle(new Shockwave(loc, true, 25f)); AddParticle(new Shockwave(loc, false, 10f)); Sound.PlayCue("explode"); QuakeManager.SetQuake(.5f); QuakeManager.SetBlast(1f, loc); } /// <summary> /// Make dust to match bullet exit wound. /// </summary> /// <param name="loc">Location of impact</param> /// <param name="traj">Bullet trajectory</param> public void MakeBulletDust(Vector2 loc, Vector2 traj) { for (int i = 0; i < 16; i++) { AddParticle(new Smoke(loc, Rand.GetRandomVector2(-50f, 50f, -50f, 10f) - traj * Rand.GetRandomFloat(0.001f, 0.1f), 1f, 1f, 1f, 0.25f, Rand.GetRandomFloat(0.05f, 0.25f), Rand.GetRandomInt(0, 4))); AddParticle(new Smoke(loc, Rand.GetRandomVector2(-50f, 50f, -50f, 10f), 0.5f, 0.5f, 0.5f, 0.25f, Rand.GetRandomFloat(0.1f, 0.5f), Rand.GetRandomInt(0, 4))); } } /// <summary> /// Make blood splash that splatters in a direction. /// </summary> /// <param name="loc">Location of blood impact</param> /// <param name="traj">Blood splatter direction</param> public void MakeBloodSplash(Vector2 loc, Vector2 traj) { traj += Rand.GetRandomVector2(-100f, 100f, -100f, 100f); for (int i = 0; i < 64; i++) { AddParticle(new Blood(loc, traj * Rand.GetRandomFloat(0.1f, 3.5f) + Rand.GetRandomVector2(-70f, 70f, -70f, 70f), 1f, 0f, 0f, 1f, Rand.GetRandomFloat(0.01f, 0.25f), Rand.GetRandomInt(0, 4))); AddParticle(new Blood(loc, traj * Rand.GetRandomFloat(-0.2f, 0f) + Rand.GetRandomVector2(-120f, 120f, -120f, 120f), 1f, 0f, 0f, 1f, Rand.GetRandomFloat(0.01f, 0.25f), Rand.GetRandomInt(0, 4))); } MakeBulletDust(loc, traj * -20f); MakeBulletDust(loc, traj * 10f); } public ParticleManager(SpriteBatch sprite) { this.sprite = sprite; } /// <summary> /// Create new particle. /// </summary> /// <param name="newParticle">Particle to create</param> public void AddParticle(Particle newParticle) { AddParticle(newParticle, false); } /// <summary> /// Create new particle. /// </summary> /// <param name="newParticle">Particle to create</param> /// <param name="background">Specifies whether the particle is drawn behind characters or in front of them</param> public void AddParticle(Particle newParticle, bool background) { AddParticle(newParticle, background, false); } /// <summary> /// Creates new particle. /// </summary> /// <param name="newParticle">Particle to create</param> /// <param name="background">Specifies whether the particle is drawn behind characters or in front of them</param> /// <param name="netSent">Tells if particle has been sent over the network. If it hasn't, it will be flagged to be sent over the network at the next send.</param> public void AddParticle(Particle newParticle, bool background, bool netSent) { for (int i = 0; i < particle.Length; i++) { if (particle[i] == null) { particle[i] = newParticle; particle[i].Background = background; if (!netSent) { if (Game1.NetPlay.Joined) { if (particle[i].Owner == 1) particle[i].netSend = true; else particle[i] = null; } else if (Game1.NetPlay.Hosting) { if (particle[i].Owner != 1) particle[i].netSend = true; else particle[i] = null; } } break; } } } /// <summary> /// Update all active particles. /// </summary> /// <param name="frameTime">Time delta that has elpased since the last udpate</param> /// <param name="map">The game map</param> /// <param name="c">The characters array</param> public void UpdateParticles(float frameTime, Map map, Character[] c) { for (int i = 0; i < particle.Length; i++) { if (particle[i] != null) { particle[i].Update(frameTime, map, this, c); if (!particle[i].Exists) { particle[i] = null; } } } } /// <summary> /// Write all sendable particles to the network packet writer. /// </summary> /// <param name="writer">PacketWriter to write to</param> public void NetWriteParticles(PacketWriter writer) { for (int i = 0; i < particle.Length; i++) if (particle[i] != null) { if (particle[i].netSend) { particle[i].NetWrite(writer); particle[i].netSend = false; } } } /// <summary> /// Draw all active particles. /// </summary> /// <param name="spritesTex">Texture to use for particles</param> /// <param name="background">Specifies whether this is a background draw pass or foreground draw pass</param> public void DrawParticles(Texture2D spritesTex, bool background) { sprite.Begin(SpriteSortMode.BackToFront, BlendState.AlphaBlend); foreach (Particle p in particle) { if (p != null) { if (!p.Additive && p.Background == background && !p.refract) p.Draw(sprite, spritesTex); } } sprite.End(); sprite.Begin(SpriteSortMode.BackToFront, BlendState.Additive); foreach (Particle p in particle) { if (p != null) { if (p.Additive && p.Background == background && !p.refract) p.Draw(sprite, spritesTex); } } sprite.End(); } /// <summary> /// Draw all active refract particles. Refractive particles are covered in chapter 11. /// </summary> /// <param name="spritesTex">Texture to use for particles</param> public void DrawRefractParticles(Texture2D spritesTex) { sprite.Begin(SpriteSortMode.BackToFront, BlendState.AlphaBlend); foreach (Particle p in particle) { if (p != null) { if (p.refract) p.Draw(sprite, spritesTex); } } sprite.End(); } } }
36.48538
171
0.467863
[ "MIT" ]
tlzyh/ZombieSmashersXNA4
GameZS/Particles/ParticleManager.cs
12,478
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class CurvedWeightedTest : MonoBehaviour { public List<Transform> weightedTransforms; public AnimationCurve weightCurve; private Wrj.WeightedElements<Transform> weightedElements; // Start is called before the first frame update void Start() { weightedElements = new Wrj.WeightedElements<Transform>(weightedTransforms, weightCurve); StartCoroutine(testRandomLoop()); } // Update is called once per frame void Update() { } IEnumerator testRandomLoop() { while (true) { Transform affected = weightedElements.GetRandom(true); float initY = affected.localScale.y; Vector3 targetScale = affected.localScale.With(y: initY + .1f); Wrj.Utils.MapToCurve.Ease.Scale(affected, targetScale, .1f); Wrj.Utils.MapToCurve.Ease.Move(affected, affected.LocalPosInDir(up: .05f), .1f); Wrj.Utils.MapToCurve.Ease.ChangeColor(affected, Color.Lerp(Color.white, Color.black, (initY - 1) / 10), .1f); yield return new WaitForSecondsRealtime(.1f); } } }
32.594595
121
0.66335
[ "MIT" ]
williamrjackson/BallBlastUnityCaseStudy
Assets/UnityScriptingUtilities/Example/CurvedWeightedTest.cs
1,208
C#
 namespace Magellan.Events { /// <summary> /// This event indicates that the action has been resolved, and pre-action filters are /// about to be invoked. /// </summary> public class PreActionFiltersNavigationEvent : NavigationEvent { } }
25.272727
92
0.640288
[ "MIT" ]
CADbloke/magellan-framework
src/Magellan/Events/PreActionFiltersNavigationEvent.cs
280
C#
namespace Ecoset.WebUI.Models { public class PaymentRequest { public decimal Amount {get;set;} public string Description {get;set;} public string ThirdPartyHash {get;set;} } }
26
47
0.658654
[ "MIT" ]
AndrewIOM/ecoset
src/web/Ecoset.WebUI/Areas/Payments/Models/PaymentRequest.cs
208
C#
using DapperInfrastructure.Extensions.Domain; using DapperInfrastructure.Extensions.Domain.Base; namespace BH.Domain.Entity.Base { /// <summary> /// 基于类型Int的Domain实体 /// </summary> public abstract class EntityWidthIntType : EntityByType<int> { /// <summary> /// 主键ID /// </summary> [Dapper.Contrib.Extensions.Key] public override int Id { get; set; } } }
22.210526
64
0.625592
[ "MIT" ]
Cotide/Dapper-Infrastructure
Code/BH.Domain/Entity/Base/EntityWidthIntType.cs
442
C#
using FreeSql.DataAnnotations; using System; using Xunit; namespace FreeSql.Tests.Odbc.PostgreSQL { public class PostgreSQLDbFirstTest { [Fact] public void GetDatabases() { var t1 = g.pgsql.DbFirst.GetDatabases(); } [Fact] public void GetTablesByDatabase() { var t2 = g.pgsql.DbFirst.GetTablesByDatabase(g.pgsql.DbFirst.GetDatabases()[1]); } } }
17.384615
92
0.590708
[ "MIT" ]
Coldairarrow/FreeSql
FreeSql.Tests/FreeSql.Tests.Provider.Odbc/PostgreSQL/PostgreSQLDbFirstTest.cs
452
C#
using Microsoft.Extensions.DependencyInjection; using NativoPlusStudio.AuthToken.Core; using NativoPlusStudio.AuthToken.Core.Extensions; using NativoPlusStudio.AuthToken.Core.Interfaces; using NativoPlusStudio.AuthToken.FIS.Configuration; using Polly; using System; namespace NativoPlusStudio.AuthToken.FIS.Extensions { public static class FisServiceCollectionExtensions { public static IServiceCollection AddFisAuthTokenProvider(this IServiceCollection services, Action<FisAuthTokenOptions, AuthTokenServicesBuilder> actions ) { var fisOptions = new FisAuthTokenOptions(); var servicesBuilder = new AuthTokenServicesBuilder() { Services = services }; actions.Invoke(fisOptions, servicesBuilder); services.AddTokenProviderHelper(fisOptions.ProtectedResource, () => { services.Configure<FisAuthTokenOptions>(f => { f.BaseUrl = fisOptions.BaseUrl; f.UserName = fisOptions.UserName; f.Password = fisOptions.Password; f.ProtectedResource = fisOptions.ProtectedResource; f.IncludeEncryptedTokenInResponse = fisOptions.IncludeEncryptedTokenInResponse; f.CheckSystems = fisOptions.CheckSystems; }); services .AddHttpClient<IAuthTokenProvider, FisAuthTokenProvider>(client => { client.DefaultRequestHeaders.Add("SOAPAction", ""); client.BaseAddress = new Uri(fisOptions.BaseUrl); }) .AddTransientHttpErrorPolicy(builder => builder.WaitAndRetryAsync(new[] { TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(5), TimeSpan.FromSeconds(10) })) .AddTransientHttpErrorPolicy(builder => builder.CircuitBreakerAsync( handledEventsAllowedBeforeBreaking: 3, durationOfBreak: TimeSpan.FromSeconds(30) )); services.AddTransient(implementationFactory => servicesBuilder.EncryptionService); services.AddTransient(implementationFactory => servicesBuilder.TokenCacheService); }); return services; } } }
40.847458
99
0.615353
[ "MIT" ]
nativoplus/NativoPlusStudio.AuthToken.Fis
NativoPlusStudio.AuthToken.FIS/Extensions/FisServiceCollectionExtensions.cs
2,412
C#
using System.Collections.Generic; using Microsoft.AspNetCore.Identity; namespace Viato.Api.Entities { public class AppUser : IdentityUser<long> { public virtual List<Organization> Organizations { get; set; } = new List<Organization>(); } }
23.818182
97
0.71374
[ "Apache-2.0" ]
viato/viato-api
src/Viato.Api/Entities/AppUser.cs
264
C#
using System; using AppRopio.Base.Core.Services.Router; using AppRopio.Base.Core.Services.ViewModelLookup; using AppRopio.ECommerce.Marked.Core.Services; using AppRopio.ECommerce.Marked.Core.Services.Implementation; using AppRopio.ECommerce.Marked.Core.ViewModels.Marked; using AppRopio.ECommerce.Marked.Core.ViewModels.Marked.Services; using MvvmCross.Core.ViewModels; using MvvmCross.Platform; using MvvmCross.Plugins.Messenger; namespace AppRopio.ECommerce.Marked.Core { public class App : MvxApplication { public override void Initialize() { Mvx.CallbackWhenRegistered<IMvxMessenger>(() => Mvx.RegisterSingleton<IMarkedObservableService>(new MarkedObservableService())); Mvx.RegisterSingleton<IMarkedConfigService>(() => new MarkedConfigService()); Mvx.RegisterSingleton<IMarkedVmService>(() => new MarkedVmService()); #region VMs registration var vmLookupService = Mvx.Resolve<IViewModelLookupService>(); vmLookupService.Register<IMarkedViewModel, MarkedViewModel>(); #endregion //register start point for current navigation module var routerService = Mvx.Resolve<IRouterService>(); routerService.Register<IMarkedViewModel>(new MarkedRouterSubscriber()); } } }
35.945946
140
0.725564
[ "Apache-2.0" ]
cryptobuks/AppRopio.Mobile
src/app-ropio/AppRopio.ECommerce/Marked/Core/App.cs
1,332
C#
using System; using System.Collections.Generic; using Umbraco.Core.Events; using Umbraco.Core.Logging; using Umbraco.Core.Models; using Umbraco.Core.Persistence.Repositories; using Umbraco.Core.Scoping; namespace Umbraco.Core.Services.Implement { internal class RedirectUrlService : ScopeRepositoryService, IRedirectUrlService { private readonly IRedirectUrlRepository _redirectUrlRepository; public RedirectUrlService(IScopeProvider provider, ILogger logger, IEventMessagesFactory eventMessagesFactory, IRedirectUrlRepository redirectUrlRepository) : base(provider, logger, eventMessagesFactory) { _redirectUrlRepository = redirectUrlRepository; } public void Register(string url, Guid contentKey, string culture = null) { using (var scope = ScopeProvider.CreateScope()) { var redir = _redirectUrlRepository.Get(url, contentKey, culture); if (redir != null) redir.CreateDateUtc = DateTime.UtcNow; else redir = new RedirectUrl { Key = Guid.NewGuid(), Url = url, ContentKey = contentKey, Culture = culture}; _redirectUrlRepository.Save(redir); scope.Complete(); } } public void Delete(IRedirectUrl redirectUrl) { using (var scope = ScopeProvider.CreateScope()) { _redirectUrlRepository.Delete(redirectUrl); scope.Complete(); } } public void Delete(Guid id) { using (var scope = ScopeProvider.CreateScope()) { _redirectUrlRepository.Delete(id); scope.Complete(); } } public void DeleteContentRedirectUrls(Guid contentKey) { using (var scope = ScopeProvider.CreateScope()) { _redirectUrlRepository.DeleteContentUrls(contentKey); scope.Complete(); } } public void DeleteAll() { using (var scope = ScopeProvider.CreateScope()) { _redirectUrlRepository.DeleteAll(); scope.Complete(); } } public IRedirectUrl GetMostRecentRedirectUrl(string url) { using (var scope = ScopeProvider.CreateScope(autoComplete: true)) { return _redirectUrlRepository.GetMostRecentUrl(url); } } public IEnumerable<IRedirectUrl> GetContentRedirectUrls(Guid contentKey) { using (var scope = ScopeProvider.CreateScope(autoComplete: true)) { return _redirectUrlRepository.GetContentUrls(contentKey); } } public IEnumerable<IRedirectUrl> GetAllRedirectUrls(long pageIndex, int pageSize, out long total) { using (var scope = ScopeProvider.CreateScope(autoComplete: true)) { return _redirectUrlRepository.GetAllUrls(pageIndex, pageSize, out total); } } public IEnumerable<IRedirectUrl> GetAllRedirectUrls(int rootContentId, long pageIndex, int pageSize, out long total) { using (var scope = ScopeProvider.CreateScope(autoComplete: true)) { return _redirectUrlRepository.GetAllUrls(rootContentId, pageIndex, pageSize, out total); } } public IEnumerable<IRedirectUrl> SearchRedirectUrls(string searchTerm, long pageIndex, int pageSize, out long total) { using (var scope = ScopeProvider.CreateScope(autoComplete: true)) { return _redirectUrlRepository.SearchUrls(searchTerm, pageIndex, pageSize, out total); } } public IRedirectUrl GetMostRecentRedirectUrl(string url, string culture) { if (string.IsNullOrWhiteSpace(culture)) return GetMostRecentRedirectUrl(url); using (var scope = ScopeProvider.CreateScope(autoComplete: true)) { return _redirectUrlRepository.GetMostRecentUrl(url, culture); } } } }
34.764228
124
0.598924
[ "MIT" ]
AaronSadlerUK/Umbraco-CMS
src/Umbraco.Core/Services/Implement/RedirectUrlService.cs
4,278
C#
using Conductor.Repositories.DTO; namespace Conductor.Repositories { public interface IArtistRepository { ArtistDTO GetArtist(string key); ArtistDTO GetArtistByMacAddress(string macAddress); void CreateArtist(ArtistDTO artist); void BindArtistToEnsemble(ArtistDTO artist, EnsembleDTO ensemble); } }
23.133333
74
0.729107
[ "Apache-2.0" ]
carstengehling/bigband
Conductor/Repositories/IArtistRepository.cs
349
C#
using System; using System.Collections.Generic; using System.Collections.Specialized; using System.Numerics; using ImGuiNET; using Microsoft.Xna.Framework.Graphics; using Parme.Core; namespace Parme.Editor.Ui.Elements.Editors { public class TextureSectionDisplayEditor : SettingsEditorBase { private readonly List<TextureSectionCoords> _sections = new List<TextureSectionCoords>(); private readonly TextureSectionEditor _textureSectionEditor; private Texture2D _texture; private IntPtr? _imguiTextureId; public TextureSectionDisplayEditor() { _textureSectionEditor = new TextureSectionEditor(); } protected override void CustomRender() { ImGui.Text($"# Of Sections: {_sections.Count}"); if (_texture != null && _imguiTextureId != null) { if (ImGui.Button("Edit")) { _textureSectionEditor.Open(); } ImGui.NewLine(); ImGui.Columns(2, "sections", false); foreach (var section in _sections) { var size = new Vector2(80, 80); var uv0 = new Vector2(section.LeftX / (float) _texture.Width, section.TopY / (float) _texture.Height); var uv1 = new Vector2(section.RightX / (float) _texture.Width, section.BottomY / (float) _texture.Height); ImGui.Image(_imguiTextureId.Value, size, uv0, uv1); ImGui.NextColumn(); } ImGui.Columns(1); _textureSectionEditor.Render(); } } protected override void OnNewSettingsLoaded() { _sections.Clear(); _sections.AddRange(EmitterSettings.TextureSections ?? Array.Empty<TextureSectionCoords>()); if (string.IsNullOrWhiteSpace(EmitterSettings.TextureFileName)) { if (_imguiTextureId != null) { MonoGameImGuiRenderer.UnbindTexture(_imguiTextureId.Value); } _texture = null; _imguiTextureId = null; } else { _texture = TextureFileLoader.LoadTexture2D(EmitterSettings.TextureFileName); _imguiTextureId = MonoGameImGuiRenderer.BindTexture(_texture); } if (_texture != null) { // Since we have no texture, there's no point to the section editor existing, so don't bother // doing anything until we actually have a texture loaded _textureSectionEditor.ApplicationState = ApplicationState; _textureSectionEditor.CommandHandler = CommandHandler; _textureSectionEditor.MonoGameImGuiRenderer = MonoGameImGuiRenderer; _textureSectionEditor.AppOperationQueue = AppOperationQueue; _textureSectionEditor.TextureFileLoader = TextureFileLoader; _textureSectionEditor.EmitterSettings = EmitterSettings; } } protected override void OnSelfManagedPropertyChanged(string propertyName) { } } }
36.912088
126
0.574278
[ "MIT" ]
KallDrexx/PaRME
Parme.Editor/Ui/Elements/Editors/TextureSectionDisplayEditor.cs
3,361
C#
using UnityEngine; using System; using System.Collections; // Создать ещё 4 уровня чтобы их было 5 не считая тренировочного с ним будет 6 // Похоже что в коде для стола придёться расширить количество доступных материалов для него до 5, и изменить назначения материалов. А именно (1 и 2 материал для поля), а (3, 4 и 5 для бордюра) // При отображении четырёх активных объектов в игре на двоих проявляеться полоска, а также в игре на одного должно быть тоже самое, также эта полоска есть в финале тоже на аватарках всё из за того что три картинки накладываються друг на друга // .Когда буду рендерить готовые окна для этих меню нужно рендерить с уже готовыми квадратами // Добавить в скрипт фотограф выбор сглаживания с помощью перечисления. а также перенести туда переменные EdgeSharpness и EdgeTreshold они обе влияют на настройку сглаживания // Проверить используеть ся ли гуи стиль "TotalScoreText" или его можно удалять // Урезать силу начальной биты настолько чтобы она оставалась всё ещё сильнее тренирововчной биты но слабее её если на неё навесить улучшение // Сделать чтобы при сохранении игры появлялься значёк в правом верхнем углу // После того как мы сыграем раунд в игре и вернёмся в главное меню у нас сложиться ситуация что у нас 2 элемента IndestructbleObject по этому после того как я сделаю сохранение игры, То я сделаю чтобы по нажатии кнопки // В главное меню удалялься IndestructbleObject // После повторного старта кнопки начать заного после гола тебе и гола противнику вылазиет ошибка в связи с событием гола возможно не подписан заного или не отписано событие решить // чтобы шайба не вылетала за пределы поля когда её тихо толкают через него. Можно попробовать брать её Velocity нормализовывать её и плюсовать к ней (Сила толкающей биты умноженная на массу толкающей биты) // плюс нужно узнать массу шайбы и приплюсовать к ней такую силу чтобы она раза в два превышала ту силу что находиться у биты // 1) Тоесть множим силу толкающей биты на её массу например 1*10 = 10 // 2) Берём массу шайбы например 1 = 1 // 3) Мы видим что масса шайбы в 10 раз меньше биты поэтому умножаем её значение на 10 // 4) Берём вектор шайбы как обычно отражаем его, нормализуем и умножаем на вдвое большее число чем это необходимо чтобы отталкивало биту это на 20 // 5) Но так бита становиться слишком быстрая а нам нужно чтобы она лишь отбросила биту, тогда можно оставлять ту же скорость но увеличивать на 1 секунду массу шайбы в 2 превышаюшую биту толкатель // 6) Возможно шайба вылетает потому что когда она отталкиваеться например от нижнего борта и летит вверх то пускает луч в верхний борт и последняя точка Hit для неё вверху в этот момент бита пускает её в низ и она не // успевает пустить луч в низ а по команде когда она не врезаеться в борт она использует последнюю точку в итоге используя последнюю точку она летит сквозь борт. Если не сработает последний способ надо придумать что нибуть // ещё // Исправить : Сделать чтобы размер текста (в меню создании профиля, в главном меню и в финальном окне уровня) высчитывалься тем же способом что и высчитываеться в скрипте PauseMenu методе StartGame проверяем 20 символами W // В скрипте StoreAndInventory удалить метод CalculateTNMatAndImr если он не используеться // В магазине в окошках улучшений и материалов не показываеться дополнительный задний мини-фон космоса // В магазине и инвентаре сделать у улучшений чтобы информационное окно отображало энергию улучшения и скорость восстановления улучшений, также тип переключаемый или активируемый и количество активаций до перезарядки если есть // Информационное окно отображает названия и информацию закрытых улучшений хотя должно писать как и у раскрасок информация закрыта // Сделать чтобы в случае не совпадения HasTab или его отсутствия или не прочтения игра не загружала это сохранение а загружала новое // Сделать наброски в Gimp 2 для новых изображений в игре // Сделать сообщение в нормальной форме для игры, убрав сообщения в консоли. Это сообщение если не хватает денег чтобы купить в игре стол а также сообщение что если стола нет то для него нельзя получить улучшение или материал // Написать PauseMenu + где будут выводиться дополнительные окна и использовать для них наброски // Сделать чтобы правильно выставлялась шайба при старте и после гола // Также после гола нужно ставить секундомер на 0 // Почемуто биты и шайба двигаються дёрганно. Как этого избежать? // Сделать чтобы если игрок пытаеться купить в магазине предмет а денег не хватает или он попросту закрыт. То проигрываем звук а в окне с объектом пишем объект закрыт или недостаточно денег или если это материал или улучшение // .....Недостаточно опыта берём тот же метод что и когда отсутствует профиль тоже самое и с деньгами // 1) Дописать программу стартового окна и начала обучения (протестировать как работают обновлённая физика и скрипты управления) // 2) Доделать магазин // В скрипте лавное меню и меню паузы убрать закоментированные старые строчки кода, выяснить какие переменные необязательны быть публичными и // сделать их приватными а также убрать лишние строчки кода во всех скриптах // Переместить методы по очереди мо смыслу и названиям в скрипте // тоже самое сделать в скриптах ObjScript и ImprovementScript // Исправить, когда стол отображаеться в окне магазина у его частей (это бордюр и поле) какие то странные углы поворота должны быть 0,0,0 Видимо стол так инстантируеться. А ещё так он инстантируеться в вигре на двоих и в окошке инвентаря там тоже это // надо исправить. // Если несколько раз создавать и удалять профили игра виснет при следующей загрузке. Скорей всего из за создания битого сохранения. Либо из за незавершённого процесса серриализации и открытого потока до следующей перезагрузки компа // Предпринять две вещи 1) отрубать доступ у игрока к инвентарю до конца процесса серриализации. и 2) сделать // чтобы битые сохранения не грузились. Определяем по весу файла хеш коду // я переделал некоторые переменные сохранения short в sbyte теперь вылазиет ошибка.. Нужно проверить в каком она месте, когда найду нужно в // скрипте PauseMenu сделать ActiveProfile тоже такойже переменной Sbyte // При нажатии на кнопку выхода из игры в главном меню сделать чтобы вылазило окошко подтверждения // 3) Cделать инвентарь игрока // 4) Сделать полное обучение Прохождение будет начинаться с нулевого уровня - обучения. далее будет обучение в магазине // 5) Заново сделать режим игрок против игрока (в игре игрок против игрока 2 игрок будет ставиться с противоположной стороны сохранённой // при прохождении первым игроком // Улушить графику : В конце игры сделть тень от стрелок падующую на меню. Тень отрендерить в ту же картинку что и стрелки // Улушить графику : В конце игры текстурировать цифры показывающие счёт уровня // Сделать магазин, разделить его на 4 категории первая биты, вторая шайбы, третяя игровые поля, четвёртая скайбоксы // У начальной биты и тренировочной биты разный размер при фотографиях и просмотре в инвентаре я исправил прыгание бит но размер отличаеться на пару пикселов убрать эту разницу // Убрать из скрипта Main menu переменную аудиоклипа и использовать её из специального скрипта работающего со звуками // Сделать чтобы освещение биты выключалось не резко а плавно уменьшаясь в размере и освещённости // В меню смены профиля и в магазине сделать отрисовку имени профиля для удобства // В режиме прохождения при выборе предметов для игры сделать другую текстуру вместо крестов для недоступных для выбора предметов типа панели с заклёпками // Разобраться со стилями которые я создавал отдельно для кнопок материалов(Если создавал), я решил не использовать для улучшений круглешки а остваить квадраты как и у материалов и переименовать таке стили как pricemats в другие говорящие что теперь... // ... они используються для обоих видов окон для материалов и для улучшений.(Пройтись по всем своим стилям и поискать во всех файлах. И те что не используються удалить) // ( Уровень - Сотоит из нескольких раундов) // ( Раунд - Состоит из времени от начала раунда до гола одному из игроков) // -------------------------------------------------------------------------------------------------------------Второстепенные задачи---------------------------------------------------------------------------------------------------------------------------- // 1) Появилась полоса в меню на фоне обзора предмета, такаяже как раньше была на аватарке нужно совместить несколько текстур // картинках 4 активных объектах какие то полоски по бокам я выячнил что это из за сглаживания настраевосого в настройках качествра и вообще из за того что окна писксель в пиксель не поподают. Решить это можно отображая картинку сзади кнопки // 2) тогда кнопка будет закрывать эти края // 3) Если во время забитого гола нажать ескейп вылезет меню паузы хотя оно должно вылазить только после того как просвестит свисток и начнёться следующий раунд // 4) При создании профиля при нажатии на поле имени буквы должны стираться // 5) Убрать ограничение имени профиля на 2 буквы и сделать ограничение на одну // -----------------------------------------------------------------------------------------------------------Мелочи 3 степенные задачи---------------------------------------------------------------------- // 1) Удалить Gui стиль avatar похоже он больше не используеться // ------------------------------------------------------------------------------------------ Стандартные показатели бит и шайб ----------------------------------------------------------------------------------- // Все биты - Mass - 1, Drag - 5, AngularDrag 0.05 // Скрипт: // NimbleBat: Mass 1.3, Force - 12 // OldBat: Mass 1.2, Force - 10 // TraningBat: Mass 1.2, Force - 5 // BeginnerPuck: Mass 1 Force - 0 // EasyTouch: Mass 1.1, Force - 0 // -------------------------------------------------------------------------- Показатели высокоуровневых бит и шайб для демонстрации физики и геймплея ----------------------------------------------------------- // Все биты - Mass - 1, Drag - 5, AngularDrag 0.05 // Сила бит * 10 // Масса бит * 2 // Масса шайб / 2 // NimbleBat: Mass 2.6, Force - 120 // OldBat: Mass 2.4, Force - 100 // TraningBat: Mass 2.4, Force - 50 // BeginnerPuck: Mass 0.5 Force - 0 // EasyTouch: Mass 0.55 Force - 0 public class GameManager : MonoBehaviour { public delegate void EventDelegate(); // Объявляем делегат для событий с возвращаемым типом значения Void // public delegate void ChangeProfDelegate(byte nomber); // Делегат для события ChangeProfile (для обозначения отсутствия активных профилей теперь используеться цифра 10) public event EventDelegate StartFirstStep; // Событие старта уровня "Первый шаг" public event EventDelegate StartSecondStep; // Событие старта уровня "Второй шаг" "Запускаеться после завершения первого шага" public event EventDelegate StartGameEvent; // Событие которое происходит при нажатии кнопки старт public event EventDelegate GoalEvent; // Событие гола public event EventDelegate LastGoalEvent; // Событие последнего гола public event EventDelegate SaveGameEvent; // Событие сохранения файла игры public event EventDelegate LoadGameEvent; // Событие загрузки файла игры // public event ChangeProfDelegate ChangeProfile; // Событие смены активного профиля // public Mode GameMode; // Режим игры public GameObject Table; // Ссылка для клона стола public GameObject Player1; // Ссылка на клон префаба биты 1 ого игрока public GameObject Player2; // Ссылка на клон префаба биты 2 ого игрока public GameObject AIBat; // Клон префаба биты компьютерного противника для режима прохождения public GameObject Puck; // Ссылка на клон префаба шайбы public short[] ObjPrize; // Призы - Номера объектов в массиве ObjectsStore который мы хотим открыть или несколько объектов public byte[] TableNomForMat; // Номера столов для которых требуеться открыть материалы public byte[] TableNomForImpr; // Номера столов для которых требуеться открыть улучшения public byte[] SkyPrize; // Призы - Номерв Скайбоксов в массиве SkyboxMats и SkyboxScreens который мы хотим открыть или несколько скайбоксов public byte[] TableMatPrize; // Призы материалы для столов в массиве TableNomForMat public byte[] TableImprPrize; // Призы материалы для столов в массиве TableNomForImpr public byte[] PAON = new byte[] {1, 1, 1}; // (PlayersAvctiveObjectsNombers) номера игроков(тоесть каждая переменная принимает только 1 или 2 соответствующую номеру игрока) для каждой категории 1 шайба, 2 стол, 3 скайбокс public ushort Bonus; // Дополнительный бонус кредитов на весь уровень для возмещения редко встречаемых сложностей от уровня к уровню public Vector3 StandPoint; // Точка на которую бита возвращаеться для защиты ворот public PauseMenu PM; // Переменная для скрипта "Меню паузы" public StoreContent SC; // Переменная для скрипта "Контент магазина" public Keeper Kep; // Переменная для скрипта "Хранитель" (или глобальная база данных) public Keeper LocalKep; // Локальная база данных нужна для второго профиля на сулчай если в игре на двоих оба игрока решили выбрать один профиль public Keeper Currentkep; // Сдесь в зависимости от условий будет находиться либо Kep либо LocalKep public StoreAndInventory SAI; // Переменная для скрипта "Хранитель" public bool Pause = false; // Переменная говорящая находиться ли игра в режиме паузы public bool GoalTrue = false; // Становиться правда если комуто был забит гол (Предохранитель от повторных голов за одну секунду) public bool RoundStarted; // Переменная говорящая начался ли раунд или игрок выбирает биты и шайбы ArtificialIntelligence AI; // Переменная для скрипта "искуственный интеллект" для биты компьютера public GameObject Gate; // Переменная для префаба ворот public Vector3 FirstPos; // Это позиция шайбы для первого игрока public Vector3 SecondPos; // Это позиция шайбы для второго игрока public Vector3 SPP1; // (Start Player Position 1) Это стартовая позиция первого игрока public Vector3 SPP2; // (Player Player Position 2) Это стартовая позиция второго игрока GameObject G1; // Ссылка на клон префаба ворот для 1 игрока public GameObject G2; // Ссылка на клон префаба ворот для 2 игрока Vector3 GP1; // (Gate Position 1) Это позиция ворот первого игрока Vector3 GP2; // (GatePosition 2) Это позиция ворот второго игрока public float WidthGate; // Ширина ворот public byte LastGoal; // Номер последних ворот в которые был забит гол public int WasherPosition; // Переменная "Позиция фишки" нужна чтобы при старте раунда определить у кого из игроков появиться фишка short residue; // Длительность последнего раунда в секундах // byte Player2Profile = 0; // Номер профиля второго игрока для игры на двоих void Start () { StartGameEvent += StartGame; // Подписываем метод "Старт игры" на событие StartGameEvent GoalEvent += Goal; // Подписываем метод "Гол" на событие GoalEvent LastGoalEvent += FinalGoal; // Подписываем метод "Последний гол" на событие LastGoalEvent GameObject GaObj = GameObject.Find("IndestructibleObject"); // Находим на сцене объект "IndestructibleObject" SC = GaObj.GetComponent<StoreContent>(); // Скрипт "StoreContent" и ложим в переменную SC Kep = GaObj.GetComponent<Keeper>(); // Скрипт "Keeper" Ложим в переменную Kep SAI = GaObj.GetComponent<StoreAndInventory>(); // Скрипт "StoreAndInventory" Ложим в переменную SAI WasherPosition = UnityEngine.Random.Range (1, 3); // генерируем случайным образом число от 1 или 2 StartFirstStep += _StartFirstStep_; // Подписываем метод _StartFirstStep_ на событие StartFirstStep Currentkep = Kep; // Ложим в текущую базу данных глобальную if(UnityEngine.SceneManagement.SceneManager.GetActiveScene().buildIndex != 0) // Если активная сцена не сцена главного меню { Kep.PM = GetComponent<PauseMenu>(); // Получаем скрипт PauseMenu и ложим в переменную PM скрипта Keeper Kep.PMP = GetComponent<PauseMenuPlus>(); // Получаем скрипт PauseMenuPlus и ложим его в переменную PMP скрипта Keeper SAI.PM = GetComponent<PauseMenu>(); // Получаем скрипт PauseMenu и ложим в переменную PM скрипта StoreAndInventory Kep.GM = this; // Ложим этот скрипт в переменную GM скрипта Keeper SAI.GM = this; // Ложми этот скрипт в переменную GM скрипта StoreAndInventory PM.PlayersInform = GaObj.transform.GetChild(0).GetComponent<Canvas>(); // Находим канвас PlayerInformation и ложим в переменную PM.PlayerInform LocalKep = this.gameObject.AddComponent<Keeper>(); // Создаём новый компонент Keeper на объеке GameManager и присваиваем его как новую локальную базу данных с уже заполненными значениями базы данных kep CallStartFirstStep(); // Вызываем событие StartFirstStep пользуясь для этого методом CallStartFirstStep } } void _StartFirstStep_() // Этот метод вызываеться после выполнения метода FillObjTex в скрипте keeper { CalculatePosObjects(); // Расчитываем позиции объектов SetStartPositions(); // Расставляем выбранные объекты по своим местам StartSecondStep(); // Вызываем событие второго шага } public void RepeatLevel() // Этот метод обнуляет результаты и ставит стартовое окно для игры заного { PM.TimeMoves = true; // Говорим что времени снова можно идти RoundStarted = false; // Говорим что раунд ещё не началься GetComponent<AudioSource>().Stop(); // Прекращаем проигрывание музыки аплодисментов PM.Min = PM.Sec = 0; // Обнуляем время раунда минуты и секунды PM.LPS = PM.RPS = 0; // Обнуляем очки правого и левого игрока PM.ScorePlayer1 = PM.ScorePlayer2 = 0; // Обнуляем очки первого и второго игрока PM.Rounds = 0; // Обнуляем количество отыгранных раундов PM.LPFC = PM.RPFC = 0; // Обнуляем количество заработанных кредитов за раунд у левого и правого игрока GoalTrue = false; // Сообщаем переменной GoalTrue что в этом раунде ещё не кому не был забит гол RestartGameObjects(); // Расставляем объекты по местам PM.Window = GameMenuWins.Start; // Ставим окно старта Debug.Log(PM.LPS + " " + PM.RPS); } void StartGame() { Debug.Log("Запущенно событие старта игры"); if (WasherPosition == 1) // Если переменная WasherPosition равна 1 Puck.transform.position = FirstPos; // Ставим шайбу в первую позицию else if (WasherPosition == 2) // Если переменная WasherPosition равна 2 Puck.transform.position = SecondPos; // Ставим шайбу во вторую позицию if(UnityEngine.SceneManagement.SceneManager.GetActiveScene().name != "PlayerVsPlayer") // Если это не сцена для игры на двоих Player2.GetComponent<ArtificialIntelligence>().AIActivation(); // Вызываем активацию искуственного интеллекта у второго игрока RoundStarted = true; // Ставим значение переменной RoundStarted правда Pause = false; // Сбрасываем игру с паузы } public void CalculatePosObjects() // Этот метод на основе разных параметров определяет позиции объектов { byte LevelTable = 0; // Это временная переменная для стола float FP = SC.ObjectsStore[Kep.ActiveObjects[Kep.ActiveProfile, 0]].GetComponent<MeshRenderer>().bounds.size.x; // Получаем диаметр биты 1 игрока float PuckSize = SC.ObjectsStore[Kep.ActiveObjects[Kep.ActiveProfile, 1]].GetComponent<MeshRenderer>().bounds.size.x; // Получаем размер шайбы float LOTF = 0; // Длинна от центра поля до ворот float SP = 0; // Ставим диаметр биты второго игрока в начале как 0 if(UnityEngine.SceneManagement.SceneManager.GetActiveScene().name != "PlayerVsPlayer") // Если это не сцена для игры на двоих) { LevelTable = Table.GetComponent<ObjectScript>().ObjectLevel; // Получаем уровень стола и присваиваем этот уровень переменной LevelTable WidthGate = (float)(((LevelTable-1) * 110) * 0.04 + 4); // Получаем ширину ворот для данного поля SP = AIBat.GetComponent<MeshRenderer>().bounds.size.x; // Получаем диаметр биты компьютерного противника и присваиваем как диаметр биты второго игрока LOTF = (float)(((LevelTable-1) * 25) * 0.18 + 18) / 2; // Вычисляем длинну от центра поля до ворот и присваиваем её переменной LOTF(LengthOfThisField) } else // Иначе если это сцена игры на двоих { if(Kep.SecondActiveProfile == 10) // Если для второго игрока не выбран активный профиль { SP = ((GameObject)Resources.Load("Models/Prefabs/Bats/1_Level/GhostBat")).GetComponent<MeshRenderer>().bounds.size.x; // Получаем размер биты призрачной шайбы по оси x LevelTable = SC.ObjectsStore[Kep.ActiveObjects[Kep.ActiveProfile, 2]].GetComponent<ObjectScript>().ObjectLevel; // Получаем уровень активного стола первого игрока и присваиваем этот уровень переменной LevelTable LOTF = (float)(((LevelTable-1) * 25) * 0.18 + 18) / 2; // Вычисляем длинну от центра поля до ворот и присваиваем её переменной LOTF(LengthOfThisField) } else // Иначе если для второго игрока выбран активный профиль { // высчитываем позиции по другой схеме SP = SC.ObjectsStore[Kep.ActiveObjects[Kep.SecondActiveProfile,0]].GetComponent<MeshRenderer>().bounds.size.x; // Получаем размер биты второго игрока по оси x для выбранного профиля if(PAON[0] == 2) // Если активная шайба для этой сцены у 2 игрока PuckSize = SC.ObjectsStore[Kep.ActiveObjects[Kep.ActiveProfile, 1]].GetComponent<MeshRenderer>().bounds.size.x; // Пересчитываем размер шайбы на случай если для игры на двоих стоит другая активная шайба if(PAON[1] == 1) // Если активный стол для этой сцены у 1 игрока LevelTable = SC.ObjectsStore[Kep.ActiveObjects[Kep.ActiveProfile, 2]].GetComponent<ObjectScript>().ObjectLevel; // Получаем уровень активного стола 1 игрока и присваиваем этот уровень переменной LevelTable else if(PAON[2] == 2) // Иначе если активный стол для этой сцены у 2 игрока LevelTable = SC.ObjectsStore[Kep.ActiveObjects[PAON[1] ,2]].GetComponent<ObjectScript>().ObjectLevel; // Получаем уровень стола активного для этой сцены LOTF = (float)(((LevelTable-1) * 25) * 0.18 + 18) / 2; // Вычисляем длинну от центра поля до ворот и присваиваем её переменной LOTF(LengthOfThisField) } WidthGate = (float)(((LevelTable-1) * 110) * 0.04 + 4); // Получаем ширину ворот для данного поля и заносим её в переменную WidthGate } if(Kep.RightSide[Kep.ActiveProfile] == true) // Если переменная "Правая сторона" игрока правда { SPP1 = new Vector3(LOTF + 0.1f, 0, 0); // Назначаем первому игроку позицию с права GP1 = new Vector3(LOTF + 0.6f, 0, 0); // И его ворота с права SPP2 = new Vector3(LOTF - LOTF*2 -0.1f, 0, 0); // А второму игроку позицию слева GP2 = new Vector3(LOTF - LOTF*2 - 0.6f, 0, 0); // И его ворота слева FirstPos.x = SPP1.x-(FP/2)-0.5f-(PuckSize/2); // Первая позиция шайбы это позиция первого игрока - его радиус - условленное расстояние - радиус шайбы SecondPos.x = SPP2.x+(SP/2)+0.5f+(PuckSize/2); // Вторая позиция шайбы это позиция второго игрока + его радиус + условленное расстояние + радиус шайбы } else // Иначе если переменная "Правая сторона" ложь { SPP1 = new Vector3(LOTF - LOTF*2 -0.1f, 0, 0); // Назначаем первому игроку позицию с лева GP1 = new Vector3(LOTF - LOTF*2 - 0.6f, 0, 0); // И его ворота с лева SPP2 = new Vector3(LOTF + 0.1f, 0, 0); // А второму игроку позицию справа GP2 = new Vector3(LOTF + 0.6f, 0, 0); // И его ворота справа FirstPos.x = SPP1.x+(FP/2)+0.5f+(PuckSize/2); // Первая позиция шайбы это позиция первого игрока + его радиус + условленное расстояние + радиус шайбы SecondPos.x = SPP2.x-(SP/2)-0.5f-(PuckSize/2); // Вторая позиция шайбы это позиция второго игрока - его радиус - условленное расстояние - радиус шайбы } } void SetStartPositions() // Этот метод расставляет объекты согласно просчитанным для них позициям в методе CalculatePosObjects { Player1 = Instantiate(SC.ObjectsStore[Kep.ActiveObjects[Kep.ActiveProfile, 0]], SPP1, Quaternion.identity) as GameObject; // Ставим 1 биту на просчитанную позицию для первого игрока byte FirstBatMatNom = Kep.ActiveMats[Kep.ActiveProfile][Kep.ActiveObjects[Kep.ActiveProfile,0]]; // У переменной LastObjects спрашиваем номер биты, по этому номеру узнаём номер активного материала у этой биты Player1.GetComponent<Renderer>().material = Player1.GetComponent<ObjectScript>().FirstMaterials[FirstBatMatNom]; // Присваиваем объекту новый материал SetBatImprovement(1); // Если есть активное улучшение устанавливаем улучшение на биту 1 игрока Gate = (GameObject)Resources.Load("Models/Prefabs/GateTrigger"); // Ложим префаб ворот в переменную Gate if(UnityEngine.SceneManagement.SceneManager.GetActiveScene().name != "PlayerVsPlayer") // Если это не сцена для игры на двоих) { Player1.AddComponent<PlayerController>(); // Вешаем на первую биту скрипт управления битой Player1.GetComponent<PlayerController>().NomberPlayer = 1; // Присваиваем переменной NomberPlayer этого скрипта значение 1 Player2 = Instantiate(AIBat, SPP2, Quaternion.identity) as GameObject; // Ставим 2 биту на просчитанную позицию второго игрока Player2.AddComponent<ArtificialIntelligence>(); // Вешаем на вторую биту скрипт управления компьютером Puck = Instantiate(SC.ObjectsStore[Kep.ActiveObjects[Kep.ActiveProfile, 1]]) as GameObject; // Ставим выбранную шайбу в координаты указанные в её префабе и заносим ссылку на неё в переменную puck Puck.AddComponent<Puck>(); // Вешаем на шайбу скрипт шайбы Puck.GetComponent<Puck>().StartPath = transform.position; // Присваиваем переменной StartPath текущую позицию шайбы if(Kep.RightSide[Kep.ActiveProfile] == true) // Если переменная активного игрока "Правая сторона" равна правда { PM.RightAv = Kep.PlayersAv[Kep.ActiveProfile]; // Присваиваем переменной PM.RightAv аватар активного игрока PM.LeftAv = Player2.GetComponent<ObjectScript>().Avatar; // Присваиваем переменной PM.LeftAv аватар компьютера PM.RPN = Kep.NamesProfiles[Kep.ActiveProfile]; // Присваиваем переменной PM.RPN имя активного игрока PM.LPN = AIBat.GetComponent<ObjectScript>().NPCName; // Присваиваем переменной PM.LPN имя биты компьютера Player1.GetComponent<PlayerController>().RightPlayer = true; // Указываем в скрипте PlayerController 1 игрока что он стоит с права } else // Иначе если переменная активного игрока "Правая сторона" равна ложь { PM.LeftAv = Kep.PlayersAv[Kep.ActiveProfile]; // Присваиваем переменной PM.LeftAv аватар активного игрока PM.RightAv = Player2.GetComponent<ObjectScript>().Avatar; // Присваиваем переменной PM.RightAv аватар компьютера PM.LPN = Kep.NamesProfiles[Kep.ActiveProfile]; // Присваиваем переменной PM.LPN имя биты компьютера PM.RPN = AIBat.GetComponent<ObjectScript>().NPCName; // Присваиваем переменной PM.RPN имя активного игрока Player1.GetComponent<PlayerController>().RightPlayer = false; // Указываем в скрипте PlayerController 1 игрока что он стоит с лева } } else // Иначе если режим игры игрок против игрока { if(Kep.SecondActiveProfile == 10) // Если для второго игрока не выбран активный профиль { Player2 = (GameObject)Instantiate(Resources.Load("Models/Prefabs/Bats/1_Level/GhostBat"), SPP2, Quaternion.identity); // Инстантируем префаб призрачной биты на просчитанную позицию 2 игрока и ложим её копию в Player 2 Puck = Instantiate(SC.ObjectsStore[Kep.ActiveObjects[Kep.ActiveProfile, 1]]) as GameObject; // Ставим выбранную шайбу в координаты указанные в её префабе и заносим ссылку на неё в переменную puck Table = Instantiate(SC.ObjectsStore[Kep.ActiveObjects[Kep.ActiveProfile, 2]]); // Инастантируем активный стол 1 игрока на сцену RenderSettings.skybox = SC.SkyboxMats[Kep.ActiveObjects[Kep.ActiveProfile, 3]]; // Назначаем сцене в качестве скайбокса, активный скайбокс выбранный для 1 игрока } else // Иначе если для второго игрока выбран активный профиль { // Расставляем объекты по другой схеме Player2 = (GameObject)Instantiate(SC.ObjectsStore[Currentkep.ActiveObjects[Kep.SecondActiveProfile,0]], SPP2,Quaternion.identity);// Инстантируем префаб активной биты 2 игрока на просчитанную позицию 2 игрока и ложим её копию в Player 2 byte SecondBatMatNom = Currentkep.ActiveMats[Kep.SecondActiveProfile][Currentkep.ActiveObjects[Kep.SecondActiveProfile,0]]; // У переменной LastObjects спрашиваем номер биты, по этому номеру узнаём номер активного материала у этой биты Player2.GetComponent<Renderer>().material = Player2.GetComponent<ObjectScript>().FirstMaterials[SecondBatMatNom]; // Присваиваем бите второго игрока новый материал SetBatImprovement(2); // Если есть активное улучшение устанавливаем улучшение на биту 2 игрока Player1.AddComponent<PlayerController>(); // Вешаем на первую биту скрипт управления битой Player1.GetComponent<PlayerController>().NomberPlayer = 1; // Присваиваем переменной NomberPlayer этого скрипта значение 1 Player2.AddComponent<PlayerController>(); // Вешаем на вторую биту скрипт управления битой Player2.GetComponent<PlayerController>().NomberPlayer = 2; // Присваиваем переменной NomberPlayer этого скрипта значение 2 if(PAON[0] == 1) // Если активная шайба для этой сцены у 1 игрока Puck = Instantiate(SC.ObjectsStore[Kep.ActiveObjects[Kep.ActiveProfile, 1]]) as GameObject; // Ставим активную шайбу 1 игрока в координаты указанные в её префабе и заносим ссылку на неё в переменную puck else if(PAON[0] == 2) // Если активная шайба для этой сцены у 2 игрока Puck = Instantiate(SC.ObjectsStore[Currentkep.ActiveObjects[Kep.SecondActiveProfile, 1]]) as GameObject; // Ставим выбранную шайбу в координаты указанные в её префабе и заносим ссылку на неё в переменную puck if(PAON[1] == 1) // Если активный стол для этой сцены у 1 игрока Table = Instantiate(SC.ObjectsStore[Kep.ActiveObjects[Kep.ActiveProfile, 2]]); // Инастантируем активный стол 1 игрока на сцену else if(PAON[1] == 2) // Если активный стол для этой сцены у 2 игрока Table = Instantiate(SC.ObjectsStore[Currentkep.ActiveObjects[Kep.SecondActiveProfile, 2]]); // Инастантируем активный стол выбранного игрока на сцену if(PAON[2] == 1) // Если активный скайбокс для этогй сцены у 1 игрока RenderSettings.skybox = SC.SkyboxMats[Kep.ActiveObjects[Kep.ActiveProfile, 3]]; // Назначаем сцене в качестве скайбокса, активный скайбокс выбранный для 1 игрока if(PAON[2] == 2) // Если активный скайбокс для этогй сцены у 2 игрока RenderSettings.skybox = SC.SkyboxMats[Currentkep.ActiveObjects[Kep.SecondActiveProfile, 3]]; // Назначаем сцене в качестве скайбокса, активный скайбокс выбранный для 1 игрока Puck.AddComponent<Puck>(); // Вешаем на шайбу скрипт шайбы Puck.GetComponent<Puck>().StartPath = transform.position; // Присваиваем переменной StartPath текущую позицию шайбы if(Kep.RightSide[Kep.ActiveProfile] == true) // Если переменная активного игрока "Правая сторона" равна правда { PM.RightAv = Kep.PlayersAv[Kep.ActiveProfile]; // Присваиваем переменной PM.RightAv аватар активного игрока PM.LeftAv = Currentkep.PlayersAv[Kep.SecondActiveProfile]; // Присваиваем переменной PM.LeftAv аватар второго активного игрока PM.RPN = Kep.NamesProfiles[Kep.ActiveProfile]; // Присваиваем переменной PM.RPN имя активного игрока PM.LPN = Currentkep.NamesProfiles[Kep.SecondActiveProfile]; // Присваиваем переменной PM.LPN имя второго активного игрока Player1.GetComponent<PlayerController>().RightPlayer = true; // Указываем в скрипте PlayerController 1 игрока что он стоит с права Player2.GetComponent<PlayerController>().RightPlayer = false; // Указываем в скрипте PlayerController 2 игрока что он стоит с лева } else // Иначе если переменная активного игрока "Правая сторона" равна ложь { PM.LeftAv = Kep.PlayersAv[Kep.ActiveProfile]; // Присваиваем переменной PM.LeftAv аватар активного игрока PM.RightAv = Currentkep.PlayersAv[Kep.SecondActiveProfile]; // Присваиваем переменной PM.LeftAv аватар второго активного игрока PM.LPN = Kep.NamesProfiles[Kep.ActiveProfile]; // Присваиваем переменной PM.LPN имя биты активного игрока PM.RPN = Currentkep.NamesProfiles[Kep.SecondActiveProfile]; // Присваиваем переменной PM.LPN имя второго активного игрока Player1.GetComponent<PlayerController>().RightPlayer = false; // Указываем в скрипте PlayerController 1 игрока что он стоит с лева Player2.GetComponent<PlayerController>().RightPlayer = true; // Указываем в скрипте PlayerController 2 игрока что он стоит с права } } } G1 = Instantiate(Gate, GP1, Quaternion.identity) as GameObject; // Инстантируем ворота 1 игрока по просч. поз. и заносим ссылку на них в G1 G2 = Instantiate(Gate, GP2, Quaternion.identity) as GameObject; // Инстантируем ворота 2 игрока по просч. поз. и заносим ссылку на них G2.transform.localScale = G1.transform.localScale = new Vector3(0.8f, 0.5f, WidthGate); // Присваиваем обоим воротам просчитанную ширину G1.GetComponent<GateTrigger>().PlayerGate = 1; // Указываем 1 воротам что они ворота 1 игрока G2.GetComponent<GateTrigger>().PlayerGate = 2; // Указываем 2 воротам что они ворота 2 игрока Table.transform.GetChild(0).GetChild(0).GetComponent<Light>().enabled = true; // Включаем 1 источник освещения стола Table.transform.GetChild(0).GetChild(1).GetComponent<Light>().enabled = true; // Включаем 2 источник освещения стола Table.transform.GetChild(0).GetChild(2).GetComponent<Light>().enabled = true; // Включаем 3 источник освещения стола Table.transform.GetChild(0).GetChild(3).GetComponent<Light>().enabled = true; // Включаем 4 источник освещения стола } void SetBatImprovement(byte NomberPlayer) // Этот метод устанавливает улучшение на биту в будующем переделать и под остальные объекты шайбу и стол { if(NomberPlayer == 1) // Если нам нужно установить улучшение на 1 игрока { ObjectScript OS = Player1.GetComponent<ObjectScript>(); // Извлекаем из 1 игрока его ObjectScript short BatNom = Kep.ActiveObjects[Kep.ActiveProfile,0]; // Обращаемся к массиву LastObjects и узнаём номер биты в массиве ObjectsStore byte ImprNom = Kep.ActiveImprs[Kep.ActiveProfile][BatNom]; // Узнаём из сохранения номер активного улучшения в скрипте ObjectStore if(ImprNom != 10) // Если у биты 1 игрока есть активное улучшение { // Прикрепляем улучшение к бите 1 игрока GameObject BatImprovement = (GameObject)Instantiate(OS.Improvements[ImprNom], Player1.transform.position, Player1.transform.rotation); // Помещаем на сцену клон префаба улучшения а ссылку на клон отправляем в BatImprovement BatImprovement.transform.parent = Player1.transform; // Прикрепляем к бите её активное улучшение Player1.GetComponent<Rigidbody>().mass += BatImprovement.GetComponent<ImprovementScript>().Mass; // Добавляем к весу биты вес улучшения BatImprovement.GetComponent<ImprovementScript>().enabled = true; // Включаем скрипт улучшения BatImprovement.GetComponent<ImprovementScript>().ObjRigb = Player1.GetComponent<Rigidbody>(); // Ложим компонент Ridgidbody Игрока в переменную скрипта улучшения ObjRidg if(Kep.RightSide[Kep.ActiveProfile]) // Если 1 игрок играет с права BatImprovement.GetComponent<ImprovementScript>().RSide = true; // Указываем скрипту улучшения что он прикреплён к правой стороне else // Иначе если 1 игрок играет с лева BatImprovement.GetComponent<ImprovementScript>().RSide = false; // Указываем скрипту улучшения что он прикреплён к левой стороне } } else if(NomberPlayer == 2) // Если мы устанавливаем улучшение на 2 игрока { ObjectScript OS = Player2.GetComponent<ObjectScript>(); // Извлекаем из 2 игрока его ObjectScript short BatNom = 0; // Номер биты byte ImprNom = 0; // Номер активного улучшения в магазине ObjectStore if(Kep.ActiveProfile != Kep.SecondActiveProfile) // Если у первого и второго игрока разные профили профили то обращаемся кглобальной базе данных { BatNom = Kep.ActiveObjects[Kep.SecondActiveProfile,0]; // Обращаемся к массиву LastObjects и узнаём номер биты в массиве ObjectsStore ImprNom = Kep.ActiveImprs[Kep.SecondActiveProfile][BatNom]; // Узнаём из сохранения номер активного улучшения в скрипте keeper } else // Иначе если у них одинаковые профили обращаемся к локальной базе данных { BatNom = LocalKep.ActiveObjects[Kep.SecondActiveProfile,0]; // Обращаемся к массиву LastObjects и узнаём номер биты в массиве ObjectsStore ImprNom = LocalKep.ActiveImprs[Kep.SecondActiveProfile][BatNom]; // Узнаём из сохранения номер активного улучшения в скрипте keeper } if(ImprNom != 10) // Если у биты 2 игрока есть активное улучшение {// Прикрепляем улучшение к бите 2 игрока GameObject BatImprovement = (GameObject)Instantiate(OS.Improvements[ImprNom], Player2.transform.position, Player2.transform.rotation); // Помещаем на сцену клон префаба улучшения а ссылку на клон отправляем в BatImprovement BatImprovement.transform.parent = Player2.transform; // Прикрепляем к бите её активное улучшение Player2.GetComponent<Rigidbody>().mass += BatImprovement.GetComponent<ImprovementScript>().Mass; // Добавляем к весу биты вес улучшения BatImprovement.GetComponent<ImprovementScript>().enabled = true; // Включаем скрипт улучшения BatImprovement.GetComponent<ImprovementScript>().ObjRigb = Player2.GetComponent<Rigidbody>(); // Ложим компонент Ridgidbody Игрока в переменную скрипта улучшения ObjRidg if(Kep.RightSide[Kep.ActiveProfile]) // Если 1 игрок играет с права BatImprovement.GetComponent<ImprovementScript>().RSide = false; // Указываем скрипту улучшения что он прикреплён к левой стороне else // Иначе если 1 игрок играет с лева BatImprovement.GetComponent<ImprovementScript>().RSide = true; // Указываем скрипту улучшения что он прикреплён к правой стороне } } } public void RestartGameObjects() // Этот метод вызываеться при нажатии кнопки "инвертировать позиции" при старте уровня и в других случаях когда настройки объетов были изменены и нужно их отобразить на объектах { if(UnityEngine.SceneManagement.SceneManager.GetActiveScene().name == "PlayerVsPlayer") // Если уровень игры на двоих Destroy(Table); // Уничтожаем стол Destroy(Player1); // Уничтожаем биту первого игрока на сцене Destroy(Player2); // Уничтожаем биту второго игрока на сцене Destroy(Puck); // Уничтожаем шайбу на сцене Destroy(G1); // Уничтожаем клон префаба ворот для 1 игрока Destroy(G2); // Уничтожаем клон префаба ворот для 2 игрока CalculatePosObjects(); // Высчитываем заного позиции объектов SetStartPositions(); // Заного расставляем их по местам } public void CallStartFirstStep() // Этот метод вызывает событие StartFirstStep { if(StartFirstStep != null) // Если в списке события StartFirstStep есть подписанные на него методы StartFirstStep(); // Вызываем StartFirstStep } public void CallStartGame() { StartGameEvent(); // Вызываем событие старта игры } public void CallGoalEvent(byte NomberGate) // Этот метод вызываеться один раз чтобы вызвать событие гола, просчитать и записать статистичесские данные { GoalTrue = true; // Ставим значение true переменной GoalTrue говорящее что в этом раунде уже был забит кому то гол PM.TimeMoves = false; // Ставим значение переменной PM.TimeMoves ложь StatisticCalculation(NomberGate); // Производим просчёт статистики if(PM.ScorePlayer1 < 3 & PM.ScorePlayer2 < 3) // Если у первого и у второго игрока насчитываеться меньше 3 очков { GoalEvent(); // Вызываем событие GoalEvent } else if(PM.ScorePlayer1 >= 3 | PM.ScorePlayer2 >= 3) // Если у одного из игроков уже 3 очка { LastGoalEvent(); // Вызываем событие LastGoalEvent } } void Goal() // Этот метод вызываеться событием CallGoalEvent { Pause = true; // Говорим что игра находиться в режиме паузы StartCoroutine(AfterGoal()); // Вызываем коронтину AfterGoal } IEnumerator AfterGoal() // Этот метод вызываеться в методе Goal { yield return new WaitForSeconds(5); // Ждём 4 секунды PM.TimeMoves = true; // Ставим значение переменной PM.TimeMoves правда GoalTrue = false; // Ставим значение false переменной GoalTrue говорящее что в этом раунде гол не был забит ещё не кому Pause = false; // Говорим что игра вышла из режима паузы } void FinalGoal() // Этот метод вызываеться событием LastGoalEvent { Pause = true; // Говорим что игра находиться в режиме паузы if(UnityEngine.SceneManagement.SceneManager.GetActiveScene().name != "PlayerVsPlayer") // Если это не сцена для игры на двоих) { PM.BatExp = EC (out PM.PuckExp); // Высчитываем опыт для шайбы и биты для случая если победил первый игрок Kep.PlayedLevels[Kep.ActiveProfile] = Convert.ToByte(UnityEngine.SceneManagement.SceneManager.GetActiveScene().name); // Заносим номер сыгранного уровня в переменную последнего сыгранного уровня if(PM.ScorePlayer2 < PM.ScorePlayer1) // Если победил игрок (Человек) { PM.NextLevelTransition = true; // Делаем активной кнопку "Следующий уровень" if(Kep.Progress[Kep.ActiveProfile] == Convert.ToByte(UnityEngine.SceneManagement.SceneManager.GetActiveScene().name)) // Если переменная Progress равна номеру имени текущего уровня { Kep.Progress[Kep.ActiveProfile] ++; // То для этого профиля увеличиваем progress на 1 } } else // Иначе если победил компьютер if(Kep.Progress[Kep.ActiveProfile] > Convert.ToByte(UnityEngine.SceneManagement.SceneManager.GetActiveScene().name)) // Если переменная Progress больше текущего уровня значит следующий уровень уже открыт PM.NextLevelTransition = true; // Делаем активной кнопку "Следующий уровень" } // В конце уровня когда мы его сыграли мы смотрим // 1) Победил ли игрок // 2) Совпадает ли переменная Kep.Progress которая отвечает за следующий уровень доступный для прохождения совпадает с текущим уровнем значит мы прошли текущий уровень // 3) Если ответ на оба эти условия да if(PM.ScorePlayer2 < PM.ScorePlayer1) // Если победил игрок (Человек) { PM.TexsPrizes = Kep.CalculateTexsPrizes(/*ObjPrize ,SkyPrize*/); // Заполняем массив текстур призов PM.ShowPrizes = true; // Разрешаем PauseMenu показывать призы } if(PM.ScorePlayer2 > PM.ScorePlayer1) // Если победил игрок 2 (Компьютер) урезаем опыт 1 игрока в 2 раза { if(PM.BatExp >= 1) // И если опыт набранный в PM.BatExp Больше или равен 1 PM.BatExp = PM.BatExp/2; // Cтавим заработанный опыт 1 else if(PM.BatExp < 1) // Иначе если опыт в PM.BatExp меньше 1 PM.BatExp = 0; // Cтавим опыт биты 0 if(PM.PuckExp >= 1) // Если опыт набранный в PM.PuckExp Больше или равен 1 PM.PuckExp = PM.PuckExp/2; // Cтавим заработанный опыт 1 else if(PM.PuckExp < 1) // Иначе если опты в PM.PuckExp Меньше 1 PM.PuckExp = 0; // Cтавим опыт шайбы 0 } Kep.OpenMatsAndImprs(); // Открываем какой нибуть материал или улучшение у биты или у шайбы игрока если у них для этого достаточно опыта Kep.SaveGame(); // Вызываем событие SaveGame } void StatisticCalculation(byte NomberGate) // Этот метод подсчитывает статитстику каждый гол { PM.Scoregoal = LastGoal = NomberGate; // Присваиваем переменной LastGoal номер ворот в который был забит гол а потом это значение присваиваем PM.Scoregoal PM.FullTimeMin[PM.Rounds] = PM.Min.ToString("00"); // Присваиваем отформатированные минуты переменной PM.FullTimeMin PM.FullTimeSec[PM.Rounds] = PM.Sec.ToString("00"); // Присваиваем отформатированные секунды переменной PM.FullTimeSec if(PM.Rounds == 0) // Если это первый раунд { PM.RoundTimeMin[PM.Rounds] = PM.FullTimeMin[PM.Rounds]; // То присваиваем переменной PM.RoundTimeMin[PM.Rounds] переменную PM.FullTimeMin[PM.Rounds] PM.RoundTimeSec[PM.Rounds] = PM.FullTimeSec[PM.Rounds]; // А также присваиваем PM.RoundTimeSec[PM.Rounds] переменную PM.FullTimeSec[PM.Rounds] residue = (short)(PM.Min * 60 + PM.Sec); // Переводим время первого раунда в секунды } else // Иначе если это уже не первый раунд { int NowTime = PM.Min * 60 + PM.Sec; // Переводим полное время с этим раундом в секунды int LastTime = Convert.ToInt32(PM.FullTimeMin[PM.Rounds -1]) * 60 + Convert.ToInt32(PM.FullTimeSec[PM.Rounds -1]); // Переводим полное время до этого раунда в секунды residue = (byte)(NowTime - LastTime); // Отнимаем общее время с этим раундом от общего времени до этого раунда получаем длительность этого раунда в секундах short ResultMin = (short)(residue / 60); // Делим секунды на 60 получаем минуты float ResultSec = (float)(residue % 60); // Заносим оставшиеся после деления секунды PM.RoundTimeMin[PM.Rounds] = ResultMin.ToString("00"); // Конвертируем в строку и заносим в массив минуты этого раунда PM.RoundTimeSec[PM.Rounds] = ResultSec.ToString("00"); // Конвертируем в сторку и заносим в массив секунды этого раунда } if(NomberGate == 1) // Если гол игроку 1 { PM.ScorePlayer2 ++; // Засчитываем очко игроку 2 if(Kep.RightSide[Kep.ActiveProfile] == true) // Если значение переменной (Kep.RightSide равно правда) { PM.RightGoal[PM.Rounds] = true; // То засчитываем гол правому игроку PM.LPS = PM.ScorePlayer2; // И записываем левому игроку очки второго игрока PM.LPRC[PM.Rounds] = CC(Player1); // Указываем количество заработанных кредитов левого игрока за этот раунд PM.LPFC += PM.LPRC[PM.Rounds]; // Прибавляем к финальному количеству кредитов левого игрока заработанных за весь уровень } else // Если значение переменной (Kep.RightSide равно ложь) { PM.RightGoal[PM.Rounds] = false; // То засчитываем гол левому игроку PM.RPS = PM.ScorePlayer2; // И записываем правому игроку очки второго игрока PM.RPRC[PM.Rounds] = CC(Player1); // Указываем количество заработанных кредиты правого игрока за этот раунд PM.RPFC += PM.RPRC[PM.Rounds]; // Прибавляем к финальному количеству кредитов правого игрока заработанных за весь уровень } } else if(NomberGate == 2) // Иначе если гол игроку 2 { PM.ScorePlayer1 ++; // Засчитываем очко игроку 1 if(Kep.RightSide[Kep.ActiveProfile] == false) // Если значение переменной (Kep.RightSide равно ложь) { PM.RightGoal[PM.Rounds] = true; // То засчитываем гол правому игроку PM.LPS = PM.ScorePlayer1; // И записываем левому игроку очки первого игрока PM.LPRC[PM.Rounds] = CC(Player2); // Указываем количество заработанных кредиты левого игрока за этот раунд PM.LPFC += PM.LPRC[PM.Rounds]; // Прибавляем к финальному количеству кредитов левого игрока заработанных за весь уровень Kep.Credits[Kep.ActiveProfile] += PM.LPRC[PM.Rounds]; // Прибавляем к счёту 1 игрока } else // Если значение переменной (Kep.RightSide равно правда) { PM.RightGoal[PM.Rounds] = false; // То засчитываем гол левому игроку PM.RPS = PM.ScorePlayer1; // И записываем правому игроку очки первого игрока PM.RPRC[PM.Rounds] = CC(Player2); // Указываем количество заработанных кредиты правого игрока за этот раунд PM.RPFC += PM.RPRC[PM.Rounds]; // Прибавляем к финальному количеству кредитов правого игрока заработанных за весь уровень Kep.Credits[Kep.ActiveProfile] += PM.RPRC[PM.Rounds]; // Прибавляем к счёту 1 игрока } } PM.LPSs[PM.Rounds] = PM.LPS; // Запоминаем счёт для этого раунда для левого игрока PM.RPSs[PM.Rounds] = PM.RPS; // Запоминаем счёт для этого раунда для правого игрока PM.Rounds ++; // Ставим что был отыгран ещё один раунд } int CC(GameObject PlayerGoal) // (CreditsCalculation) Этот метод расчитывает количество кредитов игрока { float mass; // Масса игрока которому забит гол помноженная X2 float Force; // Сила игрока которому забит гол помноженная X2 byte LvlBat; // Уровень биты игрока которому забит гол X8 byte LvlTable; // Уровень стола на котором происходит игра X8 short Bonustime; // Время раунда в секундах - 2 минуты используеться для конвертации в бонусные кредиты за быстрое прохождение int Result; // Результат - Сколько кредитов получает победитель этого раунда mass = PlayerGoal.GetComponent<Rigidbody>().mass*2; // Берём массу биты игрока которому забили гол умножаем на 2 и заносим в переменную mass Force = PlayerGoal.GetComponent<ObjectScript>().Force*2; // Берём силу биты игрока которому забили гол умножаем на 2 и заносим в переменную Force LvlBat = (byte)(PlayerGoal.GetComponent<ObjectScript>().ObjectLevel*8); // Берём уровень биты игрока которому забили гол умножаем на 8 и заносим в переменную LvlBat LvlTable = (byte)(Table.GetComponent<ObjectScript>().ObjectLevel*8); // Берём уровень стола на котором происходит игра умножаем на 8 и заносим в переменную LvlTable Bonustime = (short)(120 - residue); // Берём среднее время прохождения уровня 2 минуты отнимаем время прохождения игроком в сек. и присваиваем переменной BonusTime Result = (int)(mass + Force + LvlBat + LvlTable + Bonustime + Bonus); // Подсчитываем все переменные влияющие на награду в кредитах и присваиваем переменной Result return Result; } int EC(out int PuckExp) // (ExpirienceCalculation) Этот метод расчитывает количество опыта для шайбы игрока и его биты и возвращает результаты (Вызываем в конце уровня перед выведением статистики) { int BatExp; // Здесь будет храниться высчитанный опыт для биты short LastBat = Kep.ActiveObjects[Kep.ActiveProfile,0]; // Получаем номер выбранной биты игрока в массиве ObjectsStore и ложим в переменную LastBat short LastPuck = Kep.ActiveObjects[Kep.ActiveProfile,1]; // Получаем номер выбранной шайбы игрока в массиве ObjectsStore и ложим в переменную LastPuck ObjectScript ObjScrAi = Player2.GetComponent<ObjectScript>(); // Ложим компонент компьютерного игрока "ObjectScript" в переменную ObjScrAi ObjectScript ObjScrPlayer = Player1.GetComponent<ObjectScript>(); // Ложим компонент игрока "ObjectScript" в переменную ObjScrPlayer ObjectScript ObjScrPuck = Puck.GetComponent<ObjectScript>(); // Ложим компонент шайбы игрока "ObjectScript" в переменную ObjScrPuck BatExp = (int)(((ObjScrAi.Mass - ObjScrPlayer.Mass) + 2) * 10); // Отнимаем от массы биты игрока компьютера массу биты игрока +2 * 10 и присваиваем опыту биты BatExp += (int)(((ObjScrAi.Force - ObjScrPlayer.Force) + 2) * 2); // Отнимаем от силы биты игрока компьютера силу биты игрока +2 * 2 и плюсуем к опыту биты PuckExp = (int)((ObjScrAi.Mass - ObjScrPuck.Mass)* 4); // Отнимаем от массы биты компьютерного игрока массу шайбы игрока * 4 и присваиваем к опыту шайбы Kep.ObjectsExpirience[Kep.ActiveProfile][LastBat] += BatExp; // Добавляем в сохранениях бите заработанный за раунд опыт Kep.ObjectsExpirience[Kep.ActiveProfile][LastPuck] += PuckExp; // Добавляем в сохранениях шабе заработанный за раунд опыт return BatExp; // Возвращаем высчитанный опты для биты } public void CallLoadGameEvent() // Этот метод используеться для вызова события LoadProfiles { LoadGameEvent(); // Вызываем событие LoadGameEvent } public void CallSaveGame() // Этот метод используеться для вызова события перезаписывания профиля { SaveGameEvent(); // Вызываем событие SaveGameEvent } void OnDisable() // Вызываем этот метод перед уничтожением объекта { StartGameEvent -= StartGame; // Отписываем метод "Старт игры" от события StartGameEvent GoalEvent -= Goal; // Отписываем метод "Гол" от события GoalEvent LastGoalEvent -= FinalGoal; // Отписываем метод "Последний гол" от события LastGoalEvent StartFirstStep -= _StartFirstStep_; // Отписываем метод "_Начать первый шаг_" от события StartFirstStep } }
77.951009
257
0.714407
[ "Apache-2.0" ]
SERGZV/Slide_Repository
SlideProject/Assets/Scripts/GameManager.cs
77,471
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Facebook; using FacebookAds.Interfaces; /// <summary> /// The MIT License (MIT) /// /// Copyright (c) 2017 - Luke Paris (Paradoxis) | Searchresult Performancemarketing /// /// 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. /// </summary> /// <date>2017-11-12 14:56:48</date> /// <author>Luke Paris (Paradoxis) | luke@paradoxis.nl</author> /// /// <remarks> /// This file was automatically generated using the Facebook Ads /// PHP SDK to C# converter found in this library under '/src/SdkConverter/' /// For more information please refer to the official documentation /// </remarks> namespace FacebookAds.Object { public class WebAppLink : AbstractCrudObject { /// <summary> /// Initializes a new instance of the <see cref="WebAppLink"/> class. /// </summary> /// <param name="id">The identifier.</param> /// <param name="parentId">The parent identifier.</param> /// <param name="client">The client.</param> public WebAppLink(string id, string parentId = null, FacebookClient client = null) : base(id, parentId, client) { } /// <summary>Gets the endpoint of the API call.</summary> /// <returns>Endpoint URL</returns> protected override string GetEndpoint() { return ""; } } }
38.59375
123
0.695547
[ "MIT" ]
AsimKhan2019/Facebook-Ads-SDK-C-
src/FacebookAds/FacebookAds/Object/WebAppLink.cs
2,470
C#
#region License // // The Open Toolkit Library License // // Copyright (c) 2006 - 2008 the Open Toolkit library, except where noted. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights to // use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of // the Software, and to permit persons to whom the Software is furnished to do // so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. // #endregion using System; using System.Collections.Generic; using System.Text; using System.Runtime.InteropServices; using OpenTK.Input; using System.Security; using Microsoft.Win32; using System.Diagnostics; namespace OpenTK.Platform.Windows { sealed class WinMMJoystick : IJoystickDriver { #region Fields List<JoystickDevice> sticks = new List<JoystickDevice>(); IList<JoystickDevice> sticks_readonly; // Todo: Read the joystick name from the registry. //static readonly string RegistryJoyConfig = @"Joystick%dConfiguration"; //static readonly string RegistryJoyName = @"Joystick%dOEMName"; //static readonly string RegstryJoyCurrent = @"CurrentJoystickSettings"; bool disposed; #endregion #region Constructors public WinMMJoystick() { sticks_readonly = sticks.AsReadOnly(); // WinMM supports up to 16 joysticks. int number = 0; while (number < UnsafeNativeMethods.joyGetNumDevs()) { JoystickDevice<WinMMJoyDetails> stick = OpenJoystick(number++); if (stick != null) { sticks.Add(stick); } } } #endregion #region Private Members JoystickDevice<WinMMJoyDetails> OpenJoystick(int number) { JoystickDevice<WinMMJoyDetails> stick = null; JoyCaps caps; JoystickError result = UnsafeNativeMethods.joyGetDevCaps(number, out caps, JoyCaps.SizeInBytes); if (result != JoystickError.NoError) return null; int num_axes = caps.NumAxes; if ((caps.Capabilities & JoystCapsFlags.HasPov) != 0) num_axes += 2; stick = new JoystickDevice<WinMMJoyDetails>(number, num_axes, caps.NumButtons); stick.Details = new WinMMJoyDetails(num_axes); // Make sure to reverse the vertical axes, so that +1 points up and -1 points down. int axis = 0; if (axis < caps.NumAxes) { stick.Details.Min[axis] = caps.XMin; stick.Details.Max[axis] = caps.XMax; axis++; } if (axis < caps.NumAxes) { stick.Details.Min[axis] = caps.YMax; stick.Details.Max[axis] = caps.YMin; axis++; } if (axis < caps.NumAxes) { stick.Details.Min[axis] = caps.ZMax; stick.Details.Max[axis] = caps.ZMin; axis++; } if (axis < caps.NumAxes) { stick.Details.Min[axis] = caps.RMin; stick.Details.Max[axis] = caps.RMax; axis++; } if (axis < caps.NumAxes) { stick.Details.Min[axis] = caps.UMin; stick.Details.Max[axis] = caps.UMax; axis++; } if (axis < caps.NumAxes) { stick.Details.Min[axis] = caps.VMax; stick.Details.Max[axis] = caps.VMin; axis++; } if ((caps.Capabilities & JoystCapsFlags.HasPov) != 0) { stick.Details.PovType = PovType.Exists; if ((caps.Capabilities & JoystCapsFlags.HasPov4Dir) != 0) stick.Details.PovType |= PovType.Discrete; if ((caps.Capabilities & JoystCapsFlags.HasPovContinuous) != 0) stick.Details.PovType |= PovType.Continuous; } #warning "Implement joystick name detection for WinMM." stick.Description = String.Format("Joystick/Joystick #{0} ({1} axes, {2} buttons)", number, stick.Axis.Count, stick.Button.Count); // Todo: Try to get the device name from the registry. Oh joy! //string key_path = String.Format("{0}\\{1}\\{2}", RegistryJoyConfig, caps.RegKey, RegstryJoyCurrent); //RegistryKey key = Registry.LocalMachine.OpenSubKey(key_path, false); //if (key == null) // key = Registry.CurrentUser.OpenSubKey(key_path, false); //if (key == null) // stick.Description = String.Format("USB Joystick {0} ({1} axes, {2} buttons)", number, stick.Axis.Count, stick.Button.Count); //else //{ // key.Close(); //} if (stick != null) Debug.Print("Found joystick on device number {0}", number); return stick; } #endregion #region IJoystickDriver public int DeviceCount { get { return sticks.Count; } } public IList<JoystickDevice> Joysticks { get { return sticks_readonly; } } public void Poll() { foreach (JoystickDevice<WinMMJoyDetails> js in sticks) { JoyInfoEx info = new JoyInfoEx(); info.Size = JoyInfoEx.SizeInBytes; info.Flags = JoystickFlags.All; UnsafeNativeMethods.joyGetPosEx(js.Id, ref info); int num_axes = js.Axis.Count; if ((js.Details.PovType & PovType.Exists) != 0) num_axes -= 2; // Because the last two axis are used for POV input. int axis = 0; if (axis < num_axes) { js.SetAxis((JoystickAxis)axis, js.Details.CalculateOffset((float)info.XPos, axis)); axis++; } if (axis < num_axes) { js.SetAxis((JoystickAxis)axis, js.Details.CalculateOffset((float)info.YPos, axis)); axis++; } if (axis < num_axes) { js.SetAxis((JoystickAxis)axis, js.Details.CalculateOffset((float)info.ZPos, axis)); axis++; } if (axis < num_axes) { js.SetAxis((JoystickAxis)axis, js.Details.CalculateOffset((float)info.RPos, axis)); axis++; } if (axis < num_axes) { js.SetAxis((JoystickAxis)axis, js.Details.CalculateOffset((float)info.UPos, axis)); axis++; } if (axis < num_axes) { js.SetAxis((JoystickAxis)axis, js.Details.CalculateOffset((float)info.VPos, axis)); axis++; } if ((js.Details.PovType & PovType.Exists) != 0) { float x = 0, y = 0; // A discrete POV returns specific values for left, right, etc. // A continuous POV returns an integer indicating an angle in degrees * 100, e.g. 18000 == 180.00 degrees. // The vast majority of joysticks have discrete POVs, so we'll treat all of them as discrete for simplicity. if ((JoystickPovPosition)info.Pov != JoystickPovPosition.Centered) { if (info.Pov > (int)JoystickPovPosition.Left || info.Pov < (int)JoystickPovPosition.Right) { y = 1; } if ((info.Pov > (int)JoystickPovPosition.Forward) && (info.Pov < (int)JoystickPovPosition.Backward)) { x = 1; } if ((info.Pov > (int)JoystickPovPosition.Right) && (info.Pov < (int)JoystickPovPosition.Left)) { y = -1; } if (info.Pov > (int)JoystickPovPosition.Backward) { x = -1; } } //if ((js.Details.PovType & PovType.Discrete) != 0) //{ // if ((JoystickPovPosition)info.Pov == JoystickPovPosition.Centered) // { x = 0; y = 0; } // else if ((JoystickPovPosition)info.Pov == JoystickPovPosition.Forward) // { x = 0; y = -1; } // else if ((JoystickPovPosition)info.Pov == JoystickPovPosition.Left) // { x = -1; y = 0; } // else if ((JoystickPovPosition)info.Pov == JoystickPovPosition.Backward) // { x = 0; y = 1; } // else if ((JoystickPovPosition)info.Pov == JoystickPovPosition.Right) // { x = 1; y = 0; } //} //else if ((js.Details.PovType & PovType.Continuous) != 0) //{ // if ((JoystickPovPosition)info.Pov == JoystickPovPosition.Centered) // { // // This approach moves the hat on a circle, not a square as it should. // float angle = (float)(System.Math.PI * info.Pov / 18000.0 + System.Math.PI / 2); // x = (float)System.Math.Cos(angle); // y = (float)System.Math.Sin(angle); // if (x < 0.001) // x = 0; // if (y < 0.001) // y = 0; // } //} //else // throw new NotImplementedException("Please post an issue report at http://www.opentk.com/issues"); js.SetAxis((JoystickAxis)axis++, x); js.SetAxis((JoystickAxis)axis++, y); } int button = 0; while (button < js.Button.Count) { js.SetButton((JoystickButton)button, (info.Buttons & (1 << button)) != 0); button++; } } } #endregion #region IDisposable public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } void Dispose(bool manual) { if (!disposed) { if (manual) { } disposed = true; } } ~WinMMJoystick() { Dispose(false); } #endregion #region UnsafeNativeMethods [Flags] enum JoystickFlags { X = 0x1, Y = 0x2, Z = 0x4, R = 0x8, U = 0x10, V = 0x20, Pov = 0x40, Buttons = 0x80, All = X | Y | Z | R | U | V | Pov | Buttons } enum JoystickError : uint { NoError = 0, InvalidParameters = 165, NoCanDo = 166, Unplugged = 167 //MM_NoDriver = 6, //MM_InvalidParameter = 11 } [Flags] enum JoystCapsFlags { HasZ = 0x1, HasR = 0x2, HasU = 0x4, HasV = 0x8, HasPov = 0x16, HasPov4Dir = 0x32, HasPovContinuous = 0x64 } enum JoystickPovPosition : ushort { Centered = 0xFFFF, Forward = 0, Right = 9000, Backward = 18000, Left = 27000 } struct JoyCaps { public ushort Mid; public ushort ProductId; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)] public string ProductName; public int XMin; public int XMax; public int YMin; public int YMax; public int ZMin; public int ZMax; public int NumButtons; public int PeriodMin; public int PeriodMax; public int RMin; public int RMax; public int UMin; public int UMax; public int VMin; public int VMax; public JoystCapsFlags Capabilities; public int MaxAxes; public int NumAxes; public int MaxButtons; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)] public string RegKey; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)] public string OemVxD; public static readonly int SizeInBytes; static JoyCaps() { SizeInBytes = Marshal.SizeOf(default(JoyCaps)); } } struct JoyInfoEx { public int Size; [MarshalAs(UnmanagedType.I4)] public JoystickFlags Flags; public int XPos; public int YPos; public int ZPos; public int RPos; public int UPos; public int VPos; public uint Buttons; public uint ButtonNumber; public int Pov; uint Reserved1; uint Reserved2; public static readonly int SizeInBytes; static JoyInfoEx() { SizeInBytes = Marshal.SizeOf(default(JoyInfoEx)); } } static class UnsafeNativeMethods { [DllImport("Winmm.dll"), SuppressUnmanagedCodeSecurity] public static extern JoystickError joyGetDevCaps(int uJoyID, out JoyCaps pjc, int cbjc); [DllImport("Winmm.dll"), SuppressUnmanagedCodeSecurity] public static extern uint joyGetPosEx(int uJoyID, ref JoyInfoEx pji); [DllImport("Winmm.dll"), SuppressUnmanagedCodeSecurity] public static extern int joyGetNumDevs(); } #endregion #region enum PovType [Flags] enum PovType { None = 0x0, Exists = 0x1, Discrete = 0x2, Continuous = 0x4 } #endregion #region struct WinMMJoyDetails struct WinMMJoyDetails { public readonly float[] Min, Max; // Minimum and maximum offset of each axis. public PovType PovType; public WinMMJoyDetails(int num_axes) { Min = new float[num_axes]; Max = new float[num_axes]; PovType = PovType.None; } public float CalculateOffset(float pos, int axis) { float offset = (2 * (pos - Min[axis])) / (Max[axis] - Min[axis]) - 1; if (offset > 1) return 1; else if (offset < -1) return -1; else if (offset < 0.001f && offset > -0.001f) return 0; else return offset; } } #endregion } }
36.069444
142
0.515916
[ "MIT" ]
PaintLab/PixelFarm.External
src/MiniOpenTk/OpenTk.Platforms/Platform/Windows/WinMMJoystick.cs
15,584
C#
using Dolittle.Mapping; using Machine.Specifications; using System.Linq; namespace Dolittle.Mapping.Specs.for_MappingTargets.given { public class no_mapping_targets : all_dependencies { protected static MappingTargets targets; Establish context = () => { mapping_targets_mock.Setup(m => m.GetEnumerator()).Returns(new IMappingTarget[0].AsEnumerable().GetEnumerator()); targets = new MappingTargets(mapping_targets_mock.Object); }; } }
28.111111
125
0.6917
[ "MIT" ]
joelhoisko/DotNET.Fundamentals
Specifications/Mapping/for_MappingTargets/given/no_mapping_targets.cs
508
C#
using GymWare.DataAccess.DAL; using GymWare.Entities; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using GymWare.Entities.DTO; namespace GymWare.Logic { public class UsuarioLogic { private UsuarioRepository _us = new UsuarioRepository(); private DietaRepository _di = new DietaRepository(); private RutinaRepository _ru = new RutinaRepository(); private DietaComidaLogic _dc = new DietaComidaLogic(); private RutinaEjercicioLogic _re = new RutinaEjercicioLogic(); private AsistenciaLogic _as = new AsistenciaLogic(); public List<Cliente> GetAll() { return _us.GetAll(); } public UsuarioLogeadoDTO CheckUsuario(UsuarioLoginDTO usuarioLoginDTO) { UsuarioLogeadoDTO usuarioLogeado = new UsuarioLogeadoDTO(); Cliente cliente = _us.CheckCliente(usuarioLoginDTO); if (cliente != null) { List<Dieta> dietas = _di.GetAllDietasByUser(cliente.ClienteId); usuarioLogeado.DietasComidas = new List<DietaComida>(); foreach (var d in dietas) { List<DietaComida> dc = _dc.GetDietaConComidas(d.DietaId); foreach (var dc1 in dc) { usuarioLogeado.DietasComidas.Add(dc1); } } List<Rutina> rutinas = _ru.GetAllRutinasByUser(cliente.ClienteId); usuarioLogeado.RutinasEjercicios = new List<RutinaEjercicio>(); foreach (var r in rutinas) { List<RutinaEjercicio> re = _re.GetRutinaConEjercicios(r.RutinaId); foreach (var re1 in re) { usuarioLogeado.RutinasEjercicios.Add(re1); } } List<Asistencia> asis = _as.GetAsistenciasByUser(cliente.ClienteId); foreach (var a in asis) { AsistenciaCalendar ac = new AsistenciaCalendar(); ac.title = "Asistencia"; ac.start = a.Fecha.ToString("yyyy-MM-dd"); ac.end = a.Fecha.ToString("yyyy-MM-dd"); usuarioLogeado.Asistencias.Add(ac); } usuarioLogeado.Cliente = cliente; usuarioLogeado.Mensaje = "Cliente logueado correctamente"; return usuarioLogeado; } else { usuarioLogeado.Empleado = _us.CheckEmpleado(usuarioLoginDTO); if (usuarioLogeado.Empleado != null) { usuarioLogeado.Mensaje = "Empleado logueado correctamente"; return usuarioLogeado; } else { usuarioLogeado.Mensaje = "Error al intentar loguear"; return usuarioLogeado; } } } public bool Insert(Cliente cliente) { return _us.Insert(cliente); } } }
37.022727
86
0.531614
[ "MIT" ]
GMM-UTN/GymWare
GymWare-Backend/GymWare.Logic/UsuarioLogic.cs
3,260
C#
using Microsoft.EntityFrameworkCore.Migrations; namespace AppBoilerplate.Migrations { public partial class Upgrade_ABP_380 : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.AlterColumn<string>( name: "UserName", table: "AbpUsers", maxLength: 256, nullable: false, oldClrType: typeof(string), oldMaxLength: 32); migrationBuilder.AlterColumn<string>( name: "NormalizedUserName", table: "AbpUsers", maxLength: 256, nullable: false, oldClrType: typeof(string), oldMaxLength: 32); migrationBuilder.AlterColumn<string>( name: "UserName", table: "AbpUserAccounts", maxLength: 256, nullable: true, oldClrType: typeof(string), oldMaxLength: 32, oldNullable: true); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.AlterColumn<string>( name: "UserName", table: "AbpUsers", maxLength: 32, nullable: false, oldClrType: typeof(string), oldMaxLength: 256); migrationBuilder.AlterColumn<string>( name: "NormalizedUserName", table: "AbpUsers", maxLength: 32, nullable: false, oldClrType: typeof(string), oldMaxLength: 256); migrationBuilder.AlterColumn<string>( name: "UserName", table: "AbpUserAccounts", maxLength: 32, nullable: true, oldClrType: typeof(string), oldMaxLength: 256, oldNullable: true); } } }
31.59375
71
0.497527
[ "MIT" ]
marcoslevy/AppBoilerplate
aspnet-core/src/AppBoilerplate.EntityFrameworkCore/Migrations/20180726102703_Upgrade_ABP_3.8.0.cs
2,024
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class AnimationManager : Singleton<AnimationManager> { private Animator anim; public void Play(string animationName) { anim.Play(animationName); } }
16.733333
59
0.76494
[ "MIT" ]
fast-coffee-moths/room
Assets/Scripts/AnimationManager.cs
253
C#
using System; using System.Collections.Generic; using System.Text; using Yanyitec.Repo; namespace Yanyitec.Org { public class Department : Record { /// <summary> /// 部门名称 /// </summary> public string Name { get; set; } /// <summary> /// 部门描述 /// </summary> public string Description { get; set; } /// <summary> /// 部门图标 /// </summary> public string Icon { get; set; } /// <summary> /// 部门路径 /// </summary> public string Path { get; set; } /// <summary> /// 部门领导 /// </summary> public Guid LeaderId { get; set; } /// <summary> /// 部门领导信息 /// </summary> public string LeaderInfo { get; set; } /// <summary> /// 上级部门Id,没有上级部门就是一个org /// </summary> public Guid? SuperDepartmentId { get; set; } /// <summary> /// 上级部门 /// </summary> public Department SuperDepartment { get; set; } /// <summary> /// 下级部门 /// </summary> public IList<Department> SubDepartments { get; set; } } }
21.851852
61
0.471186
[ "MIT" ]
yanyitec/Yanyitec.Common
Yanyitec.Common/Org/Department.cs
1,278
C#
// Copyright (c) Improbable Worlds Ltd, All Rights Reserved using System; using System.IO; using Improbable.Assets; using UnityEngine; namespace Improbable.Unity.Assets { /// <summary> /// A filesystem-based asset bundle loader. /// This implementation loads unity3d files from assets stored in the file strucuture required by the asset database. /// </summary> class LocalAssetBundleLoader : IAssetLoader<AssetBundle> { private const string entityPrefabSubdir = "unity"; private readonly string entityPrefabsPath; /// <param name="assetBundlesDir">The directory where to find asset bundles.</param> public LocalAssetBundleLoader(string assetBundlesDir) { entityPrefabsPath = Path.Combine(assetBundlesDir, entityPrefabSubdir); } public void LoadAsset(string prefabName, Action<AssetBundle> onAssetLoaded, Action<Exception> onError) { var assetBundlePath = Path.Combine(entityPrefabsPath, Platform.PrefabNameToAssetBundleName(prefabName.ToLower())); try { if (!File.Exists(assetBundlePath)) { throw new IOException(string.Format("Failed to load prefab's '{0}' asset bundle from file '{1}'.\n", prefabName, assetBundlePath) + "Asset is either missing or the local asset bundle path is incorrect."); } var assetBundle = CreateAssetBundleFromFile(assetBundlePath); if (assetBundle == null) { throw new Exception(string.Format("Failed to load prefab's '{0}' asset bundle from file '{1}'.\n", prefabName, assetBundlePath) + "Asset is most likely corrupted."); } onAssetLoaded(assetBundle); } catch (Exception e) { onError(e); } } public void CancelAllLoads() { // LoadAsset is instantaneous, so no need to do anything here. } private static AssetBundle CreateAssetBundleFromFile(string assetBundlePath) { return AssetBundle.LoadFromFile(assetBundlePath); } } }
36.046875
149
0.596446
[ "MIT" ]
samc-improbable/WizardsTutorial
workers/unity/Assets/Plugins/Improbable/Sdk/Src/Unity/Assets/LocalAssetBundleLoader.cs
2,307
C#
using GaiaProject.Engine.Model; namespace GaiaProject.Engine.Logic.Entities.Effects { public class LogEffect : Effect { public string Message { get; } public LogEffect(string message) { Message = message; } public override void ApplyTo(GaiaProjectGame game) { if (!string.IsNullOrEmpty(PlayerId)) { var player = game.GetPlayer(PlayerId); game.LogEffect(this, Message); } else { game.LogSystemMessage(Message); } } } }
17.444444
52
0.681529
[ "MIT" ]
Etchelon/gaiaproject
Backend/Libraries/Engine/Logic/Entities/Effects/LogEffect.cs
473
C#
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.VisualStudio.TestTools.UnitTesting; using TestHelper; namespace CSharpAnalyzers.Test { [TestClass] public class CompilationStartedAnalyzerWithCompilationWideAnalysisUnitTests : DiagnosticVerifier { [TestMethod] public void Test1() { var test = @" namespace MyNamespace { public class UnsecureMethodAttribute : System.Attribute { } public interface ISecureType { } public interface IUnsecureInterface { [UnsecureMethodAttribute] void F(); } class MyInterfaceImpl1 : IUnsecureInterface { public void F() {} } class MyInterfaceImpl2 : IUnsecureInterface, ISecureType { public void F() {} } class MyInterfaceImpl3 : ISecureType { public void F() {} } }"; var expected = new DiagnosticResult { Id = DiagnosticIds.CompilationStartedAnalyzerWithCompilationWideAnalysisRuleId, Message = string.Format(Resources.CompilationStartedAnalyzerWithCompilationWideAnalysisMessageFormat, "MyInterfaceImpl2", CompilationStartedAnalyzerWithCompilationWideAnalysis.SecureTypeInterfaceName, "IUnsecureInterface"), Severity = DiagnosticSeverity.Warning, Locations = new[] { new DiagnosticResultLocation("Test0.cs", 19, 11) } }; VerifyCSharpDiagnostic(test, expected); } protected override DiagnosticAnalyzer GetCSharpDiagnosticAnalyzer() { return new CompilationStartedAnalyzerWithCompilationWideAnalysis(); } } }
29.938462
239
0.651079
[ "Apache-2.0" ]
0x53A/roslyn
src/Samples/CSharp/Analyzers/CSharpAnalyzers/CSharpAnalyzers.Test/Tests/CompilationStartedAnalyzerWithCompilationWideAnalysisUnitTests.cs
1,948
C#
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using Microsoft.CodeQuality.CSharp.Analyzers.ApiDesignGuidelines; using Microsoft.CodeQuality.VisualBasic.Analyzers.ApiDesignGuidelines; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.Diagnostics; using Test.Utilities; namespace Microsoft.CodeQuality.Analyzers.ApiDesignGuidelines.UnitTests { public class DoNotHideBaseClassMethodsFixerTests : CodeFixTestBase { protected override DiagnosticAnalyzer GetCSharpDiagnosticAnalyzer() { return new DoNotHideBaseClassMethodsAnalyzer(); } protected override DiagnosticAnalyzer GetBasicDiagnosticAnalyzer() { return new DoNotHideBaseClassMethodsAnalyzer(); } protected override CodeFixProvider GetCSharpCodeFixProvider() { return new CSharpDoNotHideBaseClassMethodsFixer(); } protected override CodeFixProvider GetBasicCodeFixProvider() { return new BasicDoNotHideBaseClassMethodsFixer(); } } }
34.764706
161
0.736887
[ "Apache-2.0" ]
RikkiGibson/roslyn-analyzers
src/Microsoft.CodeQuality.Analyzers/UnitTests/ApiDesignGuidelines/DoNotHideBaseClassMethodsTests.Fixer.cs
1,184
C#
using System; using System.Collections.Generic; using System.Text; namespace Git.Controllers { using SUS.HTTP; using SUS.MvcFramework; public class HomeController : Controller { [HttpGet("/")] public HttpResponse Index() { if (this.IsUserSignedIn()) { return this.Redirect("/Repositories/All"); } return this.View(); } } }
17.76
58
0.545045
[ "MIT" ]
plambet0/GIT-Application
Apps/Git/Controllers/HomeController.cs
446
C#
using Aspose.Words; using Aspose.Words.Loading; using Aspose.Words.Saving; namespace VerifyTests; public static partial class VerifyAspose { static ConversionResult ConvertWord(Stream stream, IReadOnlyDictionary<string, object> settings) { var document = new Document(stream); return ConvertWord(document, settings); } static ConversionResult ConvertWord(Document document, IReadOnlyDictionary<string, object> settings) => new(GetInfo(document), GetWordStreams(document, settings).ToList()); static object GetInfo(Document document) => new { HasRevisions = document.HasRevisions.ToString(), DefaultLocale = (EditingLanguage)document.Styles.DefaultFont.LocaleId, Properties = GetDocumentProperties(document) }; static Dictionary<string, object> GetDocumentProperties(Document document) => document.BuiltInDocumentProperties .Where(x => x.Name != "Bytes" && x.Value.HasValue()) .ToDictionary(x => x.Name, x => x.Value); static IEnumerable<Target> GetWordStreams(Document document, IReadOnlyDictionary<string, object> settings) { var pagesToInclude = settings.GetPagesToInclude(document.PageCount); for (var pageIndex = 0; pageIndex < pagesToInclude; pageIndex++) { var options = new ImageSaveOptions(SaveFormat.Png) { PageSet = new(pageIndex) }; var stream = new MemoryStream(); document.Save(stream, options); yield return new("png", stream); } } }
36.488889
176
0.649817
[ "MIT" ]
SimonCropp/Verify.Aspose
src/Verify.Aspose/VerifyAspose_Word.cs
1,644
C#
using PlacetoPay.Redirection.Entities; using System.Collections.Generic; using System.Linq; namespace PlacetoPay.Redirection.Validators { public class AmountBaseValidator : BaseValidator { /// <summary> /// Validates if amount base entity contains the required information. /// </summary> /// <param name="entity">object</param> /// <param name="fields">list</param> /// <param name="silent">boold</param> /// <returns>bool</returns> public bool IsValid(object entity, out List<string> fields, bool silent) { List<string> errors = new List<string>(); AmountBase amountBase = (AmountBase)entity; if (amountBase.Currency == null || !Currency.IsValidCurrency(amountBase.Currency)) { errors.Add("currency"); } if (amountBase.Total == 0) { errors.Add("total"); } if (errors?.Any() ?? false) { fields = errors; ThrowValidationException(errors, "AmountBase", silent); return false; } fields = null; return true; } } }
27.711111
94
0.534884
[ "Apache-2.0" ]
placetopay-org/placetopay-redirection-csharp
src/Validators/AmountBaseValidator.cs
1,249
C#
// <copyright file="Resources.cs" company="Datadog"> // Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. // This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. // </copyright> namespace Datadog.Trace.Tools.Analyzers.ThreadAbortAnalyzer { internal static class Resources { public const string Title = "Potential infinite loop on ThreadAbortException"; public const string Description = "While blocks are vulnerable to infinite loop on ThreadAbortException due to a bug in the runtime. The catch block should rethrow a ThreadAbortException, or use a finally block."; public const string MessageFormat = "Potential infinite loop - you should rethrow Exception in catch block"; public const string CodeFixTitle = "Rethrow exception"; } }
55.9375
221
0.756425
[ "Apache-2.0" ]
DataDog/dd-trace-csharp
tracer/src/Datadog.Trace.Tools.Analyzers/ThreadAbortAnalyzer/Resources.cs
897
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 namespace DotNetNuke.Web.UI.WebControls.Internal { using System; using System.Collections.Generic; using System.Linq; using System.Web.UI.WebControls; using DotNetNuke.Entities.Content.Common; using DotNetNuke.Entities.Content.Taxonomy; using Globals = DotNetNuke.Common.Globals; /// <remarks> /// This control is only for internal use, please don't reference it in any other place as it may be removed in future. /// </remarks> public class TermsSelector : DnnComboBox { public int PortalId { get; set; } public bool IncludeSystemVocabularies { get; set; } = false; public bool IncludeTags { get; set; } = true; public List<Term> Terms { get { var terms = new List<Term>(); if (!string.IsNullOrEmpty(this.Value)) { var termRep = Util.GetTermController(); var termIds = this.Value.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries); foreach (var i in termIds) { if (!string.IsNullOrEmpty(i.Trim())) { var termId = Convert.ToInt32(i.Trim()); var term = termRep.GetTerm(termId); if (term != null) { terms.Add(term); } } } } return terms; } set { this.Value = string.Join(",", value.Select(t => t.TermId.ToString())); this.Items.Clear(); value.Select(t => new ListItem(t.Name, t.TermId.ToString()) { Selected = true }).ToList().ForEach(this.Items.Add); } } /// <inheritdoc/> public override bool MultipleSelect { get; set; } = true; /// <inheritdoc/> protected override void OnInit(EventArgs e) { base.OnInit(e); if (!string.IsNullOrEmpty(this.CssClass)) { this.CssClass = string.Format("{0} TermsSelector", this.CssClass); } else { this.CssClass = "TermsSelector"; } var includeSystem = this.IncludeSystemVocabularies.ToString().ToLowerInvariant(); var includeTags = this.IncludeTags.ToString().ToLowerInvariant(); var apiPath = Globals.ResolveUrl($"~/API/InternalServices/ItemListService/GetTerms?includeSystem={includeSystem}&includeTags={includeTags}&q="); this.Options.Preload = "focus"; this.Options.Plugins.Add("remove_button"); this.Options.Render = new RenderOption { Option = "function(item, escape) {return '<div>' + item.text + '</div>';}", }; this.Options.Load = $@"function(query, callback) {{ $.ajax({{ url: '{apiPath}' + encodeURIComponent(query), type: 'GET', error: function() {{ callback(); }}, success: function(data) {{ callback(data); }} }}); }} "; } } }
35.803738
156
0.470634
[ "MIT" ]
Mariusz11711/DNN
DNN Platform/DotNetNuke.Web/UI/WebControls/Internal/TermsSelector.cs
3,833
C#
using Microsoft.AspNet.Identity; using System.Collections.Generic; namespace MVCDatatables.Presentation.Models.Manage { public class IndexViewModel { public bool HasPassword { get; set; } public IList<UserLoginInfo> Logins { get; set; } public string PhoneNumber { get; set; } public bool TwoFactor { get; set; } public bool BrowserRemembered { get; set; } } }
27.666667
56
0.66988
[ "MIT" ]
devston/jQuery-datatables-dotnet-mvc-component
src/MVCDatatables.Presentation.Models/Manage/IndexViewModel.cs
417
C#
// ---------------------------------------------------------------------------------- // // Copyright Microsoft Corporation // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ---------------------------------------------------------------------------------- using System; using Microsoft.Azure.Commands.Sql.VulnerabilityAssessment.Model; using System.Management.Automation; using Microsoft.Azure.Commands.ResourceManager.Common.ArgumentCompleters; namespace Microsoft.Azure.Commands.Sql.VulnerabilityAssessmentSettings.Cmdlet { /// <summary> /// Updates the Vulnerability Assessment settings properties for a specific managed instance. /// </summary> [Cmdlet("Update", ResourceManager.Common.AzureRMConstants.AzureRMPrefix + "SqlInstanceVulnerabilityAssessmentSettings", SupportsShouldProcess = true, DefaultParameterSetName = UpdateSettingsWithStorageAccountNameParameterSet), OutputType(typeof(ManagedInstanceVulnerabilityAssessmentSettingsModel))] public class UpdateAzureSqlManagedInstanceVulnerabilityAssessmentSettings : UpdateAzureSqlVulnerabilityAssessmentSettingsBase { /// <summary> /// Gets or sets the name of the resource group to use. /// </summary> [Parameter(ParameterSetName = UpdateSettingsWithStorageAccountNameParameterSet, Mandatory = true, Position = 0, HelpMessage = "The name of the resource group.")] [Parameter(ParameterSetName = UpdateSettingsWithBlobStorageSasUri, Mandatory = true, Position = 0, HelpMessage = "The name of the resource group.")] [ResourceGroupCompleter] [ValidateNotNullOrEmpty] public override string ResourceGroupName { get; set; } /// <summary> /// Gets or sets the name of the managed instance to use. /// </summary> [Parameter(ParameterSetName = UpdateSettingsWithStorageAccountNameParameterSet, Mandatory = true, Position = 1, HelpMessage = "SQL Managed Instance name.")] [Parameter(ParameterSetName = UpdateSettingsWithBlobStorageSasUri, Mandatory = true, Position = 1, HelpMessage = "SQL Managed Instance name.")] [ResourceNameCompleter("Microsoft.Sql/managedInstances", "ResourceGroupName")] [ValidateNotNullOrEmpty] public string InstanceName { get; set; } protected override string GetServerName() { return InstanceName; } protected override string GetDatabaseName() { return String.Empty; } protected override ApplyToType GetResourceTypeVaAppliesTo() { return ApplyToType.ManagedInstance; } /// <summary> /// Transforms the given model object to be an object that is written out /// </summary> /// <param name="model">The about to be written model object</param> /// <returns>The prepared object to be written out</returns> protected override object TransformModelToOutputObject(VulnerabilityAssessmentSettingsModel model) { return new ManagedInstanceVulnerabilityAssessmentSettingsModel(model, GetServerName()); } } }
46.349398
304
0.649337
[ "MIT" ]
amrElroumy/azure-powershell
src/Sql/Sql/VulnerabilityAssessment/Cmdlet/VulnerabilityAssessmentSettings/ManagedInstance/UpdateAzureSqlManagedInstanceVulnerabilityAssessmentSettings.cs
3,767
C#
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the route53-2013-04-01.normal.json service model. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Net; using System.Text; using System.Xml.Serialization; using Amazon.Route53.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; namespace Amazon.Route53.Model.Internal.MarshallTransformations { /// <summary> /// Response Unmarshaller for ListReusableDelegationSets operation /// </summary> public class ListReusableDelegationSetsResponseUnmarshaller : XmlResponseUnmarshaller { /// <summary> /// Unmarshaller the response from the service to the response class. /// </summary> /// <param name="context"></param> /// <returns></returns> public override AmazonWebServiceResponse Unmarshall(XmlUnmarshallerContext context) { ListReusableDelegationSetsResponse response = new ListReusableDelegationSetsResponse(); UnmarshallResult(context,response); return response; } private static void UnmarshallResult(XmlUnmarshallerContext context, ListReusableDelegationSetsResponse response) { int originalDepth = context.CurrentDepth; int targetDepth = originalDepth + 1; if (context.IsStartOfDocument) targetDepth += 1; while (context.Read()) { if (context.IsStartElement || context.IsAttribute) { if (context.TestExpression("DelegationSets/DelegationSet", targetDepth)) { var unmarshaller = DelegationSetUnmarshaller.Instance; response.DelegationSets.Add(unmarshaller.Unmarshall(context)); continue; } if (context.TestExpression("Marker", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; response.Marker = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("IsTruncated", targetDepth)) { var unmarshaller = BoolUnmarshaller.Instance; response.IsTruncated = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("NextMarker", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; response.NextMarker = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("MaxItems", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; response.MaxItems = unmarshaller.Unmarshall(context); continue; } } else if (context.IsEndElement && context.CurrentDepth < originalDepth) { return; } } return; } /// <summary> /// Unmarshaller error response to exception. /// </summary> /// <param name="context"></param> /// <param name="innerException"></param> /// <param name="statusCode"></param> /// <returns></returns> public override AmazonServiceException UnmarshallException(XmlUnmarshallerContext context, Exception innerException, HttpStatusCode statusCode) { ErrorResponse errorResponse = ErrorResponseUnmarshaller.GetInstance().Unmarshall(context); errorResponse.InnerException = innerException; errorResponse.StatusCode = statusCode; var responseBodyBytes = context.GetResponseBodyBytes(); using (var streamCopy = new MemoryStream(responseBodyBytes)) using (var contextCopy = new XmlUnmarshallerContext(streamCopy, false, null)) { if (errorResponse.Code != null && errorResponse.Code.Equals("InvalidInput")) { return InvalidInputExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse); } } return new AmazonRoute53Exception(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode); } private static ListReusableDelegationSetsResponseUnmarshaller _instance = new ListReusableDelegationSetsResponseUnmarshaller(); internal static ListReusableDelegationSetsResponseUnmarshaller GetInstance() { return _instance; } /// <summary> /// Gets the singleton. /// </summary> public static ListReusableDelegationSetsResponseUnmarshaller Instance { get { return _instance; } } } }
39.24
162
0.594801
[ "Apache-2.0" ]
ChristopherButtars/aws-sdk-net
sdk/src/Services/Route53/Generated/Model/Internal/MarshallTransformations/ListReusableDelegationSetsResponseUnmarshaller.cs
5,886
C#
/** * Copyright 2015 Canada Health Infoway, Inc. * * 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. * * Author: $LastChangedBy: tmcgrady $ * Last modified: $LastChangedDate: 2011-05-04 15:47:15 -0400 (Wed, 04 May 2011) $ * Revision: $LastChangedRevision: 2623 $ */ /* This class was auto-generated by the message builder generator tools. */ using Ca.Infoway.Messagebuilder; namespace Ca.Infoway.Messagebuilder.Model.Ab_r02_04_03_imm.Domainvalue { public interface CentralSalish : Code { } }
37.571429
83
0.711027
[ "ECL-2.0", "Apache-2.0" ]
CanadaHealthInfoway/message-builder-dotnet
message-builder-release-ab-r02_04_03_imm/Main/Ca/Infoway/Messagebuilder/Model/Ab_r02_04_03_imm/Domainvalue/CentralSalish.cs
1,052
C#
// UrlRewriter - A .NET URL Rewriter module // Version 2.0 // // Copyright 2011 Intelligencia // Copyright 2011 Seth Yates // using System; using System.Xml; using Intelligencia.UrlRewriter.Actions; using Intelligencia.UrlRewriter.Configuration; using Intelligencia.UrlRewriter.Utilities; namespace Intelligencia.UrlRewriter.Parsers { /// <summary> /// Parser for gone actions. /// </summary> public sealed class GoneActionParser : RewriteActionParserBase { /// <summary> /// The name of the action. /// </summary> public override string Name { get { return Constants.ElementGone; } } /// <summary> /// Whether the action allows nested actions. /// </summary> public override bool AllowsNestedActions { get { return false; } } /// <summary> /// Whether the action allows attributes. /// </summary> public override bool AllowsAttributes { get { return false; } } /// <summary> /// Parses the node. /// </summary> /// <param name="node">The node to parse.</param> /// <param name="config">The rewriter configuration.</param> /// <returns>The parsed action, or null if no action parsed.</returns> public override IRewriteAction Parse(XmlNode node, IRewriterConfiguration config) { return new GoneAction(); } } }
27.350877
90
0.56703
[ "MIT" ]
sethyates/urlrewriter
src/Parsers/GoneActionParser.cs
1,559
C#
using SlipeServer.Packets.Builder; using SlipeServer.Packets.Enums; using System; using System.Collections.Generic; using System.Numerics; using System.Text; namespace SlipeServer.Packets.Definitions.Lua.ElementRpc.Player; public class ToggleControlAbility : Packet { public override PacketId PacketId => PacketId.PACKET_ID_LUA; public override PacketReliability Reliability => PacketReliability.ReliableSequenced; public override PacketPriority Priority => PacketPriority.High; public string Control { get; set; } public bool Enabled { get; set; } public ToggleControlAbility(string control, bool enabled) { this.Control = control; this.Enabled = enabled; } public override void Read(byte[] bytes) { throw new NotSupportedException(); } public override byte[] Write() { var builder = new PacketBuilder(); builder.Write((byte)ElementRpcFunction.TOGGLE_CONTROL_ABILITY); builder.WriteStringWithByteAsLength(this.Control); builder.Write((byte)(this.Enabled ? 1 : 0)); return builder.Build(); } }
28.74359
89
0.711864
[ "MIT" ]
correaAlex/Slipe-Server
SlipeServer.Packets/Definitions/Lua/ElementRpc/Player/ToggleControlAbility.cs
1,123
C#
using CStoJS.Exceptions; using CStoJS.LexerLibraries; using CStoJS.Inputs; using System; namespace CStoJS.ParserLibraries { public partial class Parser { public Token ClassModifier(){ printDebug("Class Modifier"); if( MatchAny( this.class_modifiers ) ){ return MatchOne(this.class_modifiers, ""); }else{ //EPSILON return null; } } public Token EncapsulationModifier(){ printDebug("Encapsulation Modifier"); if( MatchAny( this.encapsulation_modifiers ) ){ return MatchOne(this.encapsulation_modifiers, ""); }else{ //EPSILON return null; } } public Token OptionalModifier(){ printDebug("Optional Modifier"); if( MatchAny(this.optional_modifiers) ){ return MatchOne(this.optional_modifiers, ""); }else{ //EPSILON return null; } } } }
21.02439
55
0.651972
[ "MIT" ]
rNexeR/CSharpToJS
CStoJS/Parser/Modifiers/Modifiers.cs
862
C#
using System; using System.IO; using System.Threading; using EventStore.Common.Log; using EventStore.Common.Utils; using EventStore.Core.Bus; using EventStore.Core.Data; using EventStore.Core.Helpers; using EventStore.Core.Messages; using EventStore.Core.Services.Replication; using EventStore.Core.Services.Storage; using EventStore.Core.Services.Storage.EpochManager; using EventStore.Core.Services.Storage.ReaderIndex; using EventStore.Core.TransactionLog.Chunks; using EventStore.Core.TransactionLog.Chunks.TFChunk; using EventStore.Core.TransactionLog.LogRecords; namespace EventStore.Core.Services { public class ClusterStorageWriterService: StorageWriterService, IHandle<ReplicationMessage.ReplicaSubscribed>, IHandle<ReplicationMessage.CreateChunk>, IHandle<ReplicationMessage.RawChunkBulk>, IHandle<ReplicationMessage.DataChunkBulk> { private static readonly ILogger Log = LogManager.GetLoggerFor<ClusterStorageWriterService>(); private readonly Func<long> _getLastCommitPosition; private readonly LengthPrefixSuffixFramer _framer; private Guid _subscriptionId; private TFChunk _activeChunk; private long _subscriptionPos; private long _ackedSubscriptionPos; public ClusterStorageWriterService(IPublisher bus, ISubscriber subscribeToBus, TimeSpan minFlushDelay, TFChunkDb db, TFChunkWriter writer, IIndexWriter indexWriter, IEpochManager epochManager, Func<long> getLastCommitPosition) : base(bus, subscribeToBus, minFlushDelay, db, writer, indexWriter, epochManager) { Ensure.NotNull(getLastCommitPosition, "getLastCommitPosition"); _getLastCommitPosition = getLastCommitPosition; _framer = new LengthPrefixSuffixFramer(OnLogRecordUnframed, TFConsts.MaxLogRecordSize); SubscribeToMessage<ReplicationMessage.ReplicaSubscribed>(); SubscribeToMessage<ReplicationMessage.CreateChunk>(); SubscribeToMessage<ReplicationMessage.RawChunkBulk>(); SubscribeToMessage<ReplicationMessage.DataChunkBulk>(); } public override void Handle(SystemMessage.StateChangeMessage message) { if (message.State == VNodeState.PreMaster) { if (_activeChunk != null) { _activeChunk.MarkForDeletion(); _activeChunk = null; } _subscriptionId = Guid.Empty; _subscriptionPos = -1; _ackedSubscriptionPos = -1; } base.Handle(message); } public void Handle(ReplicationMessage.ReplicaSubscribed message) { if (_activeChunk != null) { _activeChunk.MarkForDeletion(); _activeChunk = null; } _framer.Reset(); _subscriptionId = message.SubscriptionId; _ackedSubscriptionPos = _subscriptionPos = message.SubscriptionPosition; Log.Info("=== SUBSCRIBED to [{0},{1:B}] at {2} (0x{2:X}). SubscriptionId: {3:B}.", message.MasterEndPoint, message.MasterId, message.SubscriptionPosition, message.SubscriptionId); var writerCheck = Db.Config.WriterCheckpoint.ReadNonFlushed(); if (message.SubscriptionPosition > writerCheck) { ReplicationFail("Master [{0},{1:B}] subscribed us at {2} (0x{2:X}), which is greater than our writer checkpoint {3} (0x{3:X}). REPLICATION BUG!", message.MasterEndPoint, message.MasterId, message.SubscriptionPosition, writerCheck); } if (message.SubscriptionPosition < writerCheck) { Log.Info("Master [{0},{1:B}] subscribed us at {2} (0x{2:X}), which is less than our writer checkpoint {3} (0x{3:X}). TRUNCATION IS NEEDED!", message.MasterEndPoint, message.MasterId, message.SubscriptionPosition, writerCheck); var lastCommitPosition = _getLastCommitPosition(); if (message.SubscriptionPosition > lastCommitPosition) Log.Info("ONLINE TRUNCATION IS NEEDED. NOT IMPLEMENTED. OFFLINE TRUNCATION WILL BE PERFORMED. SHUTTING DOWN NODE."); else Log.Info("OFFLINE TRUNCATION IS NEEDED (SubscribedAt {0} (0x{0:X}) <= LastCommitPosition {1} (0x{1:X})). SHUTTING DOWN NODE.", message.SubscriptionPosition, lastCommitPosition); EpochRecord lastEpoch = EpochManager.GetLastEpoch(); if (AreAnyCommittedRecordsTruncatedWithLastEpoch(message.SubscriptionPosition, lastEpoch, lastCommitPosition)) { Log.Error("Master [{0},{1:B}] subscribed us at {2} (0x{2:X}), which is less than our last epoch and LastCommitPosition {3} (0x{3:X}) >= lastEpoch.EpochPosition {3} (0x{3:X})!!! " + "That might be bad, especially if the LastCommitPosition is way beyond EpochPosition.\n" + "ATTEMPT TO TRUNCATE EPOCH WITH COMMITTED RECORDS. THIS MAY BE BAD, BUT IT IS OK IF JUST-ELECTED MASTER FAILS IMMEDIATELY AFTER ITS ELECTION.", message.MasterEndPoint, message.MasterId, message.SubscriptionPosition, lastCommitPosition, lastEpoch.EpochPosition); } Db.Config.TruncateCheckpoint.Write(message.SubscriptionPosition); Db.Config.TruncateCheckpoint.Flush(); BlockWriter = true; Bus.Publish(new ClientMessage.RequestShutdown(exitProcess: true)); return; } // subscription position == writer checkpoint // everything is ok } private bool AreAnyCommittedRecordsTruncatedWithLastEpoch(long subscriptionPosition, EpochRecord lastEpoch, long lastCommitPosition) { return lastEpoch != null && subscriptionPosition <= lastEpoch.EpochPosition && lastCommitPosition >= lastEpoch.EpochPosition; } public void Handle(ReplicationMessage.CreateChunk message) { if (_subscriptionId != message.SubscriptionId) return; if (_activeChunk != null) { _activeChunk.MarkForDeletion(); _activeChunk = null; } _framer.Reset(); if (message.IsCompletedChunk) { _activeChunk = Db.Manager.CreateTempChunk(message.ChunkHeader, message.FileSize); } else { if (message.ChunkHeader.ChunkStartNumber != Db.Manager.ChunksCount) { ReplicationFail("Received request to create a new ongoing chunk #{0}-{1}, but current chunks count is {2}.", message.ChunkHeader.ChunkStartNumber, message.ChunkHeader.ChunkEndNumber, Db.Manager.ChunksCount); } Db.Manager.AddNewChunk(message.ChunkHeader, message.FileSize); } _subscriptionPos = message.ChunkHeader.ChunkStartPosition; _ackedSubscriptionPos = _subscriptionPos; Bus.Publish(new ReplicationMessage.AckLogPosition(_subscriptionId, _ackedSubscriptionPos)); } public void Handle(ReplicationMessage.RawChunkBulk message) { if (_subscriptionId != message.SubscriptionId) return; if (_activeChunk == null) ReplicationFail("Physical chunk bulk received, but we don't have active chunk."); if (_activeChunk.ChunkHeader.ChunkStartNumber != message.ChunkStartNumber || _activeChunk.ChunkHeader.ChunkEndNumber != message.ChunkEndNumber) { Log.Error("Received RawChunkBulk for TFChunk {0}-{1}, but active chunk is {2}.", message.ChunkStartNumber, message.ChunkEndNumber, _activeChunk); return; } if (_activeChunk.RawWriterPosition != message.RawPosition) { Log.Error("Received RawChunkBulk at raw pos {0} (0x{0:X}) while current writer raw pos is {1} (0x{1:X}).", message.RawPosition, _activeChunk.RawWriterPosition); return; } if (!_activeChunk.TryAppendRawData(message.RawBytes)) { ReplicationFail("Couldn't append raw bytes to chunk {0}-{1}, raw pos: {2} (0x{2:X}), bytes length: {3} (0x{3:X}). Chunk file size: {4} (0x{4:X}).", message.ChunkStartNumber, message.ChunkEndNumber, message.RawPosition, message.RawBytes.Length, _activeChunk.FileSize); } _subscriptionPos += message.RawBytes.Length; if (message.CompleteChunk) { Log.Trace("Completing raw chunk {0}-{1}...", message.ChunkStartNumber, message.ChunkEndNumber); Writer.CompleteReplicatedRawChunk(_activeChunk); _subscriptionPos = _activeChunk.ChunkHeader.ChunkEndPosition; _framer.Reset(); _activeChunk = null; } if (message.CompleteChunk || _subscriptionPos - _ackedSubscriptionPos >= MasterReplicationService.ReplicaAckWindow) { _ackedSubscriptionPos = _subscriptionPos; Bus.Publish(new ReplicationMessage.AckLogPosition(_subscriptionId, _ackedSubscriptionPos)); } } public void Handle(ReplicationMessage.DataChunkBulk message) { Interlocked.Decrement(ref FlushMessagesInQueue); try { if (_subscriptionId != message.SubscriptionId) return; if (_activeChunk != null) ReplicationFail("Data chunk bulk received, but we have active chunk for receiving raw chunk bulks."); var chunk = Writer.CurrentChunk; if (chunk.ChunkHeader.ChunkStartNumber != message.ChunkStartNumber || chunk.ChunkHeader.ChunkEndNumber != message.ChunkEndNumber) { Log.Error("Received DataChunkBulk for TFChunk {0}-{1}, but active chunk is {2}-{3}.", message.ChunkStartNumber, message.ChunkEndNumber, chunk.ChunkHeader.ChunkStartNumber, chunk.ChunkHeader.ChunkEndNumber); return; } if (_subscriptionPos != message.SubscriptionPosition) { Log.Error("Received DataChunkBulk at SubscriptionPosition {0} (0x{0:X}) while current SubscriptionPosition is {1} (0x{1:X}).", message.SubscriptionPosition, _subscriptionPos); return; } _framer.UnFrameData(new ArraySegment<byte>(message.DataBytes)); _subscriptionPos += message.DataBytes.Length; if (message.CompleteChunk) { Log.Trace("Completing data chunk {0}-{1}...", message.ChunkStartNumber, message.ChunkEndNumber); Writer.CompleteChunk(); if (_framer.HasData) ReplicationFail("There is some data left in framer when completing chunk!"); _subscriptionPos = chunk.ChunkHeader.ChunkEndPosition; _framer.Reset(); } } catch (Exception exc) { Log.ErrorException(exc, "Exception in writer."); throw; } finally { Flush(); } if (message.CompleteChunk || _subscriptionPos - _ackedSubscriptionPos >= MasterReplicationService.ReplicaAckWindow) { _ackedSubscriptionPos = _subscriptionPos; Bus.Publish(new ReplicationMessage.AckLogPosition(_subscriptionId, _ackedSubscriptionPos)); } } private void OnLogRecordUnframed(BinaryReader reader) { var record = LogRecord.ReadFrom(reader); long newPos; if (!Writer.Write(record, out newPos)) ReplicationFail("First write failed when writing replicated record: {0}.", record); } private void ReplicationFail(string message, params object[] args) { var msg = args.Length == 0 ? message : string.Format(message, args); Log.Fatal(msg); BlockWriter = true; Application.Exit(ExitCode.Error, msg); throw new Exception(msg); } } }
47.157706
198
0.59018
[ "Apache-2.0" ]
bartelink/EventStore
src/EventStore.Core/Services/ClusterStorageWriterService.cs
13,157
C#
using System.Threading.Tasks; using Nethereum.JsonRpc.Client; namespace Nethereum.Geth.RPC.Admin { /// <Summary> /// The startWS administrative method starts an WebSocket based JSON RPC API webserver to handle client requests. All /// the parameters are optional: /// host: network interface to open the listener socket on (defaults to "localhost") /// port: network port to open the listener socket on (defaults to 8546) /// cors: cross-origin resource sharing header to use (defaults to "") /// apis: API modules to offer over this interface (defaults to "eth,net,web3") /// The method returns a boolean flag specifying whether the WebSocket RPC listener was opened or not. Please note, /// only one WebSocket endpoint is allowed to be active at any time. /// </Summary> public class AdminStartWS : RpcRequestResponseHandler<bool> { public AdminStartWS(IClient client) : base(client, ApiMethods.admin_startWS.ToString()) { } public RpcRequest BuildRequest(string host, int port, string cors, string api, object id = null) { return base.BuildRequest(id, host, port, cors, api); } public Task<bool> SendRequestAsync(string host, int port, string cors, string api, object id = null) { return base.SendRequestAsync(id, host, port, cors, api); } public Task<bool> SendRequestAsync(string host, int port, string cors, object id = null) { return base.SendRequestAsync(id, host, port, cors); } public Task<bool> SendRequestAsync(string host, int port, object id = null) { return base.SendRequestAsync(id, host, port); } public Task<bool> SendRequestAsync(string host, object id = null) { return base.SendRequestAsync(id, host); } public Task<bool> SendRequestAsync(object id = null) { return base.SendRequestAsync(id); } } }
39.403846
125
0.636896
[ "MIT" ]
Ali8668/Nethereum
src/Nethereum.Geth/RPC/Admin/AdminStartWS.cs
2,049
C#
// Copyright 2020 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gaxgrpc = Google.Api.Gax.Grpc; using gagr = Google.Api.Gax.ResourceNames; using wkt = Google.Protobuf.WellKnownTypes; using grpccore = Grpc.Core; using moq = Moq; using st = System.Threading; using stt = System.Threading.Tasks; using xunit = Xunit; namespace Google.Cloud.Talent.V4Beta1.Tests { /// <summary>Generated unit tests.</summary> public sealed class GeneratedTenantServiceClientTest { [xunit::FactAttribute] public void CreateTenantRequestObject() { moq::Mock<TenantService.TenantServiceClient> mockGrpcClient = new moq::Mock<TenantService.TenantServiceClient>(moq::MockBehavior.Strict); CreateTenantRequest request = new CreateTenantRequest { ParentAsProjectName = gagr::ProjectName.FromProject("[PROJECT]"), Tenant = new Tenant(), }; Tenant expectedResponse = new Tenant { TenantName = TenantName.FromProjectTenant("[PROJECT]", "[TENANT]"), ExternalId = "external_id9442680e", UsageType = Tenant.Types.DataUsageType.Unspecified, KeywordSearchableProfileCustomAttributes = { "keyword_searchable_profile_custom_attributes9dbf9d03", }, }; mockGrpcClient.Setup(x => x.CreateTenant(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); TenantServiceClient client = new TenantServiceClientImpl(mockGrpcClient.Object, null); Tenant response = client.CreateTenant(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task CreateTenantRequestObjectAsync() { moq::Mock<TenantService.TenantServiceClient> mockGrpcClient = new moq::Mock<TenantService.TenantServiceClient>(moq::MockBehavior.Strict); CreateTenantRequest request = new CreateTenantRequest { ParentAsProjectName = gagr::ProjectName.FromProject("[PROJECT]"), Tenant = new Tenant(), }; Tenant expectedResponse = new Tenant { TenantName = TenantName.FromProjectTenant("[PROJECT]", "[TENANT]"), ExternalId = "external_id9442680e", UsageType = Tenant.Types.DataUsageType.Unspecified, KeywordSearchableProfileCustomAttributes = { "keyword_searchable_profile_custom_attributes9dbf9d03", }, }; mockGrpcClient.Setup(x => x.CreateTenantAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Tenant>(stt::Task.FromResult(expectedResponse), null, null, null, null)); TenantServiceClient client = new TenantServiceClientImpl(mockGrpcClient.Object, null); Tenant responseCallSettings = await client.CreateTenantAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Tenant responseCancellationToken = await client.CreateTenantAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void CreateTenant() { moq::Mock<TenantService.TenantServiceClient> mockGrpcClient = new moq::Mock<TenantService.TenantServiceClient>(moq::MockBehavior.Strict); CreateTenantRequest request = new CreateTenantRequest { ParentAsProjectName = gagr::ProjectName.FromProject("[PROJECT]"), Tenant = new Tenant(), }; Tenant expectedResponse = new Tenant { TenantName = TenantName.FromProjectTenant("[PROJECT]", "[TENANT]"), ExternalId = "external_id9442680e", UsageType = Tenant.Types.DataUsageType.Unspecified, KeywordSearchableProfileCustomAttributes = { "keyword_searchable_profile_custom_attributes9dbf9d03", }, }; mockGrpcClient.Setup(x => x.CreateTenant(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); TenantServiceClient client = new TenantServiceClientImpl(mockGrpcClient.Object, null); Tenant response = client.CreateTenant(request.Parent, request.Tenant); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task CreateTenantAsync() { moq::Mock<TenantService.TenantServiceClient> mockGrpcClient = new moq::Mock<TenantService.TenantServiceClient>(moq::MockBehavior.Strict); CreateTenantRequest request = new CreateTenantRequest { ParentAsProjectName = gagr::ProjectName.FromProject("[PROJECT]"), Tenant = new Tenant(), }; Tenant expectedResponse = new Tenant { TenantName = TenantName.FromProjectTenant("[PROJECT]", "[TENANT]"), ExternalId = "external_id9442680e", UsageType = Tenant.Types.DataUsageType.Unspecified, KeywordSearchableProfileCustomAttributes = { "keyword_searchable_profile_custom_attributes9dbf9d03", }, }; mockGrpcClient.Setup(x => x.CreateTenantAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Tenant>(stt::Task.FromResult(expectedResponse), null, null, null, null)); TenantServiceClient client = new TenantServiceClientImpl(mockGrpcClient.Object, null); Tenant responseCallSettings = await client.CreateTenantAsync(request.Parent, request.Tenant, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Tenant responseCancellationToken = await client.CreateTenantAsync(request.Parent, request.Tenant, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void CreateTenantResourceNames() { moq::Mock<TenantService.TenantServiceClient> mockGrpcClient = new moq::Mock<TenantService.TenantServiceClient>(moq::MockBehavior.Strict); CreateTenantRequest request = new CreateTenantRequest { ParentAsProjectName = gagr::ProjectName.FromProject("[PROJECT]"), Tenant = new Tenant(), }; Tenant expectedResponse = new Tenant { TenantName = TenantName.FromProjectTenant("[PROJECT]", "[TENANT]"), ExternalId = "external_id9442680e", UsageType = Tenant.Types.DataUsageType.Unspecified, KeywordSearchableProfileCustomAttributes = { "keyword_searchable_profile_custom_attributes9dbf9d03", }, }; mockGrpcClient.Setup(x => x.CreateTenant(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); TenantServiceClient client = new TenantServiceClientImpl(mockGrpcClient.Object, null); Tenant response = client.CreateTenant(request.ParentAsProjectName, request.Tenant); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task CreateTenantResourceNamesAsync() { moq::Mock<TenantService.TenantServiceClient> mockGrpcClient = new moq::Mock<TenantService.TenantServiceClient>(moq::MockBehavior.Strict); CreateTenantRequest request = new CreateTenantRequest { ParentAsProjectName = gagr::ProjectName.FromProject("[PROJECT]"), Tenant = new Tenant(), }; Tenant expectedResponse = new Tenant { TenantName = TenantName.FromProjectTenant("[PROJECT]", "[TENANT]"), ExternalId = "external_id9442680e", UsageType = Tenant.Types.DataUsageType.Unspecified, KeywordSearchableProfileCustomAttributes = { "keyword_searchable_profile_custom_attributes9dbf9d03", }, }; mockGrpcClient.Setup(x => x.CreateTenantAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Tenant>(stt::Task.FromResult(expectedResponse), null, null, null, null)); TenantServiceClient client = new TenantServiceClientImpl(mockGrpcClient.Object, null); Tenant responseCallSettings = await client.CreateTenantAsync(request.ParentAsProjectName, request.Tenant, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Tenant responseCancellationToken = await client.CreateTenantAsync(request.ParentAsProjectName, request.Tenant, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetTenantRequestObject() { moq::Mock<TenantService.TenantServiceClient> mockGrpcClient = new moq::Mock<TenantService.TenantServiceClient>(moq::MockBehavior.Strict); GetTenantRequest request = new GetTenantRequest { TenantName = TenantName.FromProjectTenant("[PROJECT]", "[TENANT]"), }; Tenant expectedResponse = new Tenant { TenantName = TenantName.FromProjectTenant("[PROJECT]", "[TENANT]"), ExternalId = "external_id9442680e", UsageType = Tenant.Types.DataUsageType.Unspecified, KeywordSearchableProfileCustomAttributes = { "keyword_searchable_profile_custom_attributes9dbf9d03", }, }; mockGrpcClient.Setup(x => x.GetTenant(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); TenantServiceClient client = new TenantServiceClientImpl(mockGrpcClient.Object, null); Tenant response = client.GetTenant(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetTenantRequestObjectAsync() { moq::Mock<TenantService.TenantServiceClient> mockGrpcClient = new moq::Mock<TenantService.TenantServiceClient>(moq::MockBehavior.Strict); GetTenantRequest request = new GetTenantRequest { TenantName = TenantName.FromProjectTenant("[PROJECT]", "[TENANT]"), }; Tenant expectedResponse = new Tenant { TenantName = TenantName.FromProjectTenant("[PROJECT]", "[TENANT]"), ExternalId = "external_id9442680e", UsageType = Tenant.Types.DataUsageType.Unspecified, KeywordSearchableProfileCustomAttributes = { "keyword_searchable_profile_custom_attributes9dbf9d03", }, }; mockGrpcClient.Setup(x => x.GetTenantAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Tenant>(stt::Task.FromResult(expectedResponse), null, null, null, null)); TenantServiceClient client = new TenantServiceClientImpl(mockGrpcClient.Object, null); Tenant responseCallSettings = await client.GetTenantAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Tenant responseCancellationToken = await client.GetTenantAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetTenant() { moq::Mock<TenantService.TenantServiceClient> mockGrpcClient = new moq::Mock<TenantService.TenantServiceClient>(moq::MockBehavior.Strict); GetTenantRequest request = new GetTenantRequest { TenantName = TenantName.FromProjectTenant("[PROJECT]", "[TENANT]"), }; Tenant expectedResponse = new Tenant { TenantName = TenantName.FromProjectTenant("[PROJECT]", "[TENANT]"), ExternalId = "external_id9442680e", UsageType = Tenant.Types.DataUsageType.Unspecified, KeywordSearchableProfileCustomAttributes = { "keyword_searchable_profile_custom_attributes9dbf9d03", }, }; mockGrpcClient.Setup(x => x.GetTenant(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); TenantServiceClient client = new TenantServiceClientImpl(mockGrpcClient.Object, null); Tenant response = client.GetTenant(request.Name); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetTenantAsync() { moq::Mock<TenantService.TenantServiceClient> mockGrpcClient = new moq::Mock<TenantService.TenantServiceClient>(moq::MockBehavior.Strict); GetTenantRequest request = new GetTenantRequest { TenantName = TenantName.FromProjectTenant("[PROJECT]", "[TENANT]"), }; Tenant expectedResponse = new Tenant { TenantName = TenantName.FromProjectTenant("[PROJECT]", "[TENANT]"), ExternalId = "external_id9442680e", UsageType = Tenant.Types.DataUsageType.Unspecified, KeywordSearchableProfileCustomAttributes = { "keyword_searchable_profile_custom_attributes9dbf9d03", }, }; mockGrpcClient.Setup(x => x.GetTenantAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Tenant>(stt::Task.FromResult(expectedResponse), null, null, null, null)); TenantServiceClient client = new TenantServiceClientImpl(mockGrpcClient.Object, null); Tenant responseCallSettings = await client.GetTenantAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Tenant responseCancellationToken = await client.GetTenantAsync(request.Name, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetTenantResourceNames() { moq::Mock<TenantService.TenantServiceClient> mockGrpcClient = new moq::Mock<TenantService.TenantServiceClient>(moq::MockBehavior.Strict); GetTenantRequest request = new GetTenantRequest { TenantName = TenantName.FromProjectTenant("[PROJECT]", "[TENANT]"), }; Tenant expectedResponse = new Tenant { TenantName = TenantName.FromProjectTenant("[PROJECT]", "[TENANT]"), ExternalId = "external_id9442680e", UsageType = Tenant.Types.DataUsageType.Unspecified, KeywordSearchableProfileCustomAttributes = { "keyword_searchable_profile_custom_attributes9dbf9d03", }, }; mockGrpcClient.Setup(x => x.GetTenant(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); TenantServiceClient client = new TenantServiceClientImpl(mockGrpcClient.Object, null); Tenant response = client.GetTenant(request.TenantName); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetTenantResourceNamesAsync() { moq::Mock<TenantService.TenantServiceClient> mockGrpcClient = new moq::Mock<TenantService.TenantServiceClient>(moq::MockBehavior.Strict); GetTenantRequest request = new GetTenantRequest { TenantName = TenantName.FromProjectTenant("[PROJECT]", "[TENANT]"), }; Tenant expectedResponse = new Tenant { TenantName = TenantName.FromProjectTenant("[PROJECT]", "[TENANT]"), ExternalId = "external_id9442680e", UsageType = Tenant.Types.DataUsageType.Unspecified, KeywordSearchableProfileCustomAttributes = { "keyword_searchable_profile_custom_attributes9dbf9d03", }, }; mockGrpcClient.Setup(x => x.GetTenantAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Tenant>(stt::Task.FromResult(expectedResponse), null, null, null, null)); TenantServiceClient client = new TenantServiceClientImpl(mockGrpcClient.Object, null); Tenant responseCallSettings = await client.GetTenantAsync(request.TenantName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Tenant responseCancellationToken = await client.GetTenantAsync(request.TenantName, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void UpdateTenantRequestObject() { moq::Mock<TenantService.TenantServiceClient> mockGrpcClient = new moq::Mock<TenantService.TenantServiceClient>(moq::MockBehavior.Strict); UpdateTenantRequest request = new UpdateTenantRequest { Tenant = new Tenant(), UpdateMask = new wkt::FieldMask(), }; Tenant expectedResponse = new Tenant { TenantName = TenantName.FromProjectTenant("[PROJECT]", "[TENANT]"), ExternalId = "external_id9442680e", UsageType = Tenant.Types.DataUsageType.Unspecified, KeywordSearchableProfileCustomAttributes = { "keyword_searchable_profile_custom_attributes9dbf9d03", }, }; mockGrpcClient.Setup(x => x.UpdateTenant(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); TenantServiceClient client = new TenantServiceClientImpl(mockGrpcClient.Object, null); Tenant response = client.UpdateTenant(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task UpdateTenantRequestObjectAsync() { moq::Mock<TenantService.TenantServiceClient> mockGrpcClient = new moq::Mock<TenantService.TenantServiceClient>(moq::MockBehavior.Strict); UpdateTenantRequest request = new UpdateTenantRequest { Tenant = new Tenant(), UpdateMask = new wkt::FieldMask(), }; Tenant expectedResponse = new Tenant { TenantName = TenantName.FromProjectTenant("[PROJECT]", "[TENANT]"), ExternalId = "external_id9442680e", UsageType = Tenant.Types.DataUsageType.Unspecified, KeywordSearchableProfileCustomAttributes = { "keyword_searchable_profile_custom_attributes9dbf9d03", }, }; mockGrpcClient.Setup(x => x.UpdateTenantAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Tenant>(stt::Task.FromResult(expectedResponse), null, null, null, null)); TenantServiceClient client = new TenantServiceClientImpl(mockGrpcClient.Object, null); Tenant responseCallSettings = await client.UpdateTenantAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Tenant responseCancellationToken = await client.UpdateTenantAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void UpdateTenant() { moq::Mock<TenantService.TenantServiceClient> mockGrpcClient = new moq::Mock<TenantService.TenantServiceClient>(moq::MockBehavior.Strict); UpdateTenantRequest request = new UpdateTenantRequest { Tenant = new Tenant(), }; Tenant expectedResponse = new Tenant { TenantName = TenantName.FromProjectTenant("[PROJECT]", "[TENANT]"), ExternalId = "external_id9442680e", UsageType = Tenant.Types.DataUsageType.Unspecified, KeywordSearchableProfileCustomAttributes = { "keyword_searchable_profile_custom_attributes9dbf9d03", }, }; mockGrpcClient.Setup(x => x.UpdateTenant(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); TenantServiceClient client = new TenantServiceClientImpl(mockGrpcClient.Object, null); Tenant response = client.UpdateTenant(request.Tenant); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task UpdateTenantAsync() { moq::Mock<TenantService.TenantServiceClient> mockGrpcClient = new moq::Mock<TenantService.TenantServiceClient>(moq::MockBehavior.Strict); UpdateTenantRequest request = new UpdateTenantRequest { Tenant = new Tenant(), }; Tenant expectedResponse = new Tenant { TenantName = TenantName.FromProjectTenant("[PROJECT]", "[TENANT]"), ExternalId = "external_id9442680e", UsageType = Tenant.Types.DataUsageType.Unspecified, KeywordSearchableProfileCustomAttributes = { "keyword_searchable_profile_custom_attributes9dbf9d03", }, }; mockGrpcClient.Setup(x => x.UpdateTenantAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Tenant>(stt::Task.FromResult(expectedResponse), null, null, null, null)); TenantServiceClient client = new TenantServiceClientImpl(mockGrpcClient.Object, null); Tenant responseCallSettings = await client.UpdateTenantAsync(request.Tenant, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Tenant responseCancellationToken = await client.UpdateTenantAsync(request.Tenant, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void DeleteTenantRequestObject() { moq::Mock<TenantService.TenantServiceClient> mockGrpcClient = new moq::Mock<TenantService.TenantServiceClient>(moq::MockBehavior.Strict); DeleteTenantRequest request = new DeleteTenantRequest { TenantName = TenantName.FromProjectTenant("[PROJECT]", "[TENANT]"), }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.DeleteTenant(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); TenantServiceClient client = new TenantServiceClientImpl(mockGrpcClient.Object, null); client.DeleteTenant(request); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task DeleteTenantRequestObjectAsync() { moq::Mock<TenantService.TenantServiceClient> mockGrpcClient = new moq::Mock<TenantService.TenantServiceClient>(moq::MockBehavior.Strict); DeleteTenantRequest request = new DeleteTenantRequest { TenantName = TenantName.FromProjectTenant("[PROJECT]", "[TENANT]"), }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.DeleteTenantAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null)); TenantServiceClient client = new TenantServiceClientImpl(mockGrpcClient.Object, null); await client.DeleteTenantAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); await client.DeleteTenantAsync(request, st::CancellationToken.None); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void DeleteTenant() { moq::Mock<TenantService.TenantServiceClient> mockGrpcClient = new moq::Mock<TenantService.TenantServiceClient>(moq::MockBehavior.Strict); DeleteTenantRequest request = new DeleteTenantRequest { TenantName = TenantName.FromProjectTenant("[PROJECT]", "[TENANT]"), }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.DeleteTenant(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); TenantServiceClient client = new TenantServiceClientImpl(mockGrpcClient.Object, null); client.DeleteTenant(request.Name); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task DeleteTenantAsync() { moq::Mock<TenantService.TenantServiceClient> mockGrpcClient = new moq::Mock<TenantService.TenantServiceClient>(moq::MockBehavior.Strict); DeleteTenantRequest request = new DeleteTenantRequest { TenantName = TenantName.FromProjectTenant("[PROJECT]", "[TENANT]"), }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.DeleteTenantAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null)); TenantServiceClient client = new TenantServiceClientImpl(mockGrpcClient.Object, null); await client.DeleteTenantAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); await client.DeleteTenantAsync(request.Name, st::CancellationToken.None); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void DeleteTenantResourceNames() { moq::Mock<TenantService.TenantServiceClient> mockGrpcClient = new moq::Mock<TenantService.TenantServiceClient>(moq::MockBehavior.Strict); DeleteTenantRequest request = new DeleteTenantRequest { TenantName = TenantName.FromProjectTenant("[PROJECT]", "[TENANT]"), }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.DeleteTenant(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); TenantServiceClient client = new TenantServiceClientImpl(mockGrpcClient.Object, null); client.DeleteTenant(request.TenantName); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task DeleteTenantResourceNamesAsync() { moq::Mock<TenantService.TenantServiceClient> mockGrpcClient = new moq::Mock<TenantService.TenantServiceClient>(moq::MockBehavior.Strict); DeleteTenantRequest request = new DeleteTenantRequest { TenantName = TenantName.FromProjectTenant("[PROJECT]", "[TENANT]"), }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.DeleteTenantAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null)); TenantServiceClient client = new TenantServiceClientImpl(mockGrpcClient.Object, null); await client.DeleteTenantAsync(request.TenantName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); await client.DeleteTenantAsync(request.TenantName, st::CancellationToken.None); mockGrpcClient.VerifyAll(); } } }
55.577413
222
0.644795
[ "Apache-2.0" ]
Global19/google-cloud-dotnet
apis/Google.Cloud.Talent.V4Beta1/Google.Cloud.Talent.V4Beta1.Tests/TenantServiceClientTest.g.cs
30,512
C#
using System; using System.Collections.Generic; using System.Threading; namespace jIAnSoft.Nami.Core { /// <inheritdoc /> /// <summary> /// Queue with bounded capacity. Will throw exception if capacity does not recede prior to wait time. /// </summary> public class BoundedQueue : IQueue { private readonly object _lock = new object(); private List<Action> _actions = new List<Action>(); private bool _disposed; //private readonly IExecutor _executor; private bool _running = true; private List<Action> _toPass = new List<Action>(); ///<summary> /// Creates a bounded queue with a custom executor. ///</summary> public BoundedQueue() { MaxDepth = -1; } /// <summary> /// Max number of actions to be queued. /// </summary> public int MaxDepth { get; set; } /// <summary> /// Max time to wait for space in the queue. /// </summary> public int MaxEnqueueWaitTimeInMs { get; set; } /// <inheritdoc /> /// <summary> /// Enqueue action. /// </summary> /// <param name="action"></param> public void Enqueue(Action action) { if (!_running) { return; } lock (_lock) { if (!SpaceAvailable(1)) { return; } _actions.Add(action); Monitor.PulseAll(_lock); } } public int Count() { lock (_lock) { return _actions.Count; } } /// <inheritdoc /> /// <summary> /// Execute actions until stopped. /// </summary> public void Run() { lock (_lock) { _running = true; Monitor.PulseAll(_lock); } } /// <inheritdoc /> /// <summary> /// Stop consuming actions. /// </summary> public void Stop() { lock (_lock) { _running = false; Monitor.PulseAll(_lock); } } public Action[] DequeueAll() { lock (_lock) { if (!ReadyToDequeue()) { return null; } Lists.Swap(ref _actions, ref _toPass); _actions.Clear(); Monitor.PulseAll(_lock); var toPass = _toPass.ToArray(); return toPass; } } public void Dispose() { Dispose(true); } private bool SpaceAvailable(int toAdd) { if (!_running) { return false; } while (MaxDepth > 0 && _actions.Count + toAdd > MaxDepth) { if (MaxEnqueueWaitTimeInMs <= 0) { throw new QueueFullException(_actions.Count); } Monitor.Wait(_lock, MaxEnqueueWaitTimeInMs); if (!_running) { return false; } if (MaxDepth > 0 && _actions.Count + toAdd > MaxDepth) { throw new QueueFullException(_actions.Count); } } return true; } private bool ReadyToDequeue() { while (_actions.Count == 0 && _running) { Monitor.Wait(_lock); } return _running; } private void Dispose(bool disposing) { if (!disposing || _disposed) { return; } _disposed = true; Stop(); _actions?.Clear(); _toPass?.Clear(); } } }
23.297143
106
0.420652
[ "MIT" ]
jiansoft/nami
Nami/Core/BoundedQueue.cs
4,077
C#
using System; using System.IO; using System.Xml.Schema; namespace XsdValidator { internal class Program { private static void Main(string[] args) { Console.WriteLine("(C) 2011-2012 XSDValidator @ softlang in Koblenz"); if (args.Length < 1) { Console.WriteLine("Usage: XSDValidator file.xsd"); Environment.Exit(-1); } var fileName = args[0]; if (!fileName.EndsWith(".xsd")) { Console.WriteLine(string.Format("-> {0} is not a valid XSD file", fileName)); Environment.Exit(-1); } try { using ( var fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read, 4096, FileOptions.SequentialScan)) { try { var errors = false; XmlSchema.Read(fs, (x,y) => { errors = true; Console.WriteLine(y.Message); }); if(errors == true) throw new Exception("Not a valid XSD"); } catch(Exception ex) { Console.WriteLine(ex.Message); Console.WriteLine(string.Format("-> {0} is not a valid XSD file", fileName)); Environment.Exit(-1); } } } catch (DirectoryNotFoundException ex) { Console.WriteLine(ex.Message); Environment.Exit(-1); } catch (FileNotFoundException ex) { Console.WriteLine(ex.Message); Environment.Exit(-1); } Console.WriteLine("-> Validation succeeded"); Environment.Exit(0); } } }
31.822581
111
0.437912
[ "MIT" ]
101companies/101repo
technologies/XSDValidator/Main.cs
1,973
C#
using System; using System.Collections.Generic; using System.Threading.Tasks; using pdq.common.Logging; namespace pdq.common.Connections { public abstract class ConnectionFactory : IConnectionFactory { private readonly ILoggerProxy logger; private IDictionary<string, IConnection> connections; /// <summary> /// Create an instance of a ConnectionFactory. /// </summary> /// <param name="logger">The logger to Use.</param> public ConnectionFactory(ILoggerProxy logger) { this.connections = new Dictionary<string, IConnection>(); this.logger = logger; } public void Dispose() { this.connections = null; } public ValueTask DisposeAsync() { Dispose(); return new ValueTask(); } public IConnection Get(IConnectionDetails connectionDetails) { var t = GetAsync(connectionDetails); t.Wait(); return t.Result; } public async Task<IConnection> GetAsync(IConnectionDetails connectionDetails) { if (connectionDetails == null) throw new ArgumentNullException(nameof(connectionDetails), $"The {nameof(connectionDetails)} cannot be null, it MUST be provided when creating a connection."); if (this.connections == null) this.connections = new Dictionary<string, IConnection>(); string hash = null; try { hash = connectionDetails.GetHash(); } catch (Exception e) { this.logger.Error(e, "Error Getting connection Hash"); throw; } if(this.connections.ContainsKey(hash)) { return this.connections[hash]; } try { var connection = await ConstructConnection(connectionDetails); this.connections.Add(hash, connection); return connection; } catch (Exception e) { this.logger.Error(e, $"An error occurred attempting to get the connection."); throw; } } protected abstract Task<IConnection> ConstructConnection(IConnectionDetails connectionDetails); } }
29.048193
175
0.55786
[ "MIT" ]
daniel-buchanan/pdq
src/core/pdq.core.common/Connections/ConnectionFactory.cs
2,413
C#
using NJsonSchema; using NJsonSchema.CodeGeneration; using NSwag.CodeGeneration.TypeScript.Models; namespace NSwag.CodeGeneration.TypeScript.Templates { internal partial class JQueryCallbacksClientTemplate : ITemplate { public JQueryCallbacksClientTemplate(TypeScriptClientTemplateModel model) { Model = model; } public TypeScriptClientTemplateModel Model { get; } public string Render() { return ConversionUtilities.TrimWhiteSpaces(TransformText()); } } }
25.5
81
0.684492
[ "MIT" ]
Witivio/NSwag
src/NSwag.CodeGeneration.TypeScript/Templates/JQueryCallbacksClientTemplate.Extensions.cs
563
C#
using AsyncHotel.Data.Repositories.IRepositories; using AsyncHotel.Models; using AsyncHotel.Models.API; using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace AsyncHotel.Data.Repositories.DatabaseRepositories { public class DatabaseAmenityRepository : IAmenityRepository { private readonly HotelDbContext _context; public DatabaseAmenityRepository(HotelDbContext context) { _context = context; } public async Task<AmenityDTO> DeleteAmenity(int id) { var amenity = await _context.Amenities.FindAsync(id); if (amenity == null) { return null; } _context.Amenities.Remove(amenity); await _context.SaveChangesAsync(); var amenityToReturn = await GetOneAmenity(id); return amenityToReturn; } public async Task<IEnumerable<AmenityDTO>> GetAllAmenities() { var amenities = await _context.Amenities .Select(amenity => new AmenityDTO { Id = amenity.Id, name = amenity.name }) .ToListAsync(); return amenities; } public async Task<AmenityDTO> GetOneAmenity(int id) { var amenity = await _context.Amenities .Select(amenity => new AmenityDTO { Id = amenity.Id, name = amenity.name }) .FirstOrDefaultAsync(amenity => amenity.Id == id); return amenity; } public async Task<AmenityDTO> SaveNewAmenity(Amenity Amenity) { _context.Amenities.Add(Amenity); await _context.SaveChangesAsync(); var amenityToReturn = GetOneAmenity(Amenity.Id); return await amenityToReturn; } public async Task<bool> UpdateAmenity(int id, Amenity Amenity) { _context.Entry(Amenity).State = EntityState.Modified; try { await _context.SaveChangesAsync(); return true; } catch (DbUpdateConcurrencyException) { if (!AmenityExists(id)) { return false; } else { throw; } } } private bool AmenityExists(int id) { return _context.Amenities.Any(e => e.Id == id); } } }
26.23301
70
0.527387
[ "MIT" ]
bproorda/AsyncHotel
AsyncHotel/Data/Repositories/DatabaseRepositories/DatabaseAmenityRepository.cs
2,704
C#
using Newtonsoft.Json; using Newtonsoft.Json.Linq; using System; using System.IO; using System.Net; using System.Text; namespace CmlLib.Core.Auth { public enum MLoginResult { Success, BadRequest, WrongAccount, NeedLogin, UnknownError, NoProfile } public class MLogin { public static readonly string DefaultLoginSessionFile = Path.Combine(MinecraftPath.GetOSDefaultPath(), "logintoken.json"); public MLogin() : this(DefaultLoginSessionFile) { } public MLogin(string sessionCacheFilePath) { SessionCacheFilePath = sessionCacheFilePath; } public string SessionCacheFilePath { get; private set; } public bool SaveSession { get; set; } = true; private string CreateNewClientToken() { return Guid.NewGuid().ToString().Replace("-", ""); } private MSession CreateNewSession() { var session = new MSession(); if (SaveSession) { session.ClientToken = CreateNewClientToken(); WriteSessionCache(session); } return session; } private void WriteSessionCache(MSession session) { if (!SaveSession) return; Directory.CreateDirectory(Path.GetDirectoryName(SessionCacheFilePath)); var json = JsonConvert.SerializeObject(session); File.WriteAllText(SessionCacheFilePath, json, Encoding.UTF8); } public MSession ReadSessionCache() { if (File.Exists(SessionCacheFilePath)) { var filedata = File.ReadAllText(SessionCacheFilePath, Encoding.UTF8); try { var session = JsonConvert.DeserializeObject<MSession>(filedata, new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Ignore }); if (SaveSession && string.IsNullOrEmpty(session.ClientToken)) session.ClientToken = CreateNewClientToken(); return session; } catch (JsonReaderException) // invalid json { return CreateNewSession(); } } else { return CreateNewSession(); } } private HttpWebResponse mojangRequest(string endpoint, string postdata) { var http = WebRequest.CreateHttp(MojangServer.Auth + endpoint); http.ContentType = "application/json"; http.Method = "POST"; using (var req = new StreamWriter(http.GetRequestStream())) { req.Write(postdata); req.Flush(); } var res = http.GetResponseNoException(); return res; } private MLoginResponse parseSession(string json, string clientToken) { var job = JObject.Parse(json); //json parse var profile = job["selectedProfile"]; if (profile == null) return new MLoginResponse(MLoginResult.NoProfile, null, null, json); else { var session = new MSession() { AccessToken = job["accessToken"]?.ToString(), UUID = profile["id"]?.ToString(), Username = profile["name"]?.ToString(), ClientToken = clientToken }; WriteSessionCache(session); return new MLoginResponse(MLoginResult.Success, session, null, null); } } private MLoginResponse errorHandle(string json) { try { var job = JObject.Parse(json); var error = job["error"]?.ToString(); // error type var errormsg = job["message"]?.ToString() ?? ""; // detail error message MLoginResult result; switch (error) { case "Method Not Allowed": case "Not Found": case "Unsupported Media Type": result = MLoginResult.BadRequest; break; case "IllegalArgumentException": case "ForbiddenOperationException": result = MLoginResult.WrongAccount; break; default: result = MLoginResult.UnknownError; break; } return new MLoginResponse(result, null, errormsg, json); } catch (Exception ex) { return new MLoginResponse(MLoginResult.UnknownError, null, ex.ToString(), json); } } public MLoginResponse Authenticate(string id, string pw) { var clientToken = ReadSessionCache().ClientToken; return Authenticate(id, pw, clientToken); } public MLoginResponse Authenticate(string id, string pw, string clientToken) { var req = new JObject { { "username", id }, { "password", pw }, { "clientToken", clientToken }, { "agent", new JObject { { "name", "Minecraft" }, { "version", 1 } } } }; var resHeader = mojangRequest("authenticate", req.ToString()); using (var res = new StreamReader(resHeader.GetResponseStream())) { var rawResponse = res.ReadToEnd(); if (resHeader.StatusCode == HttpStatusCode.OK) // ResultCode == 200 return parseSession(rawResponse, clientToken); else // fail to login return errorHandle(rawResponse); } } public MLoginResponse TryAutoLogin() { var session = ReadSessionCache(); return TryAutoLogin(session); } public MLoginResponse TryAutoLogin(MSession session) { try { var result = Validate(session); if (result.Result != MLoginResult.Success) result = Refresh(session); return result; } catch (Exception ex) { return new MLoginResponse(MLoginResult.UnknownError, null, ex.ToString(), null); } } public MLoginResponse TryAutoLoginFromMojangLauncher() { var mojangAccounts = MojangLauncher.MojangLauncherAccounts.FromDefaultPath(); var activeAccount = mojangAccounts.GetActiveAccount(); return TryAutoLogin(activeAccount.ToSession()); } public MLoginResponse TryAutoLoginFromMojangLauncher(string accountFilePath) { var mojangAccounts = MojangLauncher.MojangLauncherAccounts.FromFile(accountFilePath); var activeAccount = mojangAccounts.GetActiveAccount(); return TryAutoLogin(activeAccount.ToSession()); } public MLoginResponse Refresh() { var session = ReadSessionCache(); return Refresh(session); } public MLoginResponse Refresh(MSession session) { var req = new JObject { { "accessToken", session.AccessToken }, { "clientToken", session.ClientToken }, { "selectedProfile", new JObject() { { "id", session.UUID }, { "name", session.Username } } } }; var resHeader = mojangRequest("refresh", req.ToString()); using (var res = new StreamReader(resHeader.GetResponseStream())) { var rawResponse = res.ReadToEnd(); if ((int)resHeader.StatusCode / 100 == 2) return parseSession(rawResponse, session.ClientToken); else return errorHandle(rawResponse); } } public MLoginResponse Validate() { var session = ReadSessionCache(); return Validate(session); } public MLoginResponse Validate(MSession session) { JObject req = new JObject { { "accessToken", session.AccessToken }, { "clientToken", session.ClientToken } }; var resHeader = mojangRequest("validate", req.ToString()); using (var res = new StreamReader(resHeader.GetResponseStream())) { if (resHeader.StatusCode == HttpStatusCode.NoContent) // StatusCode == 204 return new MLoginResponse(MLoginResult.Success, session, null, null); else return new MLoginResponse(MLoginResult.NeedLogin, null, null, null); } } public void DeleteTokenFile() { if (File.Exists(SessionCacheFilePath)) File.Delete(SessionCacheFilePath); } public bool Invalidate() { var session = ReadSessionCache(); return Invalidate(session); } public bool Invalidate(MSession session) { var job = new JObject { { "accessToken", session.AccessToken }, { "clientToken", session.ClientToken } }; var res = mojangRequest("invalidate", job.ToString()); return res.StatusCode == HttpStatusCode.NoContent; // 204 } public bool Signout(string id, string pw) { var job = new JObject { { "username", id }, { "password", pw } }; var res = mojangRequest("signout", job.ToString()); return res.StatusCode == HttpStatusCode.NoContent; // 204 } } public static class HttpWebResponseExt { public static HttpWebResponse GetResponseNoException(this HttpWebRequest req) { try { return (HttpWebResponse)req.GetResponse(); } catch (WebException we) { var resp = we.Response as HttpWebResponse; if (resp == null) throw; return resp; } } } }
32.752266
130
0.506964
[ "MIT" ]
NamuTree0345/CmlLib.Core
CmlLib/Core/Auth/MLogin.cs
10,843
C#
// <copyright file="Startup.cs" company="Quamotion bv"> // Copyright (c) Quamotion bv. All rights reserved. // </copyright> using Kaponata.Kubernetes; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; namespace Kaponata.Api { /// <summary> /// This class contains startup information for the Kaponata API server. /// </summary> public class Startup { /// <summary> /// Configures services that are used by the Kaponata API server. /// </summary> /// <param name="services"> /// The service collection to which to add the services. /// </param> /// <seealso href="http://go.microsoft.com/fwlink/?LinkID=398940"/> public void ConfigureServices(IServiceCollection services) { services.AddHealthChecks(); services.AddControllers(); services.AddKubernetes(); } /// <summary> /// Specifies how the ASP.NET application will respond to individual HTTP requests. /// </summary> /// <param name="app"> /// The application to configure. /// </param> /// <param name="env"> /// The current hosting environment. /// </param> public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } #if DEBUG app.UseCors(o => { o.AllowAnyOrigin(); o.AllowAnyHeader(); o.AllowAnyMethod(); }); #endif app.Use((context, next) => { context.Response.Headers["X-Kaponata-Version"] = ThisAssembly.AssemblyInformationalVersion; return next.Invoke(); }); app.UseRouting(); app.UseEndpoints(endpoints => { endpoints.MapGet("/", async context => { context.Response.ContentType = "text/plain"; await context.Response.WriteAsync("Hello World!"); }); endpoints.MapControllers(); endpoints.MapHealthChecks("/health/ready"); endpoints.MapHealthChecks("/health/alive"); }); } } }
30.585366
107
0.545455
[ "MIT" ]
kaponata-io/kaponata
src/Kaponata.Api/Startup.cs
2,508
C#
// Copyright © Amer Koleci and Contributors. // Licensed under the MIT License (MIT). See LICENSE in the repository root for more information. namespace Vortice.Graphics.Samples; class Program { static void Main() { ValidationMode validationMode = ValidationMode.Disabled; #if DEBUG validationMode = ValidationMode.Enabled; #endif BackendType preferredBackend = BackendType.Count; //preferredBackend = BackendType.Vulkan; using HelloWorldApp app = new(preferredBackend, validationMode); app.Run(); } }
26.904762
97
0.707965
[ "MIT" ]
amerkoleci/Vortice.GPU
samples/HelloWorld/Program.cs
566
C#
// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information. // Ported from um/sapi.h in the Windows SDK for Windows 10.0.19041.0 // Original source is Copyright © Microsoft. All rights reserved. using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; namespace TerraFX.Interop { [Guid("6D60EB64-ACED-40A6-BBF3-4E557F71DEE2")] [NativeTypeName("struct ISpeechRecoResultDispatch : IDispatch")] public unsafe partial struct ISpeechRecoResultDispatch { public void** lpVtbl; [MethodImpl(MethodImplOptions.AggressiveInlining)] [return: NativeTypeName("HRESULT")] public int QueryInterface([NativeTypeName("const IID &")] Guid* riid, [NativeTypeName("void **")] void** ppvObject) { return ((delegate* unmanaged<ISpeechRecoResultDispatch*, Guid*, void**, int>)(lpVtbl[0]))((ISpeechRecoResultDispatch*)Unsafe.AsPointer(ref this), riid, ppvObject); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [return: NativeTypeName("ULONG")] public uint AddRef() { return ((delegate* unmanaged<ISpeechRecoResultDispatch*, uint>)(lpVtbl[1]))((ISpeechRecoResultDispatch*)Unsafe.AsPointer(ref this)); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [return: NativeTypeName("ULONG")] public uint Release() { return ((delegate* unmanaged<ISpeechRecoResultDispatch*, uint>)(lpVtbl[2]))((ISpeechRecoResultDispatch*)Unsafe.AsPointer(ref this)); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [return: NativeTypeName("HRESULT")] public int GetTypeInfoCount([NativeTypeName("UINT *")] uint* pctinfo) { return ((delegate* unmanaged<ISpeechRecoResultDispatch*, uint*, int>)(lpVtbl[3]))((ISpeechRecoResultDispatch*)Unsafe.AsPointer(ref this), pctinfo); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [return: NativeTypeName("HRESULT")] public int GetTypeInfo([NativeTypeName("UINT")] uint iTInfo, [NativeTypeName("LCID")] uint lcid, [NativeTypeName("ITypeInfo **")] ITypeInfo** ppTInfo) { return ((delegate* unmanaged<ISpeechRecoResultDispatch*, uint, uint, ITypeInfo**, int>)(lpVtbl[4]))((ISpeechRecoResultDispatch*)Unsafe.AsPointer(ref this), iTInfo, lcid, ppTInfo); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [return: NativeTypeName("HRESULT")] public int GetIDsOfNames([NativeTypeName("const IID &")] Guid* riid, [NativeTypeName("LPOLESTR *")] ushort** rgszNames, [NativeTypeName("UINT")] uint cNames, [NativeTypeName("LCID")] uint lcid, [NativeTypeName("DISPID *")] int* rgDispId) { return ((delegate* unmanaged<ISpeechRecoResultDispatch*, Guid*, ushort**, uint, uint, int*, int>)(lpVtbl[5]))((ISpeechRecoResultDispatch*)Unsafe.AsPointer(ref this), riid, rgszNames, cNames, lcid, rgDispId); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [return: NativeTypeName("HRESULT")] public int Invoke([NativeTypeName("DISPID")] int dispIdMember, [NativeTypeName("const IID &")] Guid* riid, [NativeTypeName("LCID")] uint lcid, [NativeTypeName("WORD")] ushort wFlags, [NativeTypeName("DISPPARAMS *")] DISPPARAMS* pDispParams, [NativeTypeName("VARIANT *")] VARIANT* pVarResult, [NativeTypeName("EXCEPINFO *")] EXCEPINFO* pExcepInfo, [NativeTypeName("UINT *")] uint* puArgErr) { return ((delegate* unmanaged<ISpeechRecoResultDispatch*, int, Guid*, uint, ushort, DISPPARAMS*, VARIANT*, EXCEPINFO*, uint*, int>)(lpVtbl[6]))((ISpeechRecoResultDispatch*)Unsafe.AsPointer(ref this), dispIdMember, riid, lcid, wFlags, pDispParams, pVarResult, pExcepInfo, puArgErr); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [return: NativeTypeName("HRESULT")] public int get_RecoContext([NativeTypeName("ISpeechRecoContext **")] ISpeechRecoContext** RecoContext) { return ((delegate* unmanaged<ISpeechRecoResultDispatch*, ISpeechRecoContext**, int>)(lpVtbl[7]))((ISpeechRecoResultDispatch*)Unsafe.AsPointer(ref this), RecoContext); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [return: NativeTypeName("HRESULT")] public int get_Times([NativeTypeName("ISpeechRecoResultTimes **")] ISpeechRecoResultTimes** Times) { return ((delegate* unmanaged<ISpeechRecoResultDispatch*, ISpeechRecoResultTimes**, int>)(lpVtbl[8]))((ISpeechRecoResultDispatch*)Unsafe.AsPointer(ref this), Times); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [return: NativeTypeName("HRESULT")] public int putref_AudioFormat([NativeTypeName("ISpeechAudioFormat *")] ISpeechAudioFormat* Format) { return ((delegate* unmanaged<ISpeechRecoResultDispatch*, ISpeechAudioFormat*, int>)(lpVtbl[9]))((ISpeechRecoResultDispatch*)Unsafe.AsPointer(ref this), Format); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [return: NativeTypeName("HRESULT")] public int get_AudioFormat([NativeTypeName("ISpeechAudioFormat **")] ISpeechAudioFormat** Format) { return ((delegate* unmanaged<ISpeechRecoResultDispatch*, ISpeechAudioFormat**, int>)(lpVtbl[10]))((ISpeechRecoResultDispatch*)Unsafe.AsPointer(ref this), Format); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [return: NativeTypeName("HRESULT")] public int get_PhraseInfo([NativeTypeName("ISpeechPhraseInfo **")] ISpeechPhraseInfo** PhraseInfo) { return ((delegate* unmanaged<ISpeechRecoResultDispatch*, ISpeechPhraseInfo**, int>)(lpVtbl[11]))((ISpeechRecoResultDispatch*)Unsafe.AsPointer(ref this), PhraseInfo); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [return: NativeTypeName("HRESULT")] public int Alternates([NativeTypeName("long")] int RequestCount, [NativeTypeName("long")] int StartElement, [NativeTypeName("long")] int Elements, [NativeTypeName("ISpeechPhraseAlternates **")] ISpeechPhraseAlternates** Alternates) { return ((delegate* unmanaged<ISpeechRecoResultDispatch*, int, int, int, ISpeechPhraseAlternates**, int>)(lpVtbl[12]))((ISpeechRecoResultDispatch*)Unsafe.AsPointer(ref this), RequestCount, StartElement, Elements, Alternates); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [return: NativeTypeName("HRESULT")] public int Audio([NativeTypeName("long")] int StartElement, [NativeTypeName("long")] int Elements, [NativeTypeName("ISpeechMemoryStream **")] ISpeechMemoryStream** Stream) { return ((delegate* unmanaged<ISpeechRecoResultDispatch*, int, int, ISpeechMemoryStream**, int>)(lpVtbl[13]))((ISpeechRecoResultDispatch*)Unsafe.AsPointer(ref this), StartElement, Elements, Stream); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [return: NativeTypeName("HRESULT")] public int SpeakAudio([NativeTypeName("long")] int StartElement, [NativeTypeName("long")] int Elements, SpeechVoiceSpeakFlags Flags, [NativeTypeName("long *")] int* StreamNumber) { return ((delegate* unmanaged<ISpeechRecoResultDispatch*, int, int, SpeechVoiceSpeakFlags, int*, int>)(lpVtbl[14]))((ISpeechRecoResultDispatch*)Unsafe.AsPointer(ref this), StartElement, Elements, Flags, StreamNumber); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [return: NativeTypeName("HRESULT")] public int SaveToMemory([NativeTypeName("VARIANT *")] VARIANT* ResultBlock) { return ((delegate* unmanaged<ISpeechRecoResultDispatch*, VARIANT*, int>)(lpVtbl[15]))((ISpeechRecoResultDispatch*)Unsafe.AsPointer(ref this), ResultBlock); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [return: NativeTypeName("HRESULT")] public int DiscardResultInfo(SpeechDiscardType ValueTypes) { return ((delegate* unmanaged<ISpeechRecoResultDispatch*, SpeechDiscardType, int>)(lpVtbl[16]))((ISpeechRecoResultDispatch*)Unsafe.AsPointer(ref this), ValueTypes); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [return: NativeTypeName("HRESULT")] public int GetXMLResult(SPXMLRESULTOPTIONS Options, [NativeTypeName("BSTR *")] ushort** pResult) { return ((delegate* unmanaged<ISpeechRecoResultDispatch*, SPXMLRESULTOPTIONS, ushort**, int>)(lpVtbl[17]))((ISpeechRecoResultDispatch*)Unsafe.AsPointer(ref this), Options, pResult); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [return: NativeTypeName("HRESULT")] public int GetXMLErrorInfo([NativeTypeName("long *")] int* LineNumber, [NativeTypeName("BSTR *")] ushort** ScriptLine, [NativeTypeName("BSTR *")] ushort** Source, [NativeTypeName("BSTR *")] ushort** Description, [NativeTypeName("HRESULT *")] int* ResultCode, [NativeTypeName("VARIANT_BOOL *")] short* IsError) { return ((delegate* unmanaged<ISpeechRecoResultDispatch*, int*, ushort**, ushort**, ushort**, int*, short*, int>)(lpVtbl[18]))((ISpeechRecoResultDispatch*)Unsafe.AsPointer(ref this), LineNumber, ScriptLine, Source, Description, ResultCode, IsError); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [return: NativeTypeName("HRESULT")] public int SetTextFeedback([NativeTypeName("BSTR")] ushort* Feedback, [NativeTypeName("VARIANT_BOOL")] short WasSuccessful) { return ((delegate* unmanaged<ISpeechRecoResultDispatch*, ushort*, short, int>)(lpVtbl[19]))((ISpeechRecoResultDispatch*)Unsafe.AsPointer(ref this), Feedback, WasSuccessful); } } }
62.201258
397
0.698281
[ "MIT" ]
Perksey/terrafx.interop.windows
sources/Interop/Windows/um/sapi/ISpeechRecoResultDispatch.cs
9,892
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ using System; using System.Reflection; [assembly: System.Reflection.AssemblyCompanyAttribute("FirstWebApp")] [assembly: System.Reflection.AssemblyConfigurationAttribute("Debug")] [assembly: System.Reflection.AssemblyFileVersionAttribute("1.0.0.0")] [assembly: System.Reflection.AssemblyInformationalVersionAttribute("1.0.0")] [assembly: System.Reflection.AssemblyProductAttribute("FirstWebApp")] [assembly: System.Reflection.AssemblyTitleAttribute("FirstWebApp")] [assembly: System.Reflection.AssemblyVersionAttribute("1.0.0.0")] // Generated by the MSBuild WriteCodeFragment class.
40.958333
80
0.648016
[ "MIT" ]
MiyaSteven/CSharp
FirstWebApp/obj/Debug/netcoreapp3.1/FirstWebApp.AssemblyInfo.cs
983
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 ProService; namespace TCC_Wpf.Wizard { /// <summary> /// Interaction logic for PrimeiraSimul.xaml /// </summary> public partial class SimulacaoPreliminar : Page, ProService.IAlgoritimo { public SimulacaoPreliminar() { InitializeComponent(); } void IAlgoritimo.Acao() { } void IAlgoritimo.PassoAtual(string passo) { txtMensagem.Text = passo; } void IAlgoritimo.Progresso(double progresso) { } void IAlgoritimo.ProximaEtapa() { lblAguarde.Content = "Etapa concluída"; pgbProgresso.IsIndeterminate = false; pgbProgresso.Value = 100; } void IAlgoritimo.TempoSimulacao(double tempo) { txtMensagem.Text = "Tempo de simulção: "+tempo; } } }
23.072727
75
0.636722
[ "MIT" ]
ThiagoAguirre/PromodelImprovement
TCC_Wpf/Wizard/SimulacaoPreliminar.xaml.cs
1,274
C#
// <auto-generated /> using System; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Storage.ValueConversion; using TeamBuilder.Data; namespace TeamBuilder.Data.Migrations { [DbContext(typeof(TeamBuilderContext))] partial class TeamBuilderContextModelSnapshot : ModelSnapshot { protected override void BuildModel(ModelBuilder modelBuilder) { #pragma warning disable 612, 618 modelBuilder .HasAnnotation("ProductVersion", "2.1.1-rtm-30846") .HasAnnotation("Relational:MaxIdentifierLength", 128) .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); modelBuilder.Entity("TeamBuilder.Models.Event", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<int>("CreatorId"); b.Property<string>("Description") .HasMaxLength(250); b.Property<DateTime>("EndDate"); b.Property<string>("Name") .IsRequired() .HasMaxLength(25); b.Property<DateTime>("StartDate"); b.HasKey("Id"); b.HasIndex("CreatorId"); b.ToTable("Events"); }); modelBuilder.Entity("TeamBuilder.Models.EventTeam", b => { b.Property<int>("EventId"); b.Property<int>("TeamId"); b.HasKey("EventId", "TeamId"); b.HasIndex("TeamId"); b.ToTable("EventTeams"); }); modelBuilder.Entity("TeamBuilder.Models.Invitation", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<int>("InvitedUserId"); b.Property<bool>("IsActive"); b.Property<int>("TeamId"); b.HasKey("Id"); b.HasIndex("InvitedUserId"); b.HasIndex("TeamId"); b.ToTable("Invitaions"); }); modelBuilder.Entity("TeamBuilder.Models.Team", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("Acronym") .IsRequired() .HasMaxLength(3); b.Property<int>("CreatorId"); b.Property<string>("Description") .HasMaxLength(32); b.Property<string>("Name") .IsRequired() .HasMaxLength(25); b.HasKey("Id"); b.HasIndex("CreatorId"); b.HasIndex("Name") .IsUnique(); b.ToTable("Teams"); }); modelBuilder.Entity("TeamBuilder.Models.User", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("Age"); b.Property<string>("FirstName") .HasMaxLength(25); b.Property<string>("Gender") .IsRequired() .HasMaxLength(10); b.Property<bool>("IsDeleted"); b.Property<string>("LastName") .HasMaxLength(25); b.Property<string>("Password") .IsRequired() .HasMaxLength(30); b.Property<string>("Username") .IsRequired() .HasMaxLength(25); b.HasKey("Id"); b.HasIndex("Username") .IsUnique(); b.ToTable("Users"); }); modelBuilder.Entity("TeamBuilder.Models.UserTeam", b => { b.Property<int>("UserId"); b.Property<int>("TeamId"); b.HasKey("UserId", "TeamId"); b.HasIndex("TeamId"); b.ToTable("UserTeam"); }); modelBuilder.Entity("TeamBuilder.Models.Event", b => { b.HasOne("TeamBuilder.Models.User", "Creator") .WithMany("CreatedEvents") .HasForeignKey("CreatorId") .OnDelete(DeleteBehavior.Restrict); }); modelBuilder.Entity("TeamBuilder.Models.EventTeam", b => { b.HasOne("TeamBuilder.Models.Event", "Event") .WithMany("ParticipatingEventTeams") .HasForeignKey("EventId") .OnDelete(DeleteBehavior.Cascade); b.HasOne("TeamBuilder.Models.Team", "Team") .WithMany("Events") .HasForeignKey("TeamId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("TeamBuilder.Models.Invitation", b => { b.HasOne("TeamBuilder.Models.User", "InvitedUser") .WithMany("ReceivedInvitations") .HasForeignKey("InvitedUserId") .OnDelete(DeleteBehavior.Restrict); b.HasOne("TeamBuilder.Models.Team", "Team") .WithMany("Invittaions") .HasForeignKey("TeamId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("TeamBuilder.Models.Team", b => { b.HasOne("TeamBuilder.Models.User", "Creator") .WithMany("CreatedTeams") .HasForeignKey("CreatorId") .OnDelete(DeleteBehavior.Restrict); }); modelBuilder.Entity("TeamBuilder.Models.UserTeam", b => { b.HasOne("TeamBuilder.Models.Team", "Team") .WithMany("UserTeams") .HasForeignKey("TeamId") .OnDelete(DeleteBehavior.Cascade); b.HasOne("TeamBuilder.Models.User", "User") .WithMany("UserTeams") .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade); }); #pragma warning restore 612, 618 } } }
34.275229
125
0.462125
[ "MIT" ]
LuGeorgiev/SoftUniDBAdvanced
Workshop/TeamBuilder.Data/Migrations/TeamBuilderContextModelSnapshot.cs
7,474
C#
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.IO; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc.Abstractions; using Microsoft.AspNetCore.Mvc.Controllers; using Microsoft.AspNetCore.Mvc.ModelBinding; using Microsoft.AspNetCore.Mvc.ModelBinding.Metadata; using Microsoft.AspNetCore.Mvc.ModelBinding.Validation; using Newtonsoft.Json.Linq; using Xunit; namespace Microsoft.AspNetCore.Mvc.IntegrationTests { public class ValidationIntegrationTests { private class TransferInfo { [Range(25, 50)] public int AccountId { get; set; } public double Amount { get; set; } } private class TestController { } public static TheoryData<List<ParameterDescriptor>> MultipleActionParametersAndValidationData { get { return new TheoryData<List<ParameterDescriptor>> { // Irrespective of the order in which the parameters are defined on the action, // the validation on the TransferInfo's AccountId should occur. // Here 'accountId' parameter is bound by the prefix 'accountId' while the 'transferInfo' // property is bound using the empty prefix and the 'TransferInfo' property names. new List<ParameterDescriptor>() { new ParameterDescriptor() { Name = "accountId", ParameterType = typeof(int) }, new ParameterDescriptor() { Name = "transferInfo", ParameterType = typeof(TransferInfo), BindingInfo = new BindingInfo() { BindingSource = BindingSource.Body } } }, new List<ParameterDescriptor>() { new ParameterDescriptor() { Name = "transferInfo", ParameterType = typeof(TransferInfo), BindingInfo = new BindingInfo() { BindingSource = BindingSource.Body } }, new ParameterDescriptor() { Name = "accountId", ParameterType = typeof(int) } } }; } } [Theory] [MemberData(nameof(MultipleActionParametersAndValidationData))] public async Task ValidationIsTriggered_OnFromBodyModels(List<ParameterDescriptor> parameters) { // Arrange var actionDescriptor = new ControllerActionDescriptor() { BoundProperties = new List<ParameterDescriptor>(), Parameters = parameters }; var parameterBinder = ModelBindingTestHelper.GetParameterBinder(); var testContext = ModelBindingTestHelper.GetTestContext( request => { request.QueryString = new QueryString("?accountId=30"); request.Body = new MemoryStream(Encoding.UTF8.GetBytes("{\"accountId\": 15,\"amount\": 250.0}")); request.ContentType = "application/json"; }, actionDescriptor: actionDescriptor); var modelState = testContext.ModelState; // Act foreach (var parameter in parameters) { await parameterBinder.BindModelAsync(parameter, testContext); } // Assert Assert.False(modelState.IsValid); var entry = Assert.Single( modelState, e => string.Equals(e.Key, "AccountId", StringComparison.OrdinalIgnoreCase)).Value; var error = Assert.Single(entry.Errors); Assert.Equal(ValidationAttributeUtil.GetRangeErrorMessage(25, 50, "AccountId"), error.ErrorMessage); } [Theory] [MemberData(nameof(MultipleActionParametersAndValidationData))] public async Task MultipleActionParameter_ValidModelState(List<ParameterDescriptor> parameters) { // Since validation attribute is only present on the FromBody model's property(TransferInfo's AccountId), // validation should not trigger for the parameter which is bound from Uri. // Arrange var actionDescriptor = new ControllerActionDescriptor() { BoundProperties = new List<ParameterDescriptor>(), Parameters = parameters }; var parameterBinder = ModelBindingTestHelper.GetParameterBinder(); var testContext = ModelBindingTestHelper.GetTestContext( request => { request.QueryString = new QueryString("?accountId=10"); request.Body = new MemoryStream(Encoding.UTF8.GetBytes("{\"accountId\": 40,\"amount\": 250.0}")); request.ContentType = "application/json"; }, actionDescriptor: actionDescriptor); var modelState = testContext.ModelState; // Act foreach (var parameter in parameters) { await parameterBinder.BindModelAsync(parameter, testContext); } // Assert Assert.True(modelState.IsValid); } private class Order1 { [Required] public string CustomerName { get; set; } } [Fact] public async Task Validation_RequiredAttribute_OnSimpleTypeProperty_WithData() { // Arrange var parameterBinder = ModelBindingTestHelper.GetParameterBinder(); var parameter = new ParameterDescriptor() { Name = "parameter", ParameterType = typeof(Order1) }; var testContext = ModelBindingTestHelper.GetTestContext(request => { request.QueryString = new QueryString("?parameter.CustomerName=bill"); }); var modelState = testContext.ModelState; // Act var modelBindingResult = await parameterBinder.BindModelAsync(parameter, testContext); // Assert Assert.True(modelBindingResult.IsModelSet); var model = Assert.IsType<Order1>(modelBindingResult.Model); Assert.Equal("bill", model.CustomerName); Assert.Equal(1, modelState.Count); Assert.Equal(0, modelState.ErrorCount); Assert.True(modelState.IsValid); var entry = Assert.Single(modelState, e => e.Key == "parameter.CustomerName").Value; Assert.Equal("bill", entry.AttemptedValue); Assert.Equal("bill", entry.RawValue); Assert.Empty(entry.Errors); } [Fact] public async Task Validation_RequiredAttribute_OnSimpleTypeProperty_NoData() { // Arrange var parameterBinder = ModelBindingTestHelper.GetParameterBinder(); var parameter = new ParameterDescriptor() { Name = "parameter", ParameterType = typeof(Order1) }; var testContext = ModelBindingTestHelper.GetTestContext(request => { request.QueryString = new QueryString("?"); }); var modelState = testContext.ModelState; // Act var modelBindingResult = await parameterBinder.BindModelAsync(parameter, testContext); // Assert Assert.True(modelBindingResult.IsModelSet); var model = Assert.IsType<Order1>(modelBindingResult.Model); Assert.Null(model.CustomerName); Assert.Equal(1, modelState.Count); Assert.Equal(1, modelState.ErrorCount); Assert.False(modelState.IsValid); var entry = Assert.Single(modelState, e => e.Key == "CustomerName").Value; Assert.Null(entry.RawValue); Assert.Null(entry.AttemptedValue); Assert.Equal(ModelValidationState.Invalid, entry.ValidationState); var error = Assert.Single(entry.Errors); AssertRequiredError("CustomerName", error); } private class Order2 { [Required] public Person2 Customer { get; set; } } private class Person2 { public string Name { get; set; } } [Fact] public async Task Validation_RequiredAttribute_OnPOCOProperty_WithData() { // Arrange var parameterBinder = ModelBindingTestHelper.GetParameterBinder(); var parameter = new ParameterDescriptor() { Name = "parameter", ParameterType = typeof(Order2) }; var testContext = ModelBindingTestHelper.GetTestContext(request => { request.QueryString = new QueryString("?parameter.Customer.Name=bill"); }); var modelState = testContext.ModelState; // Act var modelBindingResult = await parameterBinder.BindModelAsync(parameter, testContext); // Assert Assert.True(modelBindingResult.IsModelSet); var model = Assert.IsType<Order2>(modelBindingResult.Model); Assert.NotNull(model.Customer); Assert.Equal("bill", model.Customer.Name); Assert.Equal(1, modelState.Count); Assert.Equal(0, modelState.ErrorCount); Assert.True(modelState.IsValid); var entry = Assert.Single(modelState, e => e.Key == "parameter.Customer.Name").Value; Assert.Equal("bill", entry.AttemptedValue); Assert.Equal("bill", entry.RawValue); Assert.Empty(entry.Errors); } [Fact] public async Task Validation_RequiredAttribute_OnPOCOProperty_NoData() { // Arrange var parameterBinder = ModelBindingTestHelper.GetParameterBinder(); var parameter = new ParameterDescriptor() { Name = "parameter", ParameterType = typeof(Order2) }; var testContext = ModelBindingTestHelper.GetTestContext(request => { request.QueryString = new QueryString("?"); }); var modelState = testContext.ModelState; // Act var modelBindingResult = await parameterBinder.BindModelAsync(parameter, testContext); // Assert Assert.True(modelBindingResult.IsModelSet); var model = Assert.IsType<Order2>(modelBindingResult.Model); Assert.Null(model.Customer); Assert.Equal(1, modelState.Count); Assert.Equal(1, modelState.ErrorCount); Assert.False(modelState.IsValid); var entry = Assert.Single(modelState, e => e.Key == "Customer").Value; Assert.Null(entry.RawValue); Assert.Null(entry.AttemptedValue); Assert.Equal(ModelValidationState.Invalid, entry.ValidationState); var error = Assert.Single(entry.Errors); AssertRequiredError("Customer", error); } private class Order3 { public Person3 Customer { get; set; } } private class Person3 { public int Age { get; set; } [Required] public string Name { get; set; } } [Fact] public async Task Validation_RequiredAttribute_OnNestedSimpleTypeProperty_WithData() { // Arrange var parameterBinder = ModelBindingTestHelper.GetParameterBinder(); var parameter = new ParameterDescriptor() { Name = "parameter", ParameterType = typeof(Order3) }; var testContext = ModelBindingTestHelper.GetTestContext(request => { request.QueryString = new QueryString("?parameter.Customer.Name=bill"); }); var modelState = testContext.ModelState; // Act var modelBindingResult = await parameterBinder.BindModelAsync(parameter, testContext); // Assert Assert.True(modelBindingResult.IsModelSet); var model = Assert.IsType<Order3>(modelBindingResult.Model); Assert.NotNull(model.Customer); Assert.Equal("bill", model.Customer.Name); Assert.Equal(1, modelState.Count); Assert.Equal(0, modelState.ErrorCount); Assert.True(modelState.IsValid); var entry = Assert.Single(modelState, e => e.Key == "parameter.Customer.Name").Value; Assert.Equal("bill", entry.AttemptedValue); Assert.Equal("bill", entry.RawValue); Assert.Empty(entry.Errors); } [Fact] public async Task Validation_RequiredAttribute_OnNestedSimpleTypeProperty_NoDataForRequiredProperty() { // Arrange var parameterBinder = ModelBindingTestHelper.GetParameterBinder(); var parameter = new ParameterDescriptor() { Name = "parameter", ParameterType = typeof(Order3) }; var testContext = ModelBindingTestHelper.GetTestContext(request => { // Force creation of the Customer model. request.QueryString = new QueryString("?parameter.Customer.Age=17"); }); var modelState = testContext.ModelState; // Act var modelBindingResult = await parameterBinder.BindModelAsync(parameter, testContext); // Assert Assert.True(modelBindingResult.IsModelSet); var model = Assert.IsType<Order3>(modelBindingResult.Model); Assert.NotNull(model.Customer); Assert.Equal(17, model.Customer.Age); Assert.Null(model.Customer.Name); Assert.Equal(2, modelState.Count); Assert.Equal(1, modelState.ErrorCount); Assert.False(modelState.IsValid); var entry = Assert.Single(modelState, e => e.Key == "parameter.Customer.Name").Value; Assert.Null(entry.RawValue); Assert.Null(entry.AttemptedValue); Assert.Equal(ModelValidationState.Invalid, entry.ValidationState); var error = Assert.Single(entry.Errors); AssertRequiredError("Name", error); } private class Order4 { [Required] public List<Item4> Items { get; set; } } private class Item4 { public int ItemId { get; set; } } [Fact] public async Task Validation_RequiredAttribute_OnCollectionProperty_WithData() { // Arrange var parameterBinder = ModelBindingTestHelper.GetParameterBinder(); var parameter = new ParameterDescriptor() { Name = "parameter", ParameterType = typeof(Order4) }; var testContext = ModelBindingTestHelper.GetTestContext(request => { request.QueryString = new QueryString("?Items[0].ItemId=17"); }); var modelState = testContext.ModelState; // Act var modelBindingResult = await parameterBinder.BindModelAsync(parameter, testContext); // Assert Assert.True(modelBindingResult.IsModelSet); var model = Assert.IsType<Order4>(modelBindingResult.Model); Assert.NotNull(model.Items); Assert.Equal(17, Assert.Single(model.Items).ItemId); Assert.Equal(1, modelState.Count); Assert.Equal(0, modelState.ErrorCount); Assert.True(modelState.IsValid); var entry = Assert.Single(modelState, e => e.Key == "Items[0].ItemId").Value; Assert.Equal("17", entry.AttemptedValue); Assert.Equal("17", entry.RawValue); Assert.Empty(entry.Errors); } [Fact] public async Task Validation_RequiredAttribute_OnCollectionProperty_NoData() { // Arrange var parameterBinder = ModelBindingTestHelper.GetParameterBinder(); var parameter = new ParameterDescriptor() { Name = "parameter", ParameterType = typeof(Order4) }; var testContext = ModelBindingTestHelper.GetTestContext(request => { // Force creation of the Customer model. request.QueryString = new QueryString("?"); }); var modelState = testContext.ModelState; // Act var modelBindingResult = await parameterBinder.BindModelAsync(parameter, testContext); // Assert Assert.True(modelBindingResult.IsModelSet); var model = Assert.IsType<Order4>(modelBindingResult.Model); Assert.Null(model.Items); Assert.Equal(1, modelState.Count); Assert.Equal(1, modelState.ErrorCount); Assert.False(modelState.IsValid); var entry = Assert.Single(modelState, e => e.Key == "Items").Value; Assert.Null(entry.RawValue); Assert.Null(entry.AttemptedValue); Assert.Equal(ModelValidationState.Invalid, entry.ValidationState); var error = Assert.Single(entry.Errors); AssertRequiredError("Items", error); } private class Order5 { [Required] public int? ProductId { get; set; } public string Name { get; set; } } [Fact] public async Task Validation_RequiredAttribute_OnPOCOPropertyOfBoundElement_WithData() { // Arrange var parameterBinder = ModelBindingTestHelper.GetParameterBinder(); var parameter = new ParameterDescriptor() { Name = "parameter", ParameterType = typeof(List<Order5>) }; var testContext = ModelBindingTestHelper.GetTestContext(request => { request.QueryString = new QueryString("?parameter[0].ProductId=17"); }); var modelState = testContext.ModelState; // Act var modelBindingResult = await parameterBinder.BindModelAsync(parameter, testContext); // Assert Assert.True(modelBindingResult.IsModelSet); var model = Assert.IsType<List<Order5>>(modelBindingResult.Model); Assert.Equal(17, Assert.Single(model).ProductId); Assert.Equal(1, modelState.Count); Assert.Equal(0, modelState.ErrorCount); Assert.True(modelState.IsValid); var entry = Assert.Single(modelState, e => e.Key == "parameter[0].ProductId").Value; Assert.Equal("17", entry.AttemptedValue); Assert.Equal("17", entry.RawValue); Assert.Empty(entry.Errors); } [Fact] public async Task Validation_RequiredAttribute_OnPOCOPropertyOfBoundElement_NoDataForRequiredProperty() { // Arrange var parameterBinder = ModelBindingTestHelper.GetParameterBinder(); var parameter = new ParameterDescriptor() { Name = "parameter", ParameterType = typeof(List<Order5>) }; var testContext = ModelBindingTestHelper.GetTestContext(request => { // Force creation of the Customer model. request.QueryString = new QueryString("?parameter[0].Name=bill"); }); var modelState = testContext.ModelState; // Act var modelBindingResult = await parameterBinder.BindModelAsync(parameter, testContext); // Assert Assert.True(modelBindingResult.IsModelSet); var model = Assert.IsType<List<Order5>>(modelBindingResult.Model); var item = Assert.Single(model); Assert.Null(item.ProductId); Assert.Equal("bill", item.Name); Assert.Equal(2, modelState.Count); Assert.Equal(1, modelState.ErrorCount); Assert.False(modelState.IsValid); var entry = Assert.Single(modelState, e => e.Key == "parameter[0].ProductId").Value; Assert.Null(entry.RawValue); Assert.Null(entry.AttemptedValue); Assert.Equal(ModelValidationState.Invalid, entry.ValidationState); var error = Assert.Single(entry.Errors); AssertRequiredError("ProductId", error); } private class Order6 { [StringLength(5, ErrorMessage = "Too Long.")] public string Name { get; set; } } [Fact] public async Task Validation_StringLengthAttribute_OnPropertyOfPOCO_Valid() { // Arrange var parameterBinder = ModelBindingTestHelper.GetParameterBinder(); var parameter = new ParameterDescriptor() { Name = "parameter", ParameterType = typeof(Order6) }; var testContext = ModelBindingTestHelper.GetTestContext(request => { request.QueryString = new QueryString("?parameter.Name=bill"); }); var modelState = testContext.ModelState; // Act var modelBindingResult = await parameterBinder.BindModelAsync(parameter, testContext); // Assert Assert.True(modelBindingResult.IsModelSet); var model = Assert.IsType<Order6>(modelBindingResult.Model); Assert.Equal("bill", model.Name); Assert.Equal(1, modelState.Count); Assert.Equal(0, modelState.ErrorCount); Assert.True(modelState.IsValid); var entry = Assert.Single(modelState, e => e.Key == "parameter.Name").Value; Assert.Equal("bill", entry.AttemptedValue); Assert.Equal("bill", entry.RawValue); Assert.Empty(entry.Errors); } [Fact] public async Task Validation_StringLengthAttribute_OnPropertyOfPOCO_Invalid() { // Arrange var parameterBinder = ModelBindingTestHelper.GetParameterBinder(); var parameter = new ParameterDescriptor() { Name = "parameter", ParameterType = typeof(Order6) }; var testContext = ModelBindingTestHelper.GetTestContext(request => { request.QueryString = new QueryString("?parameter.Name=billybob"); }); var modelState = testContext.ModelState; // Act var modelBindingResult = await parameterBinder.BindModelAsync(parameter, testContext); // Assert Assert.True(modelBindingResult.IsModelSet); var model = Assert.IsType<Order6>(modelBindingResult.Model); Assert.Equal("billybob", model.Name); Assert.Equal(1, modelState.Count); Assert.Equal(1, modelState.ErrorCount); Assert.False(modelState.IsValid); var entry = Assert.Single(modelState, e => e.Key == "parameter.Name").Value; Assert.Equal("billybob", entry.AttemptedValue); Assert.Equal("billybob", entry.RawValue); var error = Assert.Single(entry.Errors); Assert.Equal("Too Long.", error.ErrorMessage); Assert.Null(error.Exception); } private class Order7 { public Person7 Customer { get; set; } } private class Person7 { [StringLength(5, ErrorMessage = "Too Long.")] public string Name { get; set; } } [Fact] public async Task Validation_StringLengthAttribute_OnPropertyOfNestedPOCO_Valid() { // Arrange var parameterBinder = ModelBindingTestHelper.GetParameterBinder(); var parameter = new ParameterDescriptor() { Name = "parameter", ParameterType = typeof(Order7) }; var testContext = ModelBindingTestHelper.GetTestContext(request => { request.QueryString = new QueryString("?parameter.Customer.Name=bill"); }); var modelState = testContext.ModelState; // Act var modelBindingResult = await parameterBinder.BindModelAsync(parameter, testContext); // Assert Assert.True(modelBindingResult.IsModelSet); var model = Assert.IsType<Order7>(modelBindingResult.Model); Assert.Equal("bill", model.Customer.Name); Assert.Equal(1, modelState.Count); Assert.Equal(0, modelState.ErrorCount); Assert.True(modelState.IsValid); var entry = Assert.Single(modelState, e => e.Key == "parameter.Customer.Name").Value; Assert.Equal("bill", entry.AttemptedValue); Assert.Equal("bill", entry.RawValue); Assert.Empty(entry.Errors); } [Fact] public async Task Validation_StringLengthAttribute_OnPropertyOfNestedPOCO_Invalid() { // Arrange var parameterBinder = ModelBindingTestHelper.GetParameterBinder(); var parameter = new ParameterDescriptor() { Name = "parameter", ParameterType = typeof(Order7) }; var testContext = ModelBindingTestHelper.GetTestContext(request => { request.QueryString = new QueryString("?parameter.Customer.Name=billybob"); }); var modelState = testContext.ModelState; // Act var modelBindingResult = await parameterBinder.BindModelAsync(parameter, testContext); // Assert Assert.True(modelBindingResult.IsModelSet); var model = Assert.IsType<Order7>(modelBindingResult.Model); Assert.Equal("billybob", model.Customer.Name); Assert.Equal(1, modelState.Count); Assert.Equal(1, modelState.ErrorCount); Assert.False(modelState.IsValid); var entry = Assert.Single(modelState, e => e.Key == "parameter.Customer.Name").Value; Assert.Equal("billybob", entry.AttemptedValue); Assert.Equal("billybob", entry.RawValue); var error = Assert.Single(entry.Errors); Assert.Equal("Too Long.", error.ErrorMessage); Assert.Null(error.Exception); } [Fact] public async Task Validation_StringLengthAttribute_OnPropertyOfNestedPOCO_NoData() { // Arrange var parameterBinder = ModelBindingTestHelper.GetParameterBinder(); var parameter = new ParameterDescriptor() { Name = "parameter", ParameterType = typeof(Order7) }; var testContext = ModelBindingTestHelper.GetTestContext(request => { request.QueryString = new QueryString("?"); }); var modelState = testContext.ModelState; // Act var modelBindingResult = await parameterBinder.BindModelAsync(parameter, testContext); // Assert Assert.True(modelBindingResult.IsModelSet); var model = Assert.IsType<Order7>(modelBindingResult.Model); Assert.Null(model.Customer); Assert.Equal(0, modelState.Count); Assert.Equal(0, modelState.ErrorCount); Assert.True(modelState.IsValid); } private class Order8 { [ValidatePerson8] public Person8 Customer { get; set; } } private class Person8 { public string Name { get; set; } } private class ValidatePerson8Attribute : ValidationAttribute { protected override ValidationResult IsValid(object value, ValidationContext validationContext) { if (((Person8)value).Name == "bill") { return null; } else { return new ValidationResult("Invalid Person."); } } } [Fact] public async Task Validation_CustomAttribute_OnPOCOProperty_Valid() { // Arrange var parameterBinder = ModelBindingTestHelper.GetParameterBinder(); var parameter = new ParameterDescriptor() { Name = "parameter", ParameterType = typeof(Order8) }; var testContext = ModelBindingTestHelper.GetTestContext(request => { request.QueryString = new QueryString("?parameter.Customer.Name=bill"); }); var modelState = testContext.ModelState; // Act var modelBindingResult = await parameterBinder.BindModelAsync(parameter, testContext); // Assert Assert.True(modelBindingResult.IsModelSet); var model = Assert.IsType<Order8>(modelBindingResult.Model); Assert.Equal("bill", model.Customer.Name); Assert.Equal(1, modelState.Count); Assert.Equal(0, modelState.ErrorCount); Assert.True(modelState.IsValid); var entry = Assert.Single(modelState, e => e.Key == "parameter.Customer.Name").Value; Assert.Equal("bill", entry.AttemptedValue); Assert.Equal("bill", entry.RawValue); Assert.Empty(entry.Errors); } [Fact] public async Task Validation_CustomAttribute_OnPOCOProperty_Invalid() { // Arrange var parameterBinder = ModelBindingTestHelper.GetParameterBinder(); var parameter = new ParameterDescriptor() { Name = "parameter", ParameterType = typeof(Order8) }; var testContext = ModelBindingTestHelper.GetTestContext(request => { request.QueryString = new QueryString("?parameter.Customer.Name=billybob"); }); var modelState = testContext.ModelState; // Act var modelBindingResult = await parameterBinder.BindModelAsync(parameter, testContext); // Assert Assert.True(modelBindingResult.IsModelSet); var model = Assert.IsType<Order8>(modelBindingResult.Model); Assert.Equal("billybob", model.Customer.Name); Assert.Equal(2, modelState.Count); Assert.Equal(1, modelState.ErrorCount); Assert.False(modelState.IsValid); var entry = Assert.Single(modelState, e => e.Key == "parameter.Customer.Name").Value; Assert.Equal("billybob", entry.AttemptedValue); Assert.Equal("billybob", entry.RawValue); entry = Assert.Single(modelState, e => e.Key == "parameter.Customer").Value; Assert.Null(entry.RawValue); Assert.Null(entry.AttemptedValue); Assert.Equal(ModelValidationState.Invalid, entry.ValidationState); var error = Assert.Single(entry.Errors); Assert.Equal("Invalid Person.", error.ErrorMessage); Assert.Null(error.Exception); } private class Order9 { [ValidateProducts9] public List<Product9> Products { get; set; } } private class Product9 { public string Name { get; set; } } private class ValidateProducts9Attribute : ValidationAttribute { protected override ValidationResult IsValid(object value, ValidationContext validationContext) { if (((List<Product9>)value)[0].Name == "bill") { return null; } else { return new ValidationResult("Invalid Product."); } } } [Fact] public async Task Validation_CustomAttribute_OnCollectionElement_Valid() { // Arrange var parameterBinder = ModelBindingTestHelper.GetParameterBinder(); var parameter = new ParameterDescriptor() { Name = "parameter", ParameterType = typeof(Order9) }; var testContext = ModelBindingTestHelper.GetTestContext(request => { request.QueryString = new QueryString("?parameter.Products[0].Name=bill"); }); var modelState = testContext.ModelState; // Act var modelBindingResult = await parameterBinder.BindModelAsync(parameter, testContext); // Assert Assert.True(modelBindingResult.IsModelSet); var model = Assert.IsType<Order9>(modelBindingResult.Model); Assert.Equal("bill", Assert.Single(model.Products).Name); Assert.Equal(1, modelState.Count); Assert.Equal(0, modelState.ErrorCount); Assert.True(modelState.IsValid); var entry = Assert.Single(modelState, e => e.Key == "parameter.Products[0].Name").Value; Assert.Equal("bill", entry.AttemptedValue); Assert.Equal("bill", entry.RawValue); Assert.Empty(entry.Errors); } [Fact] public async Task Validation_CustomAttribute_OnCollectionElement_Invalid() { // Arrange var parameterBinder = ModelBindingTestHelper.GetParameterBinder(); var parameter = new ParameterDescriptor() { Name = "parameter", ParameterType = typeof(Order9) }; var testContext = ModelBindingTestHelper.GetTestContext(request => { request.QueryString = new QueryString("?parameter.Products[0].Name=billybob"); }); var modelState = testContext.ModelState; // Act var modelBindingResult = await parameterBinder.BindModelAsync(parameter, testContext); // Assert Assert.True(modelBindingResult.IsModelSet); var model = Assert.IsType<Order9>(modelBindingResult.Model); Assert.Equal("billybob", Assert.Single(model.Products).Name); Assert.Equal(2, modelState.Count); Assert.Equal(1, modelState.ErrorCount); Assert.False(modelState.IsValid); var entry = Assert.Single(modelState, e => e.Key == "parameter.Products[0].Name").Value; Assert.Equal("billybob", entry.AttemptedValue); Assert.Equal("billybob", entry.RawValue); entry = Assert.Single(modelState, e => e.Key == "parameter.Products").Value; Assert.Null(entry.RawValue); Assert.Null(entry.AttemptedValue); Assert.Equal(ModelValidationState.Invalid, entry.ValidationState); var error = Assert.Single(entry.Errors); Assert.Equal("Invalid Product.", error.ErrorMessage); Assert.Null(error.Exception); } private class Order10 { [StringLength(5, ErrorMessage = "Too Long.")] public string Name { get; set; } } [Fact] public async Task Validation_StringLengthAttribute_OnProperyOfCollectionElement_Valid() { // Arrange var parameterBinder = ModelBindingTestHelper.GetParameterBinder(); var parameter = new ParameterDescriptor() { Name = "parameter", ParameterType = typeof(List<Order10>) }; var testContext = ModelBindingTestHelper.GetTestContext(request => { request.QueryString = new QueryString("?parameter[0].Name=bill"); }); var modelState = testContext.ModelState; // Act var modelBindingResult = await parameterBinder.BindModelAsync(parameter, testContext); // Assert Assert.True(modelBindingResult.IsModelSet); var model = Assert.IsType<List<Order10>>(modelBindingResult.Model); Assert.Equal("bill", Assert.Single(model).Name); Assert.Equal(1, modelState.Count); Assert.Equal(0, modelState.ErrorCount); Assert.True(modelState.IsValid); var entry = Assert.Single(modelState, e => e.Key == "parameter[0].Name").Value; Assert.Equal("bill", entry.AttemptedValue); Assert.Equal("bill", entry.RawValue); Assert.Empty(entry.Errors); } [Fact] public async Task Validation_StringLengthAttribute_OnProperyOfCollectionElement_Invalid() { // Arrange var parameterBinder = ModelBindingTestHelper.GetParameterBinder(); var parameter = new ParameterDescriptor() { Name = "parameter", ParameterType = typeof(List<Order10>) }; var testContext = ModelBindingTestHelper.GetTestContext(request => { request.QueryString = new QueryString("?parameter[0].Name=billybob"); }); var modelState = testContext.ModelState; // Act var modelBindingResult = await parameterBinder.BindModelAsync(parameter, testContext); // Assert Assert.True(modelBindingResult.IsModelSet); var model = Assert.IsType<List<Order10>>(modelBindingResult.Model); Assert.Equal("billybob", Assert.Single(model).Name); Assert.Equal(1, modelState.Count); Assert.Equal(1, modelState.ErrorCount); Assert.False(modelState.IsValid); var entry = Assert.Single(modelState, e => e.Key == "parameter[0].Name").Value; Assert.Equal("billybob", entry.AttemptedValue); Assert.Equal("billybob", entry.RawValue); var error = Assert.Single(entry.Errors); Assert.Equal("Too Long.", error.ErrorMessage); Assert.Null(error.Exception); } [Fact] public async Task Validation_StringLengthAttribute_OnProperyOfCollectionElement_NoData() { // Arrange var parameterBinder = ModelBindingTestHelper.GetParameterBinder(); var parameter = new ParameterDescriptor() { Name = "parameter", ParameterType = typeof(List<Order10>) }; var testContext = ModelBindingTestHelper.GetTestContext(request => { request.QueryString = new QueryString("?"); }); var modelState = testContext.ModelState; // Act var modelBindingResult = await parameterBinder.BindModelAsync(parameter, testContext); // Assert Assert.True(modelBindingResult.IsModelSet); var model = Assert.IsType<List<Order10>>(modelBindingResult.Model); Assert.Empty(model); Assert.Equal(0, modelState.Count); Assert.Equal(0, modelState.ErrorCount); Assert.True(modelState.IsValid); } private class User { public int Id { get; set; } public uint Zip { get; set; } } [Fact] public async Task Validation_FormatException_ShowsInvalidValueMessage_OnSimpleTypeProperty() { // Arrange var parameterBinder = ModelBindingTestHelper.GetParameterBinder(); var parameter = new ParameterDescriptor() { Name = "parameter", ParameterType = typeof(User) }; var testContext = ModelBindingTestHelper.GetTestContext(request => { request.QueryString = new QueryString("?Id=bill"); }); var modelState = testContext.ModelState; // Act var modelBindingResult = await parameterBinder.BindModelAsync(parameter, testContext); // Assert Assert.True(modelBindingResult.IsModelSet); var model = Assert.IsType<User>(modelBindingResult.Model); Assert.Equal(0, model.Id); Assert.Equal(1, modelState.ErrorCount); Assert.False(modelState.IsValid); var state = Assert.Single(modelState); Assert.Equal("Id", state.Key); var entry = state.Value; Assert.Equal("bill", entry.AttemptedValue); Assert.Equal("bill", entry.RawValue); Assert.Single(entry.Errors); var error = entry.Errors[0]; Assert.Equal("The value 'bill' is not valid for Id.", error.ErrorMessage); } [Fact] public async Task Validation_OverflowException_ShowsInvalidValueMessage_OnSimpleTypeProperty() { // Arrange var parameterBinder = ModelBindingTestHelper.GetParameterBinder(); var parameter = new ParameterDescriptor() { Name = "parameter", ParameterType = typeof(User) }; var testContext = ModelBindingTestHelper.GetTestContext(request => { request.QueryString = new QueryString("?Zip=-123"); }); var modelState = testContext.ModelState; // Act var modelBindingResult = await parameterBinder.BindModelAsync(parameter, testContext); // Assert Assert.True(modelBindingResult.IsModelSet); var model = Assert.IsType<User>(modelBindingResult.Model); Assert.Equal<uint>(0, model.Zip); Assert.Equal(1, modelState.ErrorCount); Assert.False(modelState.IsValid); var state = Assert.Single(modelState); Assert.Equal("Zip", state.Key); var entry = state.Value; Assert.Equal("-123", entry.AttemptedValue); Assert.Equal("-123", entry.RawValue); Assert.Single(entry.Errors); var error = entry.Errors[0]; Assert.Equal("The value '-123' is not valid for Zip.", error.ErrorMessage); } private class NeverValid : IValidatableObject { public string NeverValidProperty { get; set; } public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) { return new[] { new ValidationResult("This is not valid.") }; } } private class NeverValidAttribute : ValidationAttribute { protected override ValidationResult IsValid(object value, ValidationContext validationContext) { // By default, ValidationVisitor visits _all_ properties within a non-null complex object. // But, like most reasonable ValidationAttributes, NeverValidAttribute ignores null property values. if (value == null) { return ValidationResult.Success; } return new ValidationResult("Properties with this are not valid."); } } private class ValidateSomeProperties { public NeverValid NeverValid { get; set; } [NeverValid] public string NeverValidBecauseAttribute { get; set; } [ValidateNever] [NeverValid] public string ValidateNever { get; set; } [ValidateNever] public int ValidateNeverLength => ValidateNever.Length; } [ValidateNever] private class ValidateNoProperties : ValidateSomeProperties { } [Fact] public async Task IValidatableObject_IsValidated() { // Arrange var parameter = new ParameterDescriptor { Name = "parameter", ParameterType = typeof(ValidateSomeProperties), }; var testContext = ModelBindingTestHelper.GetTestContext( request => request.QueryString = new QueryString($"?{nameof(ValidateSomeProperties.NeverValid)}.{nameof(NeverValid.NeverValidProperty)}=1")); var parameterBinder = ModelBindingTestHelper.GetParameterBinder(); var modelState = testContext.ModelState; // Act var result = await parameterBinder.BindModelAsync(parameter, testContext); // Assert Assert.True(result.IsModelSet); var model = Assert.IsType<ValidateSomeProperties>(result.Model); Assert.Equal("1", model.NeverValid.NeverValidProperty); Assert.False(modelState.IsValid); Assert.Equal(1, modelState.ErrorCount); Assert.Collection( modelState, state => { Assert.Equal(nameof(ValidateSomeProperties.NeverValid), state.Key); Assert.Equal(ModelValidationState.Invalid, state.Value.ValidationState); var error = Assert.Single(state.Value.Errors); Assert.Equal("This is not valid.", error.ErrorMessage); Assert.Null(error.Exception); }, state => { Assert.Equal( $"{nameof(ValidateSomeProperties.NeverValid)}.{nameof(NeverValid.NeverValidProperty)}", state.Key); Assert.Equal(ModelValidationState.Valid, state.Value.ValidationState); }); } [Fact] public async Task CustomValidationAttribute_IsValidated() { // Arrange var parameter = new ParameterDescriptor { Name = "parameter", ParameterType = typeof(ValidateSomeProperties), }; var testContext = ModelBindingTestHelper.GetTestContext( request => request.QueryString = new QueryString($"?{nameof(ValidateSomeProperties.NeverValidBecauseAttribute)}=1")); var parameterBinder = ModelBindingTestHelper.GetParameterBinder(); var modelState = testContext.ModelState; // Act var result = await parameterBinder.BindModelAsync(parameter, testContext); // Assert Assert.True(result.IsModelSet); var model = Assert.IsType<ValidateSomeProperties>(result.Model); Assert.Equal("1", model.NeverValidBecauseAttribute); Assert.False(modelState.IsValid); Assert.Equal(1, modelState.ErrorCount); var kvp = Assert.Single(modelState); Assert.Equal(nameof(ValidateSomeProperties.NeverValidBecauseAttribute), kvp.Key); var state = kvp.Value; Assert.NotNull(state); Assert.Equal(ModelValidationState.Invalid, state.ValidationState); var error = Assert.Single(state.Errors); Assert.Equal("Properties with this are not valid.", error.ErrorMessage); Assert.Null(error.Exception); } [Fact] public async Task ValidateNeverProperty_IsSkipped() { // Arrange var parameter = new ParameterDescriptor { Name = "parameter", ParameterType = typeof(ValidateSomeProperties), }; var testContext = ModelBindingTestHelper.GetTestContext( request => request.QueryString = new QueryString($"?{nameof(ValidateSomeProperties.ValidateNever)}=1")); var parameterBinder = ModelBindingTestHelper.GetParameterBinder(); var modelState = testContext.ModelState; // Act var result = await parameterBinder.BindModelAsync(parameter, testContext); // Assert Assert.True(result.IsModelSet); var model = Assert.IsType<ValidateSomeProperties>(result.Model); Assert.Equal("1", model.ValidateNever); Assert.True(modelState.IsValid); var kvp = Assert.Single(modelState); Assert.Equal(nameof(ValidateSomeProperties.ValidateNever), kvp.Key); var state = kvp.Value; Assert.NotNull(state); Assert.Equal(ModelValidationState.Skipped, state.ValidationState); } [Fact] public async Task ValidateNeverProperty_IsSkippedWithoutAccessingModel() { // Arrange var parameter = new ParameterDescriptor { Name = "parameter", ParameterType = typeof(ValidateSomeProperties), }; var testContext = ModelBindingTestHelper.GetTestContext(); var parameterBinder = ModelBindingTestHelper.GetParameterBinder(); var modelState = testContext.ModelState; // Act var result = await parameterBinder.BindModelAsync(parameter, testContext); // Assert Assert.True(result.IsModelSet); var model = Assert.IsType<ValidateSomeProperties>(result.Model); // Note this Exception is not thrown earlier. Assert.Throws<NullReferenceException>(() => model.ValidateNeverLength); Assert.True(modelState.IsValid); Assert.Empty(modelState); } [Theory] [InlineData(nameof(ValidateSomeProperties.NeverValid) + "." + nameof(NeverValid.NeverValidProperty))] [InlineData(nameof(ValidateSomeProperties.NeverValidBecauseAttribute))] [InlineData(nameof(ValidateSomeProperties.ValidateNever))] public async Task PropertyWithinValidateNeverType_IsSkipped(string propertyName) { // Arrange var parameter = new ParameterDescriptor { Name = "parameter", ParameterType = typeof(ValidateNoProperties), }; var testContext = ModelBindingTestHelper.GetTestContext( request => request.QueryString = new QueryString($"?{propertyName}=1")); var parameterBinder = ModelBindingTestHelper.GetParameterBinder(); var modelState = testContext.ModelState; // Act var result = await parameterBinder.BindModelAsync(parameter, testContext); // Assert Assert.True(result.IsModelSet); Assert.IsType<ValidateNoProperties>(result.Model); Assert.True(modelState.IsValid); var kvp = Assert.Single(modelState); Assert.Equal(propertyName, kvp.Key); var state = kvp.Value; Assert.NotNull(state); Assert.Equal(ModelValidationState.Skipped, state.ValidationState); } private class ValidateSometimesAttribute : Attribute, IPropertyValidationFilter { private readonly string _otherProperty; public ValidateSometimesAttribute(string otherProperty) { // Would null-check otherProperty in real life. _otherProperty = otherProperty; } public bool ShouldValidateEntry(ValidationEntry entry, ValidationEntry parentEntry) { if (entry.Metadata.MetadataKind == ModelMetadataKind.Property && parentEntry.Metadata != null) { // In real life, would throw an InvalidOperationException if otherProperty were null i.e. the // property was not known. Could also assert container is non-null (see ValidationVisitor). var container = parentEntry.Model; var otherProperty = parentEntry.Metadata.Properties[_otherProperty]; if (otherProperty.PropertyGetter(container) == null) { return false; } } return true; } } private class ValidateSomePropertiesSometimes { public string Control { get; set; } [ValidateSometimes(nameof(Control))] public int ControlLength => Control.Length; } [Fact] public async Task PropertyToSometimesSkip_IsSkipped_IfControlIsNull() { // Arrange var parameter = new ParameterDescriptor { Name = "parameter", ParameterType = typeof(ValidateSomePropertiesSometimes), }; var testContext = ModelBindingTestHelper.GetTestContext(); var parameterBinder = ModelBindingTestHelper.GetParameterBinder(); var modelState = testContext.ModelState; // Add an entry for the ControlLength property so that we can observe Skipped versus Valid states. modelState.SetModelValue( nameof(ValidateSomePropertiesSometimes.ControlLength), rawValue: null, attemptedValue: null); // Act var result = await parameterBinder.BindModelAsync(parameter, testContext); // Assert Assert.True(result.IsModelSet); var model = Assert.IsType<ValidateSomePropertiesSometimes>(result.Model); Assert.Null(model.Control); // Note this Exception is not thrown earlier. Assert.Throws<NullReferenceException>(() => model.ControlLength); Assert.True(modelState.IsValid); var kvp = Assert.Single(modelState); Assert.Equal(nameof(ValidateSomePropertiesSometimes.ControlLength), kvp.Key); Assert.Equal(ModelValidationState.Skipped, kvp.Value.ValidationState); } [Fact] public async Task PropertyToSometimesSkip_IsValidated_IfControlIsNotNull() { // Arrange var parameter = new ParameterDescriptor { Name = "parameter", ParameterType = typeof(ValidateSomePropertiesSometimes), }; var testContext = ModelBindingTestHelper.GetTestContext( request => request.QueryString = new QueryString( $"?{nameof(ValidateSomePropertiesSometimes.Control)}=1")); var parameterBinder = ModelBindingTestHelper.GetParameterBinder(); var modelState = testContext.ModelState; // Add an entry for the ControlLength property so that we can observe Skipped versus Valid states. modelState.SetModelValue( nameof(ValidateSomePropertiesSometimes.ControlLength), rawValue: null, attemptedValue: null); // Act var result = await parameterBinder.BindModelAsync(parameter, testContext); // Assert Assert.True(result.IsModelSet); var model = Assert.IsType<ValidateSomePropertiesSometimes>(result.Model); Assert.Equal("1", model.Control); Assert.Equal(1, model.ControlLength); Assert.True(modelState.IsValid); Assert.Collection( modelState, state => Assert.Equal(nameof(ValidateSomePropertiesSometimes.Control), state.Key), state => { Assert.Equal(nameof(ValidateSomePropertiesSometimes.ControlLength), state.Key); Assert.Equal(ModelValidationState.Valid, state.Value.ValidationState); }); } private class Order11 { public IEnumerable<Address> ShippingAddresses { get; set; } public Address HomeAddress { get; set; } [FromBody] public Address OfficeAddress { get; set; } } private class Address { public int Street { get; set; } public string State { get; set; } [Range(10000, 99999)] public int Zip { get; set; } public Country Country { get; set; } } private class Country { public string Name { get; set; } } [Fact] public async Task TypeBasedExclusion_ForBodyAndNonBodyBoundModels() { // Arrange var parameter = new ParameterDescriptor { Name = "parameter", ParameterType = typeof(Order11) }; MvcOptions testOptions = null; var input = "{\"Zip\":\"47\"}"; var testContext = ModelBindingTestHelper.GetTestContext( request => { request.QueryString = new QueryString("?HomeAddress.Country.Name=US&ShippingAddresses[0].Zip=45&HomeAddress.Zip=46"); request.Body = new MemoryStream(Encoding.UTF8.GetBytes(input)); request.ContentType = "application/json"; }, options => { options.ModelMetadataDetailsProviders.Add(new SuppressChildValidationMetadataProvider(typeof(Address))); testOptions = options; }); var parameterBinder = ModelBindingTestHelper.GetParameterBinder(testOptions); var modelState = testContext.ModelState; // Act var modelBindingResult = await parameterBinder.BindModelAsync(parameter, testContext); Assert.Equal(3, modelState.Count); Assert.Equal(0, modelState.ErrorCount); Assert.True(modelState.IsValid); var entry = Assert.Single(modelState, e => e.Key == "HomeAddress.Country.Name").Value; Assert.Equal("US", entry.AttemptedValue); Assert.Equal("US", entry.RawValue); Assert.Equal(ModelValidationState.Skipped, entry.ValidationState); entry = Assert.Single(modelState, e => e.Key == "ShippingAddresses[0].Zip").Value; Assert.Equal("45", entry.AttemptedValue); Assert.Equal("45", entry.RawValue); Assert.Equal(ModelValidationState.Skipped, entry.ValidationState); entry = Assert.Single(modelState, e => e.Key == "HomeAddress.Zip").Value; Assert.Equal("46", entry.AttemptedValue); Assert.Equal("46", entry.RawValue); Assert.Equal(ModelValidationState.Skipped, entry.ValidationState); } [Fact] public async Task FromBody_JToken_ExcludedFromValidation() { // Arrange var parameterBinder = ModelBindingTestHelper.GetParameterBinder(new TestMvcOptions().Value); var parameter = new ParameterDescriptor { Name = "Parameter1", BindingInfo = new BindingInfo { BinderModelName = "CustomParameter", BindingSource = BindingSource.Body }, ParameterType = typeof(JToken) }; var testContext = ModelBindingTestHelper.GetTestContext( request => { request.Body = new MemoryStream(Encoding.UTF8.GetBytes("{ message: \"Hello\" }")); request.ContentType = "application/json"; }); var httpContext = testContext.HttpContext; var modelState = testContext.ModelState; // We need to add another model state entry which should get marked as skipped so // we can prove that the JObject was skipped. modelState.SetModelValue("CustomParameter.message", "Hello", "Hello"); // Act var modelBindingResult = await parameterBinder.BindModelAsync(parameter, testContext); // Assert Assert.True(modelBindingResult.IsModelSet); Assert.NotNull(modelBindingResult.Model); var message = Assert.IsType<JObject>(modelBindingResult.Model).GetValue("message").Value<string>(); Assert.Equal("Hello", message); Assert.True(modelState.IsValid); Assert.Equal(1, modelState.Count); var entry = Assert.Single(modelState, kvp => kvp.Key == "CustomParameter.message"); Assert.Equal(ModelValidationState.Skipped, entry.Value.ValidationState); } // Regression test for https://github.com/aspnet/Mvc/issues/3743 // // A cancellation token that's bound with the empty prefix will end up suppressing // the empty prefix. Since the empty prefix is a prefix of everything, this will // basically result in clearing out all model errors, which is BAD. // // The fix is to treat non-user-input as have a key of null, which means that the MSD // isn't even examined when it comes to supressing validation. [Fact] public async Task CancellationToken_WithEmptyPrefix_DoesNotSuppressUnrelatedErrors() { // Arrange var parameterBinder = ModelBindingTestHelper.GetParameterBinder(new TestMvcOptions().Value); var parameter = new ParameterDescriptor { Name = "cancellationToken", ParameterType = typeof(CancellationToken) }; var testContext = ModelBindingTestHelper.GetTestContext(); var httpContext = testContext.HttpContext; var modelState = testContext.ModelState; // We need to add another model state entry - we want this to be ignored. modelState.SetModelValue("message", "Hello", "Hello"); // Act var modelBindingResult = await parameterBinder.BindModelAsync(parameter, testContext); // Assert Assert.True(modelBindingResult.IsModelSet); Assert.NotNull(modelBindingResult.Model); Assert.IsType<CancellationToken>(modelBindingResult.Model); Assert.False(modelState.IsValid); Assert.Equal(1, modelState.Count); var entry = Assert.Single(modelState, kvp => kvp.Key == "message"); Assert.Equal(ModelValidationState.Unvalidated, entry.Value.ValidationState); } // Similar to CancellationToken_WithEmptyPrefix_DoesNotSuppressUnrelatedErrors - binding the body // with the empty prefix should not cause unrelated modelstate entries to get suppressed. [Fact] public async Task FromBody_WithEmptyPrefix_DoesNotSuppressUnrelatedErrors_Valid() { // Arrange var parameterBinder = ModelBindingTestHelper.GetParameterBinder(new TestMvcOptions().Value); var parameter = new ParameterDescriptor { Name = "Parameter1", BindingInfo = new BindingInfo { BindingSource = BindingSource.Body }, ParameterType = typeof(Greeting) }; var testContext = ModelBindingTestHelper.GetTestContext( request => { request.Body = new MemoryStream(Encoding.UTF8.GetBytes("{ message: \"Hello\" }")); request.ContentType = "application/json"; }); var httpContext = testContext.HttpContext; var modelState = testContext.ModelState; // We need to add another model state entry which should not get changed. modelState.SetModelValue("other.key", "1", "1"); // Act var modelBindingResult = await parameterBinder.BindModelAsync(parameter, testContext); // Assert Assert.True(modelBindingResult.IsModelSet); Assert.NotNull(modelBindingResult.Model); var message = Assert.IsType<Greeting>(modelBindingResult.Model).Message; Assert.Equal("Hello", message); Assert.False(modelState.IsValid); Assert.Equal(1, modelState.Count); var entry = Assert.Single(modelState, kvp => kvp.Key == "other.key"); Assert.Equal(ModelValidationState.Unvalidated, entry.Value.ValidationState); } // Similar to CancellationToken_WithEmptyPrefix_DoesNotSuppressUnrelatedErrors - binding the body // with the empty prefix should not cause unrelated modelstate entries to get suppressed. [Fact] public async Task FromBody_WithEmptyPrefix_DoesNotSuppressUnrelatedErrors_Invalid() { // Arrange var parameterBinder = ModelBindingTestHelper.GetParameterBinder(new TestMvcOptions().Value); var parameter = new ParameterDescriptor { Name = "Parameter1", BindingInfo = new BindingInfo { BindingSource = BindingSource.Body }, ParameterType = typeof(Greeting) }; var testContext = ModelBindingTestHelper.GetTestContext( request => { // This string is too long and will have a validation error. request.Body = new MemoryStream(Encoding.UTF8.GetBytes("{ message: \"Hello There\" }")); request.ContentType = "application/json"; }); var httpContext = testContext.HttpContext; var modelState = testContext.ModelState; // We need to add another model state entry which should not get changed. modelState.SetModelValue("other.key", "1", "1"); // Act var modelBindingResult = await parameterBinder.BindModelAsync(parameter, testContext); // Assert Assert.True(modelBindingResult.IsModelSet); Assert.NotNull(modelBindingResult.Model); var message = Assert.IsType<Greeting>(modelBindingResult.Model).Message; Assert.Equal("Hello There", message); Assert.False(modelState.IsValid); Assert.Equal(2, modelState.Count); var entry = Assert.Single(modelState, kvp => kvp.Key == "Message"); Assert.Equal(ModelValidationState.Invalid, entry.Value.ValidationState); entry = Assert.Single(modelState, kvp => kvp.Key == "other.key"); Assert.Equal(ModelValidationState.Unvalidated, entry.Value.ValidationState); } private class Greeting { [StringLength(5)] public string Message { get; set; } } private static void AssertRequiredError(string key, ModelError error) { Assert.Equal(ValidationAttributeUtil.GetRequiredErrorMessage(key), error.ErrorMessage); Assert.Null(error.Exception); } } }
37.204459
130
0.577091
[ "Apache-2.0" ]
erravimishracse/Mvc
test/Microsoft.AspNetCore.Mvc.IntegrationTests/ValidationIntegrationTests.cs
68,419
C#
using CTRE.Phoenix; using Microsoft.SPOT; namespace yearone2018 { public class Deliver //delivering the ball into the connect four box { private const float minPWMSignalRange = 553f; // private const float maxPWMSignalRange = 2425f; private const float maxPWMSignalRange = 2450f; private const float pwmOutput = 4200f; private static Deliver instance = null; // a singlex which will make it so we don't need to define deliver twice if we have it in auton and teleop instead have it once. public static Deliver GetInstance() { if (instance == null) { instance = new Deliver(); } return instance; } private const float DELIVER = -0.2f; // This will change depending on how FAB mounts the servo private const float HOLD = -1.0f; // This will change depending on how FAB mounts the servo private CANifier deliverServo; //What the servo is called public enum DELIVERSTATE //State { //The enum HoldBalls, Deliver } private DELIVERSTATE m_currentState; private Deliver() //constructor same name as class name { //Defining the servo Robotmap map = Robotmap.GetInstance(); deliverServo = Robotmap.GETCANController(); m_currentState = DELIVERSTATE.HoldBalls; } public DELIVERSTATE GetCurrentState() //current state { return m_currentState; } public void setState(DELIVERSTATE state) //allowing you to change the state/set state { m_currentState = state; } public void Run() { switch(m_currentState) //This is telling us if we are going to Holdball, Deliver or default { case DELIVERSTATE.HoldBalls: holdBalls(); break; case DELIVERSTATE.Deliver: deliver(); break; default: Debug.Print("deliver.setState called with invalid state"); break; } } private void holdBalls() { Robotmap map = Robotmap.GetInstance(); float pulses = LinearInterpolation.Calculate(HOLD, -1.0f, minPWMSignalRange, 1.0f, maxPWMSignalRange); float percentOut = pulses / pwmOutput; deliverServo.EnablePWMOutput((int)map.GetDeliverMec_ID(), true); deliverServo.SetPWMOutput(map.GetDeliverMec_ID(), percentOut); //move servo } private void deliver() { Robotmap map = Robotmap.GetInstance(); float pulses = LinearInterpolation.Calculate(DELIVER, -1.0f, minPWMSignalRange, 1.0f, maxPWMSignalRange); float percentOut = pulses / pwmOutput; deliverServo.EnablePWMOutput((int)map.GetDeliverMec_ID(), true); deliverServo.SetPWMOutput(map.GetDeliverMec_ID(), percentOut); //move servo } } }
41.126582
177
0.561711
[ "MIT" ]
Team302/2018Year1Robot
Deliver.cs
3,251
C#
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Net.Http; using System.Net.Http.Headers; using System.Web.Http; using System.Web.Http.Controllers; using System.Web.Http.Description; using Planru.DistributedServices.WebAPI.Areas.HelpPage.ModelDescriptions; using Planru.DistributedServices.WebAPI.Areas.HelpPage.Models; namespace Planru.DistributedServices.WebAPI.Areas.HelpPage { public static class HelpPageConfigurationExtensions { private const string ApiModelPrefix = "MS_HelpPageApiModel_"; /// <summary> /// Sets the documentation provider for help page. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="documentationProvider">The documentation provider.</param> public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider) { config.Services.Replace(typeof(IDocumentationProvider), documentationProvider); } /// <summary> /// Sets the objects that will be used by the formatters to produce sample requests/responses. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleObjects">The sample objects.</param> public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects) { config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects; } /// <summary> /// Sets the sample request directly for the specified media type and action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample request directly for the specified media type and action with parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample request directly for the specified media type of the action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample response directly for the specified media type of the action with specific parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample directly for all actions with the specified media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample); } /// <summary> /// Sets the sample directly for all actions with the specified type and media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> /// <param name="type">The parameter type or return type of an action.</param> public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type); } /// <summary> /// Gets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <returns>The help page sample generator.</returns> public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config) { return (HelpPageSampleGenerator)config.Properties.GetOrAdd( typeof(HelpPageSampleGenerator), k => new HelpPageSampleGenerator()); } /// <summary> /// Sets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleGenerator">The help page sample generator.</param> public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator) { config.Properties.AddOrUpdate( typeof(HelpPageSampleGenerator), k => sampleGenerator, (k, o) => sampleGenerator); } /// <summary> /// Gets the model description generator. /// </summary> /// <param name="config">The configuration.</param> /// <returns>The <see cref="ModelDescriptionGenerator"/></returns> public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config) { return (ModelDescriptionGenerator)config.Properties.GetOrAdd( typeof(ModelDescriptionGenerator), k => InitializeModelDescriptionGenerator(config)); } /// <summary> /// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param> /// <returns> /// An <see cref="HelpPageApiModel"/> /// </returns> public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId) { object model; string modelId = ApiModelPrefix + apiDescriptionId; if (!config.Properties.TryGetValue(modelId, out model)) { Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions; ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase)); if (apiDescription != null) { model = GenerateApiModel(apiDescription, config); config.Properties.TryAdd(modelId, model); } } return (HelpPageApiModel)model; } private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config) { HelpPageApiModel apiModel = new HelpPageApiModel() { ApiDescription = apiDescription, }; ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator(); HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); GenerateUriParameters(apiModel, modelGenerator); GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator); GenerateResourceDescription(apiModel, modelGenerator); GenerateSamples(apiModel, sampleGenerator); return apiModel; } private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromUri) { HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor; Type parameterType = null; ModelDescription typeDescription = null; ComplexTypeModelDescription complexTypeDescription = null; if (parameterDescriptor != null) { parameterType = parameterDescriptor.ParameterType; typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType); complexTypeDescription = typeDescription as ComplexTypeModelDescription; } // Example: // [TypeConverter(typeof(PointConverter))] // public class Point // { // public Point(int x, int y) // { // X = x; // Y = y; // } // public int X { get; set; } // public int Y { get; set; } // } // Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection. // // public class Point // { // public int X { get; set; } // public int Y { get; set; } // } // Regular complex class Point will have properties X and Y added to UriParameters collection. if (complexTypeDescription != null && !IsBindableWithTypeConverter(parameterType)) { foreach (ParameterDescription uriParameter in complexTypeDescription.Properties) { apiModel.UriParameters.Add(uriParameter); } } else if (parameterDescriptor != null) { ParameterDescription uriParameter = AddParameterDescription(apiModel, apiParameter, typeDescription); if (!parameterDescriptor.IsOptional) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" }); } object defaultValue = parameterDescriptor.DefaultValue; if (defaultValue != null) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) }); } } else { Debug.Assert(parameterDescriptor == null); // If parameterDescriptor is null, this is an undeclared route parameter which only occurs // when source is FromUri. Ignored in request model and among resource parameters but listed // as a simple string here. ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string)); AddParameterDescription(apiModel, apiParameter, modelDescription); } } } } private static bool IsBindableWithTypeConverter(Type parameterType) { if (parameterType == null) { return false; } return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string)); } private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel, ApiParameterDescription apiParameter, ModelDescription typeDescription) { ParameterDescription parameterDescription = new ParameterDescription { Name = apiParameter.Name, Documentation = apiParameter.Documentation, TypeDescription = typeDescription, }; apiModel.UriParameters.Add(parameterDescription); return parameterDescription; } private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromBody) { Type parameterType = apiParameter.ParameterDescriptor.ParameterType; apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); apiModel.RequestDocumentation = apiParameter.Documentation; } else if (apiParameter.ParameterDescriptor != null && apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)) { Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); if (parameterType != null) { apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); } } } } private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ResponseDescription response = apiModel.ApiDescription.ResponseDescription; Type responseType = response.ResponseType ?? response.DeclaredType; if (responseType != null && responseType != typeof(void)) { apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType); } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")] private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator) { try { foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription)) { apiModel.SampleRequests.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription)) { apiModel.SampleResponses.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } } catch (Exception e) { apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture, "An exception has occurred while generating the sample. Exception message: {0}", HelpPageSampleGenerator.UnwrapException(e).Message)); } } private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType) { parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault( p => p.Source == ApiParameterSource.FromBody || (p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))); if (parameterDescription == null) { resourceType = null; return false; } resourceType = parameterDescription.ParameterDescriptor.ParameterType; if (resourceType == typeof(HttpRequestMessage)) { HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); } if (resourceType == null) { parameterDescription = null; return false; } return true; } private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config) { ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config); Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions; foreach (ApiDescription api in apis) { ApiParameterDescription parameterDescription; Type parameterType; if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType)) { modelGenerator.GetOrCreateModelDescription(parameterType); } } return modelGenerator; } private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample) { InvalidSample invalidSample = sample as InvalidSample; if (invalidSample != null) { apiModel.ErrorMessages.Add(invalidSample.ErrorMessage); } } } }
51.59188
196
0.623732
[ "MIT" ]
liepnguyen/Planru
Planru.DistributedServices.WebAPI/Areas/HelpPage/HelpPageConfigurationExtensions.cs
24,145
C#
/* * QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals. * Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System; using System.Collections.Generic; using System.Linq; using QuantConnect.Data.Market; using QuantConnect.Interfaces; using QuantConnect.Securities; using QuantConnect.Securities.Option; using QuantConnect.Util; namespace QuantConnect.Data.UniverseSelection { /// <summary> /// Defines a universe for a single option chain /// </summary> public class OptionChainUniverse : Universe { private static readonly IReadOnlyList<TickType> QuotesAndTrades = new[] { TickType.Quote, TickType.Trade }; private BaseData _underlying; private readonly Option _option; private readonly UniverseSettings _universeSettings; /// <summary> /// Initializes a new instance of the <see cref="OptionChainUniverse"/> class /// </summary> /// <param name="option">The canonical option chain security</param> /// <param name="universeSettings">The universe settings to be used for new subscriptions</param> /// <param name="securityInitializer">The security initializer to use on newly created securities</param> public OptionChainUniverse(Option option, UniverseSettings universeSettings, ISecurityInitializer securityInitializer = null) : base(option.SubscriptionDataConfig, securityInitializer) { _option = option; _universeSettings = universeSettings; } /// <summary> /// Gets the settings used for subscriptons added for this universe /// </summary> public override UniverseSettings UniverseSettings { get { return _universeSettings; } } /// <summary> /// Performs universe selection using the data specified /// </summary> /// <param name="utcTime">The current utc time</param> /// <param name="data">The symbols to remain in the universe</param> /// <returns>The data that passes the filter</returns> public override IEnumerable<Symbol> SelectSymbols(DateTime utcTime, BaseDataCollection data) { var optionsUniverseDataCollection = data as OptionChainUniverseDataCollection; if (optionsUniverseDataCollection == null) { throw new ArgumentException(string.Format("Expected data of type '{0}'", typeof (OptionChainUniverseDataCollection).Name)); } _underlying = optionsUniverseDataCollection.Underlying ?? _underlying; optionsUniverseDataCollection.Underlying = _underlying; if (_underlying == null || data.Data.Count == 0) { return Unchanged; } var availableContracts = optionsUniverseDataCollection.Data.Select(x => x.Symbol); var results = _option.ContractFilter.Filter(availableContracts, _underlying).ToHashSet(); // we save off the filtered results to the universe data collection for later // population into the OptionChain. This is non-ideal and could be remedied by // the universe subscription emitting a special type after selection that could // be checked for in TimeSlice.Create, but for now this will do optionsUniverseDataCollection.FilteredContracts = results; return results; } /// <summary> /// Gets the subscription requests to be added for the specified security /// </summary> /// <param name="security">The security to get subscriptions for</param> /// <param name="currentTimeUtc">The current time in utc. This is the frontier time of the algorithm</param> /// <param name="maximumEndTimeUtc">The max end time</param> /// <returns>All subscriptions required by this security</returns> public override IEnumerable<SubscriptionRequest> GetSubscriptionRequests(Security security, DateTime currentTimeUtc, DateTime maximumEndTimeUtc) { // we want to return both quote and trade subscriptions return QuotesAndTrades .Select(tickType => new SubscriptionDataConfig( objectType: GetDataType(UniverseSettings.Resolution, tickType), symbol: security.Symbol, resolution: UniverseSettings.Resolution, dataTimeZone: Configuration.DataTimeZone, exchangeTimeZone: security.Exchange.TimeZone, fillForward: UniverseSettings.FillForward, extendedHours: UniverseSettings.ExtendedMarketHours, isInternalFeed: false, isCustom: false, tickType: tickType, isFilteredSubscription: true )) .Select(config => new SubscriptionRequest( isUniverseSubscription: false, universe: this, security: security, configuration: config, startTimeUtc: currentTimeUtc, endTimeUtc: maximumEndTimeUtc )); } /// <summary> /// Creates and configures a security for the specified symbol /// </summary> /// <param name="symbol">The symbol of the security to be created</param> /// <param name="algorithm">The algorithm instance</param> /// <param name="marketHoursDatabase">The market hours database</param> /// <param name="symbolPropertiesDatabase">The symbol properties database</param> /// <returns>The newly initialized security object</returns> public override Security CreateSecurity(Symbol symbol, IAlgorithm algorithm, MarketHoursDatabase marketHoursDatabase, SymbolPropertiesDatabase symbolPropertiesDatabase) { // set the underlying security and pricing model from the canonical security var option = (Option)base.CreateSecurity(symbol, algorithm, marketHoursDatabase, symbolPropertiesDatabase); option.Underlying = _option.Underlying; option.PriceModel = _option.PriceModel; return option; } /// <summary> /// Determines whether or not the specified security can be removed from /// this universe. This is useful to prevent securities from being taken /// out of a universe before the algorithm has had enough time to make /// decisions on the security /// </summary> /// <param name="utcTime">The current utc time</param> /// <param name="security">The security to check if its ok to remove</param> /// <returns>True if we can remove the security, false otherwise</returns> public override bool CanRemoveMember(DateTime utcTime, Security security) { // if we haven't begun receiving data for this security then it's safe to remove var lastData = security.Cache.GetData(); if (lastData == null) { return true; } // only remove members on day changes, this prevents us from needing to // fast forward contracts continuously as price moves and out filtered // contracts change thoughout the day var localTime = utcTime.ConvertFromUtc(security.Exchange.TimeZone); if (localTime.Date != lastData.Time.Date) { return true; } return false; } /// <summary> /// Gets the data type required for the specified combination of resolution and tick type /// </summary> private static Type GetDataType(Resolution resolution, TickType tickType) { if (resolution == Resolution.Tick) return typeof(Tick); if (tickType == TickType.Quote) return typeof(QuoteBar); return typeof(TradeBar); } } }
46.751351
176
0.642965
[ "Apache-2.0" ]
DavidBenko/Lean
Common/Data/UniverseSelection/OptionChainUniverse.cs
8,651
C#
using EShopOnAbp.PaymentService.DbMigrations; using EShopOnAbp.PaymentService.EntityFrameworkCore; using EShopOnAbp.Shared.Hosting.AspNetCore; using EShopOnAbp.Shared.Hosting.Microservices; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Cors; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using System; using System.Collections.Generic; using System.Linq; using Volo.Abp; using Volo.Abp.Modularity; using Volo.Abp.Threading; namespace EShopOnAbp.PaymentService { [DependsOn( typeof(PaymentServiceApplicationModule), typeof(PaymentServiceEntityFrameworkCoreModule), typeof(PaymentServiceHttpApiModule), typeof(EShopOnAbpSharedHostingMicroservicesModule) )] public class PaymentServiceHttpApiHostModule : AbpModule { public override void ConfigureServices(ServiceConfigurationContext context) { var hostingEnvironment = context.Services.GetHostingEnvironment(); var configuration = context.Services.GetConfiguration(); JwtBearerConfigurationHelper.Configure(context, "PaymentService"); // SwaggerConfigurationHelper.Configure(context, "Payment Service API"); SwaggerWithAuthConfigurationHelper.Configure( context: context, authority: configuration["AuthServer:Authority"], scopes: new Dictionary<string, string> /* Requested scopes for authorization code request and descriptions for swagger UI only */ { {"PaymentService", "Payment Service API"}, }, apiTitle: "Payment Service API" ); context.Services.AddCors(options => { options.AddDefaultPolicy(builder => { builder .WithOrigins( configuration["App:CorsOrigins"] .Split(",", StringSplitOptions.RemoveEmptyEntries) .Select(o => o.Trim().RemovePostFix("/")) .ToArray() ) .WithAbpExposedHeaders() .SetIsOriginAllowedToAllowWildcardSubdomains() .AllowAnyHeader() .AllowAnyMethod() .AllowCredentials(); }); }); } public override void OnApplicationInitialization(ApplicationInitializationContext context) { var app = context.GetApplicationBuilder(); var env = context.GetEnvironment(); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseCorrelationId(); app.UseCors(); app.UseAbpRequestLocalization(); app.UseStaticFiles(); app.UseRouting(); // app.UseHttpMetrics(); app.UseAuthentication(); app.UseAbpClaimsMap(); app.UseAuthorization(); app.UseSwagger(); app.UseSwaggerUI(options => { options.SwaggerEndpoint("/swagger/v1/swagger.json", "Payment Service API"); }); app.UseAbpSerilogEnrichers(); app.UseAuditing(); app.UseUnitOfWork(); app.UseConfiguredEndpoints(endpoints => { // endpoints.MapMetrics(); }); } public override void OnPostApplicationInitialization(ApplicationInitializationContext context) { using (var scope = context.ServiceProvider.CreateScope()) { AsyncHelper.RunSync( () => scope.ServiceProvider .GetRequiredService<PaymentServiceDatabaseMigrationChecker>() .CheckAsync() ); } } } }
37.149533
145
0.576604
[ "MIT" ]
xyfy/eShopOnAbp
services/payment/src/EShopOnAbp.PaymentService.HttpApi.Host/PaymentServiceHttpApiHostModule.cs
3,975
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class EnemyTurretShooting : MonoBehaviour { public GameObject arrowPrefab; public AudioSource shootingSound; public float shootForce; public Transform spawnRotation; public Transform spawnPosition; public void shootArrow() { GameObject arrow = Instantiate(arrowPrefab, spawnPosition.position, spawnRotation.rotation); Rigidbody rb = arrow.GetComponent<Rigidbody>(); shootForce = 20 + (-spawnRotation.localRotation.y * 20); rb.velocity = spawnRotation.forward * shootForce; } }
21.625
64
0.692197
[ "Apache-2.0" ]
pdtbinh/Unity_Boomee-Game
Scripts/MainGameScripts/Enemy/EnemyTurretShooting.cs
694
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace org.secc.ChangeManager.Utilities { public class SecurityChangeDetail { public int ChangeRequestId { get; set; } public string PreviousEmail { get; set; } public string CurrentEmail { get; set; } public List<string> ChangeDetails { get; set; } } }
24.647059
55
0.692124
[ "ECL-2.0" ]
engineeringdrew/RockPlugins
Plugins/org.secc.ChangeManager/Utilities/SecurityChangeDetail.cs
421
C#
using System; using Langly.Patterns; using Xunit; namespace Langly { public class Patterns_Tests { } }
11.888889
30
0.747664
[ "BSD-3-Clause" ]
roy98/LibLangly
Tests.CSharp/Langly/Patterns_Tests.cs
109
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.LB.Inputs { public sealed class ListenerDefaultActionArgs : Pulumi.ResourceArgs { /// <summary> /// Configuration block for using Amazon Cognito to authenticate users. Specify only when `type` is `authenticate-cognito`. Detailed below. /// </summary> [Input("authenticateCognito")] public Input<Inputs.ListenerDefaultActionAuthenticateCognitoArgs>? AuthenticateCognito { get; set; } /// <summary> /// Configuration block for an identity provider that is compliant with OpenID Connect (OIDC). Specify only when `type` is `authenticate-oidc`. Detailed below. /// </summary> [Input("authenticateOidc")] public Input<Inputs.ListenerDefaultActionAuthenticateOidcArgs>? AuthenticateOidc { get; set; } /// <summary> /// Information for creating an action that returns a custom HTTP response. Required if `type` is `fixed-response`. /// </summary> [Input("fixedResponse")] public Input<Inputs.ListenerDefaultActionFixedResponseArgs>? FixedResponse { get; set; } /// <summary> /// Configuration block for creating an action that distributes requests among one or more target groups. Specify only if `type` is `forward`. If you specify both `forward` block and `target_group_arn` attribute, you can specify only one target group using `forward` and it must be the same target group specified in `target_group_arn`. Detailed below. /// </summary> [Input("forward")] public Input<Inputs.ListenerDefaultActionForwardArgs>? Forward { get; set; } /// <summary> /// Order for the action. This value is required for rules with multiple actions. The action with the lowest value for order is performed first. Valid values are between `1` and `50000`. /// </summary> [Input("order")] public Input<int>? Order { get; set; } /// <summary> /// Configuration block for creating a redirect action. Required if `type` is `redirect`. Detailed below. /// </summary> [Input("redirect")] public Input<Inputs.ListenerDefaultActionRedirectArgs>? Redirect { get; set; } /// <summary> /// ARN of the Target Group to which to route traffic. Specify only if `type` is `forward` and you want to route to a single target group. To route to one or more target groups, use a `forward` block instead. /// </summary> [Input("targetGroupArn")] public Input<string>? TargetGroupArn { get; set; } /// <summary> /// Type of routing action. Valid values are `forward`, `redirect`, `fixed-response`, `authenticate-cognito` and `authenticate-oidc`. /// </summary> [Input("type", required: true)] public Input<string> Type { get; set; } = null!; public ListenerDefaultActionArgs() { } } }
47.661765
360
0.662758
[ "ECL-2.0", "Apache-2.0" ]
RafalSumislawski/pulumi-aws
sdk/dotnet/LB/Inputs/ListenerDefaultActionArgs.cs
3,241
C#
using Northwind.EntityLayer.Concrete.Bases; #nullable disable namespace Northwind.EntityLayer.Concrete.Models { public partial class ProductsAboveAveragePrice : EntityBase { public string ProductName { get; set; } public decimal? UnitPrice { get; set; } } }
22.230769
63
0.712803
[ "MIT" ]
142-Bupa-Acibadem-FullStack-Bootcamp/week-5-assignment-1-yahyaerdoan
Northwind.EntityLayer/Concrete/Models/ProductsAboveAveragePrice.cs
291
C#
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.Coyote.Specifications; using Xunit; using Xunit.Abstractions; namespace Microsoft.Coyote.BugFinding.Tests { public class TaskWhenAllTests : BaseBugFindingTest { public TaskWhenAllTests(ITestOutputHelper output) : base(output) { } private static async Task WriteAsync(SharedEntry entry, int value) { await Task.CompletedTask; entry.Value = value; } private static async Task WriteWithDelayAsync(SharedEntry entry, int value) { await Task.Delay(1); entry.Value = value; } [Fact(Timeout = 5000)] public void TestWhenAllWithTwoSynchronousTasks() { this.TestWithError(async () => { SharedEntry entry = new SharedEntry(); Task task1 = WriteAsync(entry, 5); Task task2 = WriteAsync(entry, 3); await Task.WhenAll(task1, task2); AssertSharedEntryValue(entry, 5); }, configuration: this.GetConfiguration().WithTestingIterations(200), expectedError: "Value is 3 instead of 5.", replay: true); } [Fact(Timeout = 5000)] public void TestWhenAllWithTwoAsynchronousTasks() { this.TestWithError(async () => { SharedEntry entry = new SharedEntry(); Task task1 = WriteWithDelayAsync(entry, 3); Task task2 = WriteWithDelayAsync(entry, 5); await Task.WhenAll(task1, task2); AssertSharedEntryValue(entry, 5); }, configuration: this.GetConfiguration().WithTestingIterations(200), expectedError: "Value is 3 instead of 5.", replay: true); } [Fact(Timeout = 5000)] public void TestWhenAllWithTwoParallelTasks() { this.TestWithError(async () => { SharedEntry entry = new SharedEntry(); Task task1 = Task.Run(async () => { await WriteAsync(entry, 3); }); Task task2 = Task.Run(async () => { await WriteAsync(entry, 5); }); await Task.WhenAll(task1, task2); AssertSharedEntryValue(entry, 5); }, configuration: this.GetConfiguration().WithTestingIterations(200), expectedError: "Value is 3 instead of 5.", replay: true); } [Fact(Timeout = 5000)] public void TestWhenAllWithTwoSynchronousTaskWithResults() { this.TestWithError(async () => { SharedEntry entry = new SharedEntry(); Task<int> task1 = entry.GetWriteResultAsync(5); Task<int> task2 = entry.GetWriteResultAsync(3); int[] results = await Task.WhenAll(task1, task2); Specification.Assert(results.Length is 2, "Result count is '{0}' instead of 2.", results.Length); Specification.Assert(results[0] == 5 && results[1] is 3, "Found unexpected value."); Specification.Assert(results[0] == results[1], "Results are equal."); }, configuration: this.GetConfiguration().WithTestingIterations(200), expectedError: "Results are equal.", replay: true); } [Fact(Timeout = 5000)] public void TestWhenAllWithTwoAsynchronousTaskWithResults() { this.TestWithError(async () => { SharedEntry entry = new SharedEntry(); Task<int> task1 = entry.GetWriteResultWithDelayAsync(5); Task<int> task2 = entry.GetWriteResultWithDelayAsync(3); int[] results = await Task.WhenAll(task1, task2); Specification.Assert(results.Length is 2, "Result count is '{0}' instead of 2.", results.Length); Specification.Assert(results[0] == 5 && results[1] is 3, "Found unexpected value."); }, configuration: this.GetConfiguration().WithTestingIterations(200), expectedError: "Found unexpected value.", replay: true); } [Fact(Timeout = 5000)] public void TestWhenAllWithTwoParallelSynchronousTaskWithResults() { this.TestWithError(async () => { SharedEntry entry = new SharedEntry(); Task<int> task1 = Task.Run(async () => { return await entry.GetWriteResultAsync(5); }); Task<int> task2 = Task.Run(async () => { return await entry.GetWriteResultAsync(3); }); int[] results = await Task.WhenAll(task1, task2); Specification.Assert(results.Length is 2, "Result count is '{0}' instead of 2.", results.Length); Specification.Assert(results[0] == 5, $"The first task result is {results[0]} instead of 5."); Specification.Assert(results[1] is 3, $"The second task result is {results[1]} instead of 3."); Specification.Assert(false, "Reached test assertion."); }, configuration: this.GetConfiguration().WithTestingIterations(300), expectedError: "Reached test assertion.", replay: true); } [Fact(Timeout = 5000)] public void TestWhenAllWithTwoParallelAsynchronousTaskWithResults() { this.TestWithError(async () => { SharedEntry entry = new SharedEntry(); Task<int> task1 = Task.Run(async () => { return await entry.GetWriteResultWithDelayAsync(5); }); Task<int> task2 = Task.Run(async () => { return await entry.GetWriteResultWithDelayAsync(3); }); int[] results = await Task.WhenAll(task1, task2); Specification.Assert(results.Length is 2, "Result count is '{0}' instead of 2.", results.Length); Specification.Assert(results[0] == 5 && results[1] is 3, "Found unexpected value."); }, configuration: this.GetConfiguration().WithTestingIterations(200), expectedError: "Found unexpected value.", replay: true); } [Fact(Timeout = 5000)] public void TestWhenAllWithAsyncCaller() { this.TestWithError(async () => { SharedEntry entry = new SharedEntry(); Func<Task> whenAll = async () => { List<Task> tasks = new List<Task>(); for (int i = 0; i < 2; i++) { tasks.Add(Task.Delay(1)); } entry.Value = 3; await Task.WhenAll(tasks); entry.Value = 1; }; var task = whenAll(); AssertSharedEntryValue(entry, 1); await task; }, configuration: this.GetConfiguration().WithTestingIterations(200), expectedError: "Value is 3 instead of 1.", replay: true); } [Fact(Timeout = 5000)] public void TestWhenAllWithResultAndAsyncCaller() { this.TestWithError(async () => { SharedEntry entry = new SharedEntry(); Func<Task> whenAll = async () => { List<Task<int>> tasks = new List<Task<int>>(); for (int i = 0; i < 2; i++) { tasks.Add(Task.Run(() => 1)); } entry.Value = 3; await Task.WhenAll(tasks); entry.Value = 1; }; var task = whenAll(); AssertSharedEntryValue(entry, 1); await task; }, configuration: this.GetConfiguration().WithTestingIterations(200), expectedError: "Value is 3 instead of 1.", replay: true); } [Fact(Timeout = 5000)] public void TestWhenAllWithException() { this.TestWithError(async () => { Task task1 = Task.Run(async () => { await Task.CompletedTask; ThrowException<InvalidOperationException>(); }); Task task2 = Task.Run(async () => { await Task.CompletedTask; ThrowException<NotSupportedException>(); }); Exception exception = null; try { await Task.WhenAll(task1, task2); } catch (Exception ex) { exception = ex; } Specification.Assert(exception != null, "Expected an `AggregateException`."); if (exception is AggregateException aex) { Specification.Assert(aex.InnerExceptions.Any(e => e is InvalidOperationException), "The exception is not of the expected type."); Specification.Assert(aex.InnerExceptions.Any(e => e is NotSupportedException), "The exception is not of the expected type."); } else { Specification.Assert(exception is InvalidOperationException || exception is NotSupportedException, "The exception is not of the expected type."); } Specification.Assert(task1.IsFaulted && task2.IsFaulted, "One task has not faulted."); Specification.Assert(task1.Exception.InnerException.GetType() == typeof(InvalidOperationException), "The first task exception is not of the expected type."); Specification.Assert(task2.Exception.InnerException.GetType() == typeof(NotSupportedException), "The second task exception is not of the expected type."); Specification.Assert(false, "Reached test assertion."); }, configuration: this.GetConfiguration().WithTestingIterations(200), expectedError: "Reached test assertion.", replay: true); } [Fact(Timeout = 5000)] public void TestWhenAllWithResultsAndException() { this.TestWithError(async () => { Task<int> task1 = Task.Run(async () => { await Task.CompletedTask; ThrowException<InvalidOperationException>(); return 1; }); Task<int> task2 = Task.Run(async () => { await Task.CompletedTask; ThrowException<NotSupportedException>(); return 3; }); Exception exception = null; try { await Task.WhenAll(task1, task2); } catch (Exception ex) { exception = ex; } Specification.Assert(exception != null, "Expected an `AggregateException`."); if (exception is AggregateException aex) { Specification.Assert(aex.InnerExceptions.Any(e => e is InvalidOperationException), "The exception is not of the expected type."); Specification.Assert(aex.InnerExceptions.Any(e => e is NotSupportedException), "The exception is not of the expected type."); } else { Specification.Assert(exception is InvalidOperationException || exception is NotSupportedException, "The exception is not of the expected type."); } Specification.Assert(task1.IsFaulted && task2.IsFaulted, "One task has not faulted."); Specification.Assert(task1.Exception.InnerException.GetType() == typeof(InvalidOperationException), "The first task exception is not of the expected type."); Specification.Assert(task2.Exception.InnerException.GetType() == typeof(NotSupportedException), "The second task exception is not of the expected type."); Specification.Assert(false, "Reached test assertion."); }, configuration: this.GetConfiguration().WithTestingIterations(200), expectedError: "Reached test assertion.", replay: true); } [Fact(Timeout = 5000)] public void TestWhenAllDeadlock() { this.TestWithError(async () => { // Test that `WhenAll` deadlocks because one of the tasks cannot complete until later. var tcs = new TaskCompletionSource<bool>(); await Task.WhenAll(tcs.Task, Task.Delay(1)); tcs.SetResult(true); await tcs.Task; }, errorChecker: (e) => { Assert.StartsWith("Deadlock detected.", e); }, replay: true); } [Fact(Timeout = 5000)] public void TestWhenAllWithResultsAndDeadlock() { this.TestWithError(async () => { // Test that `WhenAll` deadlocks because one of the tasks cannot complete until later. var tcs = new TaskCompletionSource<bool>(); await Task.WhenAll(tcs.Task, Task.FromResult(true)); tcs.SetResult(true); await tcs.Task; }, errorChecker: (e) => { Assert.StartsWith("Deadlock detected.", e); }, replay: true); } } }
37.901299
118
0.509457
[ "MIT" ]
Magicianred/coyote
Tests/Tests.BugFinding/Tasks/Join/TaskWhenAllTests.cs
14,594
C#
using System.Collections.Generic; using SampSharp.GameMode; namespace Grandlarc { public class SpawnPositions { public static IDictionary<City, IList<WorldPosition>> Positions = new Dictionary<City, IList<WorldPosition>> { [City.LasVenturas] = new WorldPosition[] { new WorldPosition(new Vector3(1435.8024f, 2662.3647f, 11.3926f), 1.1650f), new WorldPosition(new Vector3(1457.4762f, 2773.4868f, 10.8203f), 272.2754f), new WorldPosition(new Vector3(1739.6390f, 2803.0569f, 14.2735f), 285.3929f), new WorldPosition(new Vector3(1870.3096f, 2785.2471f, 14.2734f), 42.3102f), new WorldPosition(new Vector3(1959.7142f, 2754.6863f, 10.8203f), 181.4731f), new WorldPosition(new Vector3(2314.2556f, 2759.4504f, 10.8203f), 93.2711f), new WorldPosition(new Vector3(2216.5674f, 2715.0334f, 10.8130f), 267.6540f), new WorldPosition(new Vector3(2101.4192f, 2678.7874f, 10.8130f), 92.0607f), new WorldPosition(new Vector3(1951.1090f, 2660.3877f, 10.8203f), 180.8461f), new WorldPosition(new Vector3(1666.6949f, 2604.9861f, 10.8203f), 179.8495f), new WorldPosition(new Vector3(2808.3367f, 2421.5107f, 11.0625f), 136.2060f), new WorldPosition(new Vector3(2633.3203f, 2349.7061f, 10.6719f), 178.7175f), new WorldPosition(new Vector3(2606.6348f, 2161.7490f, 10.8203f), 88.7508f), new WorldPosition(new Vector3(2616.5286f, 2100.6226f, 10.8158f), 177.7834f), new WorldPosition(new Vector3(2491.8816f, 2397.9370f, 10.8203f), 266.6003f), new WorldPosition(new Vector3(2531.7891f, 2530.3223f, 21.8750f), 91.6686f), new WorldPosition(new Vector3(2340.6677f, 2530.4324f, 10.8203f), 177.8630f), new WorldPosition(new Vector3(2097.6855f, 2491.3313f, 14.8390f), 181.8117f), new WorldPosition(new Vector3(1893.1000f, 2423.2412f, 11.1782f), 269.4385f), new WorldPosition(new Vector3(1698.9330f, 2241.8320f, 10.8203f), 357.8584f), new WorldPosition(new Vector3(1479.4559f, 2249.0769f, 11.0234f), 306.3790f), new WorldPosition(new Vector3(1298.1548f, 2083.4016f, 10.8127f), 256.7034f), new WorldPosition(new Vector3(1117.8785f, 2304.1514f, 10.8203f), 81.5490f), new WorldPosition(new Vector3(1108.9878f, 1705.8639f, 10.8203f), 0.6785f), new WorldPosition(new Vector3(1423.9780f, 1034.4188f, 10.8203f), 90.9590f), new WorldPosition(new Vector3(1537.4377f, 752.0641f, 11.0234f), 271.6893f), new WorldPosition(new Vector3(1917.9590f, 702.6984f, 11.1328f), 359.2682f), new WorldPosition(new Vector3(2089.4785f, 658.0414f, 11.2707f), 357.3572f), new WorldPosition(new Vector3(2489.8286f, 928.3251f, 10.8280f), 67.2245f), new WorldPosition(new Vector3(2697.4717f, 856.4916f, 9.8360f), 267.0983f), new WorldPosition(new Vector3(2845.6104f, 1288.1444f, 11.3906f), 3.6506f), new WorldPosition(new Vector3(2437.9370f, 1293.1442f, 10.8203f), 86.3830f), new WorldPosition(new Vector3(2299.5430f, 1451.4177f, 10.8203f), 269.1287f), new WorldPosition(new Vector3(2214.3008f, 2041.9165f, 10.8203f), 268.7626f), new WorldPosition(new Vector3(2005.9174f, 2152.0835f, 10.8203f), 270.1372f), new WorldPosition(new Vector3(2222.1042f, 1837.4220f, 10.8203f), 88.6461f), new WorldPosition(new Vector3(2025.6753f, 1916.4363f, 12.3382f), 272.5852f), new WorldPosition(new Vector3(2087.9902f, 1516.5336f, 10.8203f), 48.9300f), new WorldPosition(new Vector3(2172.1624f, 1398.7496f, 11.0625f), 91.3783f), new WorldPosition(new Vector3(2139.1841f, 987.7975f, 10.8203f), 0.2315f), new WorldPosition(new Vector3(1860.9672f, 1030.2910f, 10.8203f), 271.6988f), new WorldPosition(new Vector3(1673.2345f, 1316.1067f, 10.8203f), 177.7294f), new WorldPosition(new Vector3(1412.6187f, 2000.0596f, 14.7396f), 271.3568f) }, [City.LosSantos] = new WorldPosition[] { new WorldPosition(new Vector3(1751.1097f, -2106.4529f, 13.5469f), 183.1979f), new WorldPosition(new Vector3(2652.6418f, -1989.9175f, 13.9988f), 182.7107f), new WorldPosition(new Vector3(2489.5225f, -1957.9258f, 13.5881f), 2.3440f), new WorldPosition(new Vector3(2689.5203f, -1695.9354f, 10.0517f), 39.5312f), new WorldPosition(new Vector3(2770.5393f, -1628.3069f, 12.1775f), 4.9637f), new WorldPosition(new Vector3(2807.9282f, -1176.8883f, 25.3805f), 173.6018f), new WorldPosition(new Vector3(2552.5417f, -958.0850f, 82.6345f), 280.2542f), new WorldPosition(new Vector3(2232.1309f, -1159.5679f, 25.8906f), 103.2939f), new WorldPosition(new Vector3(2388.1003f, -1279.8933f, 25.1291f), 94.3321f), new WorldPosition(new Vector3(2481.1885f, -1536.7186f, 24.1467f), 273.4944f), new WorldPosition(new Vector3(2495.0720f, -1687.5278f, 13.5150f), 359.6696f), new WorldPosition(new Vector3(2306.8252f, -1675.4340f, 13.9221f), 2.6271f), new WorldPosition(new Vector3(2191.8403f, -1455.8251f, 25.5391f), 267.9925f), new WorldPosition(new Vector3(1830.1359f, -1092.1849f, 23.8656f), 94.0113f), new WorldPosition(new Vector3(2015.3630f, -1717.2535f, 13.5547f), 93.3655f), new WorldPosition(new Vector3(1654.7091f, -1656.8516f, 22.5156f), 177.9729f), new WorldPosition(new Vector3(1219.0851f, -1812.8058f, 16.5938f), 190.0045f), new WorldPosition(new Vector3(1508.6849f, -1059.0846f, 25.0625f), 1.8058f), new WorldPosition(new Vector3(1421.0819f, -885.3383f, 50.6531f), 3.6516f), new WorldPosition(new Vector3(1133.8237f, -1272.1558f, 13.5469f), 192.4113f), new WorldPosition(new Vector3(1235.2196f, -1608.6111f, 13.5469f), 181.2655f), new WorldPosition(new Vector3(590.4648f, -1252.2269f, 18.2116f), 25.0473f), new WorldPosition(new Vector3(842.5260f, -1007.7679f, 28.4185f), 213.9953f), new WorldPosition(new Vector3(911.9332f, -1232.6490f, 16.9766f), 5.2999f), new WorldPosition(new Vector3(477.6021f, -1496.6207f, 20.4345f), 266.9252f), new WorldPosition(new Vector3(255.4621f, -1366.3256f, 53.1094f), 312.0852f), new WorldPosition(new Vector3(281.5446f, -1261.4562f, 73.9319f), 305.0017f), new WorldPosition(new Vector3(790.1918f, -839.8533f, 60.6328f), 191.9514f), new WorldPosition(new Vector3(1299.1859f, -801.4249f, 84.1406f), 269.5274f), new WorldPosition(new Vector3(1240.3170f, -2036.6886f, 59.9575f), 276.4659f), new WorldPosition(new Vector3(2215.5181f, -2627.8174f, 13.5469f), 273.7786f), new WorldPosition(new Vector3(2509.4346f, -2637.6543f, 13.6453f), 358.3565f) }, [City.SanFierro] = new WorldPosition[] { new WorldPosition(new Vector3(-2723.4639f, -314.8138f, 7.1839f), 43.5562f), new WorldPosition(new Vector3(-2694.5344f, 64.5550f, 4.3359f), 95.0190f), new WorldPosition(new Vector3(-2458.2000f, 134.5419f, 35.1719f), 303.9446f), new WorldPosition(new Vector3(-2796.6589f, 219.5733f, 7.1875f), 88.8288f), new WorldPosition(new Vector3(-2706.5261f, 397.7129f, 4.3672f), 179.8611f), new WorldPosition(new Vector3(-2866.7683f, 691.9363f, 23.4989f), 286.3060f), new WorldPosition(new Vector3(-2764.9543f, 785.6434f, 52.7813f), 357.6817f), new WorldPosition(new Vector3(-2660.9402f, 883.2115f, 79.7738f), 357.4440f), new WorldPosition(new Vector3(-2861.0796f, 1047.7109f, 33.6068f), 188.2750f), new WorldPosition(new Vector3(-2629.2009f, 1383.1367f, 7.1833f), 179.7006f), new WorldPosition(new Vector3(-2079.6802f, 1430.0189f, 7.1016f), 177.6486f), new WorldPosition(new Vector3(-1660.2294f, 1382.6698f, 9.8047f), 136.2952f), new WorldPosition(new Vector3(-1674.1964f, 430.3246f, 7.1797f), 226.1357f), new WorldPosition(new Vector3(-1954.9982f, 141.8080f, 27.1747f), 277.7342f), new WorldPosition(new Vector3(-1956.1447f, 287.1091f, 35.4688f), 90.4465f), new WorldPosition(new Vector3(-1888.1117f, 615.7245f, 35.1719f), 128.4498f), new WorldPosition(new Vector3(-1922.5566f, 886.8939f, 35.3359f), 272.1293f), new WorldPosition(new Vector3(-1983.3458f, 1117.0645f, 53.1243f), 271.2390f), new WorldPosition(new Vector3(-2417.6458f, 970.1491f, 45.2969f), 269.3676f), new WorldPosition(new Vector3(-2108.0171f, 902.8030f, 76.5792f), 5.7139f), new WorldPosition(new Vector3(-2097.5664f, 658.0771f, 52.3672f), 270.4487f), new WorldPosition(new Vector3(-2263.6650f, 393.7423f, 34.7708f), 136.4152f), new WorldPosition(new Vector3(-2287.5027f, 149.1875f, 35.3125f), 266.3989f), new WorldPosition(new Vector3(-2039.3571f, -97.7205f, 35.1641f), 7.4744f), new WorldPosition(new Vector3(-1867.5022f, -141.9203f, 11.8984f), 22.4499f), new WorldPosition(new Vector3(-1537.8992f, 116.0441f, 17.3226f), 120.8537f), new WorldPosition(new Vector3(-1708.4763f, 7.0187f, 3.5489f), 319.3260f), new WorldPosition(new Vector3(-1427.0858f, -288.9430f, 14.1484f), 137.0812f), new WorldPosition(new Vector3(-2173.0654f, -392.7444f, 35.3359f), 237.0159f), new WorldPosition(new Vector3(-2320.5286f, -180.3870f, 35.3135f), 179.6980f), new WorldPosition(new Vector3(-2930.0049f, 487.2518f, 4.9141f), 3.8258f) } }; } }
84.421875
97
0.594114
[ "Unlicense" ]
SampSharp/sample-gm-grandlarc
src/Grandlarc/SpawnPositions.cs
10,808
C#
//----------------------------------------------------------------------- // <copyright file="AssemblyInfo.cs" company="Akka.NET Project"> // Copyright (C) 2009-2018 Lightbend Inc. <http://www.lightbend.com> // Copyright (C) 2013-2018 .NET Foundation <https://github.com/akkadotnet/akka.net> // </copyright> //----------------------------------------------------------------------- using System.Reflection; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("System1")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("System1")] [assembly: AssemblyCopyright("Copyright © 2014")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("4ad845ed-a515-449a-84b8-0902282d8271")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
39.545455
87
0.66954
[ "Apache-2.0" ]
EajksEajks/Akka.NET
src/examples/RemoteDeploy/System1/Properties/AssemblyInfo.cs
1,743
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 schemas-2019-12-02.normal.json service model. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Net; using System.Text; using System.Xml.Serialization; using Amazon.Schemas.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; using ThirdParty.Json.LitJson; namespace Amazon.Schemas.Model.Internal.MarshallTransformations { /// <summary> /// Response Unmarshaller for CreateDiscoverer operation /// </summary> public class CreateDiscovererResponseUnmarshaller : JsonResponseUnmarshaller { /// <summary> /// Unmarshaller the response from the service to the response class. /// </summary> /// <param name="context"></param> /// <returns></returns> public override AmazonWebServiceResponse Unmarshall(JsonUnmarshallerContext context) { CreateDiscovererResponse response = new CreateDiscovererResponse(); context.Read(); int targetDepth = context.CurrentDepth; while (context.ReadAtDepth(targetDepth)) { if (context.TestExpression("Description", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; response.Description = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("DiscovererArn", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; response.DiscovererArn = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("DiscovererId", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; response.DiscovererId = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("SourceArn", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; response.SourceArn = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("State", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; response.State = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("tags", targetDepth)) { var unmarshaller = new DictionaryUnmarshaller<string, string, StringUnmarshaller, StringUnmarshaller>(StringUnmarshaller.Instance, StringUnmarshaller.Instance); response.Tags = unmarshaller.Unmarshall(context); continue; } } return response; } /// <summary> /// Unmarshaller error response to exception. /// </summary> /// <param name="context"></param> /// <param name="innerException"></param> /// <param name="statusCode"></param> /// <returns></returns> public override AmazonServiceException UnmarshallException(JsonUnmarshallerContext context, Exception innerException, HttpStatusCode statusCode) { var errorResponse = JsonErrorResponseUnmarshaller.GetInstance().Unmarshall(context); errorResponse.InnerException = innerException; errorResponse.StatusCode = statusCode; var responseBodyBytes = context.GetResponseBodyBytes(); using (var streamCopy = new MemoryStream(responseBodyBytes)) using (var contextCopy = new JsonUnmarshallerContext(streamCopy, false, null)) { if (errorResponse.Code != null && errorResponse.Code.Equals("BadRequestException")) { return BadRequestExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse); } if (errorResponse.Code != null && errorResponse.Code.Equals("ConflictException")) { return ConflictExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse); } if (errorResponse.Code != null && errorResponse.Code.Equals("ForbiddenException")) { return ForbiddenExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse); } if (errorResponse.Code != null && errorResponse.Code.Equals("InternalServerErrorException")) { return InternalServerErrorExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse); } if (errorResponse.Code != null && errorResponse.Code.Equals("ServiceUnavailableException")) { return ServiceUnavailableExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse); } if (errorResponse.Code != null && errorResponse.Code.Equals("UnauthorizedException")) { return UnauthorizedExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse); } } return new AmazonSchemasException(errorResponse.Message, errorResponse.InnerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, errorResponse.StatusCode); } private static CreateDiscovererResponseUnmarshaller _instance = new CreateDiscovererResponseUnmarshaller(); internal static CreateDiscovererResponseUnmarshaller GetInstance() { return _instance; } /// <summary> /// Gets the singleton. /// </summary> public static CreateDiscovererResponseUnmarshaller Instance { get { return _instance; } } } }
42.41875
190
0.612936
[ "Apache-2.0" ]
DetlefGolze/aws-sdk-net
sdk/src/Services/Schemas/Generated/Model/Internal/MarshallTransformations/CreateDiscovererResponseUnmarshaller.cs
6,787
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable enable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.Diagnostics { internal interface IDiagnosticAnalyzerService { /// <summary> /// Provides and caches analyzer information. /// </summary> DiagnosticAnalyzerInfoCache AnalyzerInfoCache { get; } /// <summary> /// Re-analyze given projects and documents /// </summary> void Reanalyze(Workspace workspace, IEnumerable<ProjectId>? projectIds = null, IEnumerable<DocumentId>? documentIds = null, bool highPriority = false); /// <summary> /// Get specific diagnostics currently stored in the source. returned diagnostic might be out-of-date if solution has changed but analyzer hasn't run for the new solution. /// </summary> Task<ImmutableArray<DiagnosticData>> GetSpecificCachedDiagnosticsAsync(Workspace workspace, object id, bool includeSuppressedDiagnostics = false, CancellationToken cancellationToken = default); /// <summary> /// Get diagnostics currently stored in the source. returned diagnostic might be out-of-date if solution has changed but analyzer hasn't run for the new solution. /// </summary> Task<ImmutableArray<DiagnosticData>> GetCachedDiagnosticsAsync(Workspace workspace, ProjectId? projectId = null, DocumentId? documentId = null, bool includeSuppressedDiagnostics = false, CancellationToken cancellationToken = default); /// <summary> /// Get diagnostics for the given solution. all diagnostics returned should be up-to-date with respect to the given solution. /// </summary> Task<ImmutableArray<DiagnosticData>> GetDiagnosticsAsync(Solution solution, ProjectId? projectId = null, DocumentId? documentId = null, bool includeSuppressedDiagnostics = false, CancellationToken cancellationToken = default); /// <summary> /// Force computes diagnostics and raises diagnostic events for the given project or solution. all diagnostics returned should be up-to-date with respect to the given project or solution. /// </summary> Task ForceAnalyzeAsync(Solution solution, Action<Project> onProjectAnalyzed, ProjectId? projectId = null, CancellationToken cancellationToken = default); /// <summary> /// True if given project has any diagnostics /// </summary> bool ContainsDiagnostics(Workspace workspace, ProjectId projectId); /// <summary> /// Get diagnostics of the given diagnostic ids from the given solution. all diagnostics returned should be up-to-date with respect to the given solution. /// Note that for project case, this method returns diagnostics from all project documents as well. Use <see cref="GetProjectDiagnosticsForIdsAsync(Solution, ProjectId, ImmutableHashSet{string}, bool, CancellationToken)"/> /// if you want to fetch only project diagnostics without source locations. /// </summary> Task<ImmutableArray<DiagnosticData>> GetDiagnosticsForIdsAsync(Solution solution, ProjectId? projectId = null, DocumentId? documentId = null, ImmutableHashSet<string>? diagnosticIds = null, bool includeSuppressedDiagnostics = false, CancellationToken cancellationToken = default); /// <summary> /// Get project diagnostics (diagnostics with no source location) of the given diagnostic ids from the given solution. all diagnostics returned should be up-to-date with respect to the given solution. /// Note that this method doesn't return any document diagnostics. Use <see cref="GetDiagnosticsForIdsAsync(Solution, ProjectId, DocumentId, ImmutableHashSet{string}, bool, CancellationToken)"/> to also fetch those. /// </summary> Task<ImmutableArray<DiagnosticData>> GetProjectDiagnosticsForIdsAsync(Solution solution, ProjectId? projectId = null, ImmutableHashSet<string>? diagnosticIds = null, bool includeSuppressedDiagnostics = false, CancellationToken cancellationToken = default); /// <summary> /// Try to return up to date diagnostics for the given span for the document. /// /// It will return true if it was able to return all up-to-date diagnostics. /// otherwise, false indicating there are some missing diagnostics in the diagnostic list /// </summary> Task<bool> TryAppendDiagnosticsForSpanAsync(Document document, TextSpan range, List<DiagnosticData> diagnostics, bool includeSuppressedDiagnostics = false, CancellationToken cancellationToken = default); /// <summary> /// Return up to date diagnostics for the given span for the document /// /// This can be expensive since it is force analyzing diagnostics if it doesn't have up-to-date one yet. /// If diagnosticIdOpt is not null, it gets diagnostics only for this given diagnosticIdOpt value /// </summary> Task<IEnumerable<DiagnosticData>> GetDiagnosticsForSpanAsync(Document document, TextSpan range, string? diagnosticIdOpt = null, bool includeSuppressedDiagnostics = false, Func<string, IDisposable?>? addOperationScope = null, CancellationToken cancellationToken = default); /// <summary> /// Check whether given <see cref="DiagnosticAnalyzer"/> is compilation end analyzer /// By compilation end analyzer, it means compilation end analysis here /// </summary> bool IsCompilationEndAnalyzer(DiagnosticAnalyzer analyzer, Project project, Compilation compilation); } }
65.988764
288
0.72978
[ "MIT" ]
Dean-ZhenYao-Wang/roslyn
src/Features/Core/Portable/Diagnostics/IDiagnosticAnalyzerService.cs
5,875
C#
using System; using System.Collections.Generic; using System.Linq; namespace Eto.Parse.Parsers { public sealed class RepeatCharItem : ICloneable { public Func<char, bool> Test { get; set; } public int Minimum { get; set; } public int Maximum { get; set; } RepeatCharItem(RepeatCharItem other) { Test = other.Test; Minimum = other.Minimum; Maximum = other.Maximum; } public RepeatCharItem(Func<char, bool> test, int minimum = 0, int maximum = int.MaxValue) { Test = test; Minimum = minimum; Maximum = maximum; } public static implicit operator RepeatCharItem(char literalChar) { return new RepeatCharItem(ch => ch == literalChar, 1, 1); } public object Clone() { return new RepeatCharItem(this); } } public class RepeatCharTerminal : Parser { readonly List<RepeatCharItem> _items; public IList<RepeatCharItem> Items { get { return _items; } } RepeatCharItem singleItem; protected RepeatCharTerminal(RepeatCharTerminal other, ParserCloneArgs args) : base(other, args) { _items = new List<RepeatCharItem>(other._items.Select(r => (RepeatCharItem)r.Clone())); } public RepeatCharTerminal() { _items = new List<RepeatCharItem>(); } public RepeatCharTerminal(Func<char, bool> test, int minimum = 0, int maximum = int.MaxValue) : this(new RepeatCharItem(test, minimum, maximum)) { } public RepeatCharTerminal(params RepeatCharItem[] items) { _items = items.ToList(); } public RepeatCharTerminal(IEnumerable<RepeatCharItem> items) { _items = items.ToList(); } public void Add(Func<char, bool> test, int minimum = 0, int maximum = int.MaxValue) { _items.Add(new RepeatCharItem(test, minimum, maximum)); } protected override void InnerInitialize(ParserInitializeArgs args) { base.InnerInitialize(args); if (_items.Count == 1) singleItem = _items[0]; } protected override int InnerParse(ParseArgs args) { var scanner = args.Scanner; var length = 0; var pos = scanner.Position; var ch = scanner.ReadChar(); if (singleItem != null) { var max = singleItem.Maximum; var test = singleItem.Test; beg1: if (ch == -1 || !test(unchecked((char)ch))) goto end1; length++; ch = scanner.ReadChar(); if (length < max) goto beg1; end1: if (length < singleItem.Minimum) goto abort; scanner.Position = pos + length; return length; } var itemCount = _items.Count; for (int i = 0; i < itemCount; i++) { var item = _items[i]; var count = 0; var max = item.Maximum; var test = item.Test; beg2: if (ch == -1 || !test(unchecked((char)ch))) goto end2; count++; ch = scanner.ReadChar(); if (count < max) goto beg2; end2: if (count < item.Minimum) goto abort; length += count; } scanner.Position = pos + length; return length; abort: scanner.Position = pos; return -1; } public override Parser Clone(ParserCloneArgs args) { return new RepeatCharTerminal(this, args); } } }
21.65493
95
0.653333
[ "MIT" ]
DanielDavis5/Eto.Parse
Eto.Parse/Parsers/RepeatCharTerminal.cs
3,075
C#
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the clouddirectory-2017-01-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.CloudDirectory.Model { /// <summary> /// Container for the parameters to the BatchRead operation. /// Performs all the read operations in a batch. /// </summary> public partial class BatchReadRequest : AmazonCloudDirectoryRequest { private ConsistencyLevel _consistencyLevel; private string _directoryArn; private List<BatchReadOperation> _operations = new List<BatchReadOperation>(); /// <summary> /// Gets and sets the property ConsistencyLevel. /// <para> /// Represents the manner and timing in which the successful write or update of an object /// is reflected in a subsequent read operation of that same object. /// </para> /// </summary> public ConsistencyLevel ConsistencyLevel { get { return this._consistencyLevel; } set { this._consistencyLevel = value; } } // Check to see if ConsistencyLevel property is set internal bool IsSetConsistencyLevel() { return this._consistencyLevel != null; } /// <summary> /// Gets and sets the property DirectoryArn. /// <para> /// The Amazon Resource Name (ARN) that is associated with the <a>Directory</a>. For more /// information, see <a>arns</a>. /// </para> /// </summary> [AWSProperty(Required=true)] public string DirectoryArn { get { return this._directoryArn; } set { this._directoryArn = value; } } // Check to see if DirectoryArn property is set internal bool IsSetDirectoryArn() { return this._directoryArn != null; } /// <summary> /// Gets and sets the property Operations. /// <para> /// A list of operations that are part of the batch. /// </para> /// </summary> [AWSProperty(Required=true)] public List<BatchReadOperation> Operations { get { return this._operations; } set { this._operations = value; } } // Check to see if Operations property is set internal bool IsSetOperations() { return this._operations != null && this._operations.Count > 0; } } }
32.34
112
0.622449
[ "Apache-2.0" ]
ChristopherButtars/aws-sdk-net
sdk/src/Services/CloudDirectory/Generated/Model/BatchReadRequest.cs
3,234
C#
using System.Runtime.InteropServices; namespace NiftiCS { /// <summary> /// Represents a Nifti1 Header object. This header must be read prior to /// attempting to read a Nifti1 Image object. The Nifti1 Header contains /// information relevant to the <i>type</i> of the data, as well as /// spatial and temporal information necessary for image manipulation. /// </summary> [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi, Pack = 1)] public struct Nifti1 { /// <summary> Size of the Nifti1 Header. Must be 348. </summary> public int sizeof_hdr; #region Unused by Nifti1; maintained for Analyze7.5 compatibility. /// <summary> Unused by Nifti1; maintained for Analyze7.5 compatibility. </summary> [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 10)] public string data_type; /// <summary> Unused by Nifti1; maintained for Analyze7.5 compatibility. </summary> [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 18)] public string db_name; /// <summary> Unused by Nifti1; maintained for Analyze7.5 compatibility. </summary> public int extents; /// <summary> Unused by Nifti1; maintained for Analyze7.5 compatibility. </summary> public short session_error; /// <summary> Unused by Nifti1; maintained for Analyze7.5 compatibility. </summary> public char regular; #endregion /// <summary> MRI slice ordering. </summary> public byte dim_info; /// <summary> Data array dimensions. </summary> [MarshalAs(UnmanagedType.ByValArray, SizeConst = 8)] public short[] dim; /// <summary> 1st intent parameter. </summary> public float intent_p1; /// <summary> 2nd intent parameter. </summary> public float intent_p2; /// <summary> 3rd intent parameter. </summary> public float intent_p3; /// <summary> NIFTI_INTENT_* code. </summary> public short intent_code; /// <summary> Defines the type of the data. </summary> public short datatype; /// <summary> Number of bits/voxel. </summary> public short bitpix; /// <summary> Index of the first slice. </summary> public short slice_start; /// <summary> /// Grid spacing. The first element of this array is /// also used to determine the endianness of the image. /// </summary> [MarshalAs(UnmanagedType.ByValArray, SizeConst = 8)] public float[] pixdim; /// <summary> Offset into .nii file. </summary> public float vox_offset; /// <summary> Data scaling: slope. </summary> public float scl_slope; /// <summary> Data scaling: offset </summary> public float scl_inter; /// <summary> Last slice index. </summary> public short slice_end; /// <summary> Slice timing order. </summary> public byte slice_code; /// <summary> Units of pixdim[1..4]. </summary> public byte xyzt_units; /// <summary> Maximum display intensity. </summary> public float cal_max; /// <summary> Minimum display intensity. </summary> public float cal_min; /// <summary> Duration of a single slice. </summary> public float slice_duration; /// <summary> Time axis shift. </summary> public float toffset; #region Unused by Nifti1; maintained for Analyze7.5 compatibility. /// <summary> Unused by Nifti1; maintained for Analyze7.5 compatibility. </summary> public int glmax; /// <summary> Unused by Nifti1; maintained for Analyze7.5 compatibility. </summary> public int glmin; #endregion /// <summary> Short text description of the data. </summary> [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 80)] public string descrip; /// <summary> Name of auxilliary files. </summary> [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 24)] public string aux_file; /// <summary> NIFTI_XFORM_* code. </summary> public short qform_code; /// <summary> NIFTI_XFORM_* code. </summary> public short sform_code; /// <summary> Quaternian b parameter. </summary> public float quatern_b; /// <summary> Quaternian c parameter. </summary> public float quatern_c; /// <summary> Quaternian d parameter. </summary> public float quatern_d; /// <summary> Quaternion <i>x</i> shift. </summary> public float qoffset_x; /// <summary> Quaternion <i>y</i> shift. </summary> public float qoffset_y; /// <summary> Quaternion <i>z</i> shift. </summary> public float qoffset_z; /// <summary> 1st row of affine transformation matrix. </summary> [MarshalAs(UnmanagedType.ByValArray, SizeConst = 4)] public float[] srow_x; /// <summary> 2nd row of affine transformation matrix. </summary> [MarshalAs(UnmanagedType.ByValArray, SizeConst = 4)] public float[] srow_y; /// <summary> 3rd row of affine transformation matrix. </summary> [MarshalAs(UnmanagedType.ByValArray, SizeConst = 4)] public float[] srow_z; /// <summary> Name of the data. </summary> [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 16)] public string intent_name; /// <summary> Magic number; either <i>nil</i> or <i>n+1</i>. </summary> [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 4)] public string magic; /// <summary> 3rd party extensions, e.g. AFNI. </summary> [MarshalAs(UnmanagedType.ByValArray, SizeConst = 4)] public byte[] extension; } }
41.414286
91
0.621594
[ "MIT" ]
swatalla/ioNIFTI
ioNIFTI/csnifti/Nifti1.cs
5,800
C#
namespace SFA.Apprenticeships.Domain.Raa.Interfaces.Repositories { using System.Collections.Generic; using Entities.Raa.Parties; using Models; public interface IProviderSiteReadRepository { ProviderSite GetById(int providerSiteId); ProviderSite GetByEdsUrn(string edsUrn); IReadOnlyDictionary<int, ProviderSite> GetByIds(IEnumerable<int> providerSiteIds); IEnumerable<ProviderSite> GetByProviderId(int providerId); IEnumerable<ProviderSite> Search(ProviderSiteSearchParameters searchParameters); ProviderSiteRelationship GetProviderSiteRelationship(int providerSiteRelationshipId); } public interface IProviderSiteWriteRepository { ProviderSite Create(ProviderSite providerSite); ProviderSite Update(ProviderSite providerSite); ProviderSiteRelationship Create(ProviderSiteRelationship providerSiteRelationship); void DeleteProviderSiteRelationship(int providerSiteRelationshipId); } }
33.633333
93
0.770069
[ "MIT" ]
BugsUK/FindApprenticeship
src/SFA.Apprenticeships.Domain.Raa.Interfaces/Repositories/IProviderSiteRepository.cs
1,011
C#
using System; using System.Xml.Serialization; namespace Alipay.AopSdk.Core.Domain { /// <summary> /// AlipayInsSceneSellerActivityQueryModel Data Structure. /// </summary> [Serializable] public class AlipayInsSceneSellerActivityQueryModel : AopObject { /// <summary> /// 渠道账号对应的uid,如果证据类型字段没填则必填 /// </summary> [XmlElement("channel_account_id")] public string ChannelAccountId { get; set; } /// <summary> /// 渠道账号类型,如果证据类型字段没填则必填1:支付宝账号 2:淘宝账号 /// </summary> [XmlElement("channel_account_type")] public long ChannelAccountType { get; set; } /// <summary> /// 签约的标准产品码 /// </summary> [XmlElement("sp_code")] public string SpCode { get; set; } } }
25.709677
67
0.59473
[ "MIT" ]
leixf2005/Alipay.AopSdk.Core
Alipay.AopSdk.Core/Domain/AlipayInsSceneSellerActivityQueryModel.cs
911
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("p02.PhonebookUpgrade")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("p02.PhonebookUpgrade")] [assembly: AssemblyCopyright("Copyright © 2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("af584459-5c2f-40fa-be36-363d9d6b2a01")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
38.054054
84
0.74929
[ "MIT" ]
GitHarr/SoftUni
Homework/TechModule/ProgramingFundamentals-Normal/DictionariesLambdaAndLINQ-Exercises/p02.PhonebookUpgrade/Properties/AssemblyInfo.cs
1,411
C#
namespace Utils { public static class DoubleExtension { public static double Factorial(this double i) { if (i <= 1) return 1; return i * Factorial(i - 1); } } }
16.545455
49
0.620879
[ "MIT" ]
MouradZzz/TankArena
Assets/Scripts/Extensions/DoubleExtension.cs
182
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using Android.App; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Flash_Alarm")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Flash_Alarm")] [assembly: AssemblyCopyright("Copyright © 2018")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
33.148148
77
0.750838
[ "MIT" ]
snct-ukai/Flash-Alarm
Flash Alarm/Properties/AssemblyInfo.cs
898
C#
// The MIT License (MIT) // // Copyright (c) 2014 Beanstream Internet Commerce Corp, Digital River, Inc. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // using System; namespace Beanstream { public class EmptyClass { public EmptyClass () { } } }
37.742857
81
0.732778
[ "MIT" ]
jonagh/beanstream-dotnetcore
Beanstream/EmptyClass.cs
1,323
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. // // // // Description: Factory interface to create views on collections. // // See spec at http://avalon/connecteddata/Specs/CollectionView.mht // using System; namespace System.ComponentModel { /// <summary> /// Allows an implementing collection to create a view to its data. /// Normally, user code does not call methods on this interface. /// </summary> public interface ICollectionViewFactory { /// <summary> /// Create a new view on this collection [Do not call directly]. /// </summary> /// <remarks> /// Normally this method is only called by the platform's view manager, /// not by user code. /// </remarks> ICollectionView CreateView(); } }
28.029412
79
0.653725
[ "MIT" ]
00mjk/wpf
src/Microsoft.DotNet.Wpf/src/WindowsBase/System/ComponentModel/ICollectionViewFactory.cs
953
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.Events; namespace KirinUtil { public class NetManager : MonoBehaviour { //---------------------------------- // LocalIPを取得 //---------------------------------- public string GetLocalIPAddress() { System.Net.IPHostEntry host; string localIP = "0.0.0.0"; host = System.Net.Dns.GetHostEntry(System.Net.Dns.GetHostName()); foreach (System.Net.IPAddress ip in host.AddressList) { if (ip.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork) { localIP = ip.ToString(); break; } } return localIP; } //---------------------------------- // OSC //---------------------------------- #region OSC #region var public class OSCData { public string Key; public string Address; public string Data; } private Dictionary<string, ServerLog> servers = null; private bool isRun = false; private int oscReceiveLogCount = 0; private long lastTimeStamp; public bool receiveOn; #endregion #region event [System.Serializable] public class OSCReceiveEvent : UnityEvent<List<OSCData>> { } public OSCReceiveEvent oscReceiveEvent; void OnEnable() { oscReceiveEvent.AddListener(ReceivedOSC); } void OnDisable() { oscReceiveEvent.RemoveListener(ReceivedOSC); } void ReceivedOSC(List<OSCData> data) { //print("ReceivedOSC"); } #endregion #region start / stop public void OSCStart(string ipAddress, int inComingPort, int outGoingPort) { OSCHandler.Instance.Init(ipAddress, outGoingPort, inComingPort); servers = new Dictionary<string, ServerLog>(); isRun = true; } public void OSCStop() { OSCHandler.Instance.OnApplicationQuit(); isRun = false; } #endregion #region update(send) public void OSCSend(string address, string message) { // データ送信部 OSCHandler.Instance.SendMessageToClient("OscClient", address, message); } #endregion #region update(receive) private void Update() { if (receiveOn && isRun) OSCReceiveUpdate(); } private List<OSCData> OSCReceiveUpdate() { List<OSCData> oscDataList = new List<OSCData>(); // must be called before you try to read value from osc server OSCHandler.Instance.UpdateLogs(); // データ受信 servers = OSCHandler.Instance.Servers; foreach (KeyValuePair<string, ServerLog> item in servers) { // If we have received at least one packet, // show the last received from the log in the Debug console //print("servers: " + item.Value.log.Count); //print(oscReceiveLogCount + " " + item.Value.log.Count); //if (item.Value.log.Count > 0) { //if (oscReceiveLogCount != item.Value.log.Count) { for (int i = 0; i < item.Value.packets.Count; i++) { if (lastTimeStamp < item.Value.packets[i].TimeStamp) { lastTimeStamp = item.Value.packets[i].TimeStamp; int arrayNum = item.Value.packets[i].Data.Count; if (arrayNum > 0) { OSCData oscData = new OSCData(); // Server name oscData.Key = item.Key; // OSC address oscData.Address = item.Value.packets[i].Address; // First data value string dataStr = ""; int dataCount = item.Value.packets[i].Data.Count; for (int j = 0; j < dataCount; j++) { if (j == dataCount - 1) dataStr += item.Value.packets[i].Data[j]; else dataStr += item.Value.packets[i].Data[j] + ","; } oscData.Data = dataStr; oscDataList.Add(oscData); } } } //oscReceiveLogCount = item.Value.log.Count; } if (oscDataList.Count > 0) { oscReceiveEvent.Invoke(oscDataList); //print(oscDataList[0].Data); } return oscDataList; } #endregion #endregion } }
32.096774
88
0.481206
[ "MIT" ]
mizutanikirin/KirinUtil
KirinUtil/Assets/KirinUtil/Scripts/Network/NetManager.cs
5,005
C#
using Microsoft.AspNetCore.Mvc; using Sfa.Tl.ResultsAndCertification.Web.ViewModel.PostResultsService; using System.Threading.Tasks; namespace Sfa.Tl.ResultsAndCertification.Web.UnitTests.Controllers.PostResultsServiceControllerTests.PrsSelectAssessmentSeriesPost { public abstract class TestSetup : PostResultsServiceControllerTestBase { public IActionResult Result { get; private set; } public PrsSelectAssessmentSeriesViewModel ViewModel { get; set; } public async override Task When() { Result = await Controller.PrsSelectAssessmentSeriesAsync(ViewModel); } } }
37.176471
130
0.761076
[ "MIT" ]
SkillsFundingAgency/tl-results-and-certification
src/Tests/Sfa.Tl.ResultsAndCertification.Web.UnitTests/Controllers/PostResultsServiceControllerTests/PrsSelectAssessmentSeriesPost/TestSetup.cs
634
C#
using System; using ReactiveDomain.Transport.BufferManagement; namespace ReactiveDomain.Transport.Formatting { public interface IMessageFormatter<T> { /// <summary> /// Converts the object to a <see cref="BufferPool"></see> representing a binary format of it. /// </summary> /// <param name="message">The message to convert.</param> /// <returns>A <see cref="BufferPool"></see> containing the data representing the object.</returns> BufferPool ToBufferPool(T message); /// <summary> /// Converts the object to a <see cref="ArraySegment{Byte}"></see> representing a binary format of it. /// </summary> /// <param name="message">The message to convert.</param> /// <returns>A <see cref="BufferPool"></see> containing the data representing the object.</returns> ArraySegment<byte> ToArraySegment(T message); /// <summary> /// Converts the object to a byte array representing a binary format of it. /// </summary> /// <param name="message">The message to convert.</param> /// <returns>A <see cref="BufferPool"></see> containing the data representing the object.</returns> byte[] ToArray(T message); /// <summary> /// Takes a <see cref="BufferPool"></see> and converts its contents to a message object /// </summary> /// <param name="bufferPool">The buffer pool.</param> /// <returns>A message representing the data given</returns> T From(BufferPool bufferPool); /// <summary> /// Takes an ArraySegment and converts its contents to a message object /// </summary> /// <param name="segment">The buffer pool.</param> /// <returns>A message representing the data given</returns> T From(ArraySegment<byte> segment); /// <summary> /// Takes an Array and converts its contents to a message object /// </summary> /// <param name="array">The buffer pool.</param> /// <returns>A message representing the data given</returns> T From(byte [] array); } }
42.039216
110
0.616138
[ "MIT" ]
PKI-InVivo/reactive-domain
src/ReactiveDomain.Transport/Formatting/IMessageFormatter.cs
2,144
C#
using System.Collections.Generic; using System.Security.Claims; using System.Threading.Tasks; using Barebone.ViewModels.Account; using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Authentication.Cookies; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Configuration; namespace Barebone.Controllers { public class AccountController : Controller { private readonly string _siteUserName; private readonly string _siteUserPassword; public AccountController(IConfiguration configuration) { _siteUserName = configuration["SiteUser:UserName"]; _siteUserPassword = configuration["SiteUser:Password"]; } [HttpGet] [ActionName("LogIn")] [AllowAnonymous] public async Task<IActionResult> LogInAsync() { return await Task.Run(View); } [HttpPost] [ActionName("LogIn")] [AllowAnonymous] [ValidateAntiForgeryToken] public async Task<IActionResult> LogInAsync(LogInViewModel logIn) { // Check required fields, if any empty return to login page if (!ModelState.IsValid) { logIn.Message = "Required data missing"; ModelState.AddModelError("BadUserPassword", logIn.Message); return await Task.Run(() => View(logIn)); } if (logIn.UserName == _siteUserName) { var passwordHasher = new PasswordHasher<string>(); if (passwordHasher.VerifyHashedPassword(null, _siteUserPassword, logIn.Password) == PasswordVerificationResult.Success) { var claims = new List<Claim> { new Claim(ClaimTypes.Name, logIn.UserName) }; var claimsIdentity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme); await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(claimsIdentity)); return await Task.Run(() => RedirectToAction("Index", "Barebone")); } } logIn.Message = "Invalid attempt"; return await Task.Run(() => View(logIn)); } [HttpGet] [ActionName("LogOut")] public async Task<IActionResult> Logout() { await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme); return RedirectToAction("LogIn","Account"); } #region PasswordHasher [HttpGet] [AllowAnonymous] public async Task<IActionResult> PasswordHasherAsync() { return await Task.Run(View); } [HttpPost] [ActionName("PasswordHasher")] [AllowAnonymous] public async Task<IActionResult> PasswordHasherAsync(PasswordHasherViewModel passwordHasher) { ViewBag.PasswordResult = new PasswordHasher<string>().HashPassword(null, passwordHasher.PasswordToHash); return await Task.Run(View); } #endregion } }
35.419355
138
0.618094
[ "Apache-2.0" ]
Xarkam/ExtCore-Sample-Authorize
src/Barebone/Controllers/AccountController.cs
3,294
C#