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 Addressalize.StandardData; using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text.RegularExpressions; namespace Addressalize { public class Addressalizer { public string Normalize(string source) { var segments = source.Replace(".", string.Empty).Replace(",", " ").ToUpper().Split(' ').Where(x => string.IsNullOrEmpty(x) == false); var newSegments = segments .DictionaryLookupLastOrDefault(Data.USPS_C1_Street_Suffix_Abbreviations) .DictionaryLookupAllOrDefault(Data.USPS_C2_Secondary_Unit_Designators) .DictionaryLookupAllOrDefault(Data.Numbers) .DictionaryLookupAllOrDefault(Data.Directions) .DictionaryLookupThenMergeNextOrDefault(Data.Tens) ; var result = string.Join(" ", newSegments.ToArray()); return result; } } public static class Extensions { public static string ReplaceFromDictionaryOrDefault(this string source, Dictionary<string, string> data) { return data.ContainsKey(source) ? data[source] : source; } public static IEnumerable<string> DictionaryLookupAllOrDefault(this IEnumerable<string> source, Dictionary<string, string> data) { return source.Select(x => x.ReplaceFromDictionaryOrDefault(data)); } public static IEnumerable<string> DictionaryLookupLastOrDefault(this IEnumerable<string> source, Dictionary<string, string> data) { var lastSegmentsIdToChange = source .Select((x, i) => new { index = i, inData = data.ContainsKey(x) || data.Values.Distinct().Contains(x) }) .Where((x, i) => x.inData) .Select(x => x.index) .LastOrDefault(); return source.Select((x, i) => i == lastSegmentsIdToChange ? x.ReplaceFromDictionaryOrDefault(data) : x); } public static IEnumerable<string> DictionaryLookupThenMergeNextOrDefault(this IEnumerable<string> source, Dictionary<string, string> data, Func<IEnumerable<string>, int, IEnumerable<string>> changedSegmentFunc = null) { var updatedSegments = source.DictionaryLookupAllOrDefault(data) .Select((x, i) => x == source.ElementAt(i) ? x : x + source.ElementAt(i + 1)); return updatedSegments.Where((x, i) => i == 0 || updatedSegments.ElementAt(i - 1) == source.ElementAt(i - 1)); } } }
43.383333
145
0.638878
[ "MIT" ]
3choBoomer/Addressalize
src/Addressalize/Addressalizer.cs
2,605
C#
using UnityEditor; namespace ProceduralMeshSupport { [CustomEditor(typeof(RotateMeshModifier))] public class RotateMeshModifierInspector : MeshModifierInspector { } }
18.5
68
0.762162
[ "MIT" ]
aadebdeb/ProceduralMesh
Assets/ProceduralMesh/Editor/MeshModifierInspectors/RotateMeshModifierInspector.cs
187
C#
// This file is auto-generated, don't edit it. Thanks. using System; using System.Collections.Generic; using System.IO; using Tea; namespace AlibabaCloud.SDK.Ram20150501.Models { public class CreatePolicyVersionResponse : TeaModel { [NameInMap("RequestId")] [Validation(Required=true)] public string RequestId { get; set; } [NameInMap("PolicyVersion")] [Validation(Required=true)] public CreatePolicyVersionResponsePolicyVersion PolicyVersion { get; set; } public class CreatePolicyVersionResponsePolicyVersion : TeaModel { [NameInMap("VersionId")] [Validation(Required=true)] public string VersionId { get; set; } [NameInMap("IsDefaultVersion")] [Validation(Required=true)] public bool? IsDefaultVersion { get; set; } [NameInMap("PolicyDocument")] [Validation(Required=true)] public string PolicyDocument { get; set; } [NameInMap("CreateDate")] [Validation(Required=true)] public string CreateDate { get; set; } }; } }
30.864865
83
0.625219
[ "Apache-2.0" ]
atptro/alibabacloud-sdk
ram-20150501/csharp/core/Models/CreatePolicyVersionResponse.cs
1,142
C#
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; /// <summary> /// Scriptable Object base que derivan los distintos tipos de ataques /// <para> /// Tipos de ataques propuestos: /// Target: una vez entra en rango, fija un objetivo y le hace daño sin importar que pase. /// TargetRemainInRange: canaliza el ataque y solo le hace daño si se mantiene en rango. /// MeleeArea: castea una zona en la que realiza daño. (Overlap Box) /// Proyectile: castea un proyectil en direccion de su objetivo.</para> /// </summary> public class EnemyAttackData : ScriptableObject { public float attackRange = 5f; //Rango en el cual el enemigo se quedara quieto y empezara a ejecutar el ataque. public int damage = 10; //Daño del ataque public float cooldown = 0.5f; //Enfriamiento del ataque, contado a partir de que se termino de ejecutar el ataque. public float executeTime = 0.2f; //Tiempo que le toma realizar el ataque (para darle tiempo a una animacion) public virtual void ExecuteAttack(EnemyAttack caster, PlayerHealth playerHealth) { //Para ser reemplazado en clases derivadas } //Cosas pendientes: implementar hooks para animaciones, instanciar objetos y tal }
46.37037
121
0.735623
[ "MIT" ]
gamerevar/proyecto-comunitario-1-unity
Assets/Scripts/Enemy/EnemyAttackData/EnemyAttackData.cs
1,258
C#
using System.Reflection; using System.Runtime.InteropServices; [assembly: AssemblyTitle("Calculator.Tests")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Calculator.Tests")] [assembly: AssemblyCopyright("Copyright © 2020")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] [assembly: Guid("e79c64d6-4e08-4c1e-911c-ad6f48f9b9ad")] // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
31.157895
56
0.748311
[ "MIT" ]
tschroedter/Selkie.AutoMocking
src/Example/Calculator.Tests/Properties/AssemblyInfo.cs
593
C#
namespace Bookstore.Data.Migrations { using System; using System.Data.Entity.Migrations; public partial class InitialCreate : DbMigration { public override void Up() { CreateTable( "dbo.Authors", c => new { AuthorId = c.Int(nullable: false, identity: true), Name = c.String(nullable: false, maxLength: 50), }) .PrimaryKey(t => t.AuthorId) .Index(t => t.Name, unique: true); CreateTable( "dbo.Books", c => new { BookId = c.Int(nullable: false, identity: true), Title = c.String(nullable: false), ISBN = c.String(maxLength: 13), Price = c.Decimal(precision: 18, scale: 2), WebSite = c.String(), }) .PrimaryKey(t => t.BookId) .Index(t => t.ISBN, unique: true); CreateTable( "dbo.Reviews", c => new { ReviewId = c.Int(nullable: false, identity: true), Content = c.String(nullable: false), CreatedOn = c.DateTime(nullable: false), BookId = c.Int(nullable: false), AuthorId = c.Int(), }) .PrimaryKey(t => t.ReviewId) .ForeignKey("dbo.Authors", t => t.AuthorId) .ForeignKey("dbo.Books", t => t.BookId, cascadeDelete: true) .Index(t => t.BookId) .Index(t => t.AuthorId); CreateTable( "dbo.BookAuthors", c => new { Book_BookId = c.Int(nullable: false), Author_AuthorId = c.Int(nullable: false), }) .PrimaryKey(t => new { t.Book_BookId, t.Author_AuthorId }) .ForeignKey("dbo.Books", t => t.Book_BookId, cascadeDelete: true) .ForeignKey("dbo.Authors", t => t.Author_AuthorId, cascadeDelete: true) .Index(t => t.Book_BookId) .Index(t => t.Author_AuthorId); } public override void Down() { DropForeignKey("dbo.Reviews", "BookId", "dbo.Books"); DropForeignKey("dbo.Reviews", "AuthorId", "dbo.Authors"); DropForeignKey("dbo.BookAuthors", "Author_AuthorId", "dbo.Authors"); DropForeignKey("dbo.BookAuthors", "Book_BookId", "dbo.Books"); DropIndex("dbo.BookAuthors", new[] { "Author_AuthorId" }); DropIndex("dbo.BookAuthors", new[] { "Book_BookId" }); DropIndex("dbo.Reviews", new[] { "AuthorId" }); DropIndex("dbo.Reviews", new[] { "BookId" }); DropIndex("dbo.Books", new[] { "ISBN" }); DropIndex("dbo.Authors", new[] { "Name" }); DropTable("dbo.BookAuthors"); DropTable("dbo.Reviews"); DropTable("dbo.Books"); DropTable("dbo.Authors"); } } }
40.060241
87
0.444211
[ "MIT" ]
razsilev/TelerikAcademy_Homework
Database/Bookstore and Exam/Bookstore.Data/Migrations/201409071759487_InitialCreate.cs
3,325
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System; using Azure.Core; using Azure.Storage.Queues; using Microsoft.Azure.WebJobs.Extensions.Storage.Common; using Microsoft.Extensions.Azure; using Microsoft.Extensions.Configuration; namespace Microsoft.Azure.WebJobs.Extensions.Storage.Queues { internal class QueueServiceClientProvider : StorageClientProvider<QueueServiceClient, QueueClientOptions> { public QueueServiceClientProvider(IConfiguration configuration, AzureComponentFactory componentFactory, AzureEventSourceLogForwarder logForwarder) : base(configuration, componentFactory, logForwarder) {} protected override QueueServiceClient CreateClientFromConnectionString(string connectionString, QueueClientOptions options) { return new QueueServiceClient(connectionString, options); } protected override QueueServiceClient CreateClientFromTokenCredential(Uri endpointUri, TokenCredential tokenCredential, QueueClientOptions options) { return new QueueServiceClient(endpointUri, tokenCredential, options); } } }
40.827586
155
0.78125
[ "MIT" ]
AWESOME-S-MINDSET/azure-sdk-for-net
sdk/storage/Microsoft.Azure.WebJobs.Extensions.Storage.Queues/src/QueueServiceClientProvider.cs
1,186
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; namespace SimpleTetris.Core2.Graphics { /// <summary> /// Whether a sprite takes an entire area or a portion of a <see cref="Texture2D"/> to be its texture. /// </summary> public enum SpriteModes { Single, Multiple } }
24.666667
106
0.702703
[ "MIT" ]
quachtridat/tetris-monogame
Core2/Graphics/SpriteMode.cs
446
C#
using System; using System.Collections.Generic; using System.Diagnostics; using System.Drawing; using System.Drawing.Drawing2D; using System.Linq; namespace Svg { [SvgElement("linearGradient")] public sealed class SvgLinearGradientServer : SvgGradientServer { [SvgAttribute("x1")] public SvgUnit X1 { get { return this.Attributes.GetAttribute<SvgUnit>("x1"); } set { Attributes["x1"] = value; } } [SvgAttribute("y1")] public SvgUnit Y1 { get { return this.Attributes.GetAttribute<SvgUnit>("y1"); } set { this.Attributes["y1"] = value; } } [SvgAttribute("x2")] public SvgUnit X2 { get { return this.Attributes.GetAttribute<SvgUnit>("x2"); } set { Attributes["x2"] = value; } } [SvgAttribute("y2")] public SvgUnit Y2 { get { return this.Attributes.GetAttribute<SvgUnit>("y2"); } set { this.Attributes["y2"] = value; } } private bool IsInvalid { get { // Need at least 2 colours to do the gradient fill return this.Stops.Count < 2; } } public SvgLinearGradientServer() { X1 = new SvgUnit(SvgUnitType.Percentage, 0F); Y1 = new SvgUnit(SvgUnitType.Percentage, 0F); X2 = new SvgUnit(SvgUnitType.Percentage, 100F); Y2 = new SvgUnit(SvgUnitType.Percentage, 0F); } public override Brush GetBrush(SvgVisualElement renderingElement, ISvgRenderer renderer, float opacity, bool forStroke = false) { LoadStops(renderingElement); if (this.Stops.Count < 1) return null; if (this.Stops.Count == 1) { var stopColor = this.Stops[0].GetColor(renderingElement); int alpha = (int)Math.Round((opacity * (stopColor.A/255.0f) ) * 255); Color colour = System.Drawing.Color.FromArgb(alpha, stopColor); return new SolidBrush(colour); } try { if (this.GradientUnits == SvgCoordinateUnits.ObjectBoundingBox) renderer.SetBoundable(renderingElement); var points = new PointF[] { SvgUnit.GetDevicePoint(NormalizeUnit(this.X1), NormalizeUnit(this.Y1), renderer, this), SvgUnit.GetDevicePoint(NormalizeUnit(this.X2), NormalizeUnit(this.Y2), renderer, this) }; var bounds = renderer.GetBoundable().Bounds; if (bounds.Width <= 0 || bounds.Height <= 0 || ((points[0].X == points[1].X) && (points[0].Y == points[1].Y))) { if (this.GetCallback != null) return GetCallback().GetBrush(renderingElement, renderer, opacity, forStroke); return null; } using (var transform = EffectiveGradientTransform) { var midPoint = new PointF((points[0].X + points[1].X) / 2, (points[0].Y + points[1].Y) / 2); transform.Translate(bounds.X, bounds.Y, MatrixOrder.Prepend); if (this.GradientUnits == SvgCoordinateUnits.ObjectBoundingBox) { // Transform a normal (i.e. perpendicular line) according to the transform transform.Scale(bounds.Width, bounds.Height, MatrixOrder.Prepend); transform.RotateAt(-90.0f, midPoint, MatrixOrder.Prepend); } transform.TransformPoints(points); } if (this.GradientUnits == SvgCoordinateUnits.ObjectBoundingBox) { // Transform the normal line back to a line such that the gradient still starts in the correct corners, but // has the proper normal vector based on the transforms. If you work out the geometry, these formulas should work. var midPoint = new PointF((points[0].X + points[1].X) / 2, (points[0].Y + points[1].Y) / 2); var dy = (points[1].Y - points[0].Y); var dx = (points[1].X - points[0].X); var x2 = points[0].X; var y2 = points[1].Y; if (Math.Round(dx, 4) == 0) { points[0] = new PointF(midPoint.X + dy / 2 * bounds.Width / bounds.Height, midPoint.Y); points[1] = new PointF(midPoint.X - dy / 2 * bounds.Width / bounds.Height, midPoint.Y); } else if (Math.Round(dy, 4) == 0) { points[0] = new PointF(midPoint.X, midPoint.Y - dx / 2 * bounds.Height / bounds.Width); points[1] = new PointF(midPoint.X, midPoint.Y + dx / 2 * bounds.Height / bounds.Width); ; } else { var startX = (float)((dy * dx * (midPoint.Y - y2) + Math.Pow(dx, 2) * midPoint.X + Math.Pow(dy, 2) * x2) / (Math.Pow(dx, 2) + Math.Pow(dy, 2))); var startY = dy * (startX - x2) / dx + y2; points[0] = new PointF(startX, startY); points[1] = new PointF(midPoint.X + (midPoint.X - startX), midPoint.Y + (midPoint.Y - startY)); } } var effectiveStart = points[0]; var effectiveEnd = points[1]; if (PointsToMove(renderingElement, points[0], points[1]) > LinePoints.None) { var expansion = ExpandGradient(renderingElement, points[0], points[1]); effectiveStart = expansion.StartPoint; effectiveEnd = expansion.EndPoint; } var result = new LinearGradientBrush(effectiveStart, effectiveEnd, System.Drawing.Color.Transparent, System.Drawing.Color.Transparent) { InterpolationColors = CalculateColorBlend(renderer, opacity, points[0], effectiveStart, points[1], effectiveEnd), WrapMode = WrapMode.TileFlipX }; return result; } finally { if (this.GradientUnits == SvgCoordinateUnits.ObjectBoundingBox) renderer.PopBoundable(); } } private SvgUnit NormalizeUnit(SvgUnit orig) { return (orig.Type == SvgUnitType.Percentage && this.GradientUnits == SvgCoordinateUnits.ObjectBoundingBox ? new SvgUnit(SvgUnitType.User, orig.Value / 100) : orig); } [Flags] private enum LinePoints { None = 0, Start = 1, End = 2 } private LinePoints PointsToMove(ISvgBoundable boundable, PointF specifiedStart, PointF specifiedEnd) { var bounds = boundable.Bounds; if (specifiedStart.X == specifiedEnd.X) { return (bounds.Top < specifiedStart.Y && specifiedStart.Y < bounds.Bottom ? LinePoints.Start : LinePoints.None) | (bounds.Top < specifiedEnd.Y && specifiedEnd.Y < bounds.Bottom ? LinePoints.End : LinePoints.None); } else if (specifiedStart.Y == specifiedEnd.Y) { return (bounds.Left < specifiedStart.X && specifiedStart.X < bounds.Right ? LinePoints.Start : LinePoints.None) | (bounds.Left < specifiedEnd.X && specifiedEnd.X < bounds.Right ? LinePoints.End : LinePoints.None); } return (boundable.Bounds.Contains(specifiedStart) ? LinePoints.Start : LinePoints.None) | (boundable.Bounds.Contains(specifiedEnd) ? LinePoints.End : LinePoints.None); } public struct GradientPoints { public PointF StartPoint; public PointF EndPoint; public GradientPoints(PointF startPoint, PointF endPoint) { this.StartPoint = startPoint; this.EndPoint = endPoint; } } private GradientPoints ExpandGradient(ISvgBoundable boundable, PointF specifiedStart, PointF specifiedEnd) { var pointsToMove = PointsToMove(boundable, specifiedStart, specifiedEnd); if (pointsToMove == LinePoints.None) { Debug.Fail("Unexpectedly expanding gradient when not needed!"); return new GradientPoints(specifiedStart, specifiedEnd); } var bounds = boundable.Bounds; var effectiveStart = specifiedStart; var effectiveEnd = specifiedEnd; var intersectionPoints = CandidateIntersections(bounds, specifiedStart, specifiedEnd); Debug.Assert(intersectionPoints.Count == 2, "Unanticipated number of intersection points"); if (!(Math.Sign(intersectionPoints[1].X - intersectionPoints[0].X) == Math.Sign(specifiedEnd.X - specifiedStart.X) && Math.Sign(intersectionPoints[1].Y - intersectionPoints[0].Y) == Math.Sign(specifiedEnd.Y - specifiedStart.Y))) { intersectionPoints = intersectionPoints.Reverse().ToList(); } if ((pointsToMove & LinePoints.Start) > 0) effectiveStart = intersectionPoints[0]; if ((pointsToMove & LinePoints.End) > 0) effectiveEnd = intersectionPoints[1]; switch (SpreadMethod) { case SvgGradientSpreadMethod.Reflect: case SvgGradientSpreadMethod.Repeat: var specifiedLength = CalculateDistance(specifiedStart, specifiedEnd); var specifiedUnitVector = new PointF((specifiedEnd.X - specifiedStart.X) / (float)specifiedLength, (specifiedEnd.Y - specifiedStart.Y) / (float)specifiedLength); var oppUnitVector = new PointF(-specifiedUnitVector.X, -specifiedUnitVector.Y); var startExtend = (float)(Math.Ceiling(CalculateDistance(effectiveStart, specifiedStart) / specifiedLength) * specifiedLength); effectiveStart = MovePointAlongVector(specifiedStart, oppUnitVector, startExtend); var endExtend = (float)(Math.Ceiling(CalculateDistance(effectiveEnd, specifiedEnd) / specifiedLength) * specifiedLength); effectiveEnd = MovePointAlongVector(specifiedEnd, specifiedUnitVector, endExtend); break; } return new GradientPoints(effectiveStart, effectiveEnd); } private IList<PointF> CandidateIntersections(RectangleF bounds, PointF p1, PointF p2) { var results = new List<PointF>(); if (Math.Round(Math.Abs(p1.Y - p2.Y), 4) == 0) { results.Add(new PointF(bounds.Left, p1.Y)); results.Add(new PointF(bounds.Right, p1.Y)); } else if (Math.Round(Math.Abs(p1.X - p2.X), 4) == 0) { results.Add(new PointF(p1.X, bounds.Top)); results.Add(new PointF(p1.X, bounds.Bottom)); } else { PointF candidate; // Save some effort and duplication in the trivial case if ((p1.X == bounds.Left || p1.X == bounds.Right) && (p1.Y == bounds.Top || p1.Y == bounds.Bottom)) { results.Add(p1); } else { candidate = new PointF(bounds.Left, (p2.Y - p1.Y) / (p2.X - p1.X) * (bounds.Left - p1.X) + p1.Y); if (bounds.Top <= candidate.Y && candidate.Y <= bounds.Bottom) results.Add(candidate); candidate = new PointF(bounds.Right, (p2.Y - p1.Y) / (p2.X - p1.X) * (bounds.Right - p1.X) + p1.Y); if (bounds.Top <= candidate.Y && candidate.Y <= bounds.Bottom) results.Add(candidate); } if ((p2.X == bounds.Left || p2.X == bounds.Right) && (p2.Y == bounds.Top || p2.Y == bounds.Bottom)) { results.Add(p2); } else { candidate = new PointF((bounds.Top - p1.Y) / (p2.Y - p1.Y) * (p2.X - p1.X) + p1.X, bounds.Top); if (bounds.Left <= candidate.X && candidate.X <= bounds.Right) results.Add(candidate); candidate = new PointF((bounds.Bottom - p1.Y) / (p2.Y - p1.Y) * (p2.X - p1.X) + p1.X, bounds.Bottom); if (bounds.Left <= candidate.X && candidate.X <= bounds.Right) results.Add(candidate); } } return results; } private ColorBlend CalculateColorBlend(ISvgRenderer renderer, float opacity, PointF specifiedStart, PointF effectiveStart, PointF specifiedEnd, PointF effectiveEnd) { float startExtend; float endExtend; List<Color> colors; List<float> positions; var colorBlend = GetColorBlend(renderer, opacity, false); var startDelta = CalculateDistance(specifiedStart, effectiveStart); var endDelta = CalculateDistance(specifiedEnd, effectiveEnd); if (!(startDelta > 0) && !(endDelta > 0)) { return colorBlend; } var specifiedLength = CalculateDistance(specifiedStart, specifiedEnd); var specifiedUnitVector = new PointF((specifiedEnd.X - specifiedStart.X) / (float)specifiedLength, (specifiedEnd.Y - specifiedStart.Y) / (float)specifiedLength); var effectiveLength = CalculateDistance(effectiveStart, effectiveEnd); switch (SpreadMethod) { case SvgGradientSpreadMethod.Reflect: startExtend = (float)(Math.Ceiling(CalculateDistance(effectiveStart, specifiedStart) / specifiedLength)); endExtend = (float)(Math.Ceiling(CalculateDistance(effectiveEnd, specifiedEnd) / specifiedLength)); colors = colorBlend.Colors.ToList(); positions = (from p in colorBlend.Positions select p + startExtend).ToList(); for (var i = 0; i < startExtend; i++) { if (i % 2 == 0) { for (var j = 1; j < colorBlend.Positions.Length; j++) { positions.Insert(0, (float)((startExtend - 1 - i) + 1 - colorBlend.Positions[j])); colors.Insert(0, colorBlend.Colors[j]); } } else { for (var j = 0; j < colorBlend.Positions.Length - 1; j++) { positions.Insert(j, (float)((startExtend - 1 - i) + colorBlend.Positions[j])); colors.Insert(j, colorBlend.Colors[j]); } } } int insertPos; for (var i = 0; i < endExtend; i++) { if (i % 2 == 0) { insertPos = positions.Count; for (var j = 0; j < colorBlend.Positions.Length - 1; j++) { positions.Insert(insertPos, (float)((startExtend + 1 + i) + 1 - colorBlend.Positions[j])); colors.Insert(insertPos, colorBlend.Colors[j]); } } else { for (var j = 1; j < colorBlend.Positions.Length; j++) { positions.Add((float)((startExtend + 1 + i) + colorBlend.Positions[j])); colors.Add(colorBlend.Colors[j]); } } } colorBlend.Colors = colors.ToArray(); colorBlend.Positions = (from p in positions select p / (startExtend + 1 + endExtend)).ToArray(); break; case SvgGradientSpreadMethod.Repeat: startExtend = (float)(Math.Ceiling(CalculateDistance(effectiveStart, specifiedStart) / specifiedLength)); endExtend = (float)(Math.Ceiling(CalculateDistance(effectiveEnd, specifiedEnd) / specifiedLength)); colors = new List<Color>(); positions = new List<float>(); for (int i = 0; i < startExtend + endExtend + 1; i++) { for (int j = 0; j < colorBlend.Positions.Length; j++) { positions.Add((i + colorBlend.Positions[j] * 0.9999f) / (startExtend + endExtend + 1)); colors.Add(colorBlend.Colors[j]); } } positions[positions.Count - 1] = 1.0f; colorBlend.Colors = colors.ToArray(); colorBlend.Positions = positions.ToArray(); break; default: for (var i = 0; i < colorBlend.Positions.Length; i++) { var originalPoint = MovePointAlongVector(specifiedStart, specifiedUnitVector, (float)specifiedLength * colorBlend.Positions[i]); var distanceFromEffectiveStart = CalculateDistance(effectiveStart, originalPoint); colorBlend.Positions[i] = (float)Math.Round(Math.Max(0F, Math.Min((distanceFromEffectiveStart / effectiveLength), 1.0F)), 5); } if (startDelta > 0) { colorBlend.Positions = new[] { 0F }.Concat(colorBlend.Positions).ToArray(); colorBlend.Colors = new[] { colorBlend.Colors.First() }.Concat(colorBlend.Colors).ToArray(); } if (endDelta > 0) { colorBlend.Positions = colorBlend.Positions.Concat(new[] { 1F }).ToArray(); colorBlend.Colors = colorBlend.Colors.Concat(new[] { colorBlend.Colors.Last() }).ToArray(); } break; } return colorBlend; } private static PointF CalculateClosestIntersectionPoint(PointF sourcePoint, IList<PointF> targetPoints) { Debug.Assert(targetPoints.Count == 2, "Unexpected number of intersection points!"); return CalculateDistance(sourcePoint, targetPoints[0]) < CalculateDistance(sourcePoint, targetPoints[1]) ? targetPoints[0] : targetPoints[1]; } private static PointF MovePointAlongVector(PointF start, PointF unitVector, float distance) { return start + new SizeF(unitVector.X * distance, unitVector.Y * distance); } public override SvgElement DeepCopy() { return DeepCopy<SvgLinearGradientServer>(); } public override SvgElement DeepCopy<T>() { var newObj = base.DeepCopy<T>() as SvgLinearGradientServer; newObj.X1 = this.X1; newObj.Y1 = this.Y1; newObj.X2 = this.X2; newObj.Y2 = this.Y2; return newObj; } private sealed class LineF { private float X1 { get; set; } private float Y1 { get; set; } private float X2 { get; set; } private float Y2 { get; set; } public LineF(float x1, float y1, float x2, float y2) { X1 = x1; Y1 = y1; X2 = x2; Y2 = y2; } public List<PointF> Intersection(RectangleF rectangle) { var result = new List<PointF>(); AddIfIntersect(this, new LineF(rectangle.X, rectangle.Y, rectangle.Right, rectangle.Y), result); AddIfIntersect(this, new LineF(rectangle.Right, rectangle.Y, rectangle.Right, rectangle.Bottom), result); AddIfIntersect(this, new LineF(rectangle.Right, rectangle.Bottom, rectangle.X, rectangle.Bottom), result); AddIfIntersect(this, new LineF(rectangle.X, rectangle.Bottom, rectangle.X, rectangle.Y), result); return result; } /// <remarks>http://community.topcoder.com/tc?module=Static&amp;d1=tutorials&amp;d2=geometry2</remarks> private PointF? Intersection(LineF other) { const int precision = 8; var a1 = (double)Y2 - Y1; var b1 = (double)X1 - X2; var c1 = a1 * X1 + b1 * Y1; var a2 = (double)other.Y2 - other.Y1; var b2 = (double)other.X1 - other.X2; var c2 = a2 * other.X1 + b2 * other.Y1; var det = a1 * b2 - a2 * b1; if (det == 0) { return null; } else { var xi = (b2 * c1 - b1 * c2) / det; var yi = (a1 * c2 - a2 * c1) / det; if (Math.Round(Math.Min(X1, X2), precision) <= Math.Round(xi, precision) && Math.Round(xi, precision) <= Math.Round(Math.Max(X1, X2), precision) && Math.Round(Math.Min(Y1, Y2), precision) <= Math.Round(yi, precision) && Math.Round(yi, precision) <= Math.Round(Math.Max(Y1, Y2), precision) && Math.Round(Math.Min(other.X1, other.X2), precision) <= Math.Round(xi, precision) && Math.Round(xi, precision) <= Math.Round(Math.Max(other.X1, other.X2), precision) && Math.Round(Math.Min(other.Y1, other.Y2), precision) <= Math.Round(yi, precision) && Math.Round(yi, precision) <= Math.Round(Math.Max(other.Y1, other.Y2), precision)) { return new PointF((float)xi, (float)yi); } else { return null; } } } private static void AddIfIntersect(LineF first, LineF second, ICollection<PointF> result) { var intersection = first.Intersection(second); if (intersection != null) { result.Add(intersection.Value); } } } } }
42.832734
181
0.49767
[ "MIT" ]
4vz/jovice
Aphysoft.Share/External/SVG/Painting/SvgLinearGradientServer.cs
23,815
C#
// <auto-generated /> using System; using Kanban.Models; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Migrations; using Microsoft.EntityFrameworkCore.Storage.ValueConversion; namespace Kanban.Migrations { [DbContext(typeof(KanbanContext))] [Migration("20200329231231_newnew")] partial class newnew { protected override void BuildTargetModel(ModelBuilder modelBuilder) { #pragma warning disable 612, 618 modelBuilder .HasAnnotation("ProductVersion", "2.2.4-servicing-10062") .HasAnnotation("Relational:MaxIdentifierLength", 64); modelBuilder.Entity("Kanban.Models.Manager", b => { b.Property<int>("ManagerId") .ValueGeneratedOnAdd(); b.Property<string>("ContactInfo"); b.Property<bool>("CurrentStatus"); b.Property<string>("Name"); b.Property<string>("Position"); b.Property<DateTime>("RegisteredDate"); b.HasKey("ManagerId"); b.ToTable("Managers"); }); modelBuilder.Entity("Kanban.Models.Project", b => { b.Property<int>("ProjectId") .ValueGeneratedOnAdd(); b.Property<bool>("ActiveStatus"); b.Property<string>("Content"); b.Property<DateTime>("DueDate"); b.Property<DateTime>("KickOffDate"); b.Property<string>("ProjectName"); b.HasKey("ProjectId"); b.ToTable("Projects"); }); modelBuilder.Entity("Kanban.Models.ProjectManager", b => { b.Property<int>("ProjectManagerId") .ValueGeneratedOnAdd(); b.Property<int>("ManagerId"); b.Property<int>("ProjectId"); b.HasKey("ProjectManagerId"); b.HasIndex("ManagerId"); b.HasIndex("ProjectId"); b.ToTable("ProjectManagers"); }); modelBuilder.Entity("Kanban.Models.Status", b => { b.Property<int>("StatusId") .ValueGeneratedOnAdd(); b.Property<string>("StatusName"); b.HasKey("StatusId"); b.ToTable("Statuses"); b.HasData( new { StatusId = 1, StatusName = "Idea" }, new { StatusId = 2, StatusName = "ToDo" }, new { StatusId = 3, StatusName = "Doing" }, new { StatusId = 4, StatusName = "Done" }); }); modelBuilder.Entity("Kanban.Models.ToDoList", b => { b.Property<int>("ToDoListId") .ValueGeneratedOnAdd(); b.Property<bool>("CheckCompletion"); b.Property<string>("Content"); b.Property<string>("Name"); b.Property<int>("Priority"); b.Property<int>("ProjectId"); b.Property<int>("StatusId"); b.HasKey("ToDoListId"); b.HasIndex("ProjectId"); b.HasIndex("StatusId"); b.ToTable("ToDoLists"); }); modelBuilder.Entity("Kanban.Models.ProjectManager", b => { b.HasOne("Kanban.Models.Manager", "Manager") .WithMany("Projects") .HasForeignKey("ManagerId") .OnDelete(DeleteBehavior.Cascade); b.HasOne("Kanban.Models.Project", "Project") .WithMany("Managers") .HasForeignKey("ProjectId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Kanban.Models.ToDoList", b => { b.HasOne("Kanban.Models.Project", "Project") .WithMany("ToDoLists") .HasForeignKey("ProjectId") .OnDelete(DeleteBehavior.Cascade); b.HasOne("Kanban.Models.Status", "Status") .WithMany("ToDoLists") .HasForeignKey("StatusId") .OnDelete(DeleteBehavior.Cascade); }); #pragma warning restore 612, 618 } } }
30.846154
75
0.427009
[ "MIT" ]
jiwon-seattle/Kanban.Solution
Kanban/Migrations/20200329231231_newnew.Designer.cs
5,215
C#
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace Test { /// <summary> /// WPFMenuBaseTest.xaml の相互作用ロジック /// </summary> public partial class WPFMenuBaseTestControl : UserControl, ICommand { public WPFMenuBaseTestControl() { InitializeComponent(); if (CanExecuteChanged != null) { CanExecuteChanged.ToString(); } _menu.ItemsSource = new MenuItemsDefine().ItemData; } public bool CanExecute(object parameter) { return true; } public event EventHandler CanExecuteChanged; string executeCommand; public void Execute(object parameter) { executeCommand = parameter.ToString(); } } public class ItemData : ObservableCollection<ItemData> { public ItemData() { } public ItemData(string name) { Name = name; } public string Name { get; set; } public string Command { get { return Name; } } public ItemData Children { get; set; } public override string ToString() { return Name; } } public class MenuItemsDefine { public ItemData ItemData { get; set; } public MenuItemsDefine() { ItemData = new ItemData() { new ItemData("0") { Children = new ItemData { new ItemData("0-0") { Children = new ItemData { new ItemData("0-0-0"), new ItemData("0-0-1"), new ItemData("0-0-2"), new ItemData("0-0-3"), } }, new ItemData("0-1"), new ItemData("0-2") } }, new ItemData("1") { Children = new ItemData { new ItemData("1-0") { Children = new ItemData { new ItemData("1-0-0"), new ItemData("1-0-1"), new ItemData("1-0-2"), new ItemData("1-0-3"), } }, new ItemData("1-1"), new ItemData("1-2"), new ItemData("1-3"), new ItemData("1-4"), } } }; } } }
27.333333
71
0.471206
[ "Apache-2.0" ]
Roommetro/Friendly.WPFStandardControls
Project/Test/WPFMenuBaseTestControl.xaml.cs
2,972
C#
// <auto-generated> // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/pubsub/v1/pubsub.proto // </auto-generated> // Original file comments: // Copyright 2018 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 // // 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. // // #pragma warning disable 1591 #region Designer generated code using grpc = global::Grpc.Core; namespace Google.Cloud.PubSub.V1 { /// <summary> /// The service that an application uses to manipulate topics, and to send /// messages to a topic. /// </summary> public static partial class Publisher { static readonly string __ServiceName = "google.pubsub.v1.Publisher"; static readonly grpc::Marshaller<global::Google.Cloud.PubSub.V1.Topic> __Marshaller_Topic = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.PubSub.V1.Topic.Parser.ParseFrom); static readonly grpc::Marshaller<global::Google.Cloud.PubSub.V1.UpdateTopicRequest> __Marshaller_UpdateTopicRequest = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.PubSub.V1.UpdateTopicRequest.Parser.ParseFrom); static readonly grpc::Marshaller<global::Google.Cloud.PubSub.V1.PublishRequest> __Marshaller_PublishRequest = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.PubSub.V1.PublishRequest.Parser.ParseFrom); static readonly grpc::Marshaller<global::Google.Cloud.PubSub.V1.PublishResponse> __Marshaller_PublishResponse = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.PubSub.V1.PublishResponse.Parser.ParseFrom); static readonly grpc::Marshaller<global::Google.Cloud.PubSub.V1.GetTopicRequest> __Marshaller_GetTopicRequest = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.PubSub.V1.GetTopicRequest.Parser.ParseFrom); static readonly grpc::Marshaller<global::Google.Cloud.PubSub.V1.ListTopicsRequest> __Marshaller_ListTopicsRequest = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.PubSub.V1.ListTopicsRequest.Parser.ParseFrom); static readonly grpc::Marshaller<global::Google.Cloud.PubSub.V1.ListTopicsResponse> __Marshaller_ListTopicsResponse = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.PubSub.V1.ListTopicsResponse.Parser.ParseFrom); static readonly grpc::Marshaller<global::Google.Cloud.PubSub.V1.ListTopicSubscriptionsRequest> __Marshaller_ListTopicSubscriptionsRequest = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.PubSub.V1.ListTopicSubscriptionsRequest.Parser.ParseFrom); static readonly grpc::Marshaller<global::Google.Cloud.PubSub.V1.ListTopicSubscriptionsResponse> __Marshaller_ListTopicSubscriptionsResponse = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.PubSub.V1.ListTopicSubscriptionsResponse.Parser.ParseFrom); static readonly grpc::Marshaller<global::Google.Cloud.PubSub.V1.ListTopicSnapshotsRequest> __Marshaller_ListTopicSnapshotsRequest = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.PubSub.V1.ListTopicSnapshotsRequest.Parser.ParseFrom); static readonly grpc::Marshaller<global::Google.Cloud.PubSub.V1.ListTopicSnapshotsResponse> __Marshaller_ListTopicSnapshotsResponse = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.PubSub.V1.ListTopicSnapshotsResponse.Parser.ParseFrom); static readonly grpc::Marshaller<global::Google.Cloud.PubSub.V1.DeleteTopicRequest> __Marshaller_DeleteTopicRequest = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.PubSub.V1.DeleteTopicRequest.Parser.ParseFrom); static readonly grpc::Marshaller<global::Google.Protobuf.WellKnownTypes.Empty> __Marshaller_Empty = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Protobuf.WellKnownTypes.Empty.Parser.ParseFrom); static readonly grpc::Method<global::Google.Cloud.PubSub.V1.Topic, global::Google.Cloud.PubSub.V1.Topic> __Method_CreateTopic = new grpc::Method<global::Google.Cloud.PubSub.V1.Topic, global::Google.Cloud.PubSub.V1.Topic>( grpc::MethodType.Unary, __ServiceName, "CreateTopic", __Marshaller_Topic, __Marshaller_Topic); static readonly grpc::Method<global::Google.Cloud.PubSub.V1.UpdateTopicRequest, global::Google.Cloud.PubSub.V1.Topic> __Method_UpdateTopic = new grpc::Method<global::Google.Cloud.PubSub.V1.UpdateTopicRequest, global::Google.Cloud.PubSub.V1.Topic>( grpc::MethodType.Unary, __ServiceName, "UpdateTopic", __Marshaller_UpdateTopicRequest, __Marshaller_Topic); static readonly grpc::Method<global::Google.Cloud.PubSub.V1.PublishRequest, global::Google.Cloud.PubSub.V1.PublishResponse> __Method_Publish = new grpc::Method<global::Google.Cloud.PubSub.V1.PublishRequest, global::Google.Cloud.PubSub.V1.PublishResponse>( grpc::MethodType.Unary, __ServiceName, "Publish", __Marshaller_PublishRequest, __Marshaller_PublishResponse); static readonly grpc::Method<global::Google.Cloud.PubSub.V1.GetTopicRequest, global::Google.Cloud.PubSub.V1.Topic> __Method_GetTopic = new grpc::Method<global::Google.Cloud.PubSub.V1.GetTopicRequest, global::Google.Cloud.PubSub.V1.Topic>( grpc::MethodType.Unary, __ServiceName, "GetTopic", __Marshaller_GetTopicRequest, __Marshaller_Topic); static readonly grpc::Method<global::Google.Cloud.PubSub.V1.ListTopicsRequest, global::Google.Cloud.PubSub.V1.ListTopicsResponse> __Method_ListTopics = new grpc::Method<global::Google.Cloud.PubSub.V1.ListTopicsRequest, global::Google.Cloud.PubSub.V1.ListTopicsResponse>( grpc::MethodType.Unary, __ServiceName, "ListTopics", __Marshaller_ListTopicsRequest, __Marshaller_ListTopicsResponse); static readonly grpc::Method<global::Google.Cloud.PubSub.V1.ListTopicSubscriptionsRequest, global::Google.Cloud.PubSub.V1.ListTopicSubscriptionsResponse> __Method_ListTopicSubscriptions = new grpc::Method<global::Google.Cloud.PubSub.V1.ListTopicSubscriptionsRequest, global::Google.Cloud.PubSub.V1.ListTopicSubscriptionsResponse>( grpc::MethodType.Unary, __ServiceName, "ListTopicSubscriptions", __Marshaller_ListTopicSubscriptionsRequest, __Marshaller_ListTopicSubscriptionsResponse); static readonly grpc::Method<global::Google.Cloud.PubSub.V1.ListTopicSnapshotsRequest, global::Google.Cloud.PubSub.V1.ListTopicSnapshotsResponse> __Method_ListTopicSnapshots = new grpc::Method<global::Google.Cloud.PubSub.V1.ListTopicSnapshotsRequest, global::Google.Cloud.PubSub.V1.ListTopicSnapshotsResponse>( grpc::MethodType.Unary, __ServiceName, "ListTopicSnapshots", __Marshaller_ListTopicSnapshotsRequest, __Marshaller_ListTopicSnapshotsResponse); static readonly grpc::Method<global::Google.Cloud.PubSub.V1.DeleteTopicRequest, global::Google.Protobuf.WellKnownTypes.Empty> __Method_DeleteTopic = new grpc::Method<global::Google.Cloud.PubSub.V1.DeleteTopicRequest, global::Google.Protobuf.WellKnownTypes.Empty>( grpc::MethodType.Unary, __ServiceName, "DeleteTopic", __Marshaller_DeleteTopicRequest, __Marshaller_Empty); /// <summary>Service descriptor</summary> public static global::Google.Protobuf.Reflection.ServiceDescriptor Descriptor { get { return global::Google.Cloud.PubSub.V1.PubsubReflection.Descriptor.Services[0]; } } /// <summary>Base class for server-side implementations of Publisher</summary> public abstract partial class PublisherBase { /// <summary> /// Creates the given topic with the given name. See the /// &lt;a href="https://cloud.google.com/pubsub/docs/admin#resource_names"> /// resource name rules&lt;/a>. /// </summary> /// <param name="request">The request received from the client.</param> /// <param name="context">The context of the server-side call handler being invoked.</param> /// <returns>The response to send back to the client (wrapped by a task).</returns> public virtual global::System.Threading.Tasks.Task<global::Google.Cloud.PubSub.V1.Topic> CreateTopic(global::Google.Cloud.PubSub.V1.Topic request, grpc::ServerCallContext context) { throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); } /// <summary> /// Updates an existing topic. Note that certain properties of a /// topic are not modifiable. /// </summary> /// <param name="request">The request received from the client.</param> /// <param name="context">The context of the server-side call handler being invoked.</param> /// <returns>The response to send back to the client (wrapped by a task).</returns> public virtual global::System.Threading.Tasks.Task<global::Google.Cloud.PubSub.V1.Topic> UpdateTopic(global::Google.Cloud.PubSub.V1.UpdateTopicRequest request, grpc::ServerCallContext context) { throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); } /// <summary> /// Adds one or more messages to the topic. Returns `NOT_FOUND` if the topic /// does not exist. /// </summary> /// <param name="request">The request received from the client.</param> /// <param name="context">The context of the server-side call handler being invoked.</param> /// <returns>The response to send back to the client (wrapped by a task).</returns> public virtual global::System.Threading.Tasks.Task<global::Google.Cloud.PubSub.V1.PublishResponse> Publish(global::Google.Cloud.PubSub.V1.PublishRequest request, grpc::ServerCallContext context) { throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); } /// <summary> /// Gets the configuration of a topic. /// </summary> /// <param name="request">The request received from the client.</param> /// <param name="context">The context of the server-side call handler being invoked.</param> /// <returns>The response to send back to the client (wrapped by a task).</returns> public virtual global::System.Threading.Tasks.Task<global::Google.Cloud.PubSub.V1.Topic> GetTopic(global::Google.Cloud.PubSub.V1.GetTopicRequest request, grpc::ServerCallContext context) { throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); } /// <summary> /// Lists matching topics. /// </summary> /// <param name="request">The request received from the client.</param> /// <param name="context">The context of the server-side call handler being invoked.</param> /// <returns>The response to send back to the client (wrapped by a task).</returns> public virtual global::System.Threading.Tasks.Task<global::Google.Cloud.PubSub.V1.ListTopicsResponse> ListTopics(global::Google.Cloud.PubSub.V1.ListTopicsRequest request, grpc::ServerCallContext context) { throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); } /// <summary> /// Lists the names of the subscriptions on this topic. /// </summary> /// <param name="request">The request received from the client.</param> /// <param name="context">The context of the server-side call handler being invoked.</param> /// <returns>The response to send back to the client (wrapped by a task).</returns> public virtual global::System.Threading.Tasks.Task<global::Google.Cloud.PubSub.V1.ListTopicSubscriptionsResponse> ListTopicSubscriptions(global::Google.Cloud.PubSub.V1.ListTopicSubscriptionsRequest request, grpc::ServerCallContext context) { throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); } /// <summary> /// Lists the names of the snapshots on this topic. Snapshots are used in /// &lt;a href="https://cloud.google.com/pubsub/docs/replay-overview">Seek&lt;/a> /// operations, which allow /// you to manage message acknowledgments in bulk. That is, you can set the /// acknowledgment state of messages in an existing subscription to the state /// captured by a snapshot.&lt;br>&lt;br> /// &lt;b>BETA:&lt;/b> This feature is part of a beta release. This API might be /// changed in backward-incompatible ways and is not recommended for production /// use. It is not subject to any SLA or deprecation policy. /// </summary> /// <param name="request">The request received from the client.</param> /// <param name="context">The context of the server-side call handler being invoked.</param> /// <returns>The response to send back to the client (wrapped by a task).</returns> public virtual global::System.Threading.Tasks.Task<global::Google.Cloud.PubSub.V1.ListTopicSnapshotsResponse> ListTopicSnapshots(global::Google.Cloud.PubSub.V1.ListTopicSnapshotsRequest request, grpc::ServerCallContext context) { throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); } /// <summary> /// Deletes the topic with the given name. Returns `NOT_FOUND` if the topic /// does not exist. After a topic is deleted, a new topic may be created with /// the same name; this is an entirely new topic with none of the old /// configuration or subscriptions. Existing subscriptions to this topic are /// not deleted, but their `topic` field is set to `_deleted-topic_`. /// </summary> /// <param name="request">The request received from the client.</param> /// <param name="context">The context of the server-side call handler being invoked.</param> /// <returns>The response to send back to the client (wrapped by a task).</returns> public virtual global::System.Threading.Tasks.Task<global::Google.Protobuf.WellKnownTypes.Empty> DeleteTopic(global::Google.Cloud.PubSub.V1.DeleteTopicRequest request, grpc::ServerCallContext context) { throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); } } /// <summary>Client for Publisher</summary> public partial class PublisherClient : grpc::ClientBase<PublisherClient> { /// <summary>Creates a new client for Publisher</summary> /// <param name="channel">The channel to use to make remote calls.</param> public PublisherClient(grpc::Channel channel) : base(channel) { } /// <summary>Creates a new client for Publisher that uses a custom <c>CallInvoker</c>.</summary> /// <param name="callInvoker">The callInvoker to use to make remote calls.</param> public PublisherClient(grpc::CallInvoker callInvoker) : base(callInvoker) { } /// <summary>Protected parameterless constructor to allow creation of test doubles.</summary> protected PublisherClient() : base() { } /// <summary>Protected constructor to allow creation of configured clients.</summary> /// <param name="configuration">The client configuration.</param> protected PublisherClient(ClientBaseConfiguration configuration) : base(configuration) { } /// <summary> /// Creates the given topic with the given name. See the /// &lt;a href="https://cloud.google.com/pubsub/docs/admin#resource_names"> /// resource name rules&lt;/a>. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Google.Cloud.PubSub.V1.Topic CreateTopic(global::Google.Cloud.PubSub.V1.Topic request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) { return CreateTopic(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Creates the given topic with the given name. See the /// &lt;a href="https://cloud.google.com/pubsub/docs/admin#resource_names"> /// resource name rules&lt;/a>. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Google.Cloud.PubSub.V1.Topic CreateTopic(global::Google.Cloud.PubSub.V1.Topic request, grpc::CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_CreateTopic, null, options, request); } /// <summary> /// Creates the given topic with the given name. See the /// &lt;a href="https://cloud.google.com/pubsub/docs/admin#resource_names"> /// resource name rules&lt;/a>. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Google.Cloud.PubSub.V1.Topic> CreateTopicAsync(global::Google.Cloud.PubSub.V1.Topic request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) { return CreateTopicAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Creates the given topic with the given name. See the /// &lt;a href="https://cloud.google.com/pubsub/docs/admin#resource_names"> /// resource name rules&lt;/a>. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Google.Cloud.PubSub.V1.Topic> CreateTopicAsync(global::Google.Cloud.PubSub.V1.Topic request, grpc::CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_CreateTopic, null, options, request); } /// <summary> /// Updates an existing topic. Note that certain properties of a /// topic are not modifiable. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Google.Cloud.PubSub.V1.Topic UpdateTopic(global::Google.Cloud.PubSub.V1.UpdateTopicRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) { return UpdateTopic(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Updates an existing topic. Note that certain properties of a /// topic are not modifiable. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Google.Cloud.PubSub.V1.Topic UpdateTopic(global::Google.Cloud.PubSub.V1.UpdateTopicRequest request, grpc::CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_UpdateTopic, null, options, request); } /// <summary> /// Updates an existing topic. Note that certain properties of a /// topic are not modifiable. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Google.Cloud.PubSub.V1.Topic> UpdateTopicAsync(global::Google.Cloud.PubSub.V1.UpdateTopicRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) { return UpdateTopicAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Updates an existing topic. Note that certain properties of a /// topic are not modifiable. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Google.Cloud.PubSub.V1.Topic> UpdateTopicAsync(global::Google.Cloud.PubSub.V1.UpdateTopicRequest request, grpc::CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_UpdateTopic, null, options, request); } /// <summary> /// Adds one or more messages to the topic. Returns `NOT_FOUND` if the topic /// does not exist. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Google.Cloud.PubSub.V1.PublishResponse Publish(global::Google.Cloud.PubSub.V1.PublishRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) { return Publish(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Adds one or more messages to the topic. Returns `NOT_FOUND` if the topic /// does not exist. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Google.Cloud.PubSub.V1.PublishResponse Publish(global::Google.Cloud.PubSub.V1.PublishRequest request, grpc::CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_Publish, null, options, request); } /// <summary> /// Adds one or more messages to the topic. Returns `NOT_FOUND` if the topic /// does not exist. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Google.Cloud.PubSub.V1.PublishResponse> PublishAsync(global::Google.Cloud.PubSub.V1.PublishRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) { return PublishAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Adds one or more messages to the topic. Returns `NOT_FOUND` if the topic /// does not exist. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Google.Cloud.PubSub.V1.PublishResponse> PublishAsync(global::Google.Cloud.PubSub.V1.PublishRequest request, grpc::CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_Publish, null, options, request); } /// <summary> /// Gets the configuration of a topic. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Google.Cloud.PubSub.V1.Topic GetTopic(global::Google.Cloud.PubSub.V1.GetTopicRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) { return GetTopic(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Gets the configuration of a topic. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Google.Cloud.PubSub.V1.Topic GetTopic(global::Google.Cloud.PubSub.V1.GetTopicRequest request, grpc::CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_GetTopic, null, options, request); } /// <summary> /// Gets the configuration of a topic. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Google.Cloud.PubSub.V1.Topic> GetTopicAsync(global::Google.Cloud.PubSub.V1.GetTopicRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) { return GetTopicAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Gets the configuration of a topic. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Google.Cloud.PubSub.V1.Topic> GetTopicAsync(global::Google.Cloud.PubSub.V1.GetTopicRequest request, grpc::CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_GetTopic, null, options, request); } /// <summary> /// Lists matching topics. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Google.Cloud.PubSub.V1.ListTopicsResponse ListTopics(global::Google.Cloud.PubSub.V1.ListTopicsRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) { return ListTopics(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Lists matching topics. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Google.Cloud.PubSub.V1.ListTopicsResponse ListTopics(global::Google.Cloud.PubSub.V1.ListTopicsRequest request, grpc::CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_ListTopics, null, options, request); } /// <summary> /// Lists matching topics. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Google.Cloud.PubSub.V1.ListTopicsResponse> ListTopicsAsync(global::Google.Cloud.PubSub.V1.ListTopicsRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) { return ListTopicsAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Lists matching topics. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Google.Cloud.PubSub.V1.ListTopicsResponse> ListTopicsAsync(global::Google.Cloud.PubSub.V1.ListTopicsRequest request, grpc::CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_ListTopics, null, options, request); } /// <summary> /// Lists the names of the subscriptions on this topic. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Google.Cloud.PubSub.V1.ListTopicSubscriptionsResponse ListTopicSubscriptions(global::Google.Cloud.PubSub.V1.ListTopicSubscriptionsRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) { return ListTopicSubscriptions(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Lists the names of the subscriptions on this topic. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Google.Cloud.PubSub.V1.ListTopicSubscriptionsResponse ListTopicSubscriptions(global::Google.Cloud.PubSub.V1.ListTopicSubscriptionsRequest request, grpc::CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_ListTopicSubscriptions, null, options, request); } /// <summary> /// Lists the names of the subscriptions on this topic. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Google.Cloud.PubSub.V1.ListTopicSubscriptionsResponse> ListTopicSubscriptionsAsync(global::Google.Cloud.PubSub.V1.ListTopicSubscriptionsRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) { return ListTopicSubscriptionsAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Lists the names of the subscriptions on this topic. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Google.Cloud.PubSub.V1.ListTopicSubscriptionsResponse> ListTopicSubscriptionsAsync(global::Google.Cloud.PubSub.V1.ListTopicSubscriptionsRequest request, grpc::CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_ListTopicSubscriptions, null, options, request); } /// <summary> /// Lists the names of the snapshots on this topic. Snapshots are used in /// &lt;a href="https://cloud.google.com/pubsub/docs/replay-overview">Seek&lt;/a> /// operations, which allow /// you to manage message acknowledgments in bulk. That is, you can set the /// acknowledgment state of messages in an existing subscription to the state /// captured by a snapshot.&lt;br>&lt;br> /// &lt;b>BETA:&lt;/b> This feature is part of a beta release. This API might be /// changed in backward-incompatible ways and is not recommended for production /// use. It is not subject to any SLA or deprecation policy. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Google.Cloud.PubSub.V1.ListTopicSnapshotsResponse ListTopicSnapshots(global::Google.Cloud.PubSub.V1.ListTopicSnapshotsRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) { return ListTopicSnapshots(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Lists the names of the snapshots on this topic. Snapshots are used in /// &lt;a href="https://cloud.google.com/pubsub/docs/replay-overview">Seek&lt;/a> /// operations, which allow /// you to manage message acknowledgments in bulk. That is, you can set the /// acknowledgment state of messages in an existing subscription to the state /// captured by a snapshot.&lt;br>&lt;br> /// &lt;b>BETA:&lt;/b> This feature is part of a beta release. This API might be /// changed in backward-incompatible ways and is not recommended for production /// use. It is not subject to any SLA or deprecation policy. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Google.Cloud.PubSub.V1.ListTopicSnapshotsResponse ListTopicSnapshots(global::Google.Cloud.PubSub.V1.ListTopicSnapshotsRequest request, grpc::CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_ListTopicSnapshots, null, options, request); } /// <summary> /// Lists the names of the snapshots on this topic. Snapshots are used in /// &lt;a href="https://cloud.google.com/pubsub/docs/replay-overview">Seek&lt;/a> /// operations, which allow /// you to manage message acknowledgments in bulk. That is, you can set the /// acknowledgment state of messages in an existing subscription to the state /// captured by a snapshot.&lt;br>&lt;br> /// &lt;b>BETA:&lt;/b> This feature is part of a beta release. This API might be /// changed in backward-incompatible ways and is not recommended for production /// use. It is not subject to any SLA or deprecation policy. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Google.Cloud.PubSub.V1.ListTopicSnapshotsResponse> ListTopicSnapshotsAsync(global::Google.Cloud.PubSub.V1.ListTopicSnapshotsRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) { return ListTopicSnapshotsAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Lists the names of the snapshots on this topic. Snapshots are used in /// &lt;a href="https://cloud.google.com/pubsub/docs/replay-overview">Seek&lt;/a> /// operations, which allow /// you to manage message acknowledgments in bulk. That is, you can set the /// acknowledgment state of messages in an existing subscription to the state /// captured by a snapshot.&lt;br>&lt;br> /// &lt;b>BETA:&lt;/b> This feature is part of a beta release. This API might be /// changed in backward-incompatible ways and is not recommended for production /// use. It is not subject to any SLA or deprecation policy. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Google.Cloud.PubSub.V1.ListTopicSnapshotsResponse> ListTopicSnapshotsAsync(global::Google.Cloud.PubSub.V1.ListTopicSnapshotsRequest request, grpc::CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_ListTopicSnapshots, null, options, request); } /// <summary> /// Deletes the topic with the given name. Returns `NOT_FOUND` if the topic /// does not exist. After a topic is deleted, a new topic may be created with /// the same name; this is an entirely new topic with none of the old /// configuration or subscriptions. Existing subscriptions to this topic are /// not deleted, but their `topic` field is set to `_deleted-topic_`. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Google.Protobuf.WellKnownTypes.Empty DeleteTopic(global::Google.Cloud.PubSub.V1.DeleteTopicRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) { return DeleteTopic(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Deletes the topic with the given name. Returns `NOT_FOUND` if the topic /// does not exist. After a topic is deleted, a new topic may be created with /// the same name; this is an entirely new topic with none of the old /// configuration or subscriptions. Existing subscriptions to this topic are /// not deleted, but their `topic` field is set to `_deleted-topic_`. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Google.Protobuf.WellKnownTypes.Empty DeleteTopic(global::Google.Cloud.PubSub.V1.DeleteTopicRequest request, grpc::CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_DeleteTopic, null, options, request); } /// <summary> /// Deletes the topic with the given name. Returns `NOT_FOUND` if the topic /// does not exist. After a topic is deleted, a new topic may be created with /// the same name; this is an entirely new topic with none of the old /// configuration or subscriptions. Existing subscriptions to this topic are /// not deleted, but their `topic` field is set to `_deleted-topic_`. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Google.Protobuf.WellKnownTypes.Empty> DeleteTopicAsync(global::Google.Cloud.PubSub.V1.DeleteTopicRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) { return DeleteTopicAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Deletes the topic with the given name. Returns `NOT_FOUND` if the topic /// does not exist. After a topic is deleted, a new topic may be created with /// the same name; this is an entirely new topic with none of the old /// configuration or subscriptions. Existing subscriptions to this topic are /// not deleted, but their `topic` field is set to `_deleted-topic_`. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Google.Protobuf.WellKnownTypes.Empty> DeleteTopicAsync(global::Google.Cloud.PubSub.V1.DeleteTopicRequest request, grpc::CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_DeleteTopic, null, options, request); } /// <summary>Creates a new instance of client from given <c>ClientBaseConfiguration</c>.</summary> protected override PublisherClient NewInstance(ClientBaseConfiguration configuration) { return new PublisherClient(configuration); } } /// <summary>Creates service definition that can be registered with a server</summary> /// <param name="serviceImpl">An object implementing the server-side handling logic.</param> public static grpc::ServerServiceDefinition BindService(PublisherBase serviceImpl) { return grpc::ServerServiceDefinition.CreateBuilder() .AddMethod(__Method_CreateTopic, serviceImpl.CreateTopic) .AddMethod(__Method_UpdateTopic, serviceImpl.UpdateTopic) .AddMethod(__Method_Publish, serviceImpl.Publish) .AddMethod(__Method_GetTopic, serviceImpl.GetTopic) .AddMethod(__Method_ListTopics, serviceImpl.ListTopics) .AddMethod(__Method_ListTopicSubscriptions, serviceImpl.ListTopicSubscriptions) .AddMethod(__Method_ListTopicSnapshots, serviceImpl.ListTopicSnapshots) .AddMethod(__Method_DeleteTopic, serviceImpl.DeleteTopic).Build(); } } /// <summary> /// The service that an application uses to manipulate subscriptions and to /// consume messages from a subscription via the `Pull` method or by /// establishing a bi-directional stream using the `StreamingPull` method. /// </summary> public static partial class Subscriber { static readonly string __ServiceName = "google.pubsub.v1.Subscriber"; static readonly grpc::Marshaller<global::Google.Cloud.PubSub.V1.Subscription> __Marshaller_Subscription = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.PubSub.V1.Subscription.Parser.ParseFrom); static readonly grpc::Marshaller<global::Google.Cloud.PubSub.V1.GetSubscriptionRequest> __Marshaller_GetSubscriptionRequest = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.PubSub.V1.GetSubscriptionRequest.Parser.ParseFrom); static readonly grpc::Marshaller<global::Google.Cloud.PubSub.V1.UpdateSubscriptionRequest> __Marshaller_UpdateSubscriptionRequest = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.PubSub.V1.UpdateSubscriptionRequest.Parser.ParseFrom); static readonly grpc::Marshaller<global::Google.Cloud.PubSub.V1.ListSubscriptionsRequest> __Marshaller_ListSubscriptionsRequest = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.PubSub.V1.ListSubscriptionsRequest.Parser.ParseFrom); static readonly grpc::Marshaller<global::Google.Cloud.PubSub.V1.ListSubscriptionsResponse> __Marshaller_ListSubscriptionsResponse = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.PubSub.V1.ListSubscriptionsResponse.Parser.ParseFrom); static readonly grpc::Marshaller<global::Google.Cloud.PubSub.V1.DeleteSubscriptionRequest> __Marshaller_DeleteSubscriptionRequest = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.PubSub.V1.DeleteSubscriptionRequest.Parser.ParseFrom); static readonly grpc::Marshaller<global::Google.Protobuf.WellKnownTypes.Empty> __Marshaller_Empty = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Protobuf.WellKnownTypes.Empty.Parser.ParseFrom); static readonly grpc::Marshaller<global::Google.Cloud.PubSub.V1.ModifyAckDeadlineRequest> __Marshaller_ModifyAckDeadlineRequest = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.PubSub.V1.ModifyAckDeadlineRequest.Parser.ParseFrom); static readonly grpc::Marshaller<global::Google.Cloud.PubSub.V1.AcknowledgeRequest> __Marshaller_AcknowledgeRequest = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.PubSub.V1.AcknowledgeRequest.Parser.ParseFrom); static readonly grpc::Marshaller<global::Google.Cloud.PubSub.V1.PullRequest> __Marshaller_PullRequest = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.PubSub.V1.PullRequest.Parser.ParseFrom); static readonly grpc::Marshaller<global::Google.Cloud.PubSub.V1.PullResponse> __Marshaller_PullResponse = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.PubSub.V1.PullResponse.Parser.ParseFrom); static readonly grpc::Marshaller<global::Google.Cloud.PubSub.V1.StreamingPullRequest> __Marshaller_StreamingPullRequest = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.PubSub.V1.StreamingPullRequest.Parser.ParseFrom); static readonly grpc::Marshaller<global::Google.Cloud.PubSub.V1.StreamingPullResponse> __Marshaller_StreamingPullResponse = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.PubSub.V1.StreamingPullResponse.Parser.ParseFrom); static readonly grpc::Marshaller<global::Google.Cloud.PubSub.V1.ModifyPushConfigRequest> __Marshaller_ModifyPushConfigRequest = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.PubSub.V1.ModifyPushConfigRequest.Parser.ParseFrom); static readonly grpc::Marshaller<global::Google.Cloud.PubSub.V1.GetSnapshotRequest> __Marshaller_GetSnapshotRequest = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.PubSub.V1.GetSnapshotRequest.Parser.ParseFrom); static readonly grpc::Marshaller<global::Google.Cloud.PubSub.V1.Snapshot> __Marshaller_Snapshot = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.PubSub.V1.Snapshot.Parser.ParseFrom); static readonly grpc::Marshaller<global::Google.Cloud.PubSub.V1.ListSnapshotsRequest> __Marshaller_ListSnapshotsRequest = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.PubSub.V1.ListSnapshotsRequest.Parser.ParseFrom); static readonly grpc::Marshaller<global::Google.Cloud.PubSub.V1.ListSnapshotsResponse> __Marshaller_ListSnapshotsResponse = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.PubSub.V1.ListSnapshotsResponse.Parser.ParseFrom); static readonly grpc::Marshaller<global::Google.Cloud.PubSub.V1.CreateSnapshotRequest> __Marshaller_CreateSnapshotRequest = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.PubSub.V1.CreateSnapshotRequest.Parser.ParseFrom); static readonly grpc::Marshaller<global::Google.Cloud.PubSub.V1.UpdateSnapshotRequest> __Marshaller_UpdateSnapshotRequest = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.PubSub.V1.UpdateSnapshotRequest.Parser.ParseFrom); static readonly grpc::Marshaller<global::Google.Cloud.PubSub.V1.DeleteSnapshotRequest> __Marshaller_DeleteSnapshotRequest = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.PubSub.V1.DeleteSnapshotRequest.Parser.ParseFrom); static readonly grpc::Marshaller<global::Google.Cloud.PubSub.V1.SeekRequest> __Marshaller_SeekRequest = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.PubSub.V1.SeekRequest.Parser.ParseFrom); static readonly grpc::Marshaller<global::Google.Cloud.PubSub.V1.SeekResponse> __Marshaller_SeekResponse = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.PubSub.V1.SeekResponse.Parser.ParseFrom); static readonly grpc::Method<global::Google.Cloud.PubSub.V1.Subscription, global::Google.Cloud.PubSub.V1.Subscription> __Method_CreateSubscription = new grpc::Method<global::Google.Cloud.PubSub.V1.Subscription, global::Google.Cloud.PubSub.V1.Subscription>( grpc::MethodType.Unary, __ServiceName, "CreateSubscription", __Marshaller_Subscription, __Marshaller_Subscription); static readonly grpc::Method<global::Google.Cloud.PubSub.V1.GetSubscriptionRequest, global::Google.Cloud.PubSub.V1.Subscription> __Method_GetSubscription = new grpc::Method<global::Google.Cloud.PubSub.V1.GetSubscriptionRequest, global::Google.Cloud.PubSub.V1.Subscription>( grpc::MethodType.Unary, __ServiceName, "GetSubscription", __Marshaller_GetSubscriptionRequest, __Marshaller_Subscription); static readonly grpc::Method<global::Google.Cloud.PubSub.V1.UpdateSubscriptionRequest, global::Google.Cloud.PubSub.V1.Subscription> __Method_UpdateSubscription = new grpc::Method<global::Google.Cloud.PubSub.V1.UpdateSubscriptionRequest, global::Google.Cloud.PubSub.V1.Subscription>( grpc::MethodType.Unary, __ServiceName, "UpdateSubscription", __Marshaller_UpdateSubscriptionRequest, __Marshaller_Subscription); static readonly grpc::Method<global::Google.Cloud.PubSub.V1.ListSubscriptionsRequest, global::Google.Cloud.PubSub.V1.ListSubscriptionsResponse> __Method_ListSubscriptions = new grpc::Method<global::Google.Cloud.PubSub.V1.ListSubscriptionsRequest, global::Google.Cloud.PubSub.V1.ListSubscriptionsResponse>( grpc::MethodType.Unary, __ServiceName, "ListSubscriptions", __Marshaller_ListSubscriptionsRequest, __Marshaller_ListSubscriptionsResponse); static readonly grpc::Method<global::Google.Cloud.PubSub.V1.DeleteSubscriptionRequest, global::Google.Protobuf.WellKnownTypes.Empty> __Method_DeleteSubscription = new grpc::Method<global::Google.Cloud.PubSub.V1.DeleteSubscriptionRequest, global::Google.Protobuf.WellKnownTypes.Empty>( grpc::MethodType.Unary, __ServiceName, "DeleteSubscription", __Marshaller_DeleteSubscriptionRequest, __Marshaller_Empty); static readonly grpc::Method<global::Google.Cloud.PubSub.V1.ModifyAckDeadlineRequest, global::Google.Protobuf.WellKnownTypes.Empty> __Method_ModifyAckDeadline = new grpc::Method<global::Google.Cloud.PubSub.V1.ModifyAckDeadlineRequest, global::Google.Protobuf.WellKnownTypes.Empty>( grpc::MethodType.Unary, __ServiceName, "ModifyAckDeadline", __Marshaller_ModifyAckDeadlineRequest, __Marshaller_Empty); static readonly grpc::Method<global::Google.Cloud.PubSub.V1.AcknowledgeRequest, global::Google.Protobuf.WellKnownTypes.Empty> __Method_Acknowledge = new grpc::Method<global::Google.Cloud.PubSub.V1.AcknowledgeRequest, global::Google.Protobuf.WellKnownTypes.Empty>( grpc::MethodType.Unary, __ServiceName, "Acknowledge", __Marshaller_AcknowledgeRequest, __Marshaller_Empty); static readonly grpc::Method<global::Google.Cloud.PubSub.V1.PullRequest, global::Google.Cloud.PubSub.V1.PullResponse> __Method_Pull = new grpc::Method<global::Google.Cloud.PubSub.V1.PullRequest, global::Google.Cloud.PubSub.V1.PullResponse>( grpc::MethodType.Unary, __ServiceName, "Pull", __Marshaller_PullRequest, __Marshaller_PullResponse); static readonly grpc::Method<global::Google.Cloud.PubSub.V1.StreamingPullRequest, global::Google.Cloud.PubSub.V1.StreamingPullResponse> __Method_StreamingPull = new grpc::Method<global::Google.Cloud.PubSub.V1.StreamingPullRequest, global::Google.Cloud.PubSub.V1.StreamingPullResponse>( grpc::MethodType.DuplexStreaming, __ServiceName, "StreamingPull", __Marshaller_StreamingPullRequest, __Marshaller_StreamingPullResponse); static readonly grpc::Method<global::Google.Cloud.PubSub.V1.ModifyPushConfigRequest, global::Google.Protobuf.WellKnownTypes.Empty> __Method_ModifyPushConfig = new grpc::Method<global::Google.Cloud.PubSub.V1.ModifyPushConfigRequest, global::Google.Protobuf.WellKnownTypes.Empty>( grpc::MethodType.Unary, __ServiceName, "ModifyPushConfig", __Marshaller_ModifyPushConfigRequest, __Marshaller_Empty); static readonly grpc::Method<global::Google.Cloud.PubSub.V1.GetSnapshotRequest, global::Google.Cloud.PubSub.V1.Snapshot> __Method_GetSnapshot = new grpc::Method<global::Google.Cloud.PubSub.V1.GetSnapshotRequest, global::Google.Cloud.PubSub.V1.Snapshot>( grpc::MethodType.Unary, __ServiceName, "GetSnapshot", __Marshaller_GetSnapshotRequest, __Marshaller_Snapshot); static readonly grpc::Method<global::Google.Cloud.PubSub.V1.ListSnapshotsRequest, global::Google.Cloud.PubSub.V1.ListSnapshotsResponse> __Method_ListSnapshots = new grpc::Method<global::Google.Cloud.PubSub.V1.ListSnapshotsRequest, global::Google.Cloud.PubSub.V1.ListSnapshotsResponse>( grpc::MethodType.Unary, __ServiceName, "ListSnapshots", __Marshaller_ListSnapshotsRequest, __Marshaller_ListSnapshotsResponse); static readonly grpc::Method<global::Google.Cloud.PubSub.V1.CreateSnapshotRequest, global::Google.Cloud.PubSub.V1.Snapshot> __Method_CreateSnapshot = new grpc::Method<global::Google.Cloud.PubSub.V1.CreateSnapshotRequest, global::Google.Cloud.PubSub.V1.Snapshot>( grpc::MethodType.Unary, __ServiceName, "CreateSnapshot", __Marshaller_CreateSnapshotRequest, __Marshaller_Snapshot); static readonly grpc::Method<global::Google.Cloud.PubSub.V1.UpdateSnapshotRequest, global::Google.Cloud.PubSub.V1.Snapshot> __Method_UpdateSnapshot = new grpc::Method<global::Google.Cloud.PubSub.V1.UpdateSnapshotRequest, global::Google.Cloud.PubSub.V1.Snapshot>( grpc::MethodType.Unary, __ServiceName, "UpdateSnapshot", __Marshaller_UpdateSnapshotRequest, __Marshaller_Snapshot); static readonly grpc::Method<global::Google.Cloud.PubSub.V1.DeleteSnapshotRequest, global::Google.Protobuf.WellKnownTypes.Empty> __Method_DeleteSnapshot = new grpc::Method<global::Google.Cloud.PubSub.V1.DeleteSnapshotRequest, global::Google.Protobuf.WellKnownTypes.Empty>( grpc::MethodType.Unary, __ServiceName, "DeleteSnapshot", __Marshaller_DeleteSnapshotRequest, __Marshaller_Empty); static readonly grpc::Method<global::Google.Cloud.PubSub.V1.SeekRequest, global::Google.Cloud.PubSub.V1.SeekResponse> __Method_Seek = new grpc::Method<global::Google.Cloud.PubSub.V1.SeekRequest, global::Google.Cloud.PubSub.V1.SeekResponse>( grpc::MethodType.Unary, __ServiceName, "Seek", __Marshaller_SeekRequest, __Marshaller_SeekResponse); /// <summary>Service descriptor</summary> public static global::Google.Protobuf.Reflection.ServiceDescriptor Descriptor { get { return global::Google.Cloud.PubSub.V1.PubsubReflection.Descriptor.Services[1]; } } /// <summary>Base class for server-side implementations of Subscriber</summary> public abstract partial class SubscriberBase { /// <summary> /// Creates a subscription to a given topic. See the /// &lt;a href="https://cloud.google.com/pubsub/docs/admin#resource_names"> /// resource name rules&lt;/a>. /// If the subscription already exists, returns `ALREADY_EXISTS`. /// If the corresponding topic doesn't exist, returns `NOT_FOUND`. /// /// If the name is not provided in the request, the server will assign a random /// name for this subscription on the same project as the topic, conforming /// to the /// [resource name format](https://cloud.google.com/pubsub/docs/admin#resource_names). /// The generated name is populated in the returned Subscription object. /// Note that for REST API requests, you must specify a name in the request. /// </summary> /// <param name="request">The request received from the client.</param> /// <param name="context">The context of the server-side call handler being invoked.</param> /// <returns>The response to send back to the client (wrapped by a task).</returns> public virtual global::System.Threading.Tasks.Task<global::Google.Cloud.PubSub.V1.Subscription> CreateSubscription(global::Google.Cloud.PubSub.V1.Subscription request, grpc::ServerCallContext context) { throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); } /// <summary> /// Gets the configuration details of a subscription. /// </summary> /// <param name="request">The request received from the client.</param> /// <param name="context">The context of the server-side call handler being invoked.</param> /// <returns>The response to send back to the client (wrapped by a task).</returns> public virtual global::System.Threading.Tasks.Task<global::Google.Cloud.PubSub.V1.Subscription> GetSubscription(global::Google.Cloud.PubSub.V1.GetSubscriptionRequest request, grpc::ServerCallContext context) { throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); } /// <summary> /// Updates an existing subscription. Note that certain properties of a /// subscription, such as its topic, are not modifiable. /// </summary> /// <param name="request">The request received from the client.</param> /// <param name="context">The context of the server-side call handler being invoked.</param> /// <returns>The response to send back to the client (wrapped by a task).</returns> public virtual global::System.Threading.Tasks.Task<global::Google.Cloud.PubSub.V1.Subscription> UpdateSubscription(global::Google.Cloud.PubSub.V1.UpdateSubscriptionRequest request, grpc::ServerCallContext context) { throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); } /// <summary> /// Lists matching subscriptions. /// </summary> /// <param name="request">The request received from the client.</param> /// <param name="context">The context of the server-side call handler being invoked.</param> /// <returns>The response to send back to the client (wrapped by a task).</returns> public virtual global::System.Threading.Tasks.Task<global::Google.Cloud.PubSub.V1.ListSubscriptionsResponse> ListSubscriptions(global::Google.Cloud.PubSub.V1.ListSubscriptionsRequest request, grpc::ServerCallContext context) { throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); } /// <summary> /// Deletes an existing subscription. All messages retained in the subscription /// are immediately dropped. Calls to `Pull` after deletion will return /// `NOT_FOUND`. After a subscription is deleted, a new one may be created with /// the same name, but the new one has no association with the old /// subscription or its topic unless the same topic is specified. /// </summary> /// <param name="request">The request received from the client.</param> /// <param name="context">The context of the server-side call handler being invoked.</param> /// <returns>The response to send back to the client (wrapped by a task).</returns> public virtual global::System.Threading.Tasks.Task<global::Google.Protobuf.WellKnownTypes.Empty> DeleteSubscription(global::Google.Cloud.PubSub.V1.DeleteSubscriptionRequest request, grpc::ServerCallContext context) { throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); } /// <summary> /// Modifies the ack deadline for a specific message. This method is useful /// to indicate that more time is needed to process a message by the /// subscriber, or to make the message available for redelivery if the /// processing was interrupted. Note that this does not modify the /// subscription-level `ackDeadlineSeconds` used for subsequent messages. /// </summary> /// <param name="request">The request received from the client.</param> /// <param name="context">The context of the server-side call handler being invoked.</param> /// <returns>The response to send back to the client (wrapped by a task).</returns> public virtual global::System.Threading.Tasks.Task<global::Google.Protobuf.WellKnownTypes.Empty> ModifyAckDeadline(global::Google.Cloud.PubSub.V1.ModifyAckDeadlineRequest request, grpc::ServerCallContext context) { throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); } /// <summary> /// Acknowledges the messages associated with the `ack_ids` in the /// `AcknowledgeRequest`. The Pub/Sub system can remove the relevant messages /// from the subscription. /// /// Acknowledging a message whose ack deadline has expired may succeed, /// but such a message may be redelivered later. Acknowledging a message more /// than once will not result in an error. /// </summary> /// <param name="request">The request received from the client.</param> /// <param name="context">The context of the server-side call handler being invoked.</param> /// <returns>The response to send back to the client (wrapped by a task).</returns> public virtual global::System.Threading.Tasks.Task<global::Google.Protobuf.WellKnownTypes.Empty> Acknowledge(global::Google.Cloud.PubSub.V1.AcknowledgeRequest request, grpc::ServerCallContext context) { throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); } /// <summary> /// Pulls messages from the server. The server may return `UNAVAILABLE` if /// there are too many concurrent pull requests pending for the given /// subscription. /// </summary> /// <param name="request">The request received from the client.</param> /// <param name="context">The context of the server-side call handler being invoked.</param> /// <returns>The response to send back to the client (wrapped by a task).</returns> public virtual global::System.Threading.Tasks.Task<global::Google.Cloud.PubSub.V1.PullResponse> Pull(global::Google.Cloud.PubSub.V1.PullRequest request, grpc::ServerCallContext context) { throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); } /// <summary> /// Establishes a stream with the server, which sends messages down to the /// client. The client streams acknowledgements and ack deadline modifications /// back to the server. The server will close the stream and return the status /// on any error. The server may close the stream with status `UNAVAILABLE` to /// reassign server-side resources, in which case, the client should /// re-establish the stream. Flow control can be achieved by configuring the /// underlying RPC channel. /// </summary> /// <param name="requestStream">Used for reading requests from the client.</param> /// <param name="responseStream">Used for sending responses back to the client.</param> /// <param name="context">The context of the server-side call handler being invoked.</param> /// <returns>A task indicating completion of the handler.</returns> public virtual global::System.Threading.Tasks.Task StreamingPull(grpc::IAsyncStreamReader<global::Google.Cloud.PubSub.V1.StreamingPullRequest> requestStream, grpc::IServerStreamWriter<global::Google.Cloud.PubSub.V1.StreamingPullResponse> responseStream, grpc::ServerCallContext context) { throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); } /// <summary> /// Modifies the `PushConfig` for a specified subscription. /// /// This may be used to change a push subscription to a pull one (signified by /// an empty `PushConfig`) or vice versa, or change the endpoint URL and other /// attributes of a push subscription. Messages will accumulate for delivery /// continuously through the call regardless of changes to the `PushConfig`. /// </summary> /// <param name="request">The request received from the client.</param> /// <param name="context">The context of the server-side call handler being invoked.</param> /// <returns>The response to send back to the client (wrapped by a task).</returns> public virtual global::System.Threading.Tasks.Task<global::Google.Protobuf.WellKnownTypes.Empty> ModifyPushConfig(global::Google.Cloud.PubSub.V1.ModifyPushConfigRequest request, grpc::ServerCallContext context) { throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); } /// <summary> /// Gets the configuration details of a snapshot. Snapshots are used in /// &lt;a href="https://cloud.google.com/pubsub/docs/replay-overview">Seek&lt;/a> /// operations, which allow you to manage message acknowledgments in bulk. That /// is, you can set the acknowledgment state of messages in an existing /// subscription to the state captured by a snapshot.&lt;br>&lt;br> /// &lt;b>BETA:&lt;/b> This feature is part of a beta release. This API might be /// changed in backward-incompatible ways and is not recommended for production /// use. It is not subject to any SLA or deprecation policy. /// </summary> /// <param name="request">The request received from the client.</param> /// <param name="context">The context of the server-side call handler being invoked.</param> /// <returns>The response to send back to the client (wrapped by a task).</returns> public virtual global::System.Threading.Tasks.Task<global::Google.Cloud.PubSub.V1.Snapshot> GetSnapshot(global::Google.Cloud.PubSub.V1.GetSnapshotRequest request, grpc::ServerCallContext context) { throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); } /// <summary> /// Lists the existing snapshots. Snapshots are used in /// &lt;a href="https://cloud.google.com/pubsub/docs/replay-overview">Seek&lt;/a> /// operations, which allow /// you to manage message acknowledgments in bulk. That is, you can set the /// acknowledgment state of messages in an existing subscription to the state /// captured by a snapshot.&lt;br>&lt;br> /// &lt;b>BETA:&lt;/b> This feature is part of a beta release. This API might be /// changed in backward-incompatible ways and is not recommended for production /// use. It is not subject to any SLA or deprecation policy. /// </summary> /// <param name="request">The request received from the client.</param> /// <param name="context">The context of the server-side call handler being invoked.</param> /// <returns>The response to send back to the client (wrapped by a task).</returns> public virtual global::System.Threading.Tasks.Task<global::Google.Cloud.PubSub.V1.ListSnapshotsResponse> ListSnapshots(global::Google.Cloud.PubSub.V1.ListSnapshotsRequest request, grpc::ServerCallContext context) { throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); } /// <summary> /// Creates a snapshot from the requested subscription. Snapshots are used in /// &lt;a href="https://cloud.google.com/pubsub/docs/replay-overview">Seek&lt;/a> /// operations, which allow /// you to manage message acknowledgments in bulk. That is, you can set the /// acknowledgment state of messages in an existing subscription to the state /// captured by a snapshot. /// &lt;br>&lt;br> /// &lt;b>BETA:&lt;/b> This feature is part of a beta release. This API might be /// changed in backward-incompatible ways and is not recommended for production /// use. It is not subject to any SLA or deprecation policy.&lt;br>&lt;br> /// If the snapshot already exists, returns `ALREADY_EXISTS`. /// If the requested subscription doesn't exist, returns `NOT_FOUND`. /// If the backlog in the subscription is too old -- and the resulting snapshot /// would expire in less than 1 hour -- then `FAILED_PRECONDITION` is returned. /// See also the `Snapshot.expire_time` field. If the name is not provided in /// the request, the server will assign a random /// name for this snapshot on the same project as the subscription, conforming /// to the /// [resource name format](https://cloud.google.com/pubsub/docs/admin#resource_names). /// The generated name is populated in the returned Snapshot object. Note that /// for REST API requests, you must specify a name in the request. /// </summary> /// <param name="request">The request received from the client.</param> /// <param name="context">The context of the server-side call handler being invoked.</param> /// <returns>The response to send back to the client (wrapped by a task).</returns> public virtual global::System.Threading.Tasks.Task<global::Google.Cloud.PubSub.V1.Snapshot> CreateSnapshot(global::Google.Cloud.PubSub.V1.CreateSnapshotRequest request, grpc::ServerCallContext context) { throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); } /// <summary> /// Updates an existing snapshot. Snapshots are used in /// &lt;a href="https://cloud.google.com/pubsub/docs/replay-overview">Seek&lt;/a> /// operations, which allow /// you to manage message acknowledgments in bulk. That is, you can set the /// acknowledgment state of messages in an existing subscription to the state /// captured by a snapshot.&lt;br>&lt;br> /// &lt;b>BETA:&lt;/b> This feature is part of a beta release. This API might be /// changed in backward-incompatible ways and is not recommended for production /// use. It is not subject to any SLA or deprecation policy. /// Note that certain properties of a snapshot are not modifiable. /// </summary> /// <param name="request">The request received from the client.</param> /// <param name="context">The context of the server-side call handler being invoked.</param> /// <returns>The response to send back to the client (wrapped by a task).</returns> public virtual global::System.Threading.Tasks.Task<global::Google.Cloud.PubSub.V1.Snapshot> UpdateSnapshot(global::Google.Cloud.PubSub.V1.UpdateSnapshotRequest request, grpc::ServerCallContext context) { throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); } /// <summary> /// Removes an existing snapshot. Snapshots are used in /// &lt;a href="https://cloud.google.com/pubsub/docs/replay-overview">Seek&lt;/a> /// operations, which allow /// you to manage message acknowledgments in bulk. That is, you can set the /// acknowledgment state of messages in an existing subscription to the state /// captured by a snapshot.&lt;br>&lt;br> /// &lt;b>BETA:&lt;/b> This feature is part of a beta release. This API might be /// changed in backward-incompatible ways and is not recommended for production /// use. It is not subject to any SLA or deprecation policy. /// When the snapshot is deleted, all messages retained in the snapshot /// are immediately dropped. After a snapshot is deleted, a new one may be /// created with the same name, but the new one has no association with the old /// snapshot or its subscription, unless the same subscription is specified. /// </summary> /// <param name="request">The request received from the client.</param> /// <param name="context">The context of the server-side call handler being invoked.</param> /// <returns>The response to send back to the client (wrapped by a task).</returns> public virtual global::System.Threading.Tasks.Task<global::Google.Protobuf.WellKnownTypes.Empty> DeleteSnapshot(global::Google.Cloud.PubSub.V1.DeleteSnapshotRequest request, grpc::ServerCallContext context) { throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); } /// <summary> /// Seeks an existing subscription to a point in time or to a given snapshot, /// whichever is provided in the request. Snapshots are used in /// &lt;a href="https://cloud.google.com/pubsub/docs/replay-overview">Seek&lt;/a> /// operations, which allow /// you to manage message acknowledgments in bulk. That is, you can set the /// acknowledgment state of messages in an existing subscription to the state /// captured by a snapshot. Note that both the subscription and the snapshot /// must be on the same topic.&lt;br>&lt;br> /// &lt;b>BETA:&lt;/b> This feature is part of a beta release. This API might be /// changed in backward-incompatible ways and is not recommended for production /// use. It is not subject to any SLA or deprecation policy. /// </summary> /// <param name="request">The request received from the client.</param> /// <param name="context">The context of the server-side call handler being invoked.</param> /// <returns>The response to send back to the client (wrapped by a task).</returns> public virtual global::System.Threading.Tasks.Task<global::Google.Cloud.PubSub.V1.SeekResponse> Seek(global::Google.Cloud.PubSub.V1.SeekRequest request, grpc::ServerCallContext context) { throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); } } /// <summary>Client for Subscriber</summary> public partial class SubscriberClient : grpc::ClientBase<SubscriberClient> { /// <summary>Creates a new client for Subscriber</summary> /// <param name="channel">The channel to use to make remote calls.</param> public SubscriberClient(grpc::Channel channel) : base(channel) { } /// <summary>Creates a new client for Subscriber that uses a custom <c>CallInvoker</c>.</summary> /// <param name="callInvoker">The callInvoker to use to make remote calls.</param> public SubscriberClient(grpc::CallInvoker callInvoker) : base(callInvoker) { } /// <summary>Protected parameterless constructor to allow creation of test doubles.</summary> protected SubscriberClient() : base() { } /// <summary>Protected constructor to allow creation of configured clients.</summary> /// <param name="configuration">The client configuration.</param> protected SubscriberClient(ClientBaseConfiguration configuration) : base(configuration) { } /// <summary> /// Creates a subscription to a given topic. See the /// &lt;a href="https://cloud.google.com/pubsub/docs/admin#resource_names"> /// resource name rules&lt;/a>. /// If the subscription already exists, returns `ALREADY_EXISTS`. /// If the corresponding topic doesn't exist, returns `NOT_FOUND`. /// /// If the name is not provided in the request, the server will assign a random /// name for this subscription on the same project as the topic, conforming /// to the /// [resource name format](https://cloud.google.com/pubsub/docs/admin#resource_names). /// The generated name is populated in the returned Subscription object. /// Note that for REST API requests, you must specify a name in the request. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Google.Cloud.PubSub.V1.Subscription CreateSubscription(global::Google.Cloud.PubSub.V1.Subscription request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) { return CreateSubscription(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Creates a subscription to a given topic. See the /// &lt;a href="https://cloud.google.com/pubsub/docs/admin#resource_names"> /// resource name rules&lt;/a>. /// If the subscription already exists, returns `ALREADY_EXISTS`. /// If the corresponding topic doesn't exist, returns `NOT_FOUND`. /// /// If the name is not provided in the request, the server will assign a random /// name for this subscription on the same project as the topic, conforming /// to the /// [resource name format](https://cloud.google.com/pubsub/docs/admin#resource_names). /// The generated name is populated in the returned Subscription object. /// Note that for REST API requests, you must specify a name in the request. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Google.Cloud.PubSub.V1.Subscription CreateSubscription(global::Google.Cloud.PubSub.V1.Subscription request, grpc::CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_CreateSubscription, null, options, request); } /// <summary> /// Creates a subscription to a given topic. See the /// &lt;a href="https://cloud.google.com/pubsub/docs/admin#resource_names"> /// resource name rules&lt;/a>. /// If the subscription already exists, returns `ALREADY_EXISTS`. /// If the corresponding topic doesn't exist, returns `NOT_FOUND`. /// /// If the name is not provided in the request, the server will assign a random /// name for this subscription on the same project as the topic, conforming /// to the /// [resource name format](https://cloud.google.com/pubsub/docs/admin#resource_names). /// The generated name is populated in the returned Subscription object. /// Note that for REST API requests, you must specify a name in the request. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Google.Cloud.PubSub.V1.Subscription> CreateSubscriptionAsync(global::Google.Cloud.PubSub.V1.Subscription request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) { return CreateSubscriptionAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Creates a subscription to a given topic. See the /// &lt;a href="https://cloud.google.com/pubsub/docs/admin#resource_names"> /// resource name rules&lt;/a>. /// If the subscription already exists, returns `ALREADY_EXISTS`. /// If the corresponding topic doesn't exist, returns `NOT_FOUND`. /// /// If the name is not provided in the request, the server will assign a random /// name for this subscription on the same project as the topic, conforming /// to the /// [resource name format](https://cloud.google.com/pubsub/docs/admin#resource_names). /// The generated name is populated in the returned Subscription object. /// Note that for REST API requests, you must specify a name in the request. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Google.Cloud.PubSub.V1.Subscription> CreateSubscriptionAsync(global::Google.Cloud.PubSub.V1.Subscription request, grpc::CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_CreateSubscription, null, options, request); } /// <summary> /// Gets the configuration details of a subscription. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Google.Cloud.PubSub.V1.Subscription GetSubscription(global::Google.Cloud.PubSub.V1.GetSubscriptionRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) { return GetSubscription(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Gets the configuration details of a subscription. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Google.Cloud.PubSub.V1.Subscription GetSubscription(global::Google.Cloud.PubSub.V1.GetSubscriptionRequest request, grpc::CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_GetSubscription, null, options, request); } /// <summary> /// Gets the configuration details of a subscription. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Google.Cloud.PubSub.V1.Subscription> GetSubscriptionAsync(global::Google.Cloud.PubSub.V1.GetSubscriptionRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) { return GetSubscriptionAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Gets the configuration details of a subscription. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Google.Cloud.PubSub.V1.Subscription> GetSubscriptionAsync(global::Google.Cloud.PubSub.V1.GetSubscriptionRequest request, grpc::CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_GetSubscription, null, options, request); } /// <summary> /// Updates an existing subscription. Note that certain properties of a /// subscription, such as its topic, are not modifiable. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Google.Cloud.PubSub.V1.Subscription UpdateSubscription(global::Google.Cloud.PubSub.V1.UpdateSubscriptionRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) { return UpdateSubscription(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Updates an existing subscription. Note that certain properties of a /// subscription, such as its topic, are not modifiable. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Google.Cloud.PubSub.V1.Subscription UpdateSubscription(global::Google.Cloud.PubSub.V1.UpdateSubscriptionRequest request, grpc::CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_UpdateSubscription, null, options, request); } /// <summary> /// Updates an existing subscription. Note that certain properties of a /// subscription, such as its topic, are not modifiable. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Google.Cloud.PubSub.V1.Subscription> UpdateSubscriptionAsync(global::Google.Cloud.PubSub.V1.UpdateSubscriptionRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) { return UpdateSubscriptionAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Updates an existing subscription. Note that certain properties of a /// subscription, such as its topic, are not modifiable. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Google.Cloud.PubSub.V1.Subscription> UpdateSubscriptionAsync(global::Google.Cloud.PubSub.V1.UpdateSubscriptionRequest request, grpc::CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_UpdateSubscription, null, options, request); } /// <summary> /// Lists matching subscriptions. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Google.Cloud.PubSub.V1.ListSubscriptionsResponse ListSubscriptions(global::Google.Cloud.PubSub.V1.ListSubscriptionsRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) { return ListSubscriptions(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Lists matching subscriptions. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Google.Cloud.PubSub.V1.ListSubscriptionsResponse ListSubscriptions(global::Google.Cloud.PubSub.V1.ListSubscriptionsRequest request, grpc::CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_ListSubscriptions, null, options, request); } /// <summary> /// Lists matching subscriptions. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Google.Cloud.PubSub.V1.ListSubscriptionsResponse> ListSubscriptionsAsync(global::Google.Cloud.PubSub.V1.ListSubscriptionsRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) { return ListSubscriptionsAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Lists matching subscriptions. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Google.Cloud.PubSub.V1.ListSubscriptionsResponse> ListSubscriptionsAsync(global::Google.Cloud.PubSub.V1.ListSubscriptionsRequest request, grpc::CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_ListSubscriptions, null, options, request); } /// <summary> /// Deletes an existing subscription. All messages retained in the subscription /// are immediately dropped. Calls to `Pull` after deletion will return /// `NOT_FOUND`. After a subscription is deleted, a new one may be created with /// the same name, but the new one has no association with the old /// subscription or its topic unless the same topic is specified. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Google.Protobuf.WellKnownTypes.Empty DeleteSubscription(global::Google.Cloud.PubSub.V1.DeleteSubscriptionRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) { return DeleteSubscription(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Deletes an existing subscription. All messages retained in the subscription /// are immediately dropped. Calls to `Pull` after deletion will return /// `NOT_FOUND`. After a subscription is deleted, a new one may be created with /// the same name, but the new one has no association with the old /// subscription or its topic unless the same topic is specified. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Google.Protobuf.WellKnownTypes.Empty DeleteSubscription(global::Google.Cloud.PubSub.V1.DeleteSubscriptionRequest request, grpc::CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_DeleteSubscription, null, options, request); } /// <summary> /// Deletes an existing subscription. All messages retained in the subscription /// are immediately dropped. Calls to `Pull` after deletion will return /// `NOT_FOUND`. After a subscription is deleted, a new one may be created with /// the same name, but the new one has no association with the old /// subscription or its topic unless the same topic is specified. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Google.Protobuf.WellKnownTypes.Empty> DeleteSubscriptionAsync(global::Google.Cloud.PubSub.V1.DeleteSubscriptionRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) { return DeleteSubscriptionAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Deletes an existing subscription. All messages retained in the subscription /// are immediately dropped. Calls to `Pull` after deletion will return /// `NOT_FOUND`. After a subscription is deleted, a new one may be created with /// the same name, but the new one has no association with the old /// subscription or its topic unless the same topic is specified. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Google.Protobuf.WellKnownTypes.Empty> DeleteSubscriptionAsync(global::Google.Cloud.PubSub.V1.DeleteSubscriptionRequest request, grpc::CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_DeleteSubscription, null, options, request); } /// <summary> /// Modifies the ack deadline for a specific message. This method is useful /// to indicate that more time is needed to process a message by the /// subscriber, or to make the message available for redelivery if the /// processing was interrupted. Note that this does not modify the /// subscription-level `ackDeadlineSeconds` used for subsequent messages. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Google.Protobuf.WellKnownTypes.Empty ModifyAckDeadline(global::Google.Cloud.PubSub.V1.ModifyAckDeadlineRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) { return ModifyAckDeadline(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Modifies the ack deadline for a specific message. This method is useful /// to indicate that more time is needed to process a message by the /// subscriber, or to make the message available for redelivery if the /// processing was interrupted. Note that this does not modify the /// subscription-level `ackDeadlineSeconds` used for subsequent messages. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Google.Protobuf.WellKnownTypes.Empty ModifyAckDeadline(global::Google.Cloud.PubSub.V1.ModifyAckDeadlineRequest request, grpc::CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_ModifyAckDeadline, null, options, request); } /// <summary> /// Modifies the ack deadline for a specific message. This method is useful /// to indicate that more time is needed to process a message by the /// subscriber, or to make the message available for redelivery if the /// processing was interrupted. Note that this does not modify the /// subscription-level `ackDeadlineSeconds` used for subsequent messages. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Google.Protobuf.WellKnownTypes.Empty> ModifyAckDeadlineAsync(global::Google.Cloud.PubSub.V1.ModifyAckDeadlineRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) { return ModifyAckDeadlineAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Modifies the ack deadline for a specific message. This method is useful /// to indicate that more time is needed to process a message by the /// subscriber, or to make the message available for redelivery if the /// processing was interrupted. Note that this does not modify the /// subscription-level `ackDeadlineSeconds` used for subsequent messages. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Google.Protobuf.WellKnownTypes.Empty> ModifyAckDeadlineAsync(global::Google.Cloud.PubSub.V1.ModifyAckDeadlineRequest request, grpc::CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_ModifyAckDeadline, null, options, request); } /// <summary> /// Acknowledges the messages associated with the `ack_ids` in the /// `AcknowledgeRequest`. The Pub/Sub system can remove the relevant messages /// from the subscription. /// /// Acknowledging a message whose ack deadline has expired may succeed, /// but such a message may be redelivered later. Acknowledging a message more /// than once will not result in an error. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Google.Protobuf.WellKnownTypes.Empty Acknowledge(global::Google.Cloud.PubSub.V1.AcknowledgeRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) { return Acknowledge(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Acknowledges the messages associated with the `ack_ids` in the /// `AcknowledgeRequest`. The Pub/Sub system can remove the relevant messages /// from the subscription. /// /// Acknowledging a message whose ack deadline has expired may succeed, /// but such a message may be redelivered later. Acknowledging a message more /// than once will not result in an error. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Google.Protobuf.WellKnownTypes.Empty Acknowledge(global::Google.Cloud.PubSub.V1.AcknowledgeRequest request, grpc::CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_Acknowledge, null, options, request); } /// <summary> /// Acknowledges the messages associated with the `ack_ids` in the /// `AcknowledgeRequest`. The Pub/Sub system can remove the relevant messages /// from the subscription. /// /// Acknowledging a message whose ack deadline has expired may succeed, /// but such a message may be redelivered later. Acknowledging a message more /// than once will not result in an error. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Google.Protobuf.WellKnownTypes.Empty> AcknowledgeAsync(global::Google.Cloud.PubSub.V1.AcknowledgeRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) { return AcknowledgeAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Acknowledges the messages associated with the `ack_ids` in the /// `AcknowledgeRequest`. The Pub/Sub system can remove the relevant messages /// from the subscription. /// /// Acknowledging a message whose ack deadline has expired may succeed, /// but such a message may be redelivered later. Acknowledging a message more /// than once will not result in an error. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Google.Protobuf.WellKnownTypes.Empty> AcknowledgeAsync(global::Google.Cloud.PubSub.V1.AcknowledgeRequest request, grpc::CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_Acknowledge, null, options, request); } /// <summary> /// Pulls messages from the server. The server may return `UNAVAILABLE` if /// there are too many concurrent pull requests pending for the given /// subscription. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Google.Cloud.PubSub.V1.PullResponse Pull(global::Google.Cloud.PubSub.V1.PullRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) { return Pull(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Pulls messages from the server. The server may return `UNAVAILABLE` if /// there are too many concurrent pull requests pending for the given /// subscription. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Google.Cloud.PubSub.V1.PullResponse Pull(global::Google.Cloud.PubSub.V1.PullRequest request, grpc::CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_Pull, null, options, request); } /// <summary> /// Pulls messages from the server. The server may return `UNAVAILABLE` if /// there are too many concurrent pull requests pending for the given /// subscription. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Google.Cloud.PubSub.V1.PullResponse> PullAsync(global::Google.Cloud.PubSub.V1.PullRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) { return PullAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Pulls messages from the server. The server may return `UNAVAILABLE` if /// there are too many concurrent pull requests pending for the given /// subscription. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Google.Cloud.PubSub.V1.PullResponse> PullAsync(global::Google.Cloud.PubSub.V1.PullRequest request, grpc::CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_Pull, null, options, request); } /// <summary> /// Establishes a stream with the server, which sends messages down to the /// client. The client streams acknowledgements and ack deadline modifications /// back to the server. The server will close the stream and return the status /// on any error. The server may close the stream with status `UNAVAILABLE` to /// reassign server-side resources, in which case, the client should /// re-establish the stream. Flow control can be achieved by configuring the /// underlying RPC channel. /// </summary> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncDuplexStreamingCall<global::Google.Cloud.PubSub.V1.StreamingPullRequest, global::Google.Cloud.PubSub.V1.StreamingPullResponse> StreamingPull(grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) { return StreamingPull(new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Establishes a stream with the server, which sends messages down to the /// client. The client streams acknowledgements and ack deadline modifications /// back to the server. The server will close the stream and return the status /// on any error. The server may close the stream with status `UNAVAILABLE` to /// reassign server-side resources, in which case, the client should /// re-establish the stream. Flow control can be achieved by configuring the /// underlying RPC channel. /// </summary> /// <param name="options">The options for the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncDuplexStreamingCall<global::Google.Cloud.PubSub.V1.StreamingPullRequest, global::Google.Cloud.PubSub.V1.StreamingPullResponse> StreamingPull(grpc::CallOptions options) { return CallInvoker.AsyncDuplexStreamingCall(__Method_StreamingPull, null, options); } /// <summary> /// Modifies the `PushConfig` for a specified subscription. /// /// This may be used to change a push subscription to a pull one (signified by /// an empty `PushConfig`) or vice versa, or change the endpoint URL and other /// attributes of a push subscription. Messages will accumulate for delivery /// continuously through the call regardless of changes to the `PushConfig`. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Google.Protobuf.WellKnownTypes.Empty ModifyPushConfig(global::Google.Cloud.PubSub.V1.ModifyPushConfigRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) { return ModifyPushConfig(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Modifies the `PushConfig` for a specified subscription. /// /// This may be used to change a push subscription to a pull one (signified by /// an empty `PushConfig`) or vice versa, or change the endpoint URL and other /// attributes of a push subscription. Messages will accumulate for delivery /// continuously through the call regardless of changes to the `PushConfig`. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Google.Protobuf.WellKnownTypes.Empty ModifyPushConfig(global::Google.Cloud.PubSub.V1.ModifyPushConfigRequest request, grpc::CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_ModifyPushConfig, null, options, request); } /// <summary> /// Modifies the `PushConfig` for a specified subscription. /// /// This may be used to change a push subscription to a pull one (signified by /// an empty `PushConfig`) or vice versa, or change the endpoint URL and other /// attributes of a push subscription. Messages will accumulate for delivery /// continuously through the call regardless of changes to the `PushConfig`. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Google.Protobuf.WellKnownTypes.Empty> ModifyPushConfigAsync(global::Google.Cloud.PubSub.V1.ModifyPushConfigRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) { return ModifyPushConfigAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Modifies the `PushConfig` for a specified subscription. /// /// This may be used to change a push subscription to a pull one (signified by /// an empty `PushConfig`) or vice versa, or change the endpoint URL and other /// attributes of a push subscription. Messages will accumulate for delivery /// continuously through the call regardless of changes to the `PushConfig`. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Google.Protobuf.WellKnownTypes.Empty> ModifyPushConfigAsync(global::Google.Cloud.PubSub.V1.ModifyPushConfigRequest request, grpc::CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_ModifyPushConfig, null, options, request); } /// <summary> /// Gets the configuration details of a snapshot. Snapshots are used in /// &lt;a href="https://cloud.google.com/pubsub/docs/replay-overview">Seek&lt;/a> /// operations, which allow you to manage message acknowledgments in bulk. That /// is, you can set the acknowledgment state of messages in an existing /// subscription to the state captured by a snapshot.&lt;br>&lt;br> /// &lt;b>BETA:&lt;/b> This feature is part of a beta release. This API might be /// changed in backward-incompatible ways and is not recommended for production /// use. It is not subject to any SLA or deprecation policy. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Google.Cloud.PubSub.V1.Snapshot GetSnapshot(global::Google.Cloud.PubSub.V1.GetSnapshotRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) { return GetSnapshot(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Gets the configuration details of a snapshot. Snapshots are used in /// &lt;a href="https://cloud.google.com/pubsub/docs/replay-overview">Seek&lt;/a> /// operations, which allow you to manage message acknowledgments in bulk. That /// is, you can set the acknowledgment state of messages in an existing /// subscription to the state captured by a snapshot.&lt;br>&lt;br> /// &lt;b>BETA:&lt;/b> This feature is part of a beta release. This API might be /// changed in backward-incompatible ways and is not recommended for production /// use. It is not subject to any SLA or deprecation policy. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Google.Cloud.PubSub.V1.Snapshot GetSnapshot(global::Google.Cloud.PubSub.V1.GetSnapshotRequest request, grpc::CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_GetSnapshot, null, options, request); } /// <summary> /// Gets the configuration details of a snapshot. Snapshots are used in /// &lt;a href="https://cloud.google.com/pubsub/docs/replay-overview">Seek&lt;/a> /// operations, which allow you to manage message acknowledgments in bulk. That /// is, you can set the acknowledgment state of messages in an existing /// subscription to the state captured by a snapshot.&lt;br>&lt;br> /// &lt;b>BETA:&lt;/b> This feature is part of a beta release. This API might be /// changed in backward-incompatible ways and is not recommended for production /// use. It is not subject to any SLA or deprecation policy. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Google.Cloud.PubSub.V1.Snapshot> GetSnapshotAsync(global::Google.Cloud.PubSub.V1.GetSnapshotRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) { return GetSnapshotAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Gets the configuration details of a snapshot. Snapshots are used in /// &lt;a href="https://cloud.google.com/pubsub/docs/replay-overview">Seek&lt;/a> /// operations, which allow you to manage message acknowledgments in bulk. That /// is, you can set the acknowledgment state of messages in an existing /// subscription to the state captured by a snapshot.&lt;br>&lt;br> /// &lt;b>BETA:&lt;/b> This feature is part of a beta release. This API might be /// changed in backward-incompatible ways and is not recommended for production /// use. It is not subject to any SLA or deprecation policy. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Google.Cloud.PubSub.V1.Snapshot> GetSnapshotAsync(global::Google.Cloud.PubSub.V1.GetSnapshotRequest request, grpc::CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_GetSnapshot, null, options, request); } /// <summary> /// Lists the existing snapshots. Snapshots are used in /// &lt;a href="https://cloud.google.com/pubsub/docs/replay-overview">Seek&lt;/a> /// operations, which allow /// you to manage message acknowledgments in bulk. That is, you can set the /// acknowledgment state of messages in an existing subscription to the state /// captured by a snapshot.&lt;br>&lt;br> /// &lt;b>BETA:&lt;/b> This feature is part of a beta release. This API might be /// changed in backward-incompatible ways and is not recommended for production /// use. It is not subject to any SLA or deprecation policy. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Google.Cloud.PubSub.V1.ListSnapshotsResponse ListSnapshots(global::Google.Cloud.PubSub.V1.ListSnapshotsRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) { return ListSnapshots(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Lists the existing snapshots. Snapshots are used in /// &lt;a href="https://cloud.google.com/pubsub/docs/replay-overview">Seek&lt;/a> /// operations, which allow /// you to manage message acknowledgments in bulk. That is, you can set the /// acknowledgment state of messages in an existing subscription to the state /// captured by a snapshot.&lt;br>&lt;br> /// &lt;b>BETA:&lt;/b> This feature is part of a beta release. This API might be /// changed in backward-incompatible ways and is not recommended for production /// use. It is not subject to any SLA or deprecation policy. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Google.Cloud.PubSub.V1.ListSnapshotsResponse ListSnapshots(global::Google.Cloud.PubSub.V1.ListSnapshotsRequest request, grpc::CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_ListSnapshots, null, options, request); } /// <summary> /// Lists the existing snapshots. Snapshots are used in /// &lt;a href="https://cloud.google.com/pubsub/docs/replay-overview">Seek&lt;/a> /// operations, which allow /// you to manage message acknowledgments in bulk. That is, you can set the /// acknowledgment state of messages in an existing subscription to the state /// captured by a snapshot.&lt;br>&lt;br> /// &lt;b>BETA:&lt;/b> This feature is part of a beta release. This API might be /// changed in backward-incompatible ways and is not recommended for production /// use. It is not subject to any SLA or deprecation policy. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Google.Cloud.PubSub.V1.ListSnapshotsResponse> ListSnapshotsAsync(global::Google.Cloud.PubSub.V1.ListSnapshotsRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) { return ListSnapshotsAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Lists the existing snapshots. Snapshots are used in /// &lt;a href="https://cloud.google.com/pubsub/docs/replay-overview">Seek&lt;/a> /// operations, which allow /// you to manage message acknowledgments in bulk. That is, you can set the /// acknowledgment state of messages in an existing subscription to the state /// captured by a snapshot.&lt;br>&lt;br> /// &lt;b>BETA:&lt;/b> This feature is part of a beta release. This API might be /// changed in backward-incompatible ways and is not recommended for production /// use. It is not subject to any SLA or deprecation policy. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Google.Cloud.PubSub.V1.ListSnapshotsResponse> ListSnapshotsAsync(global::Google.Cloud.PubSub.V1.ListSnapshotsRequest request, grpc::CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_ListSnapshots, null, options, request); } /// <summary> /// Creates a snapshot from the requested subscription. Snapshots are used in /// &lt;a href="https://cloud.google.com/pubsub/docs/replay-overview">Seek&lt;/a> /// operations, which allow /// you to manage message acknowledgments in bulk. That is, you can set the /// acknowledgment state of messages in an existing subscription to the state /// captured by a snapshot. /// &lt;br>&lt;br> /// &lt;b>BETA:&lt;/b> This feature is part of a beta release. This API might be /// changed in backward-incompatible ways and is not recommended for production /// use. It is not subject to any SLA or deprecation policy.&lt;br>&lt;br> /// If the snapshot already exists, returns `ALREADY_EXISTS`. /// If the requested subscription doesn't exist, returns `NOT_FOUND`. /// If the backlog in the subscription is too old -- and the resulting snapshot /// would expire in less than 1 hour -- then `FAILED_PRECONDITION` is returned. /// See also the `Snapshot.expire_time` field. If the name is not provided in /// the request, the server will assign a random /// name for this snapshot on the same project as the subscription, conforming /// to the /// [resource name format](https://cloud.google.com/pubsub/docs/admin#resource_names). /// The generated name is populated in the returned Snapshot object. Note that /// for REST API requests, you must specify a name in the request. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Google.Cloud.PubSub.V1.Snapshot CreateSnapshot(global::Google.Cloud.PubSub.V1.CreateSnapshotRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) { return CreateSnapshot(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Creates a snapshot from the requested subscription. Snapshots are used in /// &lt;a href="https://cloud.google.com/pubsub/docs/replay-overview">Seek&lt;/a> /// operations, which allow /// you to manage message acknowledgments in bulk. That is, you can set the /// acknowledgment state of messages in an existing subscription to the state /// captured by a snapshot. /// &lt;br>&lt;br> /// &lt;b>BETA:&lt;/b> This feature is part of a beta release. This API might be /// changed in backward-incompatible ways and is not recommended for production /// use. It is not subject to any SLA or deprecation policy.&lt;br>&lt;br> /// If the snapshot already exists, returns `ALREADY_EXISTS`. /// If the requested subscription doesn't exist, returns `NOT_FOUND`. /// If the backlog in the subscription is too old -- and the resulting snapshot /// would expire in less than 1 hour -- then `FAILED_PRECONDITION` is returned. /// See also the `Snapshot.expire_time` field. If the name is not provided in /// the request, the server will assign a random /// name for this snapshot on the same project as the subscription, conforming /// to the /// [resource name format](https://cloud.google.com/pubsub/docs/admin#resource_names). /// The generated name is populated in the returned Snapshot object. Note that /// for REST API requests, you must specify a name in the request. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Google.Cloud.PubSub.V1.Snapshot CreateSnapshot(global::Google.Cloud.PubSub.V1.CreateSnapshotRequest request, grpc::CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_CreateSnapshot, null, options, request); } /// <summary> /// Creates a snapshot from the requested subscription. Snapshots are used in /// &lt;a href="https://cloud.google.com/pubsub/docs/replay-overview">Seek&lt;/a> /// operations, which allow /// you to manage message acknowledgments in bulk. That is, you can set the /// acknowledgment state of messages in an existing subscription to the state /// captured by a snapshot. /// &lt;br>&lt;br> /// &lt;b>BETA:&lt;/b> This feature is part of a beta release. This API might be /// changed in backward-incompatible ways and is not recommended for production /// use. It is not subject to any SLA or deprecation policy.&lt;br>&lt;br> /// If the snapshot already exists, returns `ALREADY_EXISTS`. /// If the requested subscription doesn't exist, returns `NOT_FOUND`. /// If the backlog in the subscription is too old -- and the resulting snapshot /// would expire in less than 1 hour -- then `FAILED_PRECONDITION` is returned. /// See also the `Snapshot.expire_time` field. If the name is not provided in /// the request, the server will assign a random /// name for this snapshot on the same project as the subscription, conforming /// to the /// [resource name format](https://cloud.google.com/pubsub/docs/admin#resource_names). /// The generated name is populated in the returned Snapshot object. Note that /// for REST API requests, you must specify a name in the request. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Google.Cloud.PubSub.V1.Snapshot> CreateSnapshotAsync(global::Google.Cloud.PubSub.V1.CreateSnapshotRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) { return CreateSnapshotAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Creates a snapshot from the requested subscription. Snapshots are used in /// &lt;a href="https://cloud.google.com/pubsub/docs/replay-overview">Seek&lt;/a> /// operations, which allow /// you to manage message acknowledgments in bulk. That is, you can set the /// acknowledgment state of messages in an existing subscription to the state /// captured by a snapshot. /// &lt;br>&lt;br> /// &lt;b>BETA:&lt;/b> This feature is part of a beta release. This API might be /// changed in backward-incompatible ways and is not recommended for production /// use. It is not subject to any SLA or deprecation policy.&lt;br>&lt;br> /// If the snapshot already exists, returns `ALREADY_EXISTS`. /// If the requested subscription doesn't exist, returns `NOT_FOUND`. /// If the backlog in the subscription is too old -- and the resulting snapshot /// would expire in less than 1 hour -- then `FAILED_PRECONDITION` is returned. /// See also the `Snapshot.expire_time` field. If the name is not provided in /// the request, the server will assign a random /// name for this snapshot on the same project as the subscription, conforming /// to the /// [resource name format](https://cloud.google.com/pubsub/docs/admin#resource_names). /// The generated name is populated in the returned Snapshot object. Note that /// for REST API requests, you must specify a name in the request. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Google.Cloud.PubSub.V1.Snapshot> CreateSnapshotAsync(global::Google.Cloud.PubSub.V1.CreateSnapshotRequest request, grpc::CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_CreateSnapshot, null, options, request); } /// <summary> /// Updates an existing snapshot. Snapshots are used in /// &lt;a href="https://cloud.google.com/pubsub/docs/replay-overview">Seek&lt;/a> /// operations, which allow /// you to manage message acknowledgments in bulk. That is, you can set the /// acknowledgment state of messages in an existing subscription to the state /// captured by a snapshot.&lt;br>&lt;br> /// &lt;b>BETA:&lt;/b> This feature is part of a beta release. This API might be /// changed in backward-incompatible ways and is not recommended for production /// use. It is not subject to any SLA or deprecation policy. /// Note that certain properties of a snapshot are not modifiable. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Google.Cloud.PubSub.V1.Snapshot UpdateSnapshot(global::Google.Cloud.PubSub.V1.UpdateSnapshotRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) { return UpdateSnapshot(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Updates an existing snapshot. Snapshots are used in /// &lt;a href="https://cloud.google.com/pubsub/docs/replay-overview">Seek&lt;/a> /// operations, which allow /// you to manage message acknowledgments in bulk. That is, you can set the /// acknowledgment state of messages in an existing subscription to the state /// captured by a snapshot.&lt;br>&lt;br> /// &lt;b>BETA:&lt;/b> This feature is part of a beta release. This API might be /// changed in backward-incompatible ways and is not recommended for production /// use. It is not subject to any SLA or deprecation policy. /// Note that certain properties of a snapshot are not modifiable. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Google.Cloud.PubSub.V1.Snapshot UpdateSnapshot(global::Google.Cloud.PubSub.V1.UpdateSnapshotRequest request, grpc::CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_UpdateSnapshot, null, options, request); } /// <summary> /// Updates an existing snapshot. Snapshots are used in /// &lt;a href="https://cloud.google.com/pubsub/docs/replay-overview">Seek&lt;/a> /// operations, which allow /// you to manage message acknowledgments in bulk. That is, you can set the /// acknowledgment state of messages in an existing subscription to the state /// captured by a snapshot.&lt;br>&lt;br> /// &lt;b>BETA:&lt;/b> This feature is part of a beta release. This API might be /// changed in backward-incompatible ways and is not recommended for production /// use. It is not subject to any SLA or deprecation policy. /// Note that certain properties of a snapshot are not modifiable. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Google.Cloud.PubSub.V1.Snapshot> UpdateSnapshotAsync(global::Google.Cloud.PubSub.V1.UpdateSnapshotRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) { return UpdateSnapshotAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Updates an existing snapshot. Snapshots are used in /// &lt;a href="https://cloud.google.com/pubsub/docs/replay-overview">Seek&lt;/a> /// operations, which allow /// you to manage message acknowledgments in bulk. That is, you can set the /// acknowledgment state of messages in an existing subscription to the state /// captured by a snapshot.&lt;br>&lt;br> /// &lt;b>BETA:&lt;/b> This feature is part of a beta release. This API might be /// changed in backward-incompatible ways and is not recommended for production /// use. It is not subject to any SLA or deprecation policy. /// Note that certain properties of a snapshot are not modifiable. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Google.Cloud.PubSub.V1.Snapshot> UpdateSnapshotAsync(global::Google.Cloud.PubSub.V1.UpdateSnapshotRequest request, grpc::CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_UpdateSnapshot, null, options, request); } /// <summary> /// Removes an existing snapshot. Snapshots are used in /// &lt;a href="https://cloud.google.com/pubsub/docs/replay-overview">Seek&lt;/a> /// operations, which allow /// you to manage message acknowledgments in bulk. That is, you can set the /// acknowledgment state of messages in an existing subscription to the state /// captured by a snapshot.&lt;br>&lt;br> /// &lt;b>BETA:&lt;/b> This feature is part of a beta release. This API might be /// changed in backward-incompatible ways and is not recommended for production /// use. It is not subject to any SLA or deprecation policy. /// When the snapshot is deleted, all messages retained in the snapshot /// are immediately dropped. After a snapshot is deleted, a new one may be /// created with the same name, but the new one has no association with the old /// snapshot or its subscription, unless the same subscription is specified. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Google.Protobuf.WellKnownTypes.Empty DeleteSnapshot(global::Google.Cloud.PubSub.V1.DeleteSnapshotRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) { return DeleteSnapshot(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Removes an existing snapshot. Snapshots are used in /// &lt;a href="https://cloud.google.com/pubsub/docs/replay-overview">Seek&lt;/a> /// operations, which allow /// you to manage message acknowledgments in bulk. That is, you can set the /// acknowledgment state of messages in an existing subscription to the state /// captured by a snapshot.&lt;br>&lt;br> /// &lt;b>BETA:&lt;/b> This feature is part of a beta release. This API might be /// changed in backward-incompatible ways and is not recommended for production /// use. It is not subject to any SLA or deprecation policy. /// When the snapshot is deleted, all messages retained in the snapshot /// are immediately dropped. After a snapshot is deleted, a new one may be /// created with the same name, but the new one has no association with the old /// snapshot or its subscription, unless the same subscription is specified. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Google.Protobuf.WellKnownTypes.Empty DeleteSnapshot(global::Google.Cloud.PubSub.V1.DeleteSnapshotRequest request, grpc::CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_DeleteSnapshot, null, options, request); } /// <summary> /// Removes an existing snapshot. Snapshots are used in /// &lt;a href="https://cloud.google.com/pubsub/docs/replay-overview">Seek&lt;/a> /// operations, which allow /// you to manage message acknowledgments in bulk. That is, you can set the /// acknowledgment state of messages in an existing subscription to the state /// captured by a snapshot.&lt;br>&lt;br> /// &lt;b>BETA:&lt;/b> This feature is part of a beta release. This API might be /// changed in backward-incompatible ways and is not recommended for production /// use. It is not subject to any SLA or deprecation policy. /// When the snapshot is deleted, all messages retained in the snapshot /// are immediately dropped. After a snapshot is deleted, a new one may be /// created with the same name, but the new one has no association with the old /// snapshot or its subscription, unless the same subscription is specified. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Google.Protobuf.WellKnownTypes.Empty> DeleteSnapshotAsync(global::Google.Cloud.PubSub.V1.DeleteSnapshotRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) { return DeleteSnapshotAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Removes an existing snapshot. Snapshots are used in /// &lt;a href="https://cloud.google.com/pubsub/docs/replay-overview">Seek&lt;/a> /// operations, which allow /// you to manage message acknowledgments in bulk. That is, you can set the /// acknowledgment state of messages in an existing subscription to the state /// captured by a snapshot.&lt;br>&lt;br> /// &lt;b>BETA:&lt;/b> This feature is part of a beta release. This API might be /// changed in backward-incompatible ways and is not recommended for production /// use. It is not subject to any SLA or deprecation policy. /// When the snapshot is deleted, all messages retained in the snapshot /// are immediately dropped. After a snapshot is deleted, a new one may be /// created with the same name, but the new one has no association with the old /// snapshot or its subscription, unless the same subscription is specified. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Google.Protobuf.WellKnownTypes.Empty> DeleteSnapshotAsync(global::Google.Cloud.PubSub.V1.DeleteSnapshotRequest request, grpc::CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_DeleteSnapshot, null, options, request); } /// <summary> /// Seeks an existing subscription to a point in time or to a given snapshot, /// whichever is provided in the request. Snapshots are used in /// &lt;a href="https://cloud.google.com/pubsub/docs/replay-overview">Seek&lt;/a> /// operations, which allow /// you to manage message acknowledgments in bulk. That is, you can set the /// acknowledgment state of messages in an existing subscription to the state /// captured by a snapshot. Note that both the subscription and the snapshot /// must be on the same topic.&lt;br>&lt;br> /// &lt;b>BETA:&lt;/b> This feature is part of a beta release. This API might be /// changed in backward-incompatible ways and is not recommended for production /// use. It is not subject to any SLA or deprecation policy. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Google.Cloud.PubSub.V1.SeekResponse Seek(global::Google.Cloud.PubSub.V1.SeekRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) { return Seek(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Seeks an existing subscription to a point in time or to a given snapshot, /// whichever is provided in the request. Snapshots are used in /// &lt;a href="https://cloud.google.com/pubsub/docs/replay-overview">Seek&lt;/a> /// operations, which allow /// you to manage message acknowledgments in bulk. That is, you can set the /// acknowledgment state of messages in an existing subscription to the state /// captured by a snapshot. Note that both the subscription and the snapshot /// must be on the same topic.&lt;br>&lt;br> /// &lt;b>BETA:&lt;/b> This feature is part of a beta release. This API might be /// changed in backward-incompatible ways and is not recommended for production /// use. It is not subject to any SLA or deprecation policy. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Google.Cloud.PubSub.V1.SeekResponse Seek(global::Google.Cloud.PubSub.V1.SeekRequest request, grpc::CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_Seek, null, options, request); } /// <summary> /// Seeks an existing subscription to a point in time or to a given snapshot, /// whichever is provided in the request. Snapshots are used in /// &lt;a href="https://cloud.google.com/pubsub/docs/replay-overview">Seek&lt;/a> /// operations, which allow /// you to manage message acknowledgments in bulk. That is, you can set the /// acknowledgment state of messages in an existing subscription to the state /// captured by a snapshot. Note that both the subscription and the snapshot /// must be on the same topic.&lt;br>&lt;br> /// &lt;b>BETA:&lt;/b> This feature is part of a beta release. This API might be /// changed in backward-incompatible ways and is not recommended for production /// use. It is not subject to any SLA or deprecation policy. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Google.Cloud.PubSub.V1.SeekResponse> SeekAsync(global::Google.Cloud.PubSub.V1.SeekRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) { return SeekAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Seeks an existing subscription to a point in time or to a given snapshot, /// whichever is provided in the request. Snapshots are used in /// &lt;a href="https://cloud.google.com/pubsub/docs/replay-overview">Seek&lt;/a> /// operations, which allow /// you to manage message acknowledgments in bulk. That is, you can set the /// acknowledgment state of messages in an existing subscription to the state /// captured by a snapshot. Note that both the subscription and the snapshot /// must be on the same topic.&lt;br>&lt;br> /// &lt;b>BETA:&lt;/b> This feature is part of a beta release. This API might be /// changed in backward-incompatible ways and is not recommended for production /// use. It is not subject to any SLA or deprecation policy. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Google.Cloud.PubSub.V1.SeekResponse> SeekAsync(global::Google.Cloud.PubSub.V1.SeekRequest request, grpc::CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_Seek, null, options, request); } /// <summary>Creates a new instance of client from given <c>ClientBaseConfiguration</c>.</summary> protected override SubscriberClient NewInstance(ClientBaseConfiguration configuration) { return new SubscriberClient(configuration); } } /// <summary>Creates service definition that can be registered with a server</summary> /// <param name="serviceImpl">An object implementing the server-side handling logic.</param> public static grpc::ServerServiceDefinition BindService(SubscriberBase serviceImpl) { return grpc::ServerServiceDefinition.CreateBuilder() .AddMethod(__Method_CreateSubscription, serviceImpl.CreateSubscription) .AddMethod(__Method_GetSubscription, serviceImpl.GetSubscription) .AddMethod(__Method_UpdateSubscription, serviceImpl.UpdateSubscription) .AddMethod(__Method_ListSubscriptions, serviceImpl.ListSubscriptions) .AddMethod(__Method_DeleteSubscription, serviceImpl.DeleteSubscription) .AddMethod(__Method_ModifyAckDeadline, serviceImpl.ModifyAckDeadline) .AddMethod(__Method_Acknowledge, serviceImpl.Acknowledge) .AddMethod(__Method_Pull, serviceImpl.Pull) .AddMethod(__Method_StreamingPull, serviceImpl.StreamingPull) .AddMethod(__Method_ModifyPushConfig, serviceImpl.ModifyPushConfig) .AddMethod(__Method_GetSnapshot, serviceImpl.GetSnapshot) .AddMethod(__Method_ListSnapshots, serviceImpl.ListSnapshots) .AddMethod(__Method_CreateSnapshot, serviceImpl.CreateSnapshot) .AddMethod(__Method_UpdateSnapshot, serviceImpl.UpdateSnapshot) .AddMethod(__Method_DeleteSnapshot, serviceImpl.DeleteSnapshot) .AddMethod(__Method_Seek, serviceImpl.Seek).Build(); } } } #endregion
72.107774
391
0.709051
[ "Apache-2.0" ]
alexdoan102/google-cloud-dotnet
apis/Google.Cloud.PubSub.V1/Google.Cloud.PubSub.V1/PubsubGrpc.cs
163,252
C#
using CompanyName.ProjectName.NotificationManagement.EntityFrameworkCore; using Volo.Abp.Modularity; namespace CompanyName.ProjectName.NotificationManagement { /* Domain tests are configured to use the EF Core provider. * You can switch to MongoDB, however your domain tests should be * database independent anyway. */ [DependsOn( typeof(NotificationManagementEntityFrameworkCoreTestModule) )] public class NotificationManagementDomainTestModule : AbpModule { } }
29.166667
73
0.740952
[ "MIT" ]
shuangbaojun/abp-vnext-pro
aspnet-core/modules/NotificationManagement/test/CompanyName.ProjectName.NotificationManagement.Domain.Tests/NotificationManagementDomainTestModule.cs
525
C#
#pragma checksum "E:\Projects\SoftUni\Abraks\Abraks\Abraks.Web\Areas\Admin\Views\Rewards\Add.cshtml" "{ff1816ec-aa5e-4d10-87f7-6f4963833460}" "da2b37cb093bf0314bec25c38c8d0c00527f180a" // <auto-generated/> #pragma warning disable 1591 [assembly: global::Microsoft.AspNetCore.Razor.Hosting.RazorCompiledItemAttribute(typeof(Abraks.Web.Areas.Admin.Views.Rewards.Areas_Admin_Views_Rewards_Add), @"mvc.1.0.view", @"/Areas/Admin/Views/Rewards/Add.cshtml")] [assembly:global::Microsoft.AspNetCore.Mvc.Razor.Compilation.RazorViewAttribute(@"/Areas/Admin/Views/Rewards/Add.cshtml", typeof(Abraks.Web.Areas.Admin.Views.Rewards.Areas_Admin_Views_Rewards_Add))] namespace Abraks.Web.Areas.Admin.Views.Rewards { #line hidden using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Rendering; using Microsoft.AspNetCore.Mvc.ViewFeatures; #line 1 "E:\Projects\SoftUni\Abraks\Abraks\Abraks.Web\Areas\Admin\Views\_ViewImports.cshtml" using Microsoft.AspNetCore.Identity; #line default #line hidden #line 2 "E:\Projects\SoftUni\Abraks\Abraks\Abraks.Web\Areas\Admin\Views\_ViewImports.cshtml" using Abraks.Web.Areas.Identity; #line default #line hidden #line 3 "E:\Projects\SoftUni\Abraks\Abraks\Abraks.Web\Areas\Admin\Views\_ViewImports.cshtml" using Abraks.Models; #line default #line hidden #line 4 "E:\Projects\SoftUni\Abraks\Abraks\Abraks.Web\Areas\Admin\Views\_ViewImports.cshtml" using Abraks.Common.Admin.ViewModels.Events; #line default #line hidden #line 5 "E:\Projects\SoftUni\Abraks\Abraks\Abraks.Web\Areas\Admin\Views\_ViewImports.cshtml" using Abraks.Common.Admin.BindingModels.Events; #line default #line hidden #line 6 "E:\Projects\SoftUni\Abraks\Abraks\Abraks.Web\Areas\Admin\Views\_ViewImports.cshtml" using Abraks.Common.Admin.ViewModels.Users; #line default #line hidden #line 7 "E:\Projects\SoftUni\Abraks\Abraks\Abraks.Web\Areas\Admin\Views\_ViewImports.cshtml" using Common.Admin.BindingModels.Rewards; #line default #line hidden #line 8 "E:\Projects\SoftUni\Abraks\Abraks\Abraks.Web\Areas\Admin\Views\_ViewImports.cshtml" using Common.Admin.ViewModels.Rewards; #line default #line hidden [global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"da2b37cb093bf0314bec25c38c8d0c00527f180a", @"/Areas/Admin/Views/Rewards/Add.cshtml")] [global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"9ea90e5ba6b7e2333ae611a16f811a64deee56f4", @"/Areas/Admin/Views/_ViewImports.cshtml")] public class Areas_Admin_Views_Rewards_Add : global::Microsoft.AspNetCore.Mvc.Razor.RazorPage<Common.Admin.BindingModels.Rewards.RewardAddingBindingModel> { private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_0 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("class", new global::Microsoft.AspNetCore.Html.HtmlString("col-sm-2 col-form-label"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_1 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("class", new global::Microsoft.AspNetCore.Html.HtmlString("form-control"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_2 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("class", new global::Microsoft.AspNetCore.Html.HtmlString("text-danger"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_3 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("asp-area", "Admin", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_4 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("asp-controller", "Rewards", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_5 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("asp-action", "Index", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_6 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("class", new global::Microsoft.AspNetCore.Html.HtmlString("btn btn-info"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_7 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("asp-action", "Add", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_8 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("method", "post", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_9 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("name", "_ValidationScriptsPartial", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); #line hidden #pragma warning disable 0169 private string __tagHelperStringValueBuffer; #pragma warning restore 0169 private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperExecutionContext __tagHelperExecutionContext; private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperRunner __tagHelperRunner = new global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperRunner(); private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperScopeManager __backed__tagHelperScopeManager = null; private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperScopeManager __tagHelperScopeManager { get { if (__backed__tagHelperScopeManager == null) { __backed__tagHelperScopeManager = new global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperScopeManager(StartTagHelperWritingScope, EndTagHelperWritingScope); } return __backed__tagHelperScopeManager; } } private global::Microsoft.AspNetCore.Mvc.TagHelpers.FormTagHelper __Microsoft_AspNetCore_Mvc_TagHelpers_FormTagHelper; private global::Microsoft.AspNetCore.Mvc.TagHelpers.RenderAtEndOfFormTagHelper __Microsoft_AspNetCore_Mvc_TagHelpers_RenderAtEndOfFormTagHelper; private global::Microsoft.AspNetCore.Mvc.TagHelpers.LabelTagHelper __Microsoft_AspNetCore_Mvc_TagHelpers_LabelTagHelper; private global::Microsoft.AspNetCore.Mvc.TagHelpers.InputTagHelper __Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper; private global::Microsoft.AspNetCore.Mvc.TagHelpers.ValidationMessageTagHelper __Microsoft_AspNetCore_Mvc_TagHelpers_ValidationMessageTagHelper; private global::Microsoft.AspNetCore.Mvc.TagHelpers.TextAreaTagHelper __Microsoft_AspNetCore_Mvc_TagHelpers_TextAreaTagHelper; private global::Microsoft.AspNetCore.Mvc.TagHelpers.AnchorTagHelper __Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper; private global::Microsoft.AspNetCore.Mvc.TagHelpers.PartialTagHelper __Microsoft_AspNetCore_Mvc_TagHelpers_PartialTagHelper; #pragma warning disable 1998 public async override global::System.Threading.Tasks.Task ExecuteAsync() { #line 2 "E:\Projects\SoftUni\Abraks\Abraks\Abraks.Web\Areas\Admin\Views\Rewards\Add.cshtml" ViewData["Title"] = "Add Reward"; #line default #line hidden BeginContext(114, 31, true); WriteLiteral("\r\n<h2>Add Reward</h2>\r\n<br />\r\n"); EndContext(); BeginContext(145, 1808, false); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("form", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "edcba04962f74194a85ac9e125966841", async() => { BeginContext(224, 83, true); WriteLiteral("\r\n\r\n <div class=\"container\">\r\n <div class=\"form-group row\">\r\n "); EndContext(); BeginContext(307, 62, false); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("label", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "7cd3f4f7163041ab9de0a8e5669d6ccc", async() => { } ); __Microsoft_AspNetCore_Mvc_TagHelpers_LabelTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.LabelTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_LabelTagHelper); #line 12 "E:\Projects\SoftUni\Abraks\Abraks\Abraks.Web\Areas\Admin\Views\Rewards\Add.cshtml" __Microsoft_AspNetCore_Mvc_TagHelpers_LabelTagHelper.For = ModelExpressionProvider.CreateModelExpression(ViewData, __model => __model.Name); #line default #line hidden __tagHelperExecutionContext.AddTagHelperAttribute("asp-for", __Microsoft_AspNetCore_Mvc_TagHelpers_LabelTagHelper.For, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_0); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); EndContext(); BeginContext(369, 54, true); WriteLiteral("\r\n <div class=\"col-sm-8\">\r\n "); EndContext(); BeginContext(423, 45, false); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("input", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.SelfClosing, "a776731e54b34029ad598aefe367431c", async() => { } ); __Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.InputTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper); #line 14 "E:\Projects\SoftUni\Abraks\Abraks\Abraks.Web\Areas\Admin\Views\Rewards\Add.cshtml" __Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper.For = ModelExpressionProvider.CreateModelExpression(ViewData, __model => __model.Name); #line default #line hidden __tagHelperExecutionContext.AddTagHelperAttribute("asp-for", __Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper.For, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_1); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); EndContext(); BeginContext(468, 18, true); WriteLiteral("\r\n "); EndContext(); BeginContext(486, 59, false); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("span", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "646ebdfd7c7f4b59b3298273074217a1", async() => { } ); __Microsoft_AspNetCore_Mvc_TagHelpers_ValidationMessageTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.ValidationMessageTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_ValidationMessageTagHelper); #line 15 "E:\Projects\SoftUni\Abraks\Abraks\Abraks.Web\Areas\Admin\Views\Rewards\Add.cshtml" __Microsoft_AspNetCore_Mvc_TagHelpers_ValidationMessageTagHelper.For = ModelExpressionProvider.CreateModelExpression(ViewData, __model => __model.Name); #line default #line hidden __tagHelperExecutionContext.AddTagHelperAttribute("asp-validation-for", __Microsoft_AspNetCore_Mvc_TagHelpers_ValidationMessageTagHelper.For, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_2); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); EndContext(); BeginContext(545, 90, true); WriteLiteral("\r\n </div>\r\n </div>\r\n\r\n <div class=\"form-group row\">\r\n "); EndContext(); BeginContext(635, 69, false); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("label", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "c537da3a3c224bd09d4f7a2315c5ad20", async() => { } ); __Microsoft_AspNetCore_Mvc_TagHelpers_LabelTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.LabelTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_LabelTagHelper); #line 20 "E:\Projects\SoftUni\Abraks\Abraks\Abraks.Web\Areas\Admin\Views\Rewards\Add.cshtml" __Microsoft_AspNetCore_Mvc_TagHelpers_LabelTagHelper.For = ModelExpressionProvider.CreateModelExpression(ViewData, __model => __model.Description); #line default #line hidden __tagHelperExecutionContext.AddTagHelperAttribute("asp-for", __Microsoft_AspNetCore_Mvc_TagHelpers_LabelTagHelper.For, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_0); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); EndContext(); BeginContext(704, 54, true); WriteLiteral("\r\n <div class=\"col-sm-8\">\r\n "); EndContext(); BeginContext(758, 64, false); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("textarea", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "fe87d5e705d84824bce09b1482bc3aa6", async() => { } ); __Microsoft_AspNetCore_Mvc_TagHelpers_TextAreaTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.TextAreaTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_TextAreaTagHelper); #line 22 "E:\Projects\SoftUni\Abraks\Abraks\Abraks.Web\Areas\Admin\Views\Rewards\Add.cshtml" __Microsoft_AspNetCore_Mvc_TagHelpers_TextAreaTagHelper.For = ModelExpressionProvider.CreateModelExpression(ViewData, __model => __model.Description); #line default #line hidden __tagHelperExecutionContext.AddTagHelperAttribute("asp-for", __Microsoft_AspNetCore_Mvc_TagHelpers_TextAreaTagHelper.For, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_1); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); EndContext(); BeginContext(822, 18, true); WriteLiteral("\r\n "); EndContext(); BeginContext(840, 66, false); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("span", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "52683896a60142ea9499aa6b22bfae1e", async() => { } ); __Microsoft_AspNetCore_Mvc_TagHelpers_ValidationMessageTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.ValidationMessageTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_ValidationMessageTagHelper); #line 23 "E:\Projects\SoftUni\Abraks\Abraks\Abraks.Web\Areas\Admin\Views\Rewards\Add.cshtml" __Microsoft_AspNetCore_Mvc_TagHelpers_ValidationMessageTagHelper.For = ModelExpressionProvider.CreateModelExpression(ViewData, __model => __model.Description); #line default #line hidden __tagHelperExecutionContext.AddTagHelperAttribute("asp-validation-for", __Microsoft_AspNetCore_Mvc_TagHelpers_ValidationMessageTagHelper.For, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_2); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); EndContext(); BeginContext(906, 90, true); WriteLiteral("\r\n </div>\r\n </div>\r\n\r\n <div class=\"form-group row\">\r\n "); EndContext(); BeginContext(996, 66, false); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("label", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "3cda31367c754b40b004d397bd9117f1", async() => { } ); __Microsoft_AspNetCore_Mvc_TagHelpers_LabelTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.LabelTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_LabelTagHelper); #line 28 "E:\Projects\SoftUni\Abraks\Abraks\Abraks.Web\Areas\Admin\Views\Rewards\Add.cshtml" __Microsoft_AspNetCore_Mvc_TagHelpers_LabelTagHelper.For = ModelExpressionProvider.CreateModelExpression(ViewData, __model => __model.ImageUrl); #line default #line hidden __tagHelperExecutionContext.AddTagHelperAttribute("asp-for", __Microsoft_AspNetCore_Mvc_TagHelpers_LabelTagHelper.For, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_0); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); EndContext(); BeginContext(1062, 54, true); WriteLiteral("\r\n <div class=\"col-sm-8\">\r\n "); EndContext(); BeginContext(1116, 49, false); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("input", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.SelfClosing, "ca790ddd870a4a3b93611773dee8debe", async() => { } ); __Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.InputTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper); #line 30 "E:\Projects\SoftUni\Abraks\Abraks\Abraks.Web\Areas\Admin\Views\Rewards\Add.cshtml" __Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper.For = ModelExpressionProvider.CreateModelExpression(ViewData, __model => __model.ImageUrl); #line default #line hidden __tagHelperExecutionContext.AddTagHelperAttribute("asp-for", __Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper.For, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_1); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); EndContext(); BeginContext(1165, 18, true); WriteLiteral("\r\n "); EndContext(); BeginContext(1183, 63, false); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("span", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "2a33e9e4ef2f486b8c9442534e1c7488", async() => { } ); __Microsoft_AspNetCore_Mvc_TagHelpers_ValidationMessageTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.ValidationMessageTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_ValidationMessageTagHelper); #line 31 "E:\Projects\SoftUni\Abraks\Abraks\Abraks.Web\Areas\Admin\Views\Rewards\Add.cshtml" __Microsoft_AspNetCore_Mvc_TagHelpers_ValidationMessageTagHelper.For = ModelExpressionProvider.CreateModelExpression(ViewData, __model => __model.ImageUrl); #line default #line hidden __tagHelperExecutionContext.AddTagHelperAttribute("asp-validation-for", __Microsoft_AspNetCore_Mvc_TagHelpers_ValidationMessageTagHelper.For, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_2); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); EndContext(); BeginContext(1246, 90, true); WriteLiteral("\r\n </div>\r\n </div>\r\n\r\n <div class=\"form-group row\">\r\n "); EndContext(); BeginContext(1336, 63, false); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("label", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "f743b7b8060f47f2938eb971eb2c2b4c", async() => { } ); __Microsoft_AspNetCore_Mvc_TagHelpers_LabelTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.LabelTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_LabelTagHelper); #line 36 "E:\Projects\SoftUni\Abraks\Abraks\Abraks.Web\Areas\Admin\Views\Rewards\Add.cshtml" __Microsoft_AspNetCore_Mvc_TagHelpers_LabelTagHelper.For = ModelExpressionProvider.CreateModelExpression(ViewData, __model => __model.Event); #line default #line hidden __tagHelperExecutionContext.AddTagHelperAttribute("asp-for", __Microsoft_AspNetCore_Mvc_TagHelpers_LabelTagHelper.For, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_0); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); EndContext(); BeginContext(1399, 54, true); WriteLiteral("\r\n <div class=\"col-sm-8\">\r\n "); EndContext(); BeginContext(1453, 46, false); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("input", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.SelfClosing, "9270357af74d40d29010c11a38135bee", async() => { } ); __Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.InputTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper); #line 38 "E:\Projects\SoftUni\Abraks\Abraks\Abraks.Web\Areas\Admin\Views\Rewards\Add.cshtml" __Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper.For = ModelExpressionProvider.CreateModelExpression(ViewData, __model => __model.Event); #line default #line hidden __tagHelperExecutionContext.AddTagHelperAttribute("asp-for", __Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper.For, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_1); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); EndContext(); BeginContext(1499, 18, true); WriteLiteral("\r\n "); EndContext(); BeginContext(1517, 60, false); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("span", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "2734e3ba0ca74a7682c446487835ee03", async() => { } ); __Microsoft_AspNetCore_Mvc_TagHelpers_ValidationMessageTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.ValidationMessageTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_ValidationMessageTagHelper); #line 39 "E:\Projects\SoftUni\Abraks\Abraks\Abraks.Web\Areas\Admin\Views\Rewards\Add.cshtml" __Microsoft_AspNetCore_Mvc_TagHelpers_ValidationMessageTagHelper.For = ModelExpressionProvider.CreateModelExpression(ViewData, __model => __model.Event); #line default #line hidden __tagHelperExecutionContext.AddTagHelperAttribute("asp-validation-for", __Microsoft_AspNetCore_Mvc_TagHelpers_ValidationMessageTagHelper.For, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_2); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); EndContext(); BeginContext(1577, 224, true); WriteLiteral("\r\n </div>\r\n </div>\r\n\r\n <div class=\"form-group row\">\r\n <div class=\"col-sm-8 offset-2\">\r\n <input type=\"submit\" class=\"btn btn-success\" value=\"Add Rewards\" />\r\n "); EndContext(); BeginContext(1801, 95, false); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("a", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "b62e23b6cce6444e9b6b76692290e682", async() => { BeginContext(1886, 6, true); WriteLiteral("Cancel"); EndContext(); } ); __Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.AnchorTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper); __Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper.Area = (string)__tagHelperAttribute_3.Value; __tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_3); __Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper.Controller = (string)__tagHelperAttribute_4.Value; __tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_4); __Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper.Action = (string)__tagHelperAttribute_5.Value; __tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_5); __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_6); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); EndContext(); BeginContext(1896, 50, true); WriteLiteral("\r\n </div>\r\n </div>\r\n </div>\r\n"); EndContext(); } ); __Microsoft_AspNetCore_Mvc_TagHelpers_FormTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.FormTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_FormTagHelper); __Microsoft_AspNetCore_Mvc_TagHelpers_RenderAtEndOfFormTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.RenderAtEndOfFormTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_RenderAtEndOfFormTagHelper); __Microsoft_AspNetCore_Mvc_TagHelpers_FormTagHelper.Area = (string)__tagHelperAttribute_3.Value; __tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_3); __Microsoft_AspNetCore_Mvc_TagHelpers_FormTagHelper.Controller = (string)__tagHelperAttribute_4.Value; __tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_4); __Microsoft_AspNetCore_Mvc_TagHelpers_FormTagHelper.Action = (string)__tagHelperAttribute_7.Value; __tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_7); __Microsoft_AspNetCore_Mvc_TagHelpers_FormTagHelper.Method = (string)__tagHelperAttribute_8.Value; __tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_8); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); EndContext(); BeginContext(1953, 4, true); WriteLiteral("\r\n\r\n"); EndContext(); DefineSection("Scripts", async() => { BeginContext(1975, 6, true); WriteLiteral("\r\n "); EndContext(); BeginContext(1981, 44, false); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("partial", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.SelfClosing, "d1617f06e85547ccbb37e2538a760701", async() => { } ); __Microsoft_AspNetCore_Mvc_TagHelpers_PartialTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.PartialTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_PartialTagHelper); __Microsoft_AspNetCore_Mvc_TagHelpers_PartialTagHelper.Name = (string)__tagHelperAttribute_9.Value; __tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_9); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); EndContext(); BeginContext(2025, 2, true); WriteLiteral("\r\n"); EndContext(); } ); } #pragma warning restore 1998 [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.ViewFeatures.IModelExpressionProvider ModelExpressionProvider { get; private set; } [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.IUrlHelper Url { get; private set; } [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.IViewComponentHelper Component { get; private set; } [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.Rendering.IJsonHelper Json { get; private set; } [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.Rendering.IHtmlHelper<Common.Admin.BindingModels.Rewards.RewardAddingBindingModel> Html { get; private set; } } } #pragma warning restore 1591
74.024341
361
0.716255
[ "MIT" ]
Ceappie/Abraks
Abraks.Web/obj/Debug/netcoreapp2.1/Razor/Areas/Admin/Views/Rewards/Add.g.cshtml.cs
36,494
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. using System.Collections.Generic; using Unity.Profiling; using UnityEngine; using UnityEngine.EventSystems; namespace Microsoft.MixedReality.Toolkit.SpatialAwareness { /// <summary> /// Class providing the default implementation of the <see cref="IMixedRealitySpatialAwarenessSystem"/> interface. /// </summary> [HelpURL("https://microsoft.github.io/MixedRealityToolkit-Unity/Documentation/SpatialAwareness/SpatialAwarenessGettingStarted.html")] public class MixedRealitySpatialAwarenessSystem : BaseDataProviderAccessCoreSystem, IMixedRealitySpatialAwarenessSystem, IMixedRealityCapabilityCheck { /// <summary> /// Constructor. /// </summary> /// <param name="registrar">The <see cref="IMixedRealityServiceRegistrar"/> instance that loaded the service.</param> /// <param name="profile">The configuration profile for the service.</param> [System.Obsolete("This constructor is obsolete (registrar parameter is no longer required) and will be removed in a future version of the Microsoft Mixed Reality Toolkit.")] public MixedRealitySpatialAwarenessSystem( IMixedRealityServiceRegistrar registrar, MixedRealitySpatialAwarenessSystemProfile profile) : this(profile) { Registrar = registrar; } /// <summary> /// Constructor. /// </summary> /// <param name="registrar">The <see cref="IMixedRealityServiceRegistrar"/> instance that loaded the service.</param> /// <param name="profile">The configuration profile for the service.</param> public MixedRealitySpatialAwarenessSystem( MixedRealitySpatialAwarenessSystemProfile profile) : base(profile) { } /// <inheritdoc/> public override string Name { get; protected set; } = "Mixed Reality Spatial Awareness System"; #region IMixedRealityCapabilityCheck Implementation /// <inheritdoc /> public bool CheckCapability(MixedRealityCapability capability) { foreach (var observer in GetDataProviders<IMixedRealitySpatialAwarenessObserver>()) { IMixedRealityCapabilityCheck capabilityChecker = observer as IMixedRealityCapabilityCheck; // If one of the running data providers supports the requested capability, // the application has the needed support to leverage the desired functionality. if ((capabilityChecker != null) && capabilityChecker.CheckCapability(capability)) { return true; } } return false; } #endregion IMixedRealityCapabilityCheck Implementation #region IMixedRealityToolkitService Implementation private MixedRealitySpatialAwarenessEventData<SpatialAwarenessMeshObject> meshEventData = null; /// <inheritdoc/> public override void Initialize() { base.Initialize(); meshEventData = new MixedRealitySpatialAwarenessEventData<SpatialAwarenessMeshObject>(EventSystem.current); InitializeInternal(); } /// <summary> /// Performs initialization tasks for the spatial awareness system. /// </summary> private void InitializeInternal() { MixedRealitySpatialAwarenessSystemProfile profile = ConfigurationProfile as MixedRealitySpatialAwarenessSystemProfile; if (profile != null && GetDataProviders<IMixedRealitySpatialAwarenessObserver>().Count == 0) { // Register the spatial observers. for (int i = 0; i < profile.ObserverConfigurations.Length; i++) { MixedRealitySpatialObserverConfiguration configuration = profile.ObserverConfigurations[i]; object[] args = { this, configuration.ComponentName, configuration.Priority, configuration.ObserverProfile }; RegisterDataProvider<IMixedRealitySpatialAwarenessObserver>( configuration.ComponentType.Type, configuration.RuntimePlatform, args); } } } /// <inheritdoc/> public override void Disable() { base.Disable(); foreach (var provider in GetDataProviders<IMixedRealitySpatialAwarenessObserver>()) { UnregisterDataProvider(provider); } } /// <inheritdoc/> public override void Enable() { InitializeInternal(); // Ensure data providers are enabled (performed by the base class) base.Enable(); } /// <inheritdoc/> public override void Reset() { base.Reset(); Disable(); Initialize(); Enable(); } /// <inheritdoc/> public override void Destroy() { // Cleanup game objects created during execution. if (Application.isPlaying) { // Detach the child objects and clean up the parent. if (spatialAwarenessObjectParent != null) { if (Application.isEditor) { Object.DestroyImmediate(spatialAwarenessObjectParent); } else { spatialAwarenessObjectParent.transform.DetachChildren(); Object.Destroy(spatialAwarenessObjectParent); } spatialAwarenessObjectParent = null; } } base.Destroy(); } #endregion IMixedRealityToolkitService Implementation #region IMixedRealitySpatialAwarenessSystem Implementation /// <summary> /// The parent object, in the hierarchy, under which all observed game objects will be placed. /// </summary> private GameObject spatialAwarenessObjectParent = null; /// <inheritdoc /> public GameObject SpatialAwarenessObjectParent => spatialAwarenessObjectParent != null ? spatialAwarenessObjectParent : (spatialAwarenessObjectParent = CreateSpatialAwarenessObjectParent); /// <summary> /// Creates the parent for spatial awareness objects so that the scene hierarchy does not get overly cluttered. /// </summary> /// <returns> /// The <see href="https://docs.unity3d.com/ScriptReference/GameObject.html">GameObject</see> to which spatial awareness created objects will be parented. /// </returns> private GameObject CreateSpatialAwarenessObjectParent { get { GameObject newParent = new GameObject("Spatial Awareness System"); MixedRealityPlayspace.AddChild(newParent.transform); return newParent; } } /// <inheritdoc /> public GameObject CreateSpatialAwarenessObservationParent(string name) { GameObject objectParent = new GameObject(name); objectParent.transform.parent = SpatialAwarenessObjectParent.transform; return objectParent; } private uint nextSourceId = 0; /// <inheritdoc /> public uint GenerateNewSourceId() { return nextSourceId++; } private MixedRealitySpatialAwarenessSystemProfile spatialAwarenessSystemProfile = null; /// <inheritdoc/> public MixedRealitySpatialAwarenessSystemProfile SpatialAwarenessSystemProfile { get { if (spatialAwarenessSystemProfile == null) { spatialAwarenessSystemProfile = ConfigurationProfile as MixedRealitySpatialAwarenessSystemProfile; } return spatialAwarenessSystemProfile; } } private static readonly ProfilerMarker GetObserversPerfMarker = new ProfilerMarker("[MRTK] MixedRealitySpatialAwarenessSystem.GetObservers"); /// <inheritdoc /> public IReadOnlyList<IMixedRealitySpatialAwarenessObserver> GetObservers() { using (GetObserversPerfMarker.Auto()) { return GetDataProviders() as IReadOnlyList<IMixedRealitySpatialAwarenessObserver>; } } private static readonly ProfilerMarker GetObserversTPerfMarker = new ProfilerMarker("[MRTK] MixedRealitySpatialAwarenessSystem.GetObservers<T>"); /// <inheritdoc /> public IReadOnlyList<T> GetObservers<T>() where T : IMixedRealitySpatialAwarenessObserver { using (GetObserversTPerfMarker.Auto()) { return GetDataProviders<T>(); } } private static readonly ProfilerMarker GetObserverPerfMarker = new ProfilerMarker("[MRTK] MixedRealitySpatialAwarenessSystem.GetObserver"); /// <inheritdoc /> public IMixedRealitySpatialAwarenessObserver GetObserver(string name) { using (GetObserverPerfMarker.Auto()) { return GetDataProvider(name) as IMixedRealitySpatialAwarenessObserver; } } private static readonly ProfilerMarker GetObserverTPerfMarker = new ProfilerMarker("[MRTK] MixedRealitySpatialAwarenessSystem.GetObserver<T>"); /// <inheritdoc /> public T GetObserver<T>(string name = null) where T : IMixedRealitySpatialAwarenessObserver { using (GetObserverTPerfMarker.Auto()) { return GetDataProvider<T>(name); } } #region IMixedRealityDataProviderAccess Implementation private static readonly ProfilerMarker GetDataProvidersPerfMarker = new ProfilerMarker("[MRTK] MixedRealitySpatialAwarenessSystem.GetDataProviders"); /// <inheritdoc /> public override IReadOnlyList<T> GetDataProviders<T>() { using (GetDataProvidersPerfMarker.Auto()) { if (!typeof(IMixedRealitySpatialAwarenessObserver).IsAssignableFrom(typeof(T))) { return null; } return base.GetDataProviders<T>(); } } private static readonly ProfilerMarker GetDataProviderPerfMarker = new ProfilerMarker("[MRTK] MixedRealitySpatialAwarenessSystem.GetDataProvider"); /// <inheritdoc /> public override T GetDataProvider<T>(string name = null) { using (GetDataProviderPerfMarker.Auto()) { if (!typeof(IMixedRealitySpatialAwarenessObserver).IsAssignableFrom(typeof(T))) { return default(T); } return base.GetDataProvider<T>(name); } } #endregion IMixedRealityDataProviderAccess Implementation private static readonly ProfilerMarker ResumeObserversPerfMarker = new ProfilerMarker("[MRTK] MixedRealitySpatialAwarenessSystem.ResumeObservers"); /// <inheritdoc /> public void ResumeObservers() { using (ResumeObserversPerfMarker.Auto()) { foreach (var observer in GetDataProviders<IMixedRealitySpatialAwarenessObserver>()) { observer.Resume(); } } } private static readonly ProfilerMarker ResumeObserversTPerfMarker = new ProfilerMarker("[MRTK] MixedRealitySpatialAwarenessSystem.ResumeObservers<T>"); /// <inheritdoc /> public void ResumeObservers<T>() where T : IMixedRealitySpatialAwarenessObserver { using (ResumeObserversTPerfMarker.Auto()) { foreach (var observer in GetDataProviders<IMixedRealitySpatialAwarenessObserver>()) { if (observer is T) { observer.Resume(); } } } } private static readonly ProfilerMarker ResumeObserverPerfMarker = new ProfilerMarker("[MRTK] MixedRealitySpatialAwarenessSystem.ResumeObserver"); /// <inheritdoc /> public void ResumeObserver<T>(string name) where T : IMixedRealitySpatialAwarenessObserver { using (ResumeObserverPerfMarker.Auto()) { foreach (var observer in GetDataProviders<IMixedRealitySpatialAwarenessObserver>()) { if (observer is T && observer.Name == name) { observer.Resume(); break; } } } } private static readonly ProfilerMarker SuspendObserversPerfMarker = new ProfilerMarker("[MRTK] MixedRealitySpatialAwarenessSystem.SuspendObservers"); /// <inheritdoc /> public void SuspendObservers() { using (SuspendObserversPerfMarker.Auto()) { foreach (var observer in GetDataProviders<IMixedRealitySpatialAwarenessObserver>()) { observer.Suspend(); } } } private static readonly ProfilerMarker SuspendObserversTPerfMarker = new ProfilerMarker("[MRTK] MixedRealitySpatialAwarenessSystem.SuspendObservers<T>"); /// <inheritdoc /> public void SuspendObservers<T>() where T : IMixedRealitySpatialAwarenessObserver { using (SuspendObserversTPerfMarker.Auto()) { foreach (var observer in GetDataProviders<IMixedRealitySpatialAwarenessObserver>()) { if (observer is T) { observer.Suspend(); } } } } private static readonly ProfilerMarker SuspendObserverPerfMarker = new ProfilerMarker("[MRTK] MixedRealitySpatialAwarenessSystem.SuspendObserver"); /// <inheritdoc /> public void SuspendObserver<T>(string name) where T : IMixedRealitySpatialAwarenessObserver { using (SuspendObserverPerfMarker.Auto()) { foreach (var observer in GetDataProviders<IMixedRealitySpatialAwarenessObserver>()) { if (observer is T && observer.Name == name) { observer.Suspend(); break; } } } } private static readonly ProfilerMarker ClearObservationsPerfMarker = new ProfilerMarker("[MRTK] MixedRealitySpatialAwarenessSystem.ClearObservations"); /// <inheritdoc /> public void ClearObservations() { using (ClearObservationsPerfMarker.Auto()) { foreach (var observer in GetDataProviders<IMixedRealitySpatialAwarenessObserver>()) { observer.ClearObservations(); } } } private static readonly ProfilerMarker ClearObservationsTPerfMarker = new ProfilerMarker("[MRTK] MixedRealitySpatialAwarenessSystem.ClearObservations<T>"); /// <inheritdoc /> public void ClearObservations<T>(string name) where T : IMixedRealitySpatialAwarenessObserver { using (ClearObservationsTPerfMarker.Auto()) { T observer = GetObserver<T>(name); observer?.ClearObservations(); } } #endregion IMixedRealitySpatialAwarenessSystem Implementation } }
37.619159
196
0.600211
[ "MIT" ]
MRW-Eric/MixedRealityToolkit-Unity
Assets/MRTK/Services/SpatialAwarenessSystem/MixedRealitySpatialAwarenessSystem.cs
16,103
C#
// // Copyright (c) 2004-2018 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of Jaroslaw Kowalski nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // #if !NETSTANDARD namespace NLog.UnitTests.LayoutRenderers { using System.Collections.Specialized; using NLog.Internal; using NLog.LayoutRenderers; using Xunit; public class AppSettingTests : NLogTestBase { [Fact] public void UseAppSettingTest() { var configurationManager = new MockConfigurationManager(); const string expected = "appSettingTestValue"; configurationManager.AppSettings["appSettingTestKey"] = expected; var appSettingLayoutRenderer = new AppSettingLayoutRenderer { ConfigurationManager = configurationManager, Name = "appSettingTestKey", }; var rendered = appSettingLayoutRenderer.Render(LogEventInfo.CreateNullEvent()); Assert.Equal(expected, rendered); } [Fact] public void AppSettingOverridesDefaultTest() { var configurationManager = new MockConfigurationManager(); const string expected = "appSettingTestValue"; configurationManager.AppSettings["appSettingTestKey"] = expected; var appSettingLayoutRenderer = new AppSettingLayoutRenderer { ConfigurationManager = configurationManager, Name = "appSettingTestKey", Default = "UseDefault", }; var rendered = appSettingLayoutRenderer.Render(LogEventInfo.CreateNullEvent()); Assert.Equal(expected, rendered); } [Fact] public void FallbackToDefaultTest() { var configurationManager = new MockConfigurationManager(); const string expected = "UseDefault"; var appSettingLayoutRenderer = new AppSettingLayoutRenderer { ConfigurationManager = configurationManager, Name = "notFound", Default = "UseDefault", }; var rendered = appSettingLayoutRenderer.Render(LogEventInfo.CreateNullEvent()); Assert.Equal(expected, rendered); } [Fact] public void NoAppSettingTest() { var configurationManager = new MockConfigurationManager(); var appSettingLayoutRenderer = new AppSettingLayoutRenderer { ConfigurationManager = configurationManager, Name = "notFound", }; var rendered = appSettingLayoutRenderer.Render(LogEventInfo.CreateNullEvent()); Assert.Equal(string.Empty, rendered); } private class MockConfigurationManager : IConfigurationManager { public MockConfigurationManager() { AppSettings = new NameValueCollection(); } public NameValueCollection AppSettings { get; private set; } } } } #endif
36.967742
100
0.65925
[ "BSD-3-Clause" ]
Flokri/NLog
tests/NLog.UnitTests/LayoutRenderers/AppSettingTests.cs
4,584
C#
using System; using System.Collections.Generic; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Configuration.Memory; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using Xunit; namespace Gelf.Extensions.Logging.Tests { public class LoggingBuilderExtensionsTests { [Fact] public void Reads_GELF_logger_options_from_logging_configuration_section() { var configuration = new ConfigurationBuilder().Add(new MemoryConfigurationSource { InitialData = new Dictionary<string, string> { ["Logging:GELF:IncludeScopes"] = "false", ["Logging:GELF:Protocol"] = "HTTP", ["Logging:GELF:Host"] = "graylog-host" } }).Build(); var serviceCollection = new ServiceCollection() .AddLogging(loggingBuilder => loggingBuilder .AddConfiguration(configuration.GetSection("Logging")) .AddGelf(o => o.LogSource = "post-configured-log-source")); using var provider = serviceCollection.BuildServiceProvider(); var options = provider.GetRequiredService<IOptions<GelfLoggerOptions>>(); Assert.False(options.Value.IncludeScopes); Assert.Equal(GelfProtocol.Http, options.Value.Protocol); Assert.Equal("graylog-host", options.Value.Host); Assert.Equal("post-configured-log-source", options.Value.LogSource); } [Fact] public void Reads_GELF_logger_options_default_values() { var configuration = new ConfigurationBuilder().Build(); var serviceCollection = new ServiceCollection() .AddLogging(loggingBuilder => loggingBuilder .AddConfiguration(configuration.GetSection("Logging")) .AddGelf()); using var provider = serviceCollection.BuildServiceProvider(); var options = provider.GetRequiredService<IOptions<GelfLoggerOptions>>(); Assert.Equal(GelfProtocol.Udp, options.Value.Protocol); Assert.Equal(12201, options.Value.Port); Assert.Equal(512, options.Value.UdpCompressionThreshold); Assert.Equal(8192, options.Value.UdpMaxChunkSize); Assert.Equal(TimeSpan.FromSeconds(30), options.Value.HttpTimeout); Assert.True(options.Value.IncludeScopes); Assert.True(options.Value.CompressUdp); Assert.False(options.Value.IncludeMessageTemplates); } } }
41.092308
92
0.639835
[ "MIT" ]
joepb/gelf-extensions-logging
test/Gelf.Extensions.Logging.Tests/LoggingBuilderExtensionsTests.cs
2,673
C#
using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; namespace SokobanMonoGame.GameSystem.UI { interface UIElement { void Update(GameTime gameTime); void Draw(SpriteBatch spriteBatch); } }
19.75
43
0.7173
[ "Apache-2.0" ]
yichen0831/SokobanMonoGame
SokobanMonoGame/GameSystem/UI/UIElement.cs
239
C#
using System; using System.Collections.Generic; using System.Diagnostics; using System.Text; namespace MatrixMultiply { /// <summary> /// Class for taking measurements /// </summary> public static class Measurements { /// <summary> /// Gets elapsed time of function work /// </summary> /// <param name="function">Function to measure</param> /// <param name="matrix1">First matrix to multiply</param> /// <param name="matrix2">Second matrix to multiply</param> /// <returns>Elapsed time while function was working</returns> public static long GetTime(Func<Matrix, Matrix, Matrix> function, Matrix matrix1, Matrix matrix2) { var watch = new Stopwatch(); watch.Start(); var res = function(matrix1, matrix2); watch.Stop(); return watch.ElapsedMilliseconds; } /// <summary> /// Counts average time of matrix multiply with different dimension /// </summary> /// <param name="func">Function to take measurements on</param> static public void PrintMeasurements(Func<Matrix, Matrix, Matrix> func) { var start = 100; var step = 100; var stop = 1500; var amountOfMeasurements = 20; var range = 1000; for (var matrixDimension = start; matrixDimension <= stop; matrixDimension += step) { long expectedValue = 0; long variance = 0; for (var counter = 0; counter < amountOfMeasurements; counter++) { var matrix1 = new Matrix(matrixDimension, matrixDimension, range); var matrix2 = new Matrix(matrixDimension, matrixDimension, range); var time = GetTime(func, matrix1, matrix2); expectedValue += time; variance += time * time; } expectedValue /= amountOfMeasurements; variance /= amountOfMeasurements; variance -= expectedValue * expectedValue; Console.WriteLine($"Measurements on {matrixDimension}x{matrixDimension} matrix:"); Console.WriteLine($"Average time: {(double)(expectedValue) / 1000} seconds, standart deviation: {Math.Round(Math.Sqrt(variance) / 1000, 5)} seconds\n"); } } } }
40.196721
168
0.568108
[ "MIT" ]
AndersenSemenov/SPbU-hometask-3sem
Task_01/MatrixMultiply/Measurements.cs
2,454
C#
using Microsoft.EntityFrameworkCore.Migrations; using System; using System.Collections.Generic; namespace SeaBlog.Migrations { public partial class Upgraded_To_Abp_v3_6_1 : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.AlterColumn<string>( name: "BrowserInfo", table: "AbpUserLoginAttempts", maxLength: 512, nullable: true, oldClrType: typeof(string), oldMaxLength: 256, oldNullable: true); migrationBuilder.AlterColumn<string>( name: "BrowserInfo", table: "AbpEntityChangeSets", maxLength: 512, nullable: true, oldClrType: typeof(string), oldMaxLength: 256, oldNullable: true); migrationBuilder.AlterColumn<string>( name: "BrowserInfo", table: "AbpAuditLogs", maxLength: 512, nullable: true, oldClrType: typeof(string), oldMaxLength: 256, oldNullable: true); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.AlterColumn<string>( name: "BrowserInfo", table: "AbpUserLoginAttempts", maxLength: 256, nullable: true, oldClrType: typeof(string), oldMaxLength: 512, oldNullable: true); migrationBuilder.AlterColumn<string>( name: "BrowserInfo", table: "AbpEntityChangeSets", maxLength: 256, nullable: true, oldClrType: typeof(string), oldMaxLength: 512, oldNullable: true); migrationBuilder.AlterColumn<string>( name: "BrowserInfo", table: "AbpAuditLogs", maxLength: 256, nullable: true, oldClrType: typeof(string), oldMaxLength: 512, oldNullable: true); } } }
32.142857
71
0.509333
[ "MIT" ]
crybigsea/SeaBlog.ABP
aspnet-core/src/SeaBlog.EntityFrameworkCore/Migrations/20180509121141_Upgraded_To_Abp_v3_6_1.cs
2,252
C#
using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Reflection; using System.Text.RegularExpressions; using Signum.Engine.Basics; using Signum.Engine.DynamicQuery; using Signum.Engine.Maps; using Signum.Engine.Operations; using Signum.Entities.Translation; using Signum.Utilities; namespace Signum.Engine.Translation { public static class TranslationReplacementLogic { public static ResetLazy<Dictionary<CultureInfo, TranslationReplacementPack>> ReplacementsLazy = null!; public static void Start(SchemaBuilder sb) { if (sb.NotDefined(MethodInfo.GetCurrentMethod())) { sb.Include<TranslationReplacementEntity>() .WithSave(TranslationReplacementOperation.Save) .WithDelete(TranslationReplacementOperation.Delete) .WithQuery(() => e => new { Entity = e, e.Id, e.CultureInfo, e.WrongTranslation, e.RightTranslation, }); sb.AddUniqueIndex<TranslationReplacementEntity>(tr => new { tr.CultureInfo, tr.WrongTranslation }); ReplacementsLazy = sb.GlobalLazy(() => Database.Query<TranslationReplacementEntity>() .AgGroupToDictionary(a => a.CultureInfo.ToCultureInfo(), gr => { var dic = gr.ToDictionaryEx(a => a.WrongTranslation, a => a.RightTranslation, StringComparer.InvariantCultureIgnoreCase, "wrong translations"); var regex = new Regex(dic.Keys.ToString(Regex.Escape, "|"), RegexOptions.IgnoreCase); return new TranslationReplacementPack(dic, regex); }), new InvalidateWith(typeof(TranslationReplacementEntity))); } } public static void ReplacementFeedback(CultureInfo ci, string translationWrong, string translationRight) { if (string.IsNullOrWhiteSpace(translationWrong)) throw new ArgumentNullException(translationWrong); if (string.IsNullOrWhiteSpace(translationRight)) throw new ArgumentNullException(translationRight); if (!Database.Query<TranslationReplacementEntity>().Any(a => a.CultureInfo == ci.ToCultureInfoEntity() && a.WrongTranslation == translationWrong)) using (OperationLogic.AllowSave<TranslationReplacementEntity>()) new TranslationReplacementEntity { CultureInfo = ci.ToCultureInfoEntity(), WrongTranslation = translationWrong, RightTranslation = translationRight, }.Save(); } } public class TranslationReplacementPack { public Dictionary<string, string> Dictionary; public Regex Regex; public TranslationReplacementPack(Dictionary<string, string> dictionary, Regex regex) { Dictionary = dictionary; Regex = regex; } } }
40.39759
168
0.581271
[ "MIT" ]
AlejandroCano/extensions
Signum.Engine.Extensions/Translation/TranslationReplacementLogic.cs
3,353
C#
using SitecoreCognitiveServices.Foundation.NexSDK.View.Enums; namespace SitecoreCognitiveServices.Foundation.NexSDK.View.Models { public class ViewDeleteCriteria { public ViewDeleteCriteria(string name) { this.Name = name; } /// <summary> /// The name of the View to delete /// </summary> public string Name { get; set; } /// <summary> /// Options for cascading the delete.<br/> /// When cascade=sessions, also deletes sessions associated with the view /// </summary> public ViewCascadeOptions? Cascade { get; set; } } }
28
81
0.60559
[ "MIT" ]
markstiles/SitecoreCognitiveServices.Core
src/Foundation/NexSDK/code/View/Models/ViewDeleteCriteria.cs
646
C#
using System; using System.Collections.Generic; using System.Linq; using Foundation; using UIKit; namespace AzurePushNotificationSample.iOS { public class Application { // This is the main entry point of the application. static void Main(string[] args) { // if you want to use a different Application Delegate class from "AppDelegate" // you can specify it here. UIApplication.Main(args, null, "AppDelegate"); } } }
23.761905
91
0.645291
[ "MIT" ]
CrossGeeks/AzurePushNotificationPlugin
samples/AzurePushNotificationSample/AzurePushNotificationSample.iOS/Main.cs
501
C#
using BeatTogether.Providers; using HarmonyLib; using HMUI; using IPA.Utilities; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using QPSPDP = BeatTogether.Patches.QuickPlaySongPacksDropdownPatch; namespace BeatTogether.Patches { [HarmonyPatch(typeof(MultiplayerModeSelectionFlowCoordinator), "DidActivate")] class MultiplayerModeSelectionFlowCoordinatorDidActivatePatch { internal static void Prefix(MultiplayerModeSelectionFlowCoordinator __instance, JoiningLobbyViewController ____joiningLobbyViewController, JoinQuickPlayViewController ____joinQuickPlayViewController) { GameClassInstanceProvider classInstanceProvider = GameClassInstanceProvider.Instance; classInstanceProvider.MultiplayerModeSelectionFlowCoordinator = __instance; classInstanceProvider.JoinQuickPlayViewController = ____joinQuickPlayViewController; classInstanceProvider.JoiningLobbyViewController = ____joiningLobbyViewController; } } //[HarmonyPatch(typeof(MultiplayerModeSelectionFlowCoordinator), "HandleMultiplayerLobbyControllerDidFinish")] //class MultiplayerModeSelectionFlowCoordinatorPatch //{ // internal static bool isWaitingForPacks = false; // internal static bool Prefix(MultiplayerModeSelectionFlowCoordinator __instance, MultiplayerModeSelectionViewController viewController, MultiplayerModeSelectionViewController.MenuButton menuButton, JoiningLobbyViewController ____joiningLobbyViewController, JoinQuickPlayViewController ____joinQuickPlayViewController) // { // if (menuButton == MultiplayerModeSelectionViewController.MenuButton.QuickPlay && QPSPDP.TaskState == QPSPDP.TaskStateEnum.Running) // { // ____joiningLobbyViewController.Init("Loading Quickplay Pack Overrides"); // ____joiningLobbyViewController.didCancelEvent += OnDidCancelEvent; // //__instance.InvokeMethod<object, MultiplayerModeSelectionFlowCoordinator>("ReplaceTopViewController", new object[] { // // ____joiningLobbyViewController, null, ViewController.AnimationType.In, ViewController.AnimationDirection.Vertical}); // __instance.InvokeMethod<object, MultiplayerModeSelectionFlowCoordinator>("PresentViewController", new object[] { // ____joiningLobbyViewController, null, ViewController.AnimationDirection.Vertical, false}); // isWaitingForPacks = true; // ShowQuickPlayLobbyScreenIfWaiting(); // return false; // } else // { // isWaitingForPacks = false; // return true; // } // } // internal static void OnDidCancelEvent() // { // GameClassInstanceProvider classInstanceProvider = GameClassInstanceProvider.Instance; // //classInstanceProvider.JoinQuickPlayViewController.gameObject.SetActive(true); // //classInstanceProvider.MultiplayerModeSelectionFlowCoordinator.InvokeMethod<object, MultiplayerModeSelectionFlowCoordinator>("DismissViewController", new object[] { // // classInstanceProvider.JoiningLobbyViewController, ViewController.AnimationDirection.Vertical, null, false}); // classInstanceProvider.MultiplayerModeSelectionFlowCoordinator.InvokeMethod<object, MultiplayerModeSelectionFlowCoordinator>("PresentViewController", new object[] { // classInstanceProvider.MultiplayerModeSelectionViewController, null, ViewController.AnimationDirection.Vertical, false}); // //classInstanceProvider.MultiplayerModeSelectionFlowCoordinator.InvokeMethod<object, MultiplayerModeSelectionFlowCoordinator>("ReplaceTopViewController", new object[] { // // classInstanceProvider.MultiplayerModeSelectionViewController, null, ViewController.AnimationType.In, ViewController.AnimationDirection.Vertical}); // classInstanceProvider.JoiningLobbyViewController.didCancelEvent -= OnDidCancelEvent; // } // public static void ShowQuickPlayLobbyScreenIfWaiting() // { // GameClassInstanceProvider classInstanceProvider = GameClassInstanceProvider.Instance; // MultiplayerModeSelectionFlowCoordinator instance = classInstanceProvider.MultiplayerModeSelectionFlowCoordinator; // if (isWaitingForPacks && instance != null && classInstanceProvider.JoinQuickPlayViewController != null && QPSPDP.TaskState != QPSPDP.TaskStateEnum.Running) // { // classInstanceProvider.JoinQuickPlayViewController.Setup( // ReflectionUtil.GetField<MasterServerQuickPlaySetupData, MultiplayerModeSelectionFlowCoordinator>(instance, "_masterServerQuickPlaySetupData"), // ReflectionUtil.GetField<PlayerDataModel, MultiplayerModeSelectionFlowCoordinator>(instance, "_playerDataModel").playerData.multiplayerModeSettings); // instance.InvokeMethod<object, MultiplayerModeSelectionFlowCoordinator>("PresentViewController", new object[] { // classInstanceProvider.JoinQuickPlayViewController, null, ViewController.AnimationDirection.Vertical, false}); // } // else // { // Plugin.Logger.Debug($"isWaitingForPacks: {(isWaitingForPacks ? "true" : "false")}, QPSPDP.TaskState: {(QPSPDP.TaskState)}"); // } // } //} }
65.465116
326
0.722913
[ "MIT" ]
BeatTogether/BeatTogether
Patches/MultiplayerModeSelectionFlowCoordinatorPatch.cs
5,632
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.VisualStudio.TestTools.UnitTesting; using Microsoft.Win32; using SUT = CustomUpdateEngine.RunVbScriptAction; namespace Unit_Tests_CustomeUpdateEngine { class RunVbScriptAction { [TestClass] public class Constructor_Should { [TestMethod] public void ProperlyInitializeProperties_WhenCalled() { // Arrange SUT action = new SUT(Tools.GetXmlFragment("RunVbScript.CustAct")); // Act // Assert Assert.AreEqual(action.FullPath, @"C:\Users\Courtel\Documents\Visual Studio 2013\Projects\Wsus Package Publisher2\Unit Tests-CustomeUpdateEngine\Templates for Unit Tests\RunVbScriptAndReturn4.vbs"); Assert.IsTrue(action.KillProcess); Assert.AreEqual(action.Parameters, "4 arg1 arg2 \"arg with space\""); Assert.IsTrue(action.StoreToVariable); Assert.AreEqual(action.DelayBeforeKilling, 10); } } [TestClass] public class Run_Should { [TestMethod] public void ReturnFour_WhenCallingAScriptThatReturnFour() { // Arrange SUT action = new SUT(Tools.GetXmlFragment("RunVbScript.CustAct")); var finalResult = Tools.GetReturnCodeAction(); finalResult.ReturnMethod = global::CustomUpdateEngine.ReturnCodeAction.ReturnCodeMethod.Variable; // Act action.Run(ref finalResult); // Assert Assert.AreEqual(4, finalResult.ReturnValue); } [TestMethod] public void KillProcess_WhenTakingTooMuchTime() { // Arrange SUT action = new SUT(Tools.GetXmlFragment("RunVbScriptAndWait.CustAct")); var finalResult = Tools.GetReturnCodeAction(); finalResult.ReturnMethod = global::CustomUpdateEngine.ReturnCodeAction.ReturnCodeMethod.Variable; System.Diagnostics.Stopwatch chrono = new System.Diagnostics.Stopwatch(); // Act chrono.Start(); action.Run(ref finalResult); chrono.Stop(); // Assert Assert.AreEqual(60.0, chrono.Elapsed.TotalSeconds, 2); Assert.AreEqual(-1, finalResult.ReturnValue); } [TestMethod] public void DoNotKillProcess_WhenTakingLessTimeThatAllowed() { // Arrange SUT action = new SUT(Tools.GetXmlFragment("RunVbScriptAndWaitAndDoNotKill.CustAct")); var finalResult = Tools.GetReturnCodeAction(); finalResult.ReturnMethod = global::CustomUpdateEngine.ReturnCodeAction.ReturnCodeMethod.Variable; System.Diagnostics.Stopwatch chrono = new System.Diagnostics.Stopwatch(); // Act chrono.Start(); action.Run(ref finalResult); chrono.Stop(); // Assert Assert.AreEqual(10.0, chrono.Elapsed.TotalSeconds, 2); Assert.AreEqual(finalResult.ReturnMethod, global::CustomUpdateEngine.ReturnCodeAction.ReturnCodeMethod.Variable); Assert.AreEqual(255, finalResult.ReturnValue); } } } }
38.097826
214
0.592011
[ "MIT" ]
DCourtel/Wsus_Package_Publisher
Unit Tests/CustomeUpdateEngine/Actions/RunVbScriptAction.cs
3,507
C#
using UnityEngine; using SanAndreasUnity.Importing.Animation; namespace SanAndreasUnity.Behaviours.Weapons { public class FThrower : Weapon { // public override AnimId AimAnim { // get { // return new AnimId (AnimGroup.Flame, AnimIndex.FLAME_fire); // } // } } }
14.894737
64
0.699647
[ "MIT" ]
Almahmudrony/SanAndreasUnity
Assets/Scripts/Behaviours/Weapons/FThrower.cs
285
C#
using FlowScriptEngine; using PPDEditorCommon; namespace FlowScriptEnginePPDEditor.FlowSourceObjects.Layer { [ToolTipText("Layer_Value_Summary")] public partial class ValueFlowSourceObject : FlowSourceObjectBase { public override string Name { get { return "PPDEditor.Layer.Value"; } } [ToolTipText("Layer_Value_Layer")] public ILayer Layer { set; private get; } [ToolTipText("Layer_Value_SelectedMarks")] public object[] SelectedMarks { get { SetValue(nameof(Layer)); if (Layer != null) { return Layer.SelectedMarks; } return new object[0]; } } [ToolTipText("Layer_Value_Marks")] public object[] Marks { get { SetValue(nameof(Layer)); if (Layer != null) { return Layer.Marks; } return new object[0]; } } [ToolTipText("Layer_Value_SelectedMark")] public IEditorMarkInfo SelectedMark { get { SetValue(nameof(Layer)); if (Layer != null) { return Layer.SelectedMark; } return null; } } [ToolTipText("Layer_Value_IsSelected")] public bool IsSelected { get { SetValue(nameof(Layer)); if (Layer != null) { return Layer.IsSelected; } return false; } } } }
23.538462
69
0.431373
[ "Apache-2.0" ]
KHCmaster/PPD
Win/FlowScriptEnginePPDEditor/FlowSourceObjects/Layer/ValueFlowSourceObject.cs
1,838
C#
namespace MLSoftware.OTA { [System.CodeDom.Compiler.GeneratedCodeAttribute("Xsd2Code", "4.2.0.31")] [System.SerializableAttribute()] [System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true, Namespace="http://www.opentravel.org/OTA/2003/05")] public enum TicketingInfoTypeBookingChangeType { /// <remarks/> FlightSegment, /// <remarks/> TravelerName, /// <remarks/> Both, } }
26.611111
118
0.609603
[ "MIT" ]
Franklin89/OTA-Library
src/OTA-Library/TicketingInfoTypeBookingChangeType.cs
479
C#
using iMotto.Adapter.Readers.Requests; using iMotto.Data; using iMotto.Data.Entities; using System.Collections.Generic; using System.Threading.Tasks; namespace iMotto.Adapter.Readers.Handlers { class ReadTagCollectionsHandler:BaseHandler<ReadTagCollectionsRequest> { private readonly ICollectionRepo _collectionRepo; public ReadTagCollectionsHandler(ICollectionRepo collectionRepo) { _collectionRepo = collectionRepo; } protected async override Task<HandleResult> HandleCoreAsync(ReadTagCollectionsRequest reqObj) { var collections = await _collectionRepo.GetCollectionsByTagAsync(reqObj.Tag, reqObj.PIndex, reqObj.PSize); return new HandleResult<List<Collection>> { State=HandleStates.Success, Data=collections }; } } }
29.566667
118
0.687711
[ "MIT" ]
imotto/imotto.dnx
iMotto.Adapter.Readers/Handlers/ReadTagCollectionsHandler.cs
889
C#
using UnityEngine; using System.Collections; using System.Collections.Generic; using Pinwheel.TextureGraph; namespace Pinwheel.TextureGraph { [TNodeMetadata( Title = "Gradient Axial", CreationMenu = "Shapes & Patterns/Gradient Axial", Icon = "TextureGraph/NodeIcons/GradientAxial", Documentation = "https://docs.google.com/document/d/1kDkFHAmuMNFTbfnBpYPkjw99CrVvUNr8_gFAJH2o-7s/edit#heading=h.6az5dlk86rr5")] public class TGradientAxialNode : TAbstractTextureNode { public class TConst { public static readonly string SHADER = "Hidden/TextureGraph/GradientAxial"; public static readonly int UV_TO_LINE_MATRIX = Shader.PropertyToID("_UvToLineMatrix"); public static readonly string REFLECTED = "REFLECTED"; public static readonly int PASS = 0; } public readonly TSlot outputSlot = new TSlot("Output", TSlotType.Output, TSlotDataType.Gray, 0); private Shader shader; private Material material; [SerializeField] private TVector2Parameter startPoint; public TVector2Parameter StartPoint { get { return startPoint; } set { startPoint = value; } } [SerializeField] private TVector2Parameter endPoint; public TVector2Parameter EndPoint { get { return endPoint; } set { endPoint = value; } } [SerializeField] private TBoolParameter reflected; public TBoolParameter Reflected { get { return reflected; } set { reflected = value; } } public TGradientAxialNode() : base() { startPoint = new TVector2Parameter() { value = new Vector2(0f, 0f) }; endPoint = new TVector2Parameter() { value = new Vector2(1f, 1f) }; reflected = new TBoolParameter() { value = false }; } public override TSlot GetMainOutputSlot() { return outputSlot; } public override void Execute(TGraphContext context) { RenderTexture targetRT = context.RequestTargetRT(TSlotReference.Create(GUID, outputSlot.Id), GetRenderTextureRequest(outputSlot)); TGraphUtilities.PrepareShaderAndMaterial(TConst.SHADER, ref shader, ref material); Vector3 pos = startPoint.value; Quaternion rotation = Quaternion.FromToRotation(Vector3.right, Vector3.Normalize(endPoint.value - startPoint.value)); float d = Vector3.Distance(startPoint.value, endPoint.value); Vector3 scale = new Vector3(d, d, 1); Matrix4x4 uvToLineMatrix = Matrix4x4.TRS(pos, rotation, scale).inverse; material.SetMatrix(TConst.UV_TO_LINE_MATRIX, uvToLineMatrix); if (Reflected.value == true) { material.EnableKeyword(TConst.REFLECTED); } else { material.DisableKeyword(TConst.REFLECTED); } TDrawing.DrawFullQuad(targetRT, material, TConst.PASS); } } }
32.598131
143
0.56078
[ "MIT" ]
Abelark/Project-3---Rocket-Punch
Assets/Polaris - Low Poly Ecosystem/TextureGraph/Core/Runtime/Nodes/TGradientAxialNode.cs
3,488
C#
using System; using System.Collections.Generic; namespace Zoologico { class Program { static void Main(string[] args) { List<AnimalPlus> animais = new List<AnimalPlus>(); int countCarnivoro = 0, countHerbivoro = 0; Console.WriteLine("====================================="); Console.WriteLine("Gerenciamento de animais do Zoológico"); Console.WriteLine("====================================="); for (int i = 0; i < 2; i++) { AnimalPlus animal = new AnimalPlus(); Console.WriteLine(" "); Console.Write("Insira a espécie: "); animal.Especie = Console.ReadLine(); Console.Write("Insira o peso: "); animal.Peso = Convert.ToDouble(Console.ReadLine()); Console.Write("Insira o tipo de alimentação (Carnívoro ou Herbívoro): "); animal.TipoAlimentacao = Console.ReadLine(); if (animal.TipoAlimentacao == "Carnívoro") { countCarnivoro++; } else { countHerbivoro++; } animais.Add(animal); } Console.WriteLine(" "); Console.WriteLine("Total de Animais Carnívoros: " + countCarnivoro); Console.WriteLine("Total de Animais Herbívoros: " + countHerbivoro); Console.ReadKey(); } } } //Implemente um programa que deverá informar quantos animais são carnívoros e quantos animais são herbívoros de 10 animais informados pelo usuário. //O usuário deverá informar a espécie (exemplos: leão, jacaré, tucano, etc), peso(exemplos: 30, 90.55, 100) e tipo de alimentação (exemplos: carnívoro, herbívoro) do animal. //IMPORTANTE //É obrigatório criar/utilizar uma classe quer herde a classe Animal para representar um animal em seu programa. Você deverá implementar nessa classe todas as características/métodos que não estiverem presentes na classe base Animal. //A classe também deverá possuir um método que exiba todos os dados do animal. //Envie todo o seu projeto compactado para testes.
40.214286
233
0.572824
[ "MIT" ]
camilasmarques/fundamentals-OOP
Zoologico/Program.cs
2,288
C#
using System.Xml; using FluentAssertions; using FluentAssertions.Primitives; namespace Test.OutlookMatters.Core.TestUtils { public static class ExtensionMethods { public static XmlAssertions WithNamespace(this StringAssertions assertions, string ns, string url) { return new XmlAssertions(assertions, ns, url); } public static void ContainXmlNode(this XmlAssertions assertion, string xpath, string because) { var doc = new XmlDocument(); doc.LoadXml(assertion.Subject); var nsManager = new XmlNamespaceManager(doc.NameTable); nsManager.AddNamespace(assertion.NamespaceKey, assertion.NamespaceUri); var node = doc.SelectSingleNode(xpath, nsManager); node.Should() .NotBeNull(because); } public static void DoNotContainXmlNode(this XmlAssertions assertion, string xpath, string because) { var doc = new XmlDocument(); doc.LoadXml(assertion.Subject); var nsManager = new XmlNamespaceManager(doc.NameTable); nsManager.AddNamespace(assertion.NamespaceKey, assertion.NamespaceUri); var node = doc.SelectSingleNode(xpath, nsManager); node.Should() .BeNull(because); } } }
35.289474
106
0.645041
[ "MIT" ]
ConnectionMaster/outlook-matters
OutlookMatters.Core.Test/TestUtils/ExtensionMethods.cs
1,341
C#
using System; using Xunit; using Training20200924.Questions; using System.Collections.Generic; using System.Linq; using Training20200924.Collections; namespace Training20200924.Test { public class AtCoderTester { [Theory] [InlineData(@"5 3 3 5 R 1 G 1 B 1 RGBRR", @"13")] [InlineData(@"3 3 3 5 R 1 G 3 B 2 RBR", @"5")] [InlineData(@"8 3 5 3 R 1 G 1 B 1 RRGRRBRR", @"31")] [InlineData(@"8 3 5 3 R 1 G 100 B 1 RRGRRBRR", @"126")] public void QuestionATest(string input, string output) { var outputs = SplitByNewLine(output); IAtCoderQuestion question = new QuestionA(); var answers = SplitByNewLine(question.Solve(input).Trim()); Assert.Equal(outputs, answers); } //[Theory] //[InlineData(@"", @"")] public void QuestionBTest(string input, string output) { var outputs = SplitByNewLine(output); IAtCoderQuestion question = new QuestionB(); var answers = SplitByNewLine(question.Solve(input).Trim()); Assert.Equal(outputs, answers); } //[Theory] //[InlineData(@"", @"")] public void QuestionCTest(string input, string output) { var outputs = SplitByNewLine(output); IAtCoderQuestion question = new QuestionC(); var answers = SplitByNewLine(question.Solve(input).Trim()); Assert.Equal(outputs, answers); } //[Theory] //[InlineData(@"", @"")] public void QuestionDTest(string input, string output) { var outputs = SplitByNewLine(output); IAtCoderQuestion question = new QuestionD(); var answers = SplitByNewLine(question.Solve(input).Trim()); Assert.Equal(outputs, answers); } //[Theory] //[InlineData(@"", @"")] public void QuestionETest(string input, string output) { var outputs = SplitByNewLine(output); IAtCoderQuestion question = new QuestionE(); var answers = SplitByNewLine(question.Solve(input).Trim()); Assert.Equal(outputs, answers); } //[Theory] //[InlineData(@"", @"")] public void QuestionFTest(string input, string output) { var outputs = SplitByNewLine(output); IAtCoderQuestion question = new QuestionF(); var answers = SplitByNewLine(question.Solve(input).Trim()); Assert.Equal(outputs, answers); } void AssertNearlyEqual(IEnumerable<string> expected, IEnumerable<string> actual, double acceptableError = 1e-6) { Assert.Equal(expected.Count(), actual.Count()); foreach (var (exp, act) in (expected, actual).Zip().Select(p => (double.Parse(p.v1), double.Parse(p.v2)))) { var error = act - exp; Assert.InRange(Math.Abs(error), 0, acceptableError); } } IEnumerable<string> SplitByNewLine(string input) => input?.Split(new[] { "\r\n", "\r", "\n" }, StringSplitOptions.None) ?? new string[0]; } }
27.594828
145
0.569197
[ "MIT" ]
terry-u16/AtCoder
Training20200924/Training20200924/Training20200924.Test/AtCoderTester.cs
3,201
C#
using EPiServer.SocialAlloy.Web.Social.Models; using EPiServer.SocialAlloy.Web.Social.Models.Groups; using EPiServer.SocialAlloy.Web.Social.Models.Moderation; namespace EPiServer.SocialAlloy.Web.Social.Repositories { /// <summary> /// The interface describing operations that manage community membership moderation. /// </summary> public interface ICommunityMembershipModerationRepository { /// <summary> /// Adds a new workflow to the underlying repository for a specified community. /// </summary> /// <param name="community">The community that will be associated with the workflow</param> void AddWorkflow(Community community); /// <summary> /// Submits a membership request to the specified community's /// moderation workflow for approval. /// </summary> /// <param name="member">The member information for the membership request</param> void AddAModeratedMember(CommunityMember member); /// <summary> /// Returns a view model supporting the presentation of community /// membership moderation information. /// </summary> /// <param name="workflowId">Identifier for the selected membership moderation workflow</param> /// <returns>View model of moderation information</returns> CommunityModerationViewModel Get(string workflowId); /// <summary> /// Retrieves relevant workflow state of a member for admission to a specific community /// </summary> /// <param name="user">The user reference for the member requesting community admission</param> /// <param name="community">The community id for the community the user is looking to gain admission</param> /// <returns>The workflowitem state in moderation</returns> string GetMembershipRequestState(string user, string community); /// <summary> /// Takes action on the specified workflow item, representing a /// membership request. /// </summary> /// <param name="workflowId">The id of the workflow </param> /// <param name="action">The moderation action to be taken</param> /// <param name="userId">The unique id of the user under moderation.</param> /// <param name="communityId">The unique id of the community to which membership has been requested.</param> void Moderate(string workflowId, string action, string userId, string communityId); /// <summary> /// Returns true if the specified community has a moderation workflow, /// false otherwise. /// </summary> /// <param name="communityId">ID of the community</param> /// <returns>True if the specified community has a moderation workflow, false otherwise</returns> bool IsModerated(string communityId); } }
47.966667
116
0.66991
[ "Apache-2.0" ]
episerver/SocialAlloy
src/EPiServer.SocialAlloy.Web/Social/Repositories/Moderation/ICommunityMembershipModerationRepository.cs
2,880
C#
#nullable enable using System.Diagnostics.Contracts; using System.Runtime.CompilerServices; using System.Threading.Tasks; using LanguageExt.TypeClasses; using static LanguageExt.Prelude; namespace LanguageExt { public partial class TryAsyncT { /// <summary> /// Traverses each value in the `ta` nested monad, Then applies the monadic rules of the return type /// (which is the input nested monad, flipped: so `M<N<A>>` becomes `N<M<A>>`). /// </summary> /// <typeparam name="A">Bound value type</typeparam> /// <param name="ta">The subject traversable</param> /// <returns>Mapped monad</returns> [Pure, MethodImpl(MethodImplOptions.AggressiveInlining)] public static TryAsync<Arr<A>> Sequence<A>(this Arr<TryAsync<A>> ta) => ta.Traverse(identity); /// <summary> /// Traverses each value in the `ta` nested monad, Then applies the monadic rules of the return type /// (which is the input nested monad, flipped: so `M<N<A>>` becomes `N<M<A>>`). /// </summary> /// <typeparam name="A">Bound value type</typeparam> /// <param name="ta">The subject traversable</param> /// <returns>Mapped monad</returns> [Pure, MethodImpl(MethodImplOptions.AggressiveInlining)] public static TryAsync<Either<L, A>> Sequence<L, A>(this Either<L, TryAsync<A>> ta) => ta.Traverse(identity); /// <summary> /// Traverses each value in the `ta` nested monad, Then applies the monadic rules of the return type /// (which is the input nested monad, flipped: so `M<N<A>>` becomes `N<M<A>>`). /// </summary> /// <typeparam name="A">Bound value type</typeparam> /// <param name="ta">The subject traversable</param> /// <returns>Mapped monad</returns> [Pure, MethodImpl(MethodImplOptions.AggressiveInlining)] public static TryAsync<EitherUnsafe<L, A>> Sequence<L, A>(this EitherUnsafe<L, TryAsync<A>> ta) => ta.Traverse(identity); /// <summary> /// Traverses each value in the `ta` nested monad, Then applies the monadic rules of the return type /// (which is the input nested monad, flipped: so `M<N<A>>` becomes `N<M<A>>`). /// </summary> /// <typeparam name="A">Bound value type</typeparam> /// <param name="ta">The subject traversable</param> /// <returns>Mapped monad</returns> [Pure, MethodImpl(MethodImplOptions.AggressiveInlining)] public static TryAsync<Identity<A>> Sequence<A>(this Identity<TryAsync<A>> ta) => ta.Traverse(identity); /// <summary> /// Traverses each value in the `ta` nested monad, Then applies the monadic rules of the return type /// (which is the input nested monad, flipped: so `M<N<A>>` becomes `N<M<A>>`). /// </summary> /// <typeparam name="A">Bound value type</typeparam> /// <param name="ta">The subject traversable</param> /// <returns>Mapped monad</returns> [Pure, MethodImpl(MethodImplOptions.AggressiveInlining)] public static TryAsync<Lst<A>> Sequence<A>(this Lst<TryAsync<A>> ta) => ta.Traverse(identity); /// <summary> /// Traverses each value in the `ta` nested monad, Then applies the monadic rules of the return type /// (which is the input nested monad, flipped: so `M<N<A>>` becomes `N<M<A>>`). /// </summary> /// <typeparam name="A">Bound value type</typeparam> /// <param name="ta">The subject traversable</param> /// <returns>Mapped monad</returns> [Pure, MethodImpl(MethodImplOptions.AggressiveInlining)] public static TryAsync<TryAsync<A>> Sequence<A>(this TryAsync<TryAsync<A>> ta) => ta.Traverse(identity); /// <summary> /// Traverses each value in the `ta` nested monad, Then applies the monadic rules of the return type /// (which is the input nested monad, flipped: so `M<N<A>>` becomes `N<M<A>>`). /// </summary> /// <typeparam name="A">Bound value type</typeparam> /// <param name="ta">The subject traversable</param> /// <returns>Mapped monad</returns> [Pure, MethodImpl(MethodImplOptions.AggressiveInlining)] public static TryAsync<Fin<A>> Sequence<A>(this Fin<TryAsync<A>> ta) => ta.Traverse(identity); /// <summary> /// Traverses each value in the `ta` nested monad, Then applies the monadic rules of the return type /// (which is the input nested monad, flipped: so `M<N<A>>` becomes `N<M<A>>`). /// </summary> /// <typeparam name="A">Bound value type</typeparam> /// <param name="ta">The subject traversable</param> /// <returns>Mapped monad</returns> [Pure, MethodImpl(MethodImplOptions.AggressiveInlining)] public static TryAsync<Option<A>> Sequence<A>(this Option<TryAsync<A>> ta) => ta.Traverse(identity); /// <summary> /// Traverses each value in the `ta` nested monad, Then applies the monadic rules of the return type /// (which is the input nested monad, flipped: so `M<N<A>>` becomes `N<M<A>>`). /// </summary> /// <typeparam name="A">Bound value type</typeparam> /// <param name="ta">The subject traversable</param> /// <returns>Mapped monad</returns> [Pure, MethodImpl(MethodImplOptions.AggressiveInlining)] public static TryAsync<OptionUnsafe<A>> Sequence<A>(this OptionUnsafe<TryAsync<A>> ta) => ta.Traverse(identity); /// <summary> /// Traverses each value in the `ta` nested monad, Then applies the monadic rules of the return type /// (which is the input nested monad, flipped: so `M<N<A>>` becomes `N<M<A>>`). /// </summary> /// <typeparam name="A">Bound value type</typeparam> /// <param name="ta">The subject traversable</param> /// <returns>Mapped monad</returns> [Pure, MethodImpl(MethodImplOptions.AggressiveInlining)] public static TryAsync<Set<A>> Sequence<A>(this Set<TryAsync<A>> ta) => ta.Traverse(identity); /// <summary> /// Traverses each value in the `ta` nested monad, Then applies the monadic rules of the return type /// (which is the input nested monad, flipped: so `M<N<A>>` becomes `N<M<A>>`). /// </summary> /// <typeparam name="A">Bound value type</typeparam> /// <param name="ta">The subject traversable</param> /// <returns>Mapped monad</returns> [Pure, MethodImpl(MethodImplOptions.AggressiveInlining)] public static TryAsync<HashSet<A>> Sequence<A>(this HashSet<TryAsync<A>> ta) => ta.Traverse(identity); /// <summary> /// Traverses each value in the `ta` nested monad, Then applies the monadic rules of the return type /// (which is the input nested monad, flipped: so `M<N<A>>` becomes `N<M<A>>`). /// </summary> /// <typeparam name="A">Bound value type</typeparam> /// <param name="ta">The subject traversable</param> /// <returns>Mapped monad</returns> [Pure, MethodImpl(MethodImplOptions.AggressiveInlining)] public static TryAsync<Try<A>> Sequence<A>(this Try<TryAsync<A>> ta) => ta.Traverse(identity); /// <summary> /// Traverses each value in the `ta` nested monad, Then applies the monadic rules of the return type /// (which is the input nested monad, flipped: so `M<N<A>>` becomes `N<M<A>>`). /// </summary> /// <typeparam name="A">Bound value type</typeparam> /// <param name="ta">The subject traversable</param> /// <returns>Mapped monad</returns> [Pure, MethodImpl(MethodImplOptions.AggressiveInlining)] public static TryAsync<TryOption<A>> Sequence<A>(this TryOption<TryAsync<A>> ta) => ta.Traverse(identity); /// <summary> /// Traverses each value in the `ta` nested monad, Then applies the monadic rules of the return type /// (which is the input nested monad, flipped: so `M<N<A>>` becomes `N<M<A>>`). /// </summary> /// <typeparam name="A">Bound value type</typeparam> /// <param name="ta">The subject traversable</param> /// <returns>Mapped monad</returns> [Pure, MethodImpl(MethodImplOptions.AggressiveInlining)] public static TryAsync<Validation<FAIL, A>> Sequence<FAIL, A>(this Validation<FAIL, TryAsync<A>> ta) => ta.Traverse(identity); /// <summary> /// Traverses each value in the `ta` nested monad, Then applies the monadic rules of the return type /// (which is the input nested monad, flipped: so `M<N<A>>` becomes `N<M<A>>`). /// </summary> /// <typeparam name="A">Bound value type</typeparam> /// <param name="ta">The subject traversable</param> /// <returns>Mapped monad</returns> [Pure, MethodImpl(MethodImplOptions.AggressiveInlining)] public static TryAsync<Validation<MonoidFail, FAIL, A>> Sequence<MonoidFail, FAIL, A>(this Validation<MonoidFail, FAIL, TryAsync<A>> ta) where MonoidFail : struct, Monoid<FAIL>, Eq<FAIL> => ta.Traverse(identity); /// <summary> /// Traverses each value in the `ta` nested monad, Then applies the monadic rules of the return type /// (which is the input nested monad, flipped: so `M<N<A>>` becomes `N<M<A>>`). /// </summary> /// <typeparam name="A">Bound value type</typeparam> /// <param name="ta">The subject traversable</param> /// <returns>Mapped monad</returns> [Pure, MethodImpl(MethodImplOptions.AggressiveInlining)] public static TryAsync<Task<A>> Sequence<A>(this Task<TryAsync<A>> ta) => ta.Traverse(identity); /// <summary> /// Traverses each value in the `ta` nested monad, Then applies the monadic rules of the return type /// (which is the input nested monad, flipped: so `M<N<A>>` becomes `N<M<A>>`). /// </summary> /// <typeparam name="A">Bound value type</typeparam> /// <param name="ta">The subject traversable</param> /// <returns>Mapped monad</returns> [Pure, MethodImpl(MethodImplOptions.AggressiveInlining)] public static TryAsync<OptionAsync<A>> Sequence<A>(this OptionAsync<TryAsync<A>> ta) => ta.Traverse(identity); /// <summary> /// Traverses each value in the `ta` nested monad, Then applies the monadic rules of the return type /// (which is the input nested monad, flipped: so `M<N<A>>` becomes `N<M<A>>`). /// </summary> /// <typeparam name="A">Bound value type</typeparam> /// <param name="ta">The subject traversable</param> /// <returns>Mapped monad</returns> [Pure, MethodImpl(MethodImplOptions.AggressiveInlining)] public static TryAsync<TryOptionAsync<A>> Sequence<A>(this TryOptionAsync<TryAsync<A>> ta) => ta.Traverse(identity); /// <summary> /// Traverses each value in the `ta` nested monad, Then applies the monadic rules of the return type /// (which is the input nested monad, flipped: so `M<N<A>>` becomes `N<M<A>>`). /// </summary> /// <typeparam name="A">Bound value type</typeparam> /// <param name="ta">The subject traversable</param> /// <returns>Mapped monad</returns> [Pure, MethodImpl(MethodImplOptions.AggressiveInlining)] public static TryAsync<EitherAsync<L, A>> Sequence<L, A>(this EitherAsync<L, TryAsync<A>> ta) => ta.Traverse(identity); /// <summary> /// Traverses each value in the `ta` nested monad, Then applies the monadic rules of the return type /// (which is the input nested monad, flipped: so `M<N<A>>` becomes `N<M<A>>`). /// </summary> /// <typeparam name="A">Bound value type</typeparam> /// <param name="ta">The subject traversable</param> /// <returns>Mapped monad</returns> [Pure, MethodImpl(MethodImplOptions.AggressiveInlining)] public static TryAsync<Aff<A>> Sequence<A>(this Aff<TryAsync<A>> ta) => ta.Traverse(identity); /// <summary> /// Traverses each value in the `ta` nested monad, Then applies the monadic rules of the return type /// (which is the input nested monad, flipped: so `M<N<A>>` becomes `N<M<A>>`). /// </summary> /// <typeparam name="A">Bound value type</typeparam> /// <param name="ta">The subject traversable</param> /// <returns>Mapped monad</returns> [Pure, MethodImpl(MethodImplOptions.AggressiveInlining)] public static TryAsync<Eff<A>> Sequence<A>(this Eff<TryAsync<A>> ta) => ta.Traverse(identity); } }
53.840816
144
0.603063
[ "MIT" ]
bmazzarol/language-ext
LanguageExt.Core/Transformer/Sequence0/TryAsyncT.cs
13,191
C#
using System.Linq; using finly.Data; using finly.Models; using HotChocolate; using HotChocolate.Types; namespace finly.GraphQL.Profiles { public class ProfileType : ObjectType<Profile> { protected override void Configure(IObjectTypeDescriptor<Profile> descriptor) { // Adding description of type object for documentation descriptor.Description("Represents the file holding the clients and any of their applications, such as mortgages, loans and insurance policies"); // Removing Profile.CreateDate from schema as do not want this exposed via API descriptor .Field(p => p.CreateDate).Ignore() .Description("The date this profile was added to the system"); descriptor .Field(p => p.DisplayName) .Description("Reference number for overall profile, visible within the platform."); descriptor .Field(p => p.Clients) .ResolveWith<Resolvers>(p => p.GetClients(default!, default)) .UseDbContext<AppDbContext>() .Description("The list of clients attached to the this profile."); } // Resolves how to link Clients to Profiles. private class Resolvers { public IQueryable<Client> GetClients(Profile profile, [ScopedService] AppDbContext context) { // Only return clients that are within the Profile return context.Clients.Where(p => p.ProfileId == profile.Id); } } } }
37.186047
157
0.617261
[ "Unlicense" ]
KaimanSolutions/FinLy
GraphQL/Profiles/ProfileType.cs
1,599
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 lightsail-2016-11-28.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.Lightsail.Model { /// <summary> /// Describes a load balancer SSL/TLS certificate. /// /// /// <para> /// TLS is just an updated, more secure version of Secure Socket Layer (SSL). /// </para> /// </summary> public partial class LoadBalancerTlsCertificate { private string _arn; private DateTime? _createdAt; private string _domainName; private List<LoadBalancerTlsCertificateDomainValidationRecord> _domainValidationRecords = new List<LoadBalancerTlsCertificateDomainValidationRecord>(); private LoadBalancerTlsCertificateFailureReason _failureReason; private bool? _isAttached; private DateTime? _issuedAt; private string _issuer; private string _keyAlgorithm; private string _loadBalancerName; private ResourceLocation _location; private string _name; private DateTime? _notAfter; private DateTime? _notBefore; private LoadBalancerTlsCertificateRenewalSummary _renewalSummary; private ResourceType _resourceType; private LoadBalancerTlsCertificateRevocationReason _revocationReason; private DateTime? _revokedAt; private string _serial; private string _signatureAlgorithm; private LoadBalancerTlsCertificateStatus _status; private string _subject; private List<string> _subjectAlternativeNames = new List<string>(); private string _supportCode; private List<Tag> _tags = new List<Tag>(); /// <summary> /// Gets and sets the property Arn. /// <para> /// The Amazon Resource Name (ARN) of the SSL/TLS certificate. /// </para> /// </summary> public string Arn { get { return this._arn; } set { this._arn = value; } } // Check to see if Arn property is set internal bool IsSetArn() { return this._arn != null; } /// <summary> /// Gets and sets the property CreatedAt. /// <para> /// The time when you created your SSL/TLS certificate. /// </para> /// </summary> public DateTime CreatedAt { get { return this._createdAt.GetValueOrDefault(); } set { this._createdAt = value; } } // Check to see if CreatedAt property is set internal bool IsSetCreatedAt() { return this._createdAt.HasValue; } /// <summary> /// Gets and sets the property DomainName. /// <para> /// The domain name for your SSL/TLS certificate. /// </para> /// </summary> public string DomainName { get { return this._domainName; } set { this._domainName = value; } } // Check to see if DomainName property is set internal bool IsSetDomainName() { return this._domainName != null; } /// <summary> /// Gets and sets the property DomainValidationRecords. /// <para> /// An array of LoadBalancerTlsCertificateDomainValidationRecord objects describing the /// records. /// </para> /// </summary> public List<LoadBalancerTlsCertificateDomainValidationRecord> DomainValidationRecords { get { return this._domainValidationRecords; } set { this._domainValidationRecords = value; } } // Check to see if DomainValidationRecords property is set internal bool IsSetDomainValidationRecords() { return this._domainValidationRecords != null && this._domainValidationRecords.Count > 0; } /// <summary> /// Gets and sets the property FailureReason. /// <para> /// The validation failure reason, if any, of the certificate. /// </para> /// /// <para> /// The following failure reasons are possible: /// </para> /// <ul> <li> /// <para> /// <b> <code>NO_AVAILABLE_CONTACTS</code> </b> - This failure applies to email validation, /// which is not available for Lightsail certificates. /// </para> /// </li> <li> /// <para> /// <b> <code>ADDITIONAL_VERIFICATION_REQUIRED</code> </b> - Lightsail requires additional /// information to process this certificate request. This can happen as a fraud-protection /// measure, such as when the domain ranks within the Alexa top 1000 websites. To provide /// the required information, use the <a href="https://console.aws.amazon.com/support/home">AWS /// Support Center</a> to contact AWS Support. /// </para> /// <note> /// <para> /// You cannot request a certificate for Amazon-owned domain names such as those ending /// in amazonaws.com, cloudfront.net, or elasticbeanstalk.com. /// </para> /// </note> </li> <li> /// <para> /// <b> <code>DOMAIN_NOT_ALLOWED</code> </b> - One or more of the domain names in the /// certificate request was reported as an unsafe domain by <a href="https://www.virustotal.com/gui/home/url">VirusTotal</a>. /// To correct the problem, search for your domain name on the <a href="https://www.virustotal.com/gui/home/url">VirusTotal</a> /// website. If your domain is reported as suspicious, see <a href="https://developers.google.com/web/fundamentals/security/hacked">Google /// Help for Hacked Websites</a> to learn what you can do. /// </para> /// /// <para> /// If you believe that the result is a false positive, notify the organization that is /// reporting the domain. VirusTotal is an aggregate of several antivirus and URL scanners /// and cannot remove your domain from a block list itself. After you correct the problem /// and the VirusTotal registry has been updated, request a new certificate. /// </para> /// /// <para> /// If you see this error and your domain is not included in the VirusTotal list, visit /// the <a href="https://console.aws.amazon.com/support/home">AWS Support Center</a> and /// create a case. /// </para> /// </li> <li> /// <para> /// <b> <code>INVALID_PUBLIC_DOMAIN</code> </b> - One or more of the domain names in /// the certificate request is not valid. Typically, this is because a domain name in /// the request is not a valid top-level domain. Try to request a certificate again, correcting /// any spelling errors or typos that were in the failed request, and ensure that all /// domain names in the request are for valid top-level domains. For example, you cannot /// request a certificate for <code>example.invalidpublicdomain</code> because <code>invalidpublicdomain</code> /// is not a valid top-level domain. /// </para> /// </li> <li> /// <para> /// <b> <code>OTHER</code> </b> - Typically, this failure occurs when there is a typographical /// error in one or more of the domain names in the certificate request. Try to request /// a certificate again, correcting any spelling errors or typos that were in the failed /// request. /// </para> /// </li> </ul> /// </summary> public LoadBalancerTlsCertificateFailureReason FailureReason { get { return this._failureReason; } set { this._failureReason = value; } } // Check to see if FailureReason property is set internal bool IsSetFailureReason() { return this._failureReason != null; } /// <summary> /// Gets and sets the property IsAttached. /// <para> /// When <code>true</code>, the SSL/TLS certificate is attached to the Lightsail load /// balancer. /// </para> /// </summary> public bool IsAttached { get { return this._isAttached.GetValueOrDefault(); } set { this._isAttached = value; } } // Check to see if IsAttached property is set internal bool IsSetIsAttached() { return this._isAttached.HasValue; } /// <summary> /// Gets and sets the property IssuedAt. /// <para> /// The time when the SSL/TLS certificate was issued. /// </para> /// </summary> public DateTime IssuedAt { get { return this._issuedAt.GetValueOrDefault(); } set { this._issuedAt = value; } } // Check to see if IssuedAt property is set internal bool IsSetIssuedAt() { return this._issuedAt.HasValue; } /// <summary> /// Gets and sets the property Issuer. /// <para> /// The issuer of the certificate. /// </para> /// </summary> public string Issuer { get { return this._issuer; } set { this._issuer = value; } } // Check to see if Issuer property is set internal bool IsSetIssuer() { return this._issuer != null; } /// <summary> /// Gets and sets the property KeyAlgorithm. /// <para> /// The algorithm used to generate the key pair (the public and private key). /// </para> /// </summary> public string KeyAlgorithm { get { return this._keyAlgorithm; } set { this._keyAlgorithm = value; } } // Check to see if KeyAlgorithm property is set internal bool IsSetKeyAlgorithm() { return this._keyAlgorithm != null; } /// <summary> /// Gets and sets the property LoadBalancerName. /// <para> /// The load balancer name where your SSL/TLS certificate is attached. /// </para> /// </summary> public string LoadBalancerName { get { return this._loadBalancerName; } set { this._loadBalancerName = value; } } // Check to see if LoadBalancerName property is set internal bool IsSetLoadBalancerName() { return this._loadBalancerName != null; } /// <summary> /// Gets and sets the property Location. /// <para> /// The AWS Region and Availability Zone where you created your certificate. /// </para> /// </summary> public ResourceLocation Location { get { return this._location; } set { this._location = value; } } // Check to see if Location property is set internal bool IsSetLocation() { return this._location != null; } /// <summary> /// Gets and sets the property Name. /// <para> /// The name of the SSL/TLS certificate (e.g., <code>my-certificate</code>). /// </para> /// </summary> public string Name { get { return this._name; } set { this._name = value; } } // Check to see if Name property is set internal bool IsSetName() { return this._name != null; } /// <summary> /// Gets and sets the property NotAfter. /// <para> /// The timestamp when the SSL/TLS certificate expires. /// </para> /// </summary> public DateTime NotAfter { get { return this._notAfter.GetValueOrDefault(); } set { this._notAfter = value; } } // Check to see if NotAfter property is set internal bool IsSetNotAfter() { return this._notAfter.HasValue; } /// <summary> /// Gets and sets the property NotBefore. /// <para> /// The timestamp when the SSL/TLS certificate is first valid. /// </para> /// </summary> public DateTime NotBefore { get { return this._notBefore.GetValueOrDefault(); } set { this._notBefore = value; } } // Check to see if NotBefore property is set internal bool IsSetNotBefore() { return this._notBefore.HasValue; } /// <summary> /// Gets and sets the property RenewalSummary. /// <para> /// An object that describes the status of the certificate renewal managed by Lightsail. /// </para> /// </summary> public LoadBalancerTlsCertificateRenewalSummary RenewalSummary { get { return this._renewalSummary; } set { this._renewalSummary = value; } } // Check to see if RenewalSummary property is set internal bool IsSetRenewalSummary() { return this._renewalSummary != null; } /// <summary> /// Gets and sets the property ResourceType. /// <para> /// The resource type (e.g., <code>LoadBalancerTlsCertificate</code>). /// </para> /// <ul> <li> /// <para> /// <b> <code>Instance</code> </b> - A Lightsail instance (a virtual private server) /// </para> /// </li> <li> /// <para> /// <b> <code>StaticIp</code> </b> - A static IP address /// </para> /// </li> <li> /// <para> /// <b> <code>KeyPair</code> </b> - The key pair used to connect to a Lightsail instance /// </para> /// </li> <li> /// <para> /// <b> <code>InstanceSnapshot</code> </b> - A Lightsail instance snapshot /// </para> /// </li> <li> /// <para> /// <b> <code>Domain</code> </b> - A DNS zone /// </para> /// </li> <li> /// <para> /// <b> <code>PeeredVpc</code> </b> - A peered VPC /// </para> /// </li> <li> /// <para> /// <b> <code>LoadBalancer</code> </b> - A Lightsail load balancer /// </para> /// </li> <li> /// <para> /// <b> <code>LoadBalancerTlsCertificate</code> </b> - An SSL/TLS certificate associated /// with a Lightsail load balancer /// </para> /// </li> <li> /// <para> /// <b> <code>Disk</code> </b> - A Lightsail block storage disk /// </para> /// </li> <li> /// <para> /// <b> <code>DiskSnapshot</code> </b> - A block storage disk snapshot /// </para> /// </li> </ul> /// </summary> public ResourceType ResourceType { get { return this._resourceType; } set { this._resourceType = value; } } // Check to see if ResourceType property is set internal bool IsSetResourceType() { return this._resourceType != null; } /// <summary> /// Gets and sets the property RevocationReason. /// <para> /// The reason the certificate was revoked. This value is present only when the certificate /// status is <code>REVOKED</code>. /// </para> /// </summary> public LoadBalancerTlsCertificateRevocationReason RevocationReason { get { return this._revocationReason; } set { this._revocationReason = value; } } // Check to see if RevocationReason property is set internal bool IsSetRevocationReason() { return this._revocationReason != null; } /// <summary> /// Gets and sets the property RevokedAt. /// <para> /// The timestamp when the certificate was revoked. This value is present only when the /// certificate status is <code>REVOKED</code>. /// </para> /// </summary> public DateTime RevokedAt { get { return this._revokedAt.GetValueOrDefault(); } set { this._revokedAt = value; } } // Check to see if RevokedAt property is set internal bool IsSetRevokedAt() { return this._revokedAt.HasValue; } /// <summary> /// Gets and sets the property Serial. /// <para> /// The serial number of the certificate. /// </para> /// </summary> public string Serial { get { return this._serial; } set { this._serial = value; } } // Check to see if Serial property is set internal bool IsSetSerial() { return this._serial != null; } /// <summary> /// Gets and sets the property SignatureAlgorithm. /// <para> /// The algorithm that was used to sign the certificate. /// </para> /// </summary> public string SignatureAlgorithm { get { return this._signatureAlgorithm; } set { this._signatureAlgorithm = value; } } // Check to see if SignatureAlgorithm property is set internal bool IsSetSignatureAlgorithm() { return this._signatureAlgorithm != null; } /// <summary> /// Gets and sets the property Status. /// <para> /// The validation status of the SSL/TLS certificate. Valid values are below. /// </para> /// </summary> public LoadBalancerTlsCertificateStatus Status { get { return this._status; } set { this._status = value; } } // Check to see if Status property is set internal bool IsSetStatus() { return this._status != null; } /// <summary> /// Gets and sets the property Subject. /// <para> /// The name of the entity that is associated with the public key contained in the certificate. /// </para> /// </summary> public string Subject { get { return this._subject; } set { this._subject = value; } } // Check to see if Subject property is set internal bool IsSetSubject() { return this._subject != null; } /// <summary> /// Gets and sets the property SubjectAlternativeNames. /// <para> /// An array of strings that specify the alternate domains (e.g., <code>example2.com</code>) /// and subdomains (e.g., <code>blog.example.com</code>) for the certificate. /// </para> /// </summary> public List<string> SubjectAlternativeNames { get { return this._subjectAlternativeNames; } set { this._subjectAlternativeNames = value; } } // Check to see if SubjectAlternativeNames property is set internal bool IsSetSubjectAlternativeNames() { return this._subjectAlternativeNames != null && this._subjectAlternativeNames.Count > 0; } /// <summary> /// Gets and sets the property SupportCode. /// <para> /// The support code. Include this code in your email to support when you have questions /// about your Lightsail load balancer or SSL/TLS certificate. This code enables our support /// team to look up your Lightsail information more easily. /// </para> /// </summary> public string SupportCode { get { return this._supportCode; } set { this._supportCode = value; } } // Check to see if SupportCode property is set internal bool IsSetSupportCode() { return this._supportCode != null; } /// <summary> /// Gets and sets the property Tags. /// <para> /// The tag keys and optional values for the resource. For more information about tags /// in Lightsail, see the <a href="https://lightsail.aws.amazon.com/ls/docs/en/articles/amazon-lightsail-tags">Lightsail /// Dev Guide</a>. /// </para> /// </summary> public List<Tag> Tags { get { return this._tags; } set { this._tags = value; } } // Check to see if Tags property is set internal bool IsSetTags() { return this._tags != null && this._tags.Count > 0; } } }
34.330159
159
0.554004
[ "Apache-2.0" ]
KenHundley/aws-sdk-net
sdk/src/Services/Lightsail/Generated/Model/LoadBalancerTlsCertificate.cs
21,628
C#
using System; using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Migrations; namespace Lessplastic.Data.Migrations { public partial class LessplasticDatabase : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.CreateTable( name: "Articles", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn), Title = table.Column<string>(nullable: true), ArticleImage = table.Column<string>(nullable: true), Content = table.Column<string>(nullable: true), ContentImage = table.Column<string>(nullable: true), AdditionalContent = table.Column<string>(nullable: true), AdditionalContentImage = table.Column<string>(nullable: true), Type = table.Column<int>(nullable: false), CreatedOn = table.Column<DateTime>(nullable: false), Views = table.Column<int>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_Articles", x => x.Id); }); migrationBuilder.CreateTable( name: "AspNetRoles", columns: table => new { Id = table.Column<string>(nullable: false), Name = table.Column<string>(maxLength: 256, nullable: true), NormalizedName = table.Column<string>(maxLength: 256, nullable: true), ConcurrencyStamp = table.Column<string>(nullable: true) }, constraints: table => { table.PrimaryKey("PK_AspNetRoles", x => x.Id); }); migrationBuilder.CreateTable( name: "Educations", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn), Title = table.Column<string>(nullable: true), Content = table.Column<string>(nullable: true), ImageUrl = table.Column<string>(nullable: true), AdditionalContent = table.Column<string>(nullable: true), AdditionalContentImage = table.Column<string>(nullable: true) }, constraints: table => { table.PrimaryKey("PK_Educations", x => x.Id); }); migrationBuilder.CreateTable( name: "Towns", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn), TownName = table.Column<string>(nullable: true), Country = table.Column<string>(nullable: true) }, constraints: table => { table.PrimaryKey("PK_Towns", x => x.Id); }); migrationBuilder.CreateTable( name: "Videos", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn), Title = table.Column<string>(nullable: true), Description = table.Column<string>(nullable: true), YoutubeLink = table.Column<string>(nullable: true) }, constraints: table => { table.PrimaryKey("PK_Videos", x => x.Id); }); migrationBuilder.CreateTable( name: "AspNetRoleClaims", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn), RoleId = table.Column<string>(nullable: false), ClaimType = table.Column<string>(nullable: true), ClaimValue = table.Column<string>(nullable: true) }, constraints: table => { table.PrimaryKey("PK_AspNetRoleClaims", x => x.Id); table.ForeignKey( name: "FK_AspNetRoleClaims_AspNetRoles_RoleId", column: x => x.RoleId, principalTable: "AspNetRoles", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "AspNetUsers", columns: table => new { Id = table.Column<string>(nullable: false), UserName = table.Column<string>(maxLength: 256, nullable: true), NormalizedUserName = table.Column<string>(maxLength: 256, nullable: true), Email = table.Column<string>(maxLength: 256, nullable: true), NormalizedEmail = table.Column<string>(maxLength: 256, nullable: true), EmailConfirmed = table.Column<bool>(nullable: false), PasswordHash = table.Column<string>(nullable: true), SecurityStamp = table.Column<string>(nullable: true), ConcurrencyStamp = table.Column<string>(nullable: true), PhoneNumber = table.Column<string>(nullable: true), PhoneNumberConfirmed = table.Column<bool>(nullable: false), TwoFactorEnabled = table.Column<bool>(nullable: false), LockoutEnd = table.Column<DateTimeOffset>(nullable: true), LockoutEnabled = table.Column<bool>(nullable: false), AccessFailedCount = table.Column<int>(nullable: false), Discriminator = table.Column<string>(nullable: false), TownId = table.Column<int>(nullable: true), FullName = table.Column<string>(nullable: true) }, constraints: table => { table.PrimaryKey("PK_AspNetUsers", x => x.Id); table.ForeignKey( name: "FK_AspNetUsers_Towns_TownId", column: x => x.TownId, principalTable: "Towns", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "Events", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn), Name = table.Column<string>(nullable: true), Description = table.Column<string>(nullable: true), TownId = table.Column<int>(nullable: false), EventDate = table.Column<DateTime>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_Events", x => x.Id); table.ForeignKey( name: "FK_Events_Towns_TownId", column: x => x.TownId, principalTable: "Towns", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "AspNetUserClaims", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn), UserId = table.Column<string>(nullable: false), ClaimType = table.Column<string>(nullable: true), ClaimValue = table.Column<string>(nullable: true) }, constraints: table => { table.PrimaryKey("PK_AspNetUserClaims", x => x.Id); table.ForeignKey( name: "FK_AspNetUserClaims_AspNetUsers_UserId", column: x => x.UserId, principalTable: "AspNetUsers", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "AspNetUserLogins", columns: table => new { LoginProvider = table.Column<string>(nullable: false), ProviderKey = table.Column<string>(nullable: false), ProviderDisplayName = table.Column<string>(nullable: true), UserId = table.Column<string>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_AspNetUserLogins", x => new { x.LoginProvider, x.ProviderKey }); table.ForeignKey( name: "FK_AspNetUserLogins_AspNetUsers_UserId", column: x => x.UserId, principalTable: "AspNetUsers", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "AspNetUserRoles", columns: table => new { UserId = table.Column<string>(nullable: false), RoleId = table.Column<string>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_AspNetUserRoles", x => new { x.UserId, x.RoleId }); table.ForeignKey( name: "FK_AspNetUserRoles_AspNetRoles_RoleId", column: x => x.RoleId, principalTable: "AspNetRoles", principalColumn: "Id", onDelete: ReferentialAction.Cascade); table.ForeignKey( name: "FK_AspNetUserRoles_AspNetUsers_UserId", column: x => x.UserId, principalTable: "AspNetUsers", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "AspNetUserTokens", columns: table => new { UserId = table.Column<string>(nullable: false), LoginProvider = table.Column<string>(nullable: false), Name = table.Column<string>(nullable: false), Value = table.Column<string>(nullable: true) }, constraints: table => { table.PrimaryKey("PK_AspNetUserTokens", x => new { x.UserId, x.LoginProvider, x.Name }); table.ForeignKey( name: "FK_AspNetUserTokens_AspNetUsers_UserId", column: x => x.UserId, principalTable: "AspNetUsers", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "Comments", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn), LessplasticUserId = table.Column<string>(nullable: true), ArticleId = table.Column<int>(nullable: false), CreatedOn = table.Column<DateTime>(nullable: false), Content = table.Column<string>(nullable: true) }, constraints: table => { table.PrimaryKey("PK_Comments", x => x.Id); table.ForeignKey( name: "FK_Comments_Articles_ArticleId", column: x => x.ArticleId, principalTable: "Articles", principalColumn: "Id", onDelete: ReferentialAction.Cascade); table.ForeignKey( name: "FK_Comments_AspNetUsers_LessplasticUserId", column: x => x.LessplasticUserId, principalTable: "AspNetUsers", principalColumn: "Id", onDelete: ReferentialAction.Restrict); }); migrationBuilder.CreateTable( name: "EventsTowns", columns: table => new { EventId = table.Column<int>(nullable: false), TownId = table.Column<int>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_EventsTowns", x => new { x.EventId, x.TownId }); table.ForeignKey( name: "FK_EventsTowns_Events_EventId", column: x => x.EventId, principalTable: "Events", principalColumn: "Id", onDelete: ReferentialAction.Restrict); table.ForeignKey( name: "FK_EventsTowns_Towns_TownId", column: x => x.TownId, principalTable: "Towns", principalColumn: "Id", onDelete: ReferentialAction.Restrict); }); migrationBuilder.CreateTable( name: "UsersEvents", columns: table => new { LessplasticUserId = table.Column<string>(nullable: false), EventId = table.Column<int>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_UsersEvents", x => new { x.EventId, x.LessplasticUserId }); table.ForeignKey( name: "FK_UsersEvents_Events_EventId", column: x => x.EventId, principalTable: "Events", principalColumn: "Id", onDelete: ReferentialAction.Restrict); table.ForeignKey( name: "FK_UsersEvents_AspNetUsers_LessplasticUserId", column: x => x.LessplasticUserId, principalTable: "AspNetUsers", principalColumn: "Id", onDelete: ReferentialAction.Restrict); }); migrationBuilder.CreateIndex( name: "IX_AspNetRoleClaims_RoleId", table: "AspNetRoleClaims", column: "RoleId"); migrationBuilder.CreateIndex( name: "RoleNameIndex", table: "AspNetRoles", column: "NormalizedName", unique: true, filter: "[NormalizedName] IS NOT NULL"); migrationBuilder.CreateIndex( name: "IX_AspNetUserClaims_UserId", table: "AspNetUserClaims", column: "UserId"); migrationBuilder.CreateIndex( name: "IX_AspNetUserLogins_UserId", table: "AspNetUserLogins", column: "UserId"); migrationBuilder.CreateIndex( name: "IX_AspNetUserRoles_RoleId", table: "AspNetUserRoles", column: "RoleId"); migrationBuilder.CreateIndex( name: "IX_AspNetUsers_TownId", table: "AspNetUsers", column: "TownId"); migrationBuilder.CreateIndex( name: "EmailIndex", table: "AspNetUsers", column: "NormalizedEmail"); migrationBuilder.CreateIndex( name: "UserNameIndex", table: "AspNetUsers", column: "NormalizedUserName", unique: true, filter: "[NormalizedUserName] IS NOT NULL"); migrationBuilder.CreateIndex( name: "IX_Comments_ArticleId", table: "Comments", column: "ArticleId"); migrationBuilder.CreateIndex( name: "IX_Comments_LessplasticUserId", table: "Comments", column: "LessplasticUserId"); migrationBuilder.CreateIndex( name: "IX_Events_TownId", table: "Events", column: "TownId"); migrationBuilder.CreateIndex( name: "IX_EventsTowns_TownId", table: "EventsTowns", column: "TownId"); migrationBuilder.CreateIndex( name: "IX_UsersEvents_LessplasticUserId", table: "UsersEvents", column: "LessplasticUserId"); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropTable( name: "AspNetRoleClaims"); migrationBuilder.DropTable( name: "AspNetUserClaims"); migrationBuilder.DropTable( name: "AspNetUserLogins"); migrationBuilder.DropTable( name: "AspNetUserRoles"); migrationBuilder.DropTable( name: "AspNetUserTokens"); migrationBuilder.DropTable( name: "Comments"); migrationBuilder.DropTable( name: "Educations"); migrationBuilder.DropTable( name: "EventsTowns"); migrationBuilder.DropTable( name: "UsersEvents"); migrationBuilder.DropTable( name: "Videos"); migrationBuilder.DropTable( name: "AspNetRoles"); migrationBuilder.DropTable( name: "Articles"); migrationBuilder.DropTable( name: "Events"); migrationBuilder.DropTable( name: "AspNetUsers"); migrationBuilder.DropTable( name: "Towns"); } } }
43.360802
122
0.486106
[ "MIT" ]
HrBozhidarov/Lessplastic
LessplasticWebApp/Lessplastic.Data/Migrations/20181121172112_Lessplastic-Database.cs
19,471
C#
// Copyright (c) MASA Stack All rights reserved. // Licensed under the Apache License. See LICENSE.txt in the project root for license information. global using Masa.Auth.ApiGateways.Caller.Services.Organizations; global using Masa.Auth.ApiGateways.Caller.Services.Oss; global using Masa.Auth.ApiGateways.Caller.Services.Permissions; global using Masa.Auth.ApiGateways.Caller.Services.Projects; global using Masa.Auth.ApiGateways.Caller.Services.Sso; global using Masa.Auth.ApiGateways.Caller.Services.Subjects; global using Masa.Auth.Contracts.Admin.Infrastructure.Constants; global using Masa.Auth.Contracts.Admin.Infrastructure.Dtos; global using Masa.Auth.Contracts.Admin.Infrastructure.Enums; global using Masa.Auth.Contracts.Admin.Organizations; global using Masa.Auth.Contracts.Admin.Oss; global using Masa.Auth.Contracts.Admin.Permissions; global using Masa.Auth.Contracts.Admin.Projects; global using Masa.Auth.Contracts.Admin.Sso; global using Masa.Auth.Contracts.Admin.Subjects; global using Masa.Utils.Caller.Core; global using Masa.Utils.Caller.HttpClient; global using Microsoft.AspNetCore.Http; global using Microsoft.Extensions.DependencyInjection; global using System.Reflection; global using System.Text.Json;
49.16
98
0.837266
[ "Apache-2.0" ]
masastack/MASA.Auth
src/ApiGateways/Masa.Auth.ApiGateways.Caller/_Imports.cs
1,229
C#
#region using System.Collections.Generic; using System.Linq; using System.Text; #endregion namespace Alturos.Yolo { public class ImageAnalyzer { private readonly Dictionary<string, byte[]> _imageFormats = new Dictionary<string, byte[]>(); public ImageAnalyzer() { var bmp = Encoding.ASCII.GetBytes("BM"); //BMP var png = new byte[] {137, 80, 78, 71}; //PNG var jpeg = new byte[] {255, 216, 255}; //JPEG _imageFormats.Add("bmp", bmp); _imageFormats.Add("png", png); _imageFormats.Add("jpeg", jpeg); } public bool IsValidImageFormat(byte[] imageData) { if (imageData == null) { return false; } if (imageData.Length <= 3) { return false; } foreach (var imageFormat in _imageFormats) { if (imageData.Take(imageFormat.Value.Length).SequenceEqual(imageFormat.Value)) { return true; } } return false; } } }
23.857143
101
0.495295
[ "MIT" ]
SteffenCarlsen/Alturos.Yolo
src/Alturos.Yolo/ImageAnalyzer.cs
1,171
C#
using BTCPayServer.JsonConverters; using Newtonsoft.Json; namespace BTCPayServer.Client.Models; public class CreateInvoiceRequest : InvoiceDataBase { [JsonConverter(typeof(NumericStringJsonConverter))] public decimal? Amount { get; set; } public string[] AdditionalSearchTerms { get; set; } }
25.583333
55
0.775244
[ "MIT" ]
wforney/btcpayserver
BTCPayServer.Client/Models/CreateInvoiceRequest.cs
307
C#
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("SuperGlue.Diagnostics")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("SuperGlue.Diagnostics")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("37d1023e-467a-4910-83c5-e2b6805c84e8")]
43.818182
84
0.773859
[ "MIT" ]
MattiasJakobsson/Jajo.Web
src/SuperGlue.Diagnostics/Properties/AssemblyInfo.cs
967
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Linq; using System.Reflection; using Microsoft.AspNetCore.Mvc.Core; using Microsoft.AspNetCore.Mvc.Infrastructure; using Microsoft.AspNetCore.Mvc.ModelBinding; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; namespace Microsoft.AspNetCore.Mvc.ApplicationModels; internal class ApiBehaviorApplicationModelProvider : IApplicationModelProvider { public ApiBehaviorApplicationModelProvider( IOptions<ApiBehaviorOptions> apiBehaviorOptions, IModelMetadataProvider modelMetadataProvider, IClientErrorFactory clientErrorFactory, ILoggerFactory loggerFactory) { var options = apiBehaviorOptions.Value; ActionModelConventions = new List<IActionModelConvention>() { new ApiVisibilityConvention(), }; if (!options.SuppressMapClientErrors) { ActionModelConventions.Add(new ClientErrorResultFilterConvention()); } if (!options.SuppressModelStateInvalidFilter) { ActionModelConventions.Add(new InvalidModelStateFilterConvention()); } if (!options.SuppressConsumesConstraintForFormFileParameters) { ActionModelConventions.Add(new ConsumesConstraintForFormFileParameterConvention()); } var defaultErrorType = options.SuppressMapClientErrors ? typeof(void) : typeof(ProblemDetails); var defaultErrorTypeAttribute = new ProducesErrorResponseTypeAttribute(defaultErrorType); ActionModelConventions.Add(new ApiConventionApplicationModelConvention(defaultErrorTypeAttribute)); if (!options.SuppressInferBindingSourcesForParameters) { ActionModelConventions.Add(new InferParameterBindingInfoConvention(modelMetadataProvider)); } } /// <remarks> /// Order is set to execute after the <see cref="DefaultApplicationModelProvider"/> and allow any other user /// <see cref="IApplicationModelProvider"/> that configure routing to execute. /// </remarks> public int Order => -1000 + 100; public List<IActionModelConvention> ActionModelConventions { get; } public void OnProvidersExecuted(ApplicationModelProviderContext context) { } public void OnProvidersExecuting(ApplicationModelProviderContext context) { foreach (var controller in context.Result.Controllers) { if (!IsApiController(controller)) { continue; } foreach (var action in controller.Actions) { // Ensure ApiController is set up correctly EnsureActionIsAttributeRouted(action); foreach (var convention in ActionModelConventions) { convention.Apply(action); } } } } private static void EnsureActionIsAttributeRouted(ActionModel actionModel) { if (!IsAttributeRouted(actionModel.Controller.Selectors) && !IsAttributeRouted(actionModel.Selectors)) { // Require attribute routing with controllers annotated with ApiControllerAttribute var message = Resources.FormatApiController_AttributeRouteRequired( actionModel.DisplayName, nameof(ApiControllerAttribute)); throw new InvalidOperationException(message); } static bool IsAttributeRouted(IList<SelectorModel> selectorModel) { for (var i = 0; i < selectorModel.Count; i++) { if (selectorModel[i].AttributeRouteModel != null) { return true; } } return false; } } private static bool IsApiController(ControllerModel controller) { if (controller.Attributes.OfType<IApiBehaviorMetadata>().Any()) { return true; } var controllerAssembly = controller.ControllerType.Assembly; var assemblyAttributes = controllerAssembly.GetCustomAttributes(); return assemblyAttributes.OfType<IApiBehaviorMetadata>().Any(); } }
34.428571
112
0.663439
[ "MIT" ]
Cosifne/aspnetcore
src/Mvc/Mvc.Core/src/ApplicationModels/ApiBehaviorApplicationModelProvider.cs
4,340
C#
using Capsaicin.UnitTesting; using Capsaicin.UnitTesting.Generators.Tests; using Microsoft.VisualStudio.TestTools.UnitTesting; using System; using System.Collections.Generic; using System.Globalization; // this namespace must be included because CultureInfo is used in an expression! namespace Capsaicin.UnitTesting.Generators { [TestClass] public partial class TestDataSourceGeneratorTest { private static DummyClass<double> CreateObject3() => new DummyClass<double>("Object3", Math.Pow(3, 4)); private static IFormattable[] Objects = new[] { (IFormattable)new DummyClass<double>("Object4", Math.PI), new DummyClass<DummyClass<double>>("Object5", new DummyClass<double>("nested", 123.456)), }; /// <summary> /// Implicitly tests TestDataSourceGenerator /// </summary> /// <param name="expected"></param> /// <param name="testObject"></param> /// <param name="format"></param> /// <param name="formatProvider"></param> [TestMethod] [ExpressionDataRow("Object1: -123,456.00", "new DummyClass<int>(\"Object1\", -123456)", "N2", "null")] [ExpressionDataRow("Object2: 1.414214", "new DummyClass<double>(\"Object2\", Math.Sqrt(2))", "F6", null)] // expression may contain method call, which is usefull for complex objects: [ExpressionDataRow("Object3: 81", "CreateObject3()", null, "CultureInfo.InvariantCulture")] // expression may contain reference to static field or property: [ExpressionDataRow("Object4: 3,142", "Objects[0]", "F3", "CultureInfo.GetCultureInfo(\"de-DE\")")] [ExpressionDataRow("Object5: nested: 123.456", "Objects[1]", "", "CultureInfo.GetCultureInfo(\"en-GB\")")] public partial void GenerateTest(string expected, // not annotated with FromCSharpExpression because values are expressed with constant expressions [FromCSharpExpression] IFormattable testObject, string? format, // not annotated with FromCSharpExpression because values are expressed with constant expressions [FromCSharpExpression] IFormatProvider? formatProvider) { CultureInfo.CurrentCulture = CultureInfo.GetCultureInfo("en-GB"); Assert.AreEqual(testObject.GetType().GetGenericTypeDefinition(), typeof(DummyClass<>), $"Invalid test data. {nameof(testObject)} is not typeof {typeof(DummyClass<>).FullName}."); var actual = testObject.ToString(format, formatProvider); Assert.AreEqual(expected, actual); } /// <summary> /// Implicitly tests TestDataSourceGenerator and verifies object values are correctly evaluated /// </summary> /// <param name="notFromExpression"></param> /// <param name="fromExpression"></param> [TestMethod] [ExpressionDataRow(1.23d, "1.23d", typeof(double))] [ExpressionDataRow(0d, "0d", typeof(double))] [ExpressionDataRow(-6d, "-6d", typeof(double))] [ExpressionDataRow(0, "0", typeof(int))] public partial void Generate_ObjectValues_Test(object notFromExpression, [FromCSharpExpression] object fromExpression, Type expectedType) { Assert.IsInstanceOfType(fromExpression, expectedType); Assert.IsInstanceOfType(notFromExpression, expectedType); Assert.AreEqual(notFromExpression, fromExpression); } } }
53.169231
190
0.670139
[ "MIT" ]
hauke-w/Capsaicin.UnitTesting.Generators
Capsaicin.UnitTesting.Generators.Tests/TestDataSourceGeneratorTest.cs
3,456
C#
// -------------------------------------------------------------------------------------------------------------------- // Copyright (c) Lead Pipe Software. All rights reserved. // Licensed under the MIT License. Please see the LICENSE file in the project root for full license information. // -------------------------------------------------------------------------------------------------------------------- using Lucene.Net.Index; using Lucene.Net.Store; using Lucene.Net.Util; using System.Collections.Generic; namespace LeadPipe.Net.Lucene { /// <summary> /// Updates the search index. /// </summary> public interface ISearchIndexUpdater<TEntity, TSearchData> where TSearchData : IKeyed, new() { /// <summary> /// Updates the index. /// </summary> /// <param name="luceneVersion">The lucene version.</param> /// <param name="directory">The lucene directory.</param> /// <param name="maxFieldLength">Maximum length of the field.</param> void UpdateIndex(Version luceneVersion, Directory directory, IndexWriter.MaxFieldLength maxFieldLength); /// <summary> /// Updates the index. /// </summary> /// <param name="luceneVersion">The lucene version.</param> /// <param name="directory">The lucene directory.</param> /// <param name="maxFieldLength">Maximum length of the field.</param> /// <param name="searchData">The search data.</param> void UpdateIndex(Version luceneVersion, Directory directory, IndexWriter.MaxFieldLength maxFieldLength, IEnumerable<TSearchData> searchData); /// <summary> /// Updates the index. /// </summary> /// <param name="luceneVersion">The lucene version.</param> /// <param name="directory">The lucene directory.</param> /// <param name="maxFieldLength">Maximum length of the field.</param> /// <param name="entities">The entities.</param> void UpdateIndex(Version luceneVersion, Directory directory, IndexWriter.MaxFieldLength maxFieldLength, IEnumerable<TEntity> entities); } }
48.272727
149
0.589454
[ "MIT" ]
bbizic/LeadPipe.Net
src/LeadPipe.Net.Lucene/ISearchIndexUpdater.cs
2,126
C#
namespace ClassLib057 { public class Class087 { public static string Property => "ClassLib057"; } }
15
55
0.633333
[ "MIT" ]
333fred/performance
src/scenarios/weblarge2.0/src/ClassLib057/Class087.cs
120
C#
using System.Collections.Generic; using System.Linq; using System.Windows.Threading; namespace TCC.Data { public class Player : TSPropertyChanged { private float _critFactor; private string _name; public string Name { get => _name; set { if (_name == value) return; _name = value; NPC(); } } private ulong _entityId; public ulong EntityId { get => _entityId; set { if (_entityId != value) { _entityId = value; NPC(); } } } public uint PlayerId { get; internal set; } public uint ServerId { get; internal set; } private Class _playerclass = Class.None; public Class Class { get => _playerclass; set { if (_playerclass != value) { _playerclass = value; NPC(); } } } private Laurel _laurel; public Laurel Laurel { get => _laurel; set { if (_laurel != value) { _laurel = value; NPC(); } } } private int _level; public int Level { get => _level; set { if (_level != value) { _level = value; NPC(); } } } private int _itemLevel; public int ItemLevel { get => _itemLevel; set { if (value != _itemLevel) { _itemLevel = value; NPC(); } } } private long _maxHP; public long MaxHP { get => _maxHP; set { if (_maxHP != value) { _maxHP = value; NPC(); NPC(nameof(HpFactor)); } } } private int _maxMP; public int MaxMP { get => _maxMP; set { if (_maxMP != value) { _maxMP = value; NPC(); NPC(nameof(MpFactor)); } } } private int _maxST; public int MaxST { get => _maxST; set { if (_maxST == value) return; _maxST = value; NPC(); NPC(nameof(StFactor)); } } private uint _maxShield; public uint MaxShield { get => _maxShield; set { if (_maxShield != value) { _maxShield = value; NPC(nameof(MaxShield)); NPC(nameof(ShieldFactor)); NPC(nameof(HasShield)); } } } private float _currentHP; public float CurrentHP { get => _currentHP; set { if (_currentHP == value) return; _currentHP = value; NPC(nameof(CurrentHP)); NPC(nameof(TotalHP)); NPC(nameof(HpFactor)); } } public double HpFactor => MaxHP > 0 ? CurrentHP / MaxHP : 1; public double MpFactor => MaxMP > 0 ? CurrentMP / MaxMP : 1; public double StFactor => MaxST > 0 ? CurrentST / MaxST : 1; public double ShieldFactor => MaxShield > 0 ? CurrentShield / MaxShield : 0; public bool HasShield => ShieldFactor > 0; public float TotalHP => CurrentHP + CurrentShield; private float _currentMP; public float CurrentMP { get => _currentMP; set { if (_currentMP != value) { _currentMP = value; NPC(); NPC(nameof(MpFactor)); } } } private float _currentST; public float CurrentST { get => _currentST; set { if (_currentST != value) { _currentST = value; NPC(); NPC(nameof(StFactor)); } } } private float _currentShield; public float CurrentShield { get => _currentShield; set { if(_currentShield == value) return; if(value < 0) return; _currentShield = value; NPC(nameof(CurrentShield)); NPC(nameof(TotalHP)); NPC(nameof(ShieldFactor)); NPC(nameof(HasShield)); } } private float _flightEnergy; public float FlightEnergy { get => _flightEnergy; set { if (_flightEnergy == value) return; _flightEnergy = value; NPC(); } } private readonly List<uint> _debuffList; internal void AddToDebuffList(Abnormality ab) { if (!ab.IsBuff && !_debuffList.Contains(ab.Id)) { _debuffList.Add(ab.Id); NPC(nameof(IsDebuffed)); } } internal void RemoveFromDebuffList(Abnormality ab) { if (ab.IsBuff == false) { _debuffList.Remove(ab.Id); NPC(nameof(IsDebuffed)); } } public bool IsDebuffed => _debuffList.Count != 0; private bool _isInCombat; public bool IsInCombat { get => _isInCombat; set { if (value != _isInCombat) { _isInCombat = value; NPC(); } } } public SynchronizedObservableCollection<AbnormalityDuration> Buffs { get; set; } public SynchronizedObservableCollection<AbnormalityDuration> Debuffs { get; set; } public SynchronizedObservableCollection<AbnormalityDuration> InfBuffs { get; set; } public float CritFactor { get => _critFactor; set { if(_critFactor == value) return; _critFactor = value; NPC(); } } public void AddOrRefreshBuff(Abnormality ab, uint duration, int stacks) { var existing = Buffs.FirstOrDefault(x => x.Abnormality.Id == ab.Id); if (existing == null) { var newAb = new AbnormalityDuration(ab, duration, stacks, EntityId, Dispatcher, true/*, size * .9, size, new System.Windows.Thickness(margin)*/); Buffs.Add(newAb); if (ab.IsShield) { MaxShield = ab.ShieldSize; CurrentShield = ab.ShieldSize; } return; } existing.Duration = duration; existing.DurationLeft = duration; existing.Stacks = stacks; existing.Refresh(); } public void AddOrRefreshDebuff(Abnormality ab, uint duration, int stacks) { var existing = Debuffs.FirstOrDefault(x => x.Abnormality.Id == ab.Id); if (existing == null) { var newAb = new AbnormalityDuration(ab, duration, stacks, EntityId, Dispatcher, true/*, size * .9, size, new System.Windows.Thickness(margin)*/); Debuffs.Add(newAb); return; } existing.Duration = duration; existing.DurationLeft = duration; existing.Stacks = stacks; existing.Refresh(); } public void AddOrRefreshInfBuff(Abnormality ab, uint duration, int stacks) { var existing = InfBuffs.FirstOrDefault(x => x.Abnormality.Id == ab.Id); if (existing == null) { var newAb = new AbnormalityDuration(ab, duration, stacks, EntityId, Dispatcher, true/*, size * .9, size, new System.Windows.Thickness(margin)*/); InfBuffs.Add(newAb); return; } existing.Duration = duration; existing.DurationLeft = duration; existing.Stacks = stacks; existing.Refresh(); } public void RemoveBuff(Abnormality ab) { var buff = Buffs.FirstOrDefault(x => x.Abnormality.Id == ab.Id); if (buff == null) return; Buffs.Remove(buff); buff.Dispose(); if (ab.IsShield) { MaxShield = 0; CurrentShield = 0; } } public void RemoveDebuff(Abnormality ab) { var buff = Debuffs.FirstOrDefault(x => x.Abnormality.Id == ab.Id); if (buff == null) return; Debuffs.Remove(buff); buff.Dispose(); } public void RemoveInfBuff(Abnormality ab) { var buff = InfBuffs.FirstOrDefault(x => x.Abnormality.Id == ab.Id); if (buff == null) return; InfBuffs.Remove(buff); buff.Dispose(); } public void ClearAbnormalities() { foreach (var item in Buffs) { item.Dispose(); } foreach (var item in Debuffs) { item.Dispose(); } foreach (var item in InfBuffs) { item.Dispose(); } Buffs.Clear(); Debuffs.Clear(); InfBuffs.Clear(); _debuffList.Clear(); NPC(nameof(IsDebuffed)); } public Player() { Dispatcher = Dispatcher.CurrentDispatcher; Buffs = new SynchronizedObservableCollection<AbnormalityDuration>(Dispatcher); Debuffs = new SynchronizedObservableCollection<AbnormalityDuration>(Dispatcher); InfBuffs = new SynchronizedObservableCollection<AbnormalityDuration>(Dispatcher); _debuffList = new List<uint>(); } public Player(ulong id, string name) { Dispatcher = Dispatcher.CurrentDispatcher; Buffs = new SynchronizedObservableCollection<AbnormalityDuration>(Dispatcher); Debuffs = new SynchronizedObservableCollection<AbnormalityDuration>(Dispatcher); InfBuffs = new SynchronizedObservableCollection<AbnormalityDuration>(Dispatcher); _debuffList = new List<uint>(); _entityId = id; _name = name; } } }
27.404819
161
0.442363
[ "MIT" ]
ASPDP/Tera-custom-cooldowns
TCC.Core/Data/Player.cs
11,375
C#
using System; using Newtonsoft.Json; namespace Com.GitHub.ZachDeibert.CodeTanks.Model { public sealed class Error { [JsonProperty("error")] public bool IsError = true; [JsonProperty("type")] public string Type; [JsonProperty("message")] public string Message; public Error() { } public Error(Exception ex) { Type = ex.GetType().Name; Message = ex.Message; } } }
21.681818
50
0.563941
[ "MIT" ]
zachdeibert/code-tanks
model/Error.cs
477
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.InteropServices.WindowsRuntime; using Windows.ApplicationModel; using Windows.ApplicationModel.Activation; using Windows.Foundation; using Windows.Foundation.Collections; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Controls.Primitives; using Windows.UI.Xaml.Data; using Windows.UI.Xaml.Input; using Windows.UI.Xaml.Media; using Windows.UI.Xaml.Media.Animation; using Windows.UI.Xaml.Navigation; // The Blank Application template is documented at http://go.microsoft.com/fwlink/?LinkId=391641 namespace ButtonEnabler.WinPhone81 { /// <summary> /// Provides application-specific behavior to supplement the default Application class. /// </summary> public sealed partial class App : Application { private TransitionCollection transitions; /// <summary> /// Initializes the singleton application object. This is the first line of authored code /// executed, and as such is the logical equivalent of main() or WinMain(). /// </summary> public App() { this.InitializeComponent(); this.Suspending += this.OnSuspending; } /// <summary> /// Invoked when the application is launched normally by the end user. Other entry points /// will be used when the application is launched to open a specific file, to display /// search results, and so forth. /// </summary> /// <param name="e">Details about the launch request and process.</param> protected override void OnLaunched(LaunchActivatedEventArgs e) { #if DEBUG if (System.Diagnostics.Debugger.IsAttached) { this.DebugSettings.EnableFrameRateCounter = true; } #endif Frame rootFrame = Window.Current.Content as Frame; // Do not repeat app initialization when the Window already has content, // just ensure that the window is active if (rootFrame == null) { // Create a Frame to act as the navigation context and navigate to the first page rootFrame = new Frame(); // TODO: change this value to a cache size that is appropriate for your application rootFrame.CacheSize = 1; Xamarin.Forms.Forms.Init(e); if (e.PreviousExecutionState == ApplicationExecutionState.Terminated) { // TODO: Load state from previously suspended application } // Place the frame in the current Window Window.Current.Content = rootFrame; } if (rootFrame.Content == null) { // Removes the turnstile navigation for startup. if (rootFrame.ContentTransitions != null) { this.transitions = new TransitionCollection(); foreach (var c in rootFrame.ContentTransitions) { this.transitions.Add(c); } } rootFrame.ContentTransitions = null; rootFrame.Navigated += this.RootFrame_FirstNavigated; // When the navigation stack isn't restored navigate to the first page, // configuring the new page by passing required information as a navigation // parameter if (!rootFrame.Navigate(typeof(MainPage), e.Arguments)) { throw new Exception("Failed to create initial page"); } } // Ensure the current window is active Window.Current.Activate(); } /// <summary> /// Restores the content transitions after the app has launched. /// </summary> /// <param name="sender">The object where the handler is attached.</param> /// <param name="e">Details about the navigation event.</param> private void RootFrame_FirstNavigated(object sender, NavigationEventArgs e) { var rootFrame = sender as Frame; rootFrame.ContentTransitions = this.transitions ?? new TransitionCollection() { new NavigationThemeTransition() }; rootFrame.Navigated -= this.RootFrame_FirstNavigated; } /// <summary> /// Invoked when application execution is being suspended. Application state is saved /// without knowing whether the application will be terminated or resumed with the contents /// of memory still intact. /// </summary> /// <param name="sender">The source of the suspend request.</param> /// <param name="e">Details about the suspend request.</param> private void OnSuspending(object sender, SuspendingEventArgs e) { var deferral = e.SuspendingOperation.GetDeferral(); // TODO: Save application state and stop any background activity deferral.Complete(); } } }
38.87218
126
0.610058
[ "Apache-2.0" ]
NoleHealth/xamarin-forms-book-preview-2
Chapter16/ButtonEnabler/ButtonEnabler/ButtonEnabler.WinPhone81/App.xaml.cs
5,172
C#
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Linq; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Input; using Microsoft.CodeAnalysis.Options; using Microsoft.VisualStudio.LanguageServices.Implementation.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Options { internal partial class OptionPreviewControl : AbstractOptionPageControl { internal AbstractOptionPreviewViewModel ViewModel; private readonly IServiceProvider _serviceProvider; private readonly Func<OptionSet, IServiceProvider, AbstractOptionPreviewViewModel> _createViewModel; internal OptionPreviewControl(IServiceProvider serviceProvider, Func<OptionSet, IServiceProvider, AbstractOptionPreviewViewModel> createViewModel) : base(serviceProvider) { InitializeComponent(); // AutomationDelegatingListView is defined in ServicesVisualStudio, which has // InternalsVisibleTo this project. But, the markup compiler doesn't consider the IVT // relationship, so declaring the AutomationDelegatingListView in XAML would require // duplicating that type in this project. Declaring and setting it here avoids the // markup compiler completely, allowing us to reference the internal // AutomationDelegatingListView without issue. var listview = new AutomationDelegatingListView(); listview.Name = "Options"; listview.SelectionMode = SelectionMode.Single; listview.PreviewKeyDown += Options_PreviewKeyDown; listview.SelectionChanged += Options_SelectionChanged; listview.SetBinding(ItemsControl.ItemsSourceProperty, new Binding { Path = new PropertyPath(nameof(ViewModel.Items)) }); listViewContentControl.Content = listview; _serviceProvider = serviceProvider; _createViewModel = createViewModel; } private void Options_SelectionChanged(object sender, SelectionChangedEventArgs e) { var listView = (AutomationDelegatingListView)sender; var checkbox = listView.SelectedItem as CheckBoxOptionViewModel; if (checkbox != null) { ViewModel.UpdatePreview(checkbox.GetPreview()); } var radioButton = listView.SelectedItem as AbstractRadioButtonViewModel; if (radioButton != null) { ViewModel.UpdatePreview(radioButton.Preview); } var checkBoxWithCombo = listView.SelectedItem as CheckBoxWithComboOptionViewModel; if (checkBoxWithCombo != null) { ViewModel.UpdatePreview(checkBoxWithCombo.GetPreview()); } } private void Options_PreviewKeyDown(object sender, KeyEventArgs e) { if (e.Key == Key.Space && e.KeyboardDevice.Modifiers == ModifierKeys.None) { var listView = (AutomationDelegatingListView)sender; var checkBox = listView.SelectedItem as CheckBoxOptionViewModel; if (checkBox != null) { checkBox.IsChecked = !checkBox.IsChecked; e.Handled = true; } var radioButton = listView.SelectedItem as AbstractRadioButtonViewModel; if (radioButton != null) { radioButton.IsChecked = true; e.Handled = true; } var checkBoxWithCombo = listView.SelectedItem as CheckBoxWithComboOptionViewModel; if (checkBoxWithCombo != null) { checkBoxWithCombo.IsChecked = !checkBoxWithCombo.IsChecked; e.Handled = true; } } } internal override void SaveSettings() { var optionSet = this.OptionService.GetOptions(); var changedOptions = this.ViewModel.ApplyChangedOptions(optionSet); this.OptionService.SetOptions(changedOptions); OptionLogger.Log(optionSet, changedOptions); } internal override void LoadSettings() { this.ViewModel = _createViewModel(this.OptionService.GetOptions(), _serviceProvider); // Use the first item's preview. var firstItem = this.ViewModel.Items.OfType<CheckBoxOptionViewModel>().First(); this.ViewModel.SetOptionAndUpdatePreview(firstItem.IsChecked, firstItem.Option, firstItem.GetPreview()); DataContext = ViewModel; } internal override void Close() { base.Close(); if (this.ViewModel != null) { this.ViewModel.Dispose(); } } } }
40.392
178
0.636166
[ "Apache-2.0" ]
AArnott/roslyn
src/VisualStudio/Core/Impl/Options/OptionPreviewControl.xaml.cs
5,049
C#
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! namespace Google.Cloud.NetworkConnectivity.V1Alpha1.Snippets { using Google.Cloud.NetworkConnectivity.V1Alpha1; using Google.LongRunning; public sealed partial class GeneratedHubServiceClientStandaloneSnippets { /// <summary>Snippet for CreateHub</summary> /// <remarks> /// This snippet has been automatically generated for illustrative purposes only. /// It may require modifications to work in your environment. /// </remarks> public void CreateHub() { // Create client HubServiceClient hubServiceClient = HubServiceClient.Create(); // Initialize request argument(s) string parent = "projects/[PROJECT]/locations/[LOCATION]"; Hub hub = new Hub(); string hubId = ""; // Make the request Operation<Hub, OperationMetadata> response = hubServiceClient.CreateHub(parent, hub, hubId); // Poll until the returned long-running operation is complete Operation<Hub, OperationMetadata> completedResponse = response.PollUntilCompleted(); // Retrieve the operation result Hub result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name Operation<Hub, OperationMetadata> retrievedResponse = hubServiceClient.PollOnceCreateHub(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Hub retrievedResult = retrievedResponse.Result; } } } }
42.206897
116
0.66585
[ "Apache-2.0" ]
googleapis/googleapis-gen
google/cloud/networkconnectivity/v1alpha1/google-cloud-networkconnectivity-v1alpha1-csharp/Google.Cloud.NetworkConnectivity.V1Alpha1.StandaloneSnippets/HubServiceClient.CreateHubSnippet.g.cs
2,448
C#
using Microsoft.VisualStudio.TestTools.UnitTesting; using Shifter.Providers; namespace ShifterTest { [TestClass] public class ColorNamesProviderTest { private ColorNamesProvider _provider; [TestInitialize] public void Setup() { _provider = new ColorNamesProvider(); } [DataTestMethod] [DataRow("abc blue number", 6, "mediumblue", "royalblue")] [DataRow("abc Azure number", 6, "Aliceblue", "Mintcream")] public void ColorNames(string textIn, int position, string down, string up) { bool successDown = _provider.TryShiftLine(textIn, position, ShiftDirection.Down, out ShiftResult resultDown); bool successUp = _provider.TryShiftLine(textIn, position, ShiftDirection.Up, out ShiftResult resultUp); Assert.IsTrue(successDown); Assert.IsTrue(successUp); Assert.AreEqual(down, resultDown.ShiftedText); Assert.AreEqual(up, resultUp.ShiftedText); } } }
32.4375
121
0.648362
[ "Apache-2.0" ]
madskristensen/Shifter
test/ColorNamesProviderTest.cs
1,040
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace Sieves.Properties { /// <summary> /// A strongly-typed resource class, for looking up localized strings, etc. /// </summary> // This class was auto-generated by the StronglyTypedResourceBuilder // class via a tool like ResGen or Visual Studio. // To add or remove a member, edit your .ResX file then rerun ResGen // with the /str option, or rebuild your VS project. [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] internal class Resources { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal Resources() { } /// <summary> /// Returns the cached ResourceManager instance used by this class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Resources.ResourceManager ResourceManager { get { if ((resourceMan == null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Sieves.Properties.Resources", typeof(Resources).Assembly); resourceMan = temp; } return resourceMan; } } /// <summary> /// Overrides the current thread's CurrentUICulture property for all /// resource lookups using this strongly typed resource class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } } }
39.444444
173
0.58662
[ "MIT" ]
WriterRod/The-Modern-C-Challenge
Problem12/Sieves/Properties/Resources.Designer.cs
2,842
C#
// Copyright (c) junjie sun. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; namespace XNode.Client { /// <summary> /// NodeClient容器基类 /// </summary> public abstract class NodeClientContainerBase : INodeClientContainer { private object nodeClientListLockObj = new object(); /// <summary> /// 容器中包含的NodeClient列表 /// </summary> protected IList<INodeClient> NodeClientList { get; set; } /// <summary> /// 构造函数 /// </summary> public NodeClientContainerBase() { NodeClientList = new List<INodeClient>(); } /// <summary> /// 代理名称 /// </summary> public virtual string ProxyName { get; set; } /// <summary> /// 容器中包含的NodeClient数量 /// </summary> public virtual int Count => NodeClientList.Count; /// <summary> /// 向容器中添加NodeClient对象 /// </summary> /// <param name="nodeClient"></param> public virtual void Add(INodeClient nodeClient) { lock (nodeClientListLockObj) { NodeClientList.Add(nodeClient); } } /// <summary> /// 从容器中移除指定NodeClient对象 /// </summary> /// <param name="host">客户端地址</param> /// <param name="port">客户端端口</param> /// <param name="isDisconnect">是否将移除的Client连接关闭</param> public virtual void Remove(string host, int port, bool isDisconnect = true) { lock (nodeClientListLockObj) { var isRemove = false; var list = new List<INodeClient>(); foreach (var client in NodeClientList) { if (client.Host == host && client.Port == port) { if (isDisconnect) { client.CloseAsync().Wait(); } isRemove = true; continue; } list.Add(client); } if (isRemove) { NodeClientList = list; } } } /// <summary> /// 关闭中容器中所有NodeClient连接 /// </summary> /// <returns></returns> public async virtual Task CloseAsync() { foreach (var client in NodeClientList) { await client.CloseAsync(); } } /// <summary> /// 为容器中所有NodeClient执行连接操作 /// </summary> /// <returns></returns> public async virtual Task ConnectAsync() { foreach (var client in NodeClientList) { await client.ConnectAsync(); } } /// <summary> /// 获取NodeClient对象 /// </summary> /// <param name="serviceId">服务Id</param> /// <param name="actionId">ActionId</param> /// <param name="paramList">Action参数列表</param> /// <param name="returnType">Action返回类型</param> /// <param name="Attachments">服务调用附加数据</param> public abstract INodeClient Get(int serviceId, int actionId, object[] paramList, Type returnType, IDictionary<string, byte[]> Attachments); /// <summary> /// 获取容器中所有NodeClient对象 /// </summary> /// <returns></returns> public virtual IList<INodeClient> GetAll() { return NodeClientList; } } }
29.108527
147
0.494008
[ "MIT" ]
junjie-sun/XNode
src/XNode/XNode/Client/NodeClientContainerBase.cs
3,995
C#
using OpenMinesweeper.Core.Interface; using OpenMinesweeper.Core.Utils; using ReflectXMLDB; using System; using System.Collections.Generic; using System.IO; using System.Linq; namespace OpenMinesweeper.Core { /// <summary> /// The core of the minesweeper game. /// </summary> public class MinesweeperCore { /// <summary> /// An internal instance of the configuration loaderr. /// </summary> public SoftwareConfigLoader ConfigurationLoader { get; private set; } /// <summary> /// Gets/Sets the current path of the configuration file. /// </summary> public string ConfigurationFilePath { get { return ConfigurationLoader != null ? ConfigurationLoader.FilePath : string.Empty; } set { if (ConfigurationLoader != null) { ConfigurationLoader.Initialize(value); } } } /// <summary> /// Constructor. /// </summary> public MinesweeperCore() { ConfigurationLoader = new SoftwareConfigLoader(); } /// <summary> /// Constructor. /// </summary> /// <param name="filePath"></param> public MinesweeperCore(string filePath) : this() { ConfigurationFilePath = filePath; } #region Methods /// <summary> /// Creates a new game. /// </summary> /// <param name="power"></param> /// <returns></returns> public GameGrid NewRandomGridGame(int lineCount, int columnCount) { IGridGenerator gridGenerator = new RandomGridGenerator(); GameGrid gg = gridGenerator.Generate<GameGrid>(lineCount, columnCount); return gg; } /// <summary> /// Creates a new game. /// </summary> /// <param name="power"></param> /// <returns></returns> public GameGrid NewMazeGame(int lineCount, int columnCount) { IGridGenerator gridGenerator = new MazeGenerator(); GameGrid gg = gridGenerator.Generate<GameGrid>(lineCount, columnCount); return gg; } /// <summary> /// Saves the current game to a database. /// </summary> /// <param name="gameGrid"></param> /// <param name="folder"></param> /// <param name="filename"></param> /// <returns></returns> public bool SaveGame(GameGrid gameGrid, string state, string folder, string filename) { DatabaseHandler dh = new DatabaseHandler(); Type[] databaseTypes = new Type[] { typeof(GameStateDatabase) }; dh.SetWorkspace(folder, databaseTypes); GameState gameState = ToGameState(gameGrid, state); //If the file already exists, just update the database. string pathToDB = Path.Combine(folder, filename); if(File.Exists(pathToDB)) { dh.ImportDatabase(pathToDB, folder); } //Else, creates a new database else { dh.CreateDatabase<GameStateDatabase>(); } dh.Insert(new GameState[] { gameState }); dh.ExportDatabase(folder, System.IO.Path.GetFileNameWithoutExtension(filename)); return File.Exists(pathToDB); } /// <summary> /// Returns all saved GameStates. /// </summary> /// <param name="fileToPath"></param> /// <param name="workingDir"></param> /// <param name="gameStates"></param> /// <returns></returns> public bool GetSavedGames(string fileToPath, string workingDir, out ICollection<GameState> gameStates) { DatabaseHandler dh = new DatabaseHandler(); Type[] databaseTypes = new Type[] { typeof(GameStateDatabase) }; dh.SetWorkspace(workingDir, databaseTypes); dh.ImportDatabase(fileToPath, workingDir); gameStates = dh.Get<GameState>(); return gameStates.Any(); } /// <summary> /// Converts a GameState to a GameGrid. /// </summary> /// <param name="gameState"></param> /// <returns></returns> public GameGrid FromGameState(GameState gameState, out string state) { string line_count_str = gameState.Grid.Substring(0, 8); string column_count_str = gameState.Grid.Substring(8, 8); string cells_str = gameState.Grid.Substring(16); state = gameState.State; GameGrid gameGrid = new GameGrid(); gameGrid.LineCount = Convert.ToInt32(line_count_str, 2); gameGrid.ColumnCount = Convert.ToInt32(column_count_str, 2); //Translate cells binary string to 2D array of cells. int ln = 0, col = 0; foreach(var c in cells_str) { Cell cell = new Cell(); cell.Occupied = c != '0'; cell.Position = new Tuple<int, int>(ln, col); gameGrid.Cells.Add(cell); if (col < gameGrid.ColumnCount - 1) { col++; } else { ln++; col = 0; } } return gameGrid; } /// <summary> /// Converts a GameGrid tp a GameState. /// </summary> /// <param name="gameGrid"></param> /// <returns></returns> private GameState ToGameState(GameGrid gameGrid, string state) { string line_count = Convert.ToString(gameGrid.LineCount, 2).PadLeft(8, '0'); string column_count = Convert.ToString(gameGrid.ColumnCount, 2).PadLeft(8, '0'); string cells = string.Empty; gameGrid.Cells.ForEach(cell => cells += cell.Occupied ? "1" : "0"); GameState gameState = new GameState(); gameState.State = state; gameState.Grid = line_count + column_count + cells; gameState.Date = string.Format("{0}_{1}", DateTime.Now.ToShortDateString(), DateTime.Now.ToShortTimeString()); return gameState; } #endregion } }
31.931034
122
0.533786
[ "MIT" ]
Fe-Bell/OpenMinesweeper
OpenMinesweeper.Core/MinesweeperCore.cs
6,484
C#
namespace FluentHttp { using System; using System.IO; internal class ResponseReceivedEventArgs : EventArgs { private readonly IHttpWebResponse _response; private readonly Exception _exception; private readonly object _asyncState; public ResponseReceivedEventArgs(IHttpWebResponse response, Exception exception, object asyncState) { _response = response; _exception = exception; _asyncState = asyncState; } public object AsyncState { get { return _asyncState; } } public Exception Exception { get { return _exception; } } public IHttpWebResponse Response { get { return _response; } } public Stream ResponseSaveStream { get; set; } } }
24.861111
108
0.57095
[ "Apache-2.0" ]
prabirshrestha/FluentHttp
src/FluentHttp/Core/ResponseReceivedEventArgs.cs
895
C#
using System; using System.Collections.Generic; using System.Diagnostics; using System.Drawing; using System.Drawing.Imaging; using System.IO; using System.Linq; using System.Text; using System.Threading; using System.Windows.Forms; using BizHawk.Common; using BizHawk.Common.BufferExtensions; using BizHawk.Common.IOExtensions; using BizHawk.Client.Common; using BizHawk.Bizware.BizwareGL; using BizHawk.Emulation.Common; using BizHawk.Emulation.Common.IEmulatorExtensions; using BizHawk.Emulation.Cores.Calculators; using BizHawk.Emulation.Cores.Consoles.Nintendo.QuickNES; using BizHawk.Emulation.Cores.Nintendo.GBA; using BizHawk.Emulation.Cores.Nintendo.NES; using BizHawk.Emulation.Cores.Nintendo.SNES; using BizHawk.Emulation.Cores.Nintendo.N64; using BizHawk.Client.EmuHawk.WinFormExtensions; using BizHawk.Client.EmuHawk.ToolExtensions; using BizHawk.Client.EmuHawk.CoreExtensions; using BizHawk.Client.ApiHawk; using BizHawk.Emulation.Common.Base_Implementations; using BizHawk.Emulation.Cores.Nintendo.SNES9X; using BizHawk.Emulation.Cores.Consoles.SNK; using BizHawk.Emulation.Cores.Consoles.Sega.PicoDrive; using BizHawk.Emulation.Cores.Consoles.Nintendo.Gameboy; using BizHawk.Emulation.Cores.Atari.A7800Hawk; namespace BizHawk.Client.EmuHawk { public partial class MainForm : Form { #region Constructors and Initialization, and Tear down private void MainForm_Load(object sender, EventArgs e) { SetWindowText(); // Hide Status bar icons and general statusbar prep MainStatusBar.Padding = new Padding(MainStatusBar.Padding.Left, MainStatusBar.Padding.Top, MainStatusBar.Padding.Left, MainStatusBar.Padding.Bottom); // Workaround to remove extra padding on right PlayRecordStatusButton.Visible = false; AVIStatusLabel.Visible = false; SetPauseStatusbarIcon(); ToolFormBase.UpdateCheatRelatedTools(null, null); RebootStatusBarIcon.Visible = false; UpdateNotification.Visible = false; _statusBarDiskLightOnImage = Properties.Resources.LightOn; _statusBarDiskLightOffImage = Properties.Resources.LightOff; _linkCableOn = Properties.Resources.connect_16x16; _linkCableOff = Properties.Resources.noconnect_16x16; UpdateCoreStatusBarButton(); if (Global.Config.FirstBoot) { ProfileFirstBootLabel.Visible = true; } HandleToggleLightAndLink(); SetStatusBar(); // New version notification UpdateChecker.CheckComplete += (s2, e2) => { if (IsDisposed) { return; } this.BeginInvoke(() => { UpdateNotification.Visible = UpdateChecker.IsNewVersionAvailable; }); }; UpdateChecker.BeginCheck(); // Won't actually check unless enabled by user } static MainForm() { // If this isnt here, then our assemblyresolving hacks wont work due to the check for MainForm.INTERIM // its.. weird. dont ask. } private CoreComm CreateCoreComm() { CoreComm ret = new CoreComm(ShowMessageCoreComm, NotifyCoreComm) { ReleaseGLContext = o => GlobalWin.GLManager.ReleaseGLContext(o), RequestGLContext = (major, minor, forward) => GlobalWin.GLManager.CreateGLContext(major, minor, forward), ActivateGLContext = gl => GlobalWin.GLManager.Activate((GLManager.ContextRef)gl), DeactivateGLContext = () => GlobalWin.GLManager.Deactivate() }; return ret; } public MainForm(string[] args) { GlobalWin.MainForm = this; Global.Rewinder = new Rewinder { MessageCallback = GlobalWin.OSD.AddMessage }; Global.ControllerInputCoalescer = new ControllerInputCoalescer(); Global.FirmwareManager = new FirmwareManager(); Global.MovieSession = new MovieSession { Movie = MovieService.DefaultInstance, MovieControllerAdapter = MovieService.DefaultInstance.LogGeneratorInstance().MovieControllerAdapter, MessageCallback = GlobalWin.OSD.AddMessage, AskYesNoCallback = StateErrorAskUser, PauseCallback = PauseEmulator, ModeChangedCallback = SetMainformMovieInfo }; Icon = Properties.Resources.logo; InitializeComponent(); Global.Game = GameInfo.NullInstance; if (Global.Config.ShowLogWindow) { LogConsole.ShowConsole(); DisplayLogWindowMenuItem.Checked = true; } _throttle = new Throttle(); Global.CheatList = new CheatCollection(); Global.CheatList.Changed += ToolFormBase.UpdateCheatRelatedTools; UpdateStatusSlots(); UpdateKeyPriorityIcon(); // In order to allow late construction of this database, we hook up a delegate here to dearchive the data and provide it on demand // we could background thread this later instead if we wanted to be real clever NES.BootGodDB.GetDatabaseBytes = () => { string xmlPath = Path.Combine(PathManager.GetExeDirectoryAbsolute(), "gamedb", "NesCarts.xml"); string x7zPath = Path.Combine(PathManager.GetExeDirectoryAbsolute(), "gamedb", "NesCarts.7z"); bool loadXml = File.Exists(xmlPath); using (var nesCartFile = new HawkFile(loadXml ? xmlPath : x7zPath)) { if (!loadXml) { nesCartFile.BindFirst(); } return nesCartFile .GetStream() .ReadAllBytes(); } }; argParse.parseArguments(args); Database.LoadDatabase(Path.Combine(PathManager.GetExeDirectoryAbsolute(), "gamedb", "gamedb.txt")); // TODO GL - a lot of disorganized wiring-up here CGC.CGCBinPath = Path.Combine(PathManager.GetDllDirectory(), "cgc.exe"); PresentationPanel = new PresentationPanel(); PresentationPanel.GraphicsControl.MainWindow = true; GlobalWin.DisplayManager = new DisplayManager(PresentationPanel); Controls.Add(PresentationPanel); Controls.SetChildIndex(PresentationPanel, 0); // TODO GL - move these event handlers somewhere less obnoxious line in the On* overrides Load += (o, e) => { AllowDrop = true; DragEnter += FormDragEnter; DragDrop += FormDragDrop; }; Closing += (o, e) => { if (GlobalWin.Tools.AskSave()) { // zero 03-nov-2015 - close game after other steps. tools might need to unhook themselves from a core. Global.MovieSession.Movie.Stop(); GlobalWin.Tools.Close(); CloseGame(); // does this need to be last for any particular reason? do tool dialogs persist settings when closing? SaveConfig(); } else { e.Cancel = true; } }; ResizeBegin += (o, e) => { _inResizeLoop = true; if (GlobalWin.Sound != null) { GlobalWin.Sound.StopSound(); } }; Resize += (o, e) => { SetWindowText(); }; ResizeEnd += (o, e) => { _inResizeLoop = false; SetWindowText(); if (PresentationPanel != null) { PresentationPanel.Resized = true; } if (GlobalWin.Sound != null) { GlobalWin.Sound.StartSound(); } }; Input.Initialize(); InitControls(); var comm = CreateCoreComm(); CoreFileProvider.SyncCoreCommInputSignals(comm); Emulator = new NullEmulator(comm, Global.Config.GetCoreSettings<NullEmulator>()); Global.ActiveController = new Controller(NullController.Instance.Definition); Global.AutoFireController = _autofireNullControls; Global.AutofireStickyXORAdapter.SetOnOffPatternFromConfig(); try { GlobalWin.Sound = new Sound(Handle); } catch { string message = "Couldn't initialize sound device! Try changing the output method in Sound config."; if (Global.Config.SoundOutputMethod == Config.ESoundOutputMethod.DirectSound) { message = "Couldn't initialize DirectSound! Things may go poorly for you. Try changing your sound driver to 44.1khz instead of 48khz in mmsys.cpl."; } MessageBox.Show(message, "Initialization Error", MessageBoxButtons.OK, MessageBoxIcon.Error); Global.Config.SoundOutputMethod = Config.ESoundOutputMethod.Dummy; GlobalWin.Sound = new Sound(Handle); } GlobalWin.Sound.StartSound(); InputManager.RewireInputChain(); GlobalWin.Tools = new ToolManager(this); RewireSound(); // Workaround for windows, location is -32000 when minimized, if they close it during this time, that's what gets saved if (Global.Config.MainWndx == -32000) { Global.Config.MainWndx = 0; } if (Global.Config.MainWndy == -32000) { Global.Config.MainWndy = 0; } if (Global.Config.MainWndx != -1 && Global.Config.MainWndy != -1 && Global.Config.SaveWindowPosition) { Location = new Point(Global.Config.MainWndx, Global.Config.MainWndy); } if (argParse.socket_ip != null) { Global.Config.controller_ip = argParse.socket_ip; } if (argParse.round_over_delay > 0) { Global.Config.round_over_delay= argParse.round_over_delay; } if (argParse.emulator_speed_percent > 0) { Global.Config.emulator_speed_percent = argParse.emulator_speed_percent; } if (argParse.socket_port != null) { Global.Config.controller_port = argParse.socket_port; } if (argParse.socket_ip_p2 != null) { Global.Config.controller_ip_p2 = argParse.socket_ip_p2; } if (argParse.socket_port_p2 != null) { Global.Config.controller_port_p2 = argParse.socket_port_p2; } if (argParse.use_two_controllers) { Global.Config.use_two_controllers = true; } if (argParse.pause_after_round) { Global.Config.pause_after_round = true; } if (argParse.run_id != null) { Global.Config.run_id = argParse.run_id; } if (argParse.cmdRom != null) { // Commandline should always override auto-load var ioa = OpenAdvancedSerializer.ParseWithLegacy(argParse.cmdRom); LoadRom(argParse.cmdRom, new LoadRomArgs { OpenAdvanced = ioa }); if (Global.Game == null) { MessageBox.Show("Failed to load " + argParse.cmdRom + " specified on commandline"); } } else if (Global.Config.RecentRoms.AutoLoad && !Global.Config.RecentRoms.Empty) { LoadRomFromRecent(Global.Config.RecentRoms.MostRecent); } if (argParse.cmdMovie != null) { _supressSyncSettingsWarning = true; // We dont' want to be nagged if we are attempting to automate if (Global.Game == null) { OpenRom(); } // If user picked a game, then do the commandline logic if (!Global.Game.IsNullInstance) { var movie = MovieService.Get(argParse.cmdMovie); Global.MovieSession.ReadOnly = true; // if user is dumping and didnt supply dump length, make it as long as the loaded movie if (argParse._autoDumpLength == 0) { argParse._autoDumpLength = movie.InputLogLength; } // Copy pasta from drag & drop if (MovieImport.IsValidMovieExtension(Path.GetExtension(argParse.cmdMovie))) { string errorMsg; string warningMsg; var imported = MovieImport.ImportFile(argParse.cmdMovie, out errorMsg, out warningMsg); if (!string.IsNullOrEmpty(errorMsg)) { MessageBox.Show(errorMsg, "Conversion error", MessageBoxButtons.OK, MessageBoxIcon.Error); } else { // fix movie extension to something palatable for these purposes. // for instance, something which doesnt clobber movies you already may have had. // i'm evenly torn between this, and a file in %TEMP%, but since we dont really have a way to clean up this tempfile, i choose this: StartNewMovie(imported, false); } GlobalWin.OSD.AddMessage(warningMsg); } else { StartNewMovie(movie, false); Global.Config.RecentMovies.Add(argParse.cmdMovie); } _supressSyncSettingsWarning = false; } } else if (Global.Config.RecentMovies.AutoLoad && !Global.Config.RecentMovies.Empty) { if (Global.Game.IsNullInstance) { OpenRom(); } // If user picked a game, then do the autoload logic if (!Global.Game.IsNullInstance) { if (File.Exists(Global.Config.RecentMovies.MostRecent)) { StartNewMovie(MovieService.Get(Global.Config.RecentMovies.MostRecent), false); } else { Global.Config.RecentMovies.HandleLoadError(Global.Config.RecentMovies.MostRecent); } } } if (argParse.startFullscreen || Global.Config.StartFullscreen) { _needsFullscreenOnLoad = true; } if (!Global.Game.IsNullInstance) { if (argParse.cmdLoadState != null) { LoadState(argParse.cmdLoadState, Path.GetFileName(argParse.cmdLoadState)); } else if (argParse.cmdLoadSlot != null) { LoadQuickSave("QuickSave" + argParse.cmdLoadSlot); } else if (Global.Config.AutoLoadLastSaveSlot) { LoadQuickSave("QuickSave" + Global.Config.SaveSlot); } } //start Lua Console if requested in the command line arguments if (argParse.luaConsole) { GlobalWin.Tools.Load<LuaConsole>(); } //load Lua Script if requested in the command line arguments if (argParse.luaScript != null) { GlobalWin.Tools.LuaConsole.LoadLuaFile(argParse.luaScript); } GlobalWin.Tools.AutoLoad(); if (Global.Config.RecentWatches.AutoLoad) { GlobalWin.Tools.LoadRamWatch(!Global.Config.DisplayRamWatch); } if (Global.Config.RecentCheats.AutoLoad) { GlobalWin.Tools.Load<Cheats>(); } SetStatusBar(); if (Global.Config.StartPaused) { PauseEmulator(); } // start dumping, if appropriate if (argParse.cmdDumpType != null && argParse.cmdDumpName != null) { RecordAv(argParse.cmdDumpType, argParse.cmdDumpName); } SetMainformMovieInfo(); SynchChrome(); PresentationPanel.Control.Paint += (o, e) => { // I would like to trigger a repaint here, but this isnt done yet }; } private readonly bool _supressSyncSettingsWarning; public int ProgramRunLoop() { CheckMessages(); // can someone leave a note about why this is needed? LogConsole.PositionConsole(); // needs to be done late, after the log console snaps on top // fullscreen should snap on top even harder! if (_needsFullscreenOnLoad) { _needsFullscreenOnLoad = false; ToggleFullscreen(); } // incantation required to get the program reliably on top of the console window // we might want it in ToggleFullscreen later, but here, it needs to happen regardless BringToFront(); Activate(); BringToFront(); InitializeFpsData(); for (;;) { Input.Instance.Update(); // handle events and dispatch as a hotkey action, or a hotkey button, or an input button ProcessInput(); Global.ClientControls.LatchFromPhysical(_hotkeyCoalescer); Global.ActiveController.LatchFromPhysical(Global.ControllerInputCoalescer); Global.ActiveController.ApplyAxisConstraints( (Emulator is N64 && Global.Config.N64UseCircularAnalogConstraint) ? "Natural Circle" : null); Global.ActiveController.OR_FromLogical(Global.ClickyVirtualPadController); Global.AutoFireController.LatchFromPhysical(Global.ControllerInputCoalescer); if (Global.ClientControls["Autohold"]) { Global.StickyXORAdapter.MassToggleStickyState(Global.ActiveController.PressedButtons); Global.AutofireStickyXORAdapter.MassToggleStickyState(Global.AutoFireController.PressedButtons); } else if (Global.ClientControls["Autofire"]) { Global.AutofireStickyXORAdapter.MassToggleStickyState(Global.ActiveController.PressedButtons); } // autohold/autofire must not be affected by the following inputs Global.ActiveController.Overrides(Global.LuaAndAdaptor); if (GlobalWin.Tools.Has<LuaConsole>() && !SuppressLua) { GlobalWin.Tools.LuaConsole.ResumeScripts(false); } StepRunLoop_Core(); StepRunLoop_Throttle(); Render(); CheckMessages(); if (_exitRequestPending) { _exitRequestPending = false; Close(); } if (_exit) { break; } if (Global.Config.DispSpeedupFeatures != 0) { Thread.Sleep(0); } } Shutdown(); return _exitCode; } /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { // NOTE: this gets called twice sometimes. once by using() in Program.cs and once from winforms internals when the form is closed... if (GlobalWin.DisplayManager != null) { GlobalWin.DisplayManager.Dispose(); GlobalWin.DisplayManager = null; } if (disposing) { components?.Dispose(); } base.Dispose(disposing); } #endregion #region Pause private bool _emulatorPaused; public bool EmulatorPaused { get { return _emulatorPaused; } private set { if (_emulatorPaused && !value) // Unpausing { InitializeFpsData(); } _emulatorPaused = value; OnPauseChanged?.Invoke(this, new PauseChangedEventArgs(_emulatorPaused)); } } public delegate void PauseChangedEventHandler(object sender, PauseChangedEventArgs e); public event PauseChangedEventHandler OnPauseChanged; public class PauseChangedEventArgs : EventArgs { public PauseChangedEventArgs(bool paused) { Paused = paused; } public bool Paused { get; private set; } } #endregion #region Properties public string CurrentlyOpenRom { get; private set; } // todo - delete me and use only args instead public LoadRomArgs CurrentlyOpenRomArgs { get; private set; } public bool PauseAvi { get; set; } public bool PressFrameAdvance { get; set; } public bool HoldFrameAdvance { get; set; } // necessary for tastudio > button public bool PressRewind { get; set; } // necessary for tastudio < button public bool FastForward { get; set; } // runloop won't exec lua public bool SuppressLua { get; set; } public long MouseWheelTracker { get; private set; } private int? _pauseOnFrame; public int? PauseOnFrame // If set, upon completion of this frame, the client wil pause { get { return _pauseOnFrame; } set { _pauseOnFrame = value; SetPauseStatusbarIcon(); if (value == null) // TODO: make an Event handler instead, but the logic here is that after turbo seeking, tools will want to do a real update when the emulator finally pauses { bool skipScripts = !(Global.Config.TurboSeek && !Global.Config.RunLuaDuringTurbo && !SuppressLua); GlobalWin.Tools.UpdateToolsBefore(skipScripts); GlobalWin.Tools.UpdateToolsAfter(skipScripts); } } } public bool IsSeeking => PauseOnFrame.HasValue; private bool IsTurboSeeking => PauseOnFrame.HasValue && Global.Config.TurboSeek; private bool IsTurboing => Global.ClientControls["Turbo"] || IsTurboSeeking; #endregion #region Public Methods public void ClearHolds() { Global.StickyXORAdapter.ClearStickies(); Global.AutofireStickyXORAdapter.ClearStickies(); if (GlobalWin.Tools.Has<VirtualpadTool>()) { GlobalWin.Tools.VirtualPad.ClearVirtualPadHolds(); } } public void FlagNeedsReboot() { RebootStatusBarIcon.Visible = true; GlobalWin.OSD.AddMessage("Core reboot needed for this setting"); } /// <summary> /// Controls whether the app generates input events. should be turned off for most modal dialogs /// </summary> public bool AllowInput(bool yieldAlt) { // the main form gets input if (ActiveForm == this) { return true; } // even more special logic for TAStudio: // TODO - implement by event filter in TAStudio var maybeTAStudio = ActiveForm as TAStudio; if (maybeTAStudio != null) { if (yieldAlt) { return false; } if (maybeTAStudio.IsInMenuLoop) { return false; } } // modals that need to capture input for binding purposes get input, of course if (ActiveForm is HotkeyConfig || ActiveForm is ControllerConfig || ActiveForm is TAStudio || ActiveForm is VirtualpadTool) { return true; } // if no form is active on this process, then the background input setting applies if (ActiveForm == null && Global.Config.AcceptBackgroundInput) { return true; } return false; } // TODO: make this an actual property, set it when loading a Rom, and pass it dialogs, etc // This is a quick hack to reduce the dependency on Global.Emulator private IEmulator Emulator { get { return Global.Emulator; } set { Global.Emulator = value; _currentVideoProvider = Global.Emulator.AsVideoProviderOrDefault(); _currentSoundProvider = Global.Emulator.AsSoundProviderOrDefault(); } } private IVideoProvider _currentVideoProvider = NullVideo.Instance; private ISoundProvider _currentSoundProvider = new NullSound(44100 / 60); // Reasonable default until we have a core instance protected override void OnActivated(EventArgs e) { base.OnActivated(e); Input.Instance.ControlInputFocus(this, Input.InputFocus.Mouse, true); } protected override void OnDeactivate(EventArgs e) { Input.Instance.ControlInputFocus(this, Input.InputFocus.Mouse, false); base.OnDeactivate(e); } private void ProcessInput() { ControllerInputCoalescer conInput = (ControllerInputCoalescer)Global.ControllerInputCoalescer; for (;;) { // loop through all available events var ie = Input.Instance.DequeueEvent(); if (ie == null) { break; } // useful debugging: // Console.WriteLine(ie); // TODO - wonder what happens if we pop up something interactive as a response to one of these hotkeys? may need to purge further processing // look for hotkey bindings for this key var triggers = Global.ClientControls.SearchBindings(ie.LogicalButton.ToString()); if (triggers.Count == 0) { // Maybe it is a system alt-key which hasnt been overridden if (ie.EventType == Input.InputEventType.Press) { if (ie.LogicalButton.Alt && ie.LogicalButton.Button.Length == 1) { var c = ie.LogicalButton.Button.ToLower()[0]; if ((c >= 'a' && c <= 'z') || c == ' ') { SendAltKeyChar(c); } } if (ie.LogicalButton.Alt && ie.LogicalButton.Button == "Space") { SendPlainAltKey(32); } } // ordinarily, an alt release with nothing else would move focus to the menubar. but that is sort of useless, and hard to implement exactly right. } // zero 09-sep-2012 - all input is eligible for controller input. not sure why the above was done. // maybe because it doesnt make sense to me to bind hotkeys and controller inputs to the same keystrokes // adelikat 02-dec-2012 - implemented options for how to handle controller vs hotkey conflicts. This is primarily motivated by computer emulation and thus controller being nearly the entire keyboard bool handled; switch (Global.Config.Input_Hotkey_OverrideOptions) { default: case 0: // Both allowed conInput.Receive(ie); handled = false; if (ie.EventType == Input.InputEventType.Press) { handled = triggers.Aggregate(handled, (current, trigger) => current | CheckHotkey(trigger)); } // hotkeys which arent handled as actions get coalesced as pollable virtual client buttons if (!handled) { _hotkeyCoalescer.Receive(ie); } break; case 1: // Input overrides Hokeys conInput.Receive(ie); if (!Global.ActiveController.HasBinding(ie.LogicalButton.ToString())) { handled = false; if (ie.EventType == Input.InputEventType.Press) { handled = triggers.Aggregate(handled, (current, trigger) => current | CheckHotkey(trigger)); } // hotkeys which arent handled as actions get coalesced as pollable virtual client buttons if (!handled) { _hotkeyCoalescer.Receive(ie); } } break; case 2: // Hotkeys override Input handled = false; if (ie.EventType == Input.InputEventType.Press) { handled = triggers.Aggregate(handled, (current, trigger) => current | CheckHotkey(trigger)); } // hotkeys which arent handled as actions get coalesced as pollable virtual client buttons if (!handled) { _hotkeyCoalescer.Receive(ie); // Check for hotkeys that may not be handled through Checkhotkey() method, reject controller input mapped to these if (!triggers.Any(IsInternalHotkey)) { conInput.Receive(ie); } } break; } } // foreach event // also handle floats conInput.AcceptNewFloats(Input.Instance.GetFloats().Select(o => { // hackish if (o.Item1 == "WMouse X") { var p = GlobalWin.DisplayManager.UntransformPoint(new Point((int)o.Item2, 0)); float x = p.X / (float)_currentVideoProvider.BufferWidth; return new Tuple<string, float>("WMouse X", (x * 20000) - 10000); } if (o.Item1 == "WMouse Y") { var p = GlobalWin.DisplayManager.UntransformPoint(new Point(0, (int)o.Item2)); float y = p.Y / (float)_currentVideoProvider.BufferHeight; return new Tuple<string, float>("WMouse Y", (y * 20000) - 10000); } return o; })); } public void RebootCore() { var ioa = OpenAdvancedSerializer.ParseWithLegacy(_currentlyOpenRomPoopForAdvancedLoaderPleaseRefactorMe); if (ioa is OpenAdvanced_LibretroNoGame) { LoadRom("", CurrentlyOpenRomArgs); } else { LoadRom(ioa.SimplePath, CurrentlyOpenRomArgs); } } public void PauseEmulator() { EmulatorPaused = true; SetPauseStatusbarIcon(); } public void UnpauseEmulator() { EmulatorPaused = false; SetPauseStatusbarIcon(); } public void TogglePause() { EmulatorPaused ^= true; SetPauseStatusbarIcon(); // TODO: have tastudio set a pause status change callback, or take control over pause if (GlobalWin.Tools.Has<TAStudio>()) { GlobalWin.Tools.UpdateValues<TAStudio>(); } } public byte[] CurrentFrameBuffer(bool captureOSD) { using (var bb = captureOSD ? CaptureOSD() : MakeScreenshotImage()) { using (var img = bb.ToSysdrawingBitmap()) { ImageConverter converter = new ImageConverter(); return (byte[])converter.ConvertTo(img, typeof(byte[])); } } } public void TakeScreenshotToClipboard() { using (var bb = Global.Config.Screenshot_CaptureOSD ? CaptureOSD() : MakeScreenshotImage()) { using (var img = bb.ToSysdrawingBitmap()) { Clipboard.SetImage(img); } } //GlobalWin.OSD.AddMessage("Screenshot (raw) saved to clipboard."); } private void TakeScreenshotClientToClipboard() { using (var bb = GlobalWin.DisplayManager.RenderOffscreen(_currentVideoProvider, Global.Config.Screenshot_CaptureOSD)) { using (var img = bb.ToSysdrawingBitmap()) { Clipboard.SetImage(img); } } GlobalWin.OSD.AddMessage("Screenshot (client) saved to clipboard."); } public void TakeScreenshot() { string fmt = "{0}.{1:yyyy-MM-dd HH.mm.ss}{2}.png"; string prefix = PathManager.ScreenshotPrefix(Global.Game); var ts = DateTime.Now; string fnameBare = string.Format(fmt, prefix, ts, ""); string fname = string.Format(fmt, prefix, ts, " (0)"); // if the (0) filename exists, do nothing. we'll bump up the number later // if the bare filename exists, move it to (0) // otherwise, no related filename exists, and we can proceed with the bare filename if (File.Exists(fname)) { } else if (File.Exists(fnameBare)) { File.Move(fnameBare, fname); } else { fname = fnameBare; } int seq = 0; while (File.Exists(fname)) { var sequence = $" ({seq++})"; fname = string.Format(fmt, prefix, ts, sequence); } TakeScreenshot(fname); } public void TakeScreenshot(string path) { var fi = new FileInfo(path); if (fi.Directory != null && !fi.Directory.Exists) { fi.Directory.Create(); } using (var bb = Global.Config.Screenshot_CaptureOSD ? CaptureOSD() : MakeScreenshotImage()) { using (var img = bb.ToSysdrawingBitmap()) { img.Save(fi.FullName, ImageFormat.Png); } } /* using (var fs = new FileStream(path + "_test.bmp", FileMode.OpenOrCreate, FileAccess.Write)) QuickBmpFile.Save(Emulator.VideoProvider(), fs, r.Next(50, 500), r.Next(50, 500)); */ GlobalWin.OSD.AddMessage(fi.Name + " saved."); } public void FrameBufferResized() { // run this entire thing exactly twice, since the first resize may adjust the menu stacking for (int i = 0; i < 2; i++) { int zoom = Global.Config.TargetZoomFactors[Emulator.SystemId]; var area = Screen.FromControl(this).WorkingArea; int borderWidth = Size.Width - PresentationPanel.Control.Size.Width; int borderHeight = Size.Height - PresentationPanel.Control.Size.Height; // start at target zoom and work way down until we find acceptable zoom Size lastComputedSize = new Size(1, 1); for (; zoom >= 1; zoom--) { lastComputedSize = GlobalWin.DisplayManager.CalculateClientSize(_currentVideoProvider, zoom); if (lastComputedSize.Width + borderWidth < area.Width && lastComputedSize.Height + borderHeight < area.Height) { break; } } Console.WriteLine("Selecting display size " + lastComputedSize); // Change size Size = new Size(lastComputedSize.Width + borderWidth, lastComputedSize.Height + borderHeight); PerformLayout(); PresentationPanel.Resized = true; // Is window off the screen at this size? if (!area.Contains(Bounds)) { if (Bounds.Right > area.Right) // Window is off the right edge { Location = new Point(area.Right - Size.Width, Location.Y); } if (Bounds.Bottom > area.Bottom) // Window is off the bottom edge { Location = new Point(Location.X, area.Bottom - Size.Height); } } } } private void SynchChrome() { if (_inFullscreen) { // TODO - maybe apply a hack tracked during fullscreen here to override it FormBorderStyle = FormBorderStyle.None; MainMenuStrip.Visible = Global.Config.DispChrome_MenuFullscreen && !argParse._chromeless; MainStatusBar.Visible = Global.Config.DispChrome_StatusBarFullscreen && !argParse._chromeless; } else { MainStatusBar.Visible = Global.Config.DispChrome_StatusBarWindowed && !argParse._chromeless; MainMenuStrip.Visible = Global.Config.DispChrome_MenuWindowed && !argParse._chromeless; MaximizeBox = MinimizeBox = Global.Config.DispChrome_CaptionWindowed && !argParse._chromeless; if (Global.Config.DispChrome_FrameWindowed == 0 || argParse._chromeless) { FormBorderStyle = FormBorderStyle.None; } else if (Global.Config.DispChrome_FrameWindowed == 1) { FormBorderStyle = FormBorderStyle.SizableToolWindow; } else if (Global.Config.DispChrome_FrameWindowed == 2) { FormBorderStyle = FormBorderStyle.Sizable; } } } public void ToggleFullscreen(bool allowSuppress = false) { AutohideCursor(false); // prohibit this operation if the current controls include LMouse if (allowSuppress) { if (Global.ActiveController.HasBinding("WMouse L")) { return; } } if (!_inFullscreen) { SuspendLayout(); #if WINDOWS // Work around an AMD driver bug in >= vista: // It seems windows will activate opengl fullscreen mode when a GL control is occupying the exact space of a screen (0,0 and dimensions=screensize) // AMD cards manifest a problem under these circumstances, flickering other monitors. // It isnt clear whether nvidia cards are failing to employ this optimization, or just not flickering. // (this could be determined with more work; other side affects of the fullscreen mode include: corrupted taskbar, no modal boxes on top of GL control, no screenshots) // At any rate, we can solve this by adding a 1px black border around the GL control // Please note: It is important to do this before resizing things, otherwise momentarily a GL control without WS_BORDER will be at the magic dimensions and cause the flakeout if (Global.Config.DispFullscreenHacks && Global.Config.DispMethod == Config.EDispMethod.OpenGL) { //ATTENTION: this causes the statusbar to not work well, since the backcolor is now set to black instead of SystemColors.Control. //It seems that some statusbar elements composite with the backcolor. //Maybe we could add another control under the statusbar. with a different backcolor Padding = new Padding(1); BackColor = Color.Black; // FUTURE WORK: // re-add this padding back into the display manager (so the image will get cut off a little but, but a few more resolutions will fully fit into the screen) } #endif _windowedLocation = Location; _inFullscreen = true; SynchChrome(); WindowState = FormWindowState.Maximized; // be sure to do this after setting the chrome, otherwise it wont work fully ResumeLayout(); PresentationPanel.Resized = true; } else { SuspendLayout(); WindowState = FormWindowState.Normal; #if WINDOWS // do this even if DispFullscreenHacks arent enabled, to restore it in case it changed underneath us or something Padding = new Padding(0); // it's important that we set the form color back to this, because the statusbar icons blend onto the mainform, not onto the statusbar-- // so we need the statusbar and mainform backdrop color to match BackColor = SystemColors.Control; #endif _inFullscreen = false; SynchChrome(); Location = _windowedLocation; ResumeLayout(); FrameBufferResized(); } } private void OpenLuaConsole() { #if WINDOWS GlobalWin.Tools.Load<LuaConsole>(); #else MessageBox.Show("Sorry, Lua is not supported on this platform.", "Lua not supported", MessageBoxButtons.OK, MessageBoxIcon.Error); #endif } public void NotifyLogWindowClosing() { DisplayLogWindowMenuItem.Checked = false; } public void ClickSpeedItem(int num) { if ((ModifierKeys & Keys.Control) != 0) { SetSpeedPercentAlternate(num); } else { SetSpeedPercent(num); } } public void Unthrottle() { _unthrottled = true; } public void Throttle() { _unthrottled = false; } private void ThrottleMessage() { string ttype = ":(none)"; if (Global.Config.SoundThrottle) { ttype = ":Sound"; } if (Global.Config.VSyncThrottle) { ttype = $":Vsync{(Global.Config.VSync ? "[ena]" : "[dis]")}"; } if (Global.Config.ClockThrottle) { ttype = ":Clock"; } string xtype = _unthrottled ? "Unthrottled" : "Throttled"; string msg = $"{xtype}{ttype} "; GlobalWin.OSD.AddMessage(msg); } public void FrameSkipMessage() { GlobalWin.OSD.AddMessage("Frameskipping set to " + Global.Config.FrameSkip); } public void UpdateCheatStatus() { if (Global.CheatList.ActiveCount > 0) { CheatStatusButton.ToolTipText = "Cheats are currently active"; CheatStatusButton.Image = Properties.Resources.Freeze; CheatStatusButton.Visible = true; } else { CheatStatusButton.ToolTipText = ""; CheatStatusButton.Image = Properties.Resources.Blank; CheatStatusButton.Visible = false; } } private LibsnesCore AsSNES => Emulator as LibsnesCore; private void SNES_ToggleBg(int layer) { if (!(Emulator is LibsnesCore) && !(Emulator is Snes9x)) { return; } if (layer < 1 || layer > 4) { return; } bool result = false; if (Emulator is LibsnesCore) { var s = ((LibsnesCore)Emulator).GetSettings(); switch (layer) { case 1: result = s.ShowBG1_0 = s.ShowBG1_1 ^= true; break; case 2: result = s.ShowBG2_0 = s.ShowBG2_1 ^= true; break; case 3: result = s.ShowBG3_0 = s.ShowBG3_1 ^= true; break; case 4: result = s.ShowBG4_0 = s.ShowBG4_1 ^= true; break; } ((LibsnesCore)Emulator).PutSettings(s); } else if (Emulator is Snes9x) { var s = ((Snes9x)Emulator).GetSettings(); switch (layer) { case 1: result = s.ShowBg0 ^= true; break; case 2: result = s.ShowBg1 ^= true; break; case 3: result = s.ShowBg2 ^= true; break; case 4: result = s.ShowBg3 ^= true; break; } ((Snes9x)Emulator).PutSettings(s); } GlobalWin.OSD.AddMessage($"BG {layer} Layer " + (result ? "On" : "Off")); } private void SNES_ToggleObj(int layer) { if (!(Emulator is LibsnesCore) && !(Emulator is Snes9x)) { return; } if (layer < 1 || layer > 4) { return; } bool result = false; if (Emulator is LibsnesCore) { var s = ((LibsnesCore)Emulator).GetSettings(); switch (layer) { case 1: result = s.ShowOBJ_0 ^= true; break; case 2: result = s.ShowOBJ_1 ^= true; break; case 3: result = s.ShowOBJ_2 ^= true; break; case 4: result = s.ShowOBJ_3 ^= true; break; } ((LibsnesCore)Emulator).PutSettings(s); GlobalWin.OSD.AddMessage($"Obj {layer} Layer " + (result ? "On" : "Off")); } else if (Emulator is Snes9x) { var s = ((Snes9x)Emulator).GetSettings(); switch (layer) { case 1: result = s.ShowSprites0 ^= true; break; case 2: result = s.ShowSprites1 ^= true; break; case 3: result = s.ShowSprites2 ^= true; break; case 4: result = s.ShowSprites3 ^= true; break; } ((Snes9x)Emulator).PutSettings(s); GlobalWin.OSD.AddMessage($"Sprite {layer} Layer " + (result ? "On" : "Off")); } } public bool RunLibretroCoreChooser() { var ofd = new OpenFileDialog(); if (Global.Config.LibretroCore != null) { ofd.FileName = Path.GetFileName(Global.Config.LibretroCore); ofd.InitialDirectory = Path.GetDirectoryName(Global.Config.LibretroCore); } else { ofd.InitialDirectory = PathManager.GetPathType("Libretro", "Cores"); if (!Directory.Exists(ofd.InitialDirectory)) { Directory.CreateDirectory(ofd.InitialDirectory); } } ofd.RestoreDirectory = true; ofd.Filter = "Libretro Cores (*.dll)|*.dll"; if (ofd.ShowDialog() == DialogResult.Cancel) { return false; } Global.Config.LibretroCore = ofd.FileName; return true; } #endregion #region Private variables private Size _lastVideoSize = new Size(-1, -1), _lastVirtualSize = new Size(-1, -1); private readonly SaveSlotManager _stateSlots = new SaveSlotManager(); // AVI/WAV state private IVideoWriter _currAviWriter; private AutofireController _autofireNullControls; // Sound refator TODO: we can enforce async mode here with a property that gets/sets this but does an async check private ISoundProvider _aviSoundInputAsync; // Note: This sound provider must be in async mode! private SimpleSyncSoundProvider _dumpProxy; // an audio proxy used for dumping private bool _dumpaudiosync; // set true to for experimental AV dumping private int _avwriterResizew; private int _avwriterResizeh; private bool _avwriterpad; private bool _exit; private int _exitCode; private bool _exitRequestPending; private bool _runloopFrameProgress; private long _frameAdvanceTimestamp; private long _frameRewindTimestamp; private bool _frameRewindWasPaused; private bool _runloopFrameAdvance; private bool _lastFastForwardingOrRewinding; private bool _inResizeLoop; private readonly double _fpsUpdatesPerSecond = 4.0; private readonly double _fpsSmoothing = 8.0; private double _lastFps; private int _framesSinceLastFpsUpdate; private long _timestampLastFpsUpdate; private readonly Throttle _throttle; private bool _unthrottled; // For handling automatic pausing when entering the menu private bool _wasPaused; private bool _didMenuPause; private Cursor _blankCursor; private bool _cursorHidden; private bool _inFullscreen; private Point _windowedLocation; private bool _needsFullscreenOnLoad; private int _lastOpenRomFilter; private ArgParser argParse = new ArgParser(); // Resources private Bitmap _statusBarDiskLightOnImage; private Bitmap _statusBarDiskLightOffImage; private Bitmap _linkCableOn; private Bitmap _linkCableOff; // input state which has been destined for game controller inputs are coalesced here // public static ControllerInputCoalescer ControllerInputCoalescer = new ControllerInputCoalescer(); // input state which has been destined for client hotkey consumption are colesced here private readonly InputCoalescer _hotkeyCoalescer = new InputCoalescer(); public PresentationPanel PresentationPanel { get; } //countdown for saveram autoflushing public int AutoFlushSaveRamIn { get; set; } #endregion #region Private methods private void SetStatusBar() { if (!_inFullscreen) { MainStatusBar.Visible = Global.Config.DispChrome_StatusBarWindowed; PerformLayout(); FrameBufferResized(); } } private void SetWindowText() { string str = ""; if (_inResizeLoop) { var size = PresentationPanel.NativeSize; float ar = (float)size.Width / size.Height; str += $"({size.Width}x{size.Height})={ar} - "; } // we need to display FPS somewhere, in this case if (Global.Config.DispSpeedupFeatures == 0) { str += $"({_lastFps:0} fps) - "; } if (!string.IsNullOrEmpty(VersionInfo.CustomBuildString)) { str += VersionInfo.CustomBuildString + " "; } str += Emulator.IsNull() ? "BizHawk" : Global.SystemInfo.DisplayName; if (Global.Config.run_id != null) { str += " " + Global.Config.run_id; } if (VersionInfo.DeveloperBuild) { str += " (interim)"; } if (!Emulator.IsNull()) { str += " - " + Global.Game.Name; if (Global.MovieSession.Movie.IsActive) { str += " - " + Path.GetFileName(Global.MovieSession.Movie.Filename); } } if (!Global.Config.DispChrome_CaptionWindowed || argParse._chromeless) { str = ""; } Text = str; } private void ClearAutohold() { ClearHolds(); GlobalWin.OSD.AddMessage("Autohold keys cleared"); } private static void UpdateToolsLoadstate() { if (GlobalWin.Tools.Has<SNESGraphicsDebugger>()) { GlobalWin.Tools.SNESGraphicsDebugger.UpdateToolsLoadstate(); } } private void UpdateToolsAfter(bool fromLua = false) { GlobalWin.Tools.UpdateToolsAfter(fromLua); HandleToggleLightAndLink(); } public void UpdateDumpIcon() { DumpStatusButton.Image = Properties.Resources.Blank; DumpStatusButton.ToolTipText = ""; if (Emulator.IsNull()) { return; } else if (Global.Game == null) { return; } var status = Global.Game.Status; string annotation; if (status == RomStatus.BadDump) { DumpStatusButton.Image = Properties.Resources.ExclamationRed; annotation = "Warning: Bad ROM Dump"; } else if (status == RomStatus.Overdump) { DumpStatusButton.Image = Properties.Resources.ExclamationRed; annotation = "Warning: Overdump"; } else if (status == RomStatus.NotInDatabase) { DumpStatusButton.Image = Properties.Resources.RetroQuestion; annotation = "Warning: Unknown ROM"; } else if (status == RomStatus.TranslatedRom) { DumpStatusButton.Image = Properties.Resources.Translation; annotation = "Translated ROM"; } else if (status == RomStatus.Homebrew) { DumpStatusButton.Image = Properties.Resources.HomeBrew; annotation = "Homebrew ROM"; } else if (Global.Game.Status == RomStatus.Hack) { DumpStatusButton.Image = Properties.Resources.Hack; annotation = "Hacked ROM"; } else if (Global.Game.Status == RomStatus.Unknown) { DumpStatusButton.Image = Properties.Resources.Hack; annotation = "Warning: ROM of Unknown Character"; } else { DumpStatusButton.Image = Properties.Resources.GreenCheck; annotation = "Verified good dump"; } if (!string.IsNullOrEmpty(Emulator.CoreComm.RomStatusAnnotation)) { annotation = Emulator.CoreComm.RomStatusAnnotation; } DumpStatusButton.ToolTipText = annotation; } private void LoadSaveRam() { if (Emulator.HasSaveRam()) { try // zero says: this is sort of sketchy... but this is no time for rearchitecting { if (Global.Config.AutosaveSaveRAM) { var saveram = new FileInfo(PathManager.SaveRamPath(Global.Game)); var autosave = new FileInfo(PathManager.AutoSaveRamPath(Global.Game)); if (autosave.Exists && autosave.LastWriteTime > saveram.LastWriteTime) { GlobalWin.OSD.AddMessage("AutoSaveRAM is newer than last saved SaveRAM"); } } byte[] sram; // GBA meteor core might not know how big the saveram ought to be, so just send it the whole file // GBA vba-next core will try to eat anything, regardless of size if (Emulator is VBANext || Emulator is MGBAHawk || Emulator is NeoGeoPort) { sram = File.ReadAllBytes(PathManager.SaveRamPath(Global.Game)); } else { var oldram = Emulator.AsSaveRam().CloneSaveRam(); if (oldram == null) { // we're eating this one now. The possible negative consequence is that a user could lose // their saveram and not know why // MessageBox.Show("Error: tried to load saveram, but core would not accept it?"); return; } // why do we silently truncate\pad here instead of warning\erroring? sram = new byte[oldram.Length]; using (var reader = new BinaryReader( new FileStream(PathManager.SaveRamPath(Global.Game), FileMode.Open, FileAccess.Read))) { reader.Read(sram, 0, sram.Length); } } Emulator.AsSaveRam().StoreSaveRam(sram); AutoFlushSaveRamIn = Global.Config.FlushSaveRamFrames; } catch (IOException) { GlobalWin.OSD.AddMessage("An error occurred while loading Sram"); } } } public void FlushSaveRAM(bool autosave = false) { if (Emulator.HasSaveRam()) { string path; if (autosave) { path = PathManager.AutoSaveRamPath(Global.Game); AutoFlushSaveRamIn = Global.Config.FlushSaveRamFrames; } else { path = PathManager.SaveRamPath(Global.Game); } var file = new FileInfo(path); var newPath = path + ".new"; var newFile = new FileInfo(newPath); var backupPath = path + ".bak"; var backupFile = new FileInfo(backupPath); if (file.Directory != null && !file.Directory.Exists) { file.Directory.Create(); } var writer = new BinaryWriter(new FileStream(newPath, FileMode.Create, FileAccess.Write)); var saveram = Emulator.AsSaveRam().CloneSaveRam(); if (saveram != null) { writer.Write(saveram, 0, saveram.Length); } writer.Close(); if (file.Exists) { if (Global.Config.BackupSaveram) { if (backupFile.Exists) { backupFile.Delete(); } file.MoveTo(backupPath); } else { file.Delete(); } } newFile.MoveTo(path); } } private void RewireSound() { if (_dumpProxy != null) { // we're video dumping, so async mode only and use the DumpProxy. // note that the avi dumper has already rewired the emulator itself in this case. GlobalWin.Sound.SetInputPin(_dumpProxy); } else { bool useAsyncMode = _currentSoundProvider.CanProvideAsync && !Global.Config.SoundThrottle; _currentSoundProvider.SetSyncMode(useAsyncMode ? SyncSoundMode.Async : SyncSoundMode.Sync); GlobalWin.Sound.SetInputPin(_currentSoundProvider); } } private void HandlePlatformMenus() { var system = ""; if (!Global.Game.IsNullInstance) { system = Emulator.SystemId; } TI83SubMenu.Visible = false; NESSubMenu.Visible = false; PCESubMenu.Visible = false; SMSSubMenu.Visible = false; GBSubMenu.Visible = false; GBASubMenu.Visible = false; AtariSubMenu.Visible = false; A7800SubMenu.Visible = false; SNESSubMenu.Visible = false; PSXSubMenu.Visible = false; ColecoSubMenu.Visible = false; N64SubMenu.Visible = false; SaturnSubMenu.Visible = false; DGBSubMenu.Visible = false; GenesisSubMenu.Visible = false; wonderSwanToolStripMenuItem.Visible = false; AppleSubMenu.Visible = false; C64SubMenu.Visible = false; IntvSubMenu.Visible = false; virtualBoyToolStripMenuItem.Visible = false; sNESToolStripMenuItem.Visible = false; neoGeoPocketToolStripMenuItem.Visible = false; pCFXToolStripMenuItem.Visible = false; switch (system) { case "GEN": GenesisSubMenu.Visible = true; break; case "TI83": TI83SubMenu.Visible = true; break; case "NES": NESSubMenu.Visible = true; break; case "PCE": case "PCECD": case "SGX": PCESubMenu.Visible = true; break; case "SMS": SMSSubMenu.Text = "&SMS"; SMSSubMenu.Visible = true; break; case "SG": SMSSubMenu.Text = "&SG"; SMSSubMenu.Visible = true; break; case "GG": SMSSubMenu.Text = "&GG"; SMSSubMenu.Visible = true; break; case "GB": case "GBC": GBSubMenu.Visible = true; break; case "GBA": GBASubMenu.Visible = true; break; case "A26": AtariSubMenu.Visible = true; break; case "A78": if (Emulator is A7800Hawk) { A7800SubMenu.Visible = true; } break; case "PSX": PSXSubMenu.Visible = true; break; case "SNES": case "SGB": if (Emulator is LibsnesCore) { SNESSubMenu.Text = ((LibsnesCore)Emulator).IsSGB ? "&SGB" : "&SNES"; SNESSubMenu.Visible = true; } else if (Emulator is Snes9x) { sNESToolStripMenuItem.Visible = true; } else if (Emulator is Sameboy) { GBSubMenu.Visible = true; } break; case "Coleco": ColecoSubMenu.Visible = true; break; case "N64": N64SubMenu.Visible = true; break; case "SAT": SaturnSubMenu.Visible = true; break; case "DGB": DGBSubMenu.Visible = true; break; case "WSWAN": wonderSwanToolStripMenuItem.Visible = true; break; case "AppleII": AppleSubMenu.Visible = true; break; case "C64": C64SubMenu.Visible = true; break; case "INTV": IntvSubMenu.Visible = true; break; case "VB": virtualBoyToolStripMenuItem.Visible = true; break; case "NGP": neoGeoPocketToolStripMenuItem.Visible = true; break; case "PCFX": pCFXToolStripMenuItem.Visible = true; break; } } private void InitControls() { var controls = new Controller( new ControllerDefinition { Name = "Emulator Frontend Controls", BoolButtons = Global.Config.HotkeyBindings.Select(x => x.DisplayName).ToList() }); foreach (var b in Global.Config.HotkeyBindings) { controls.BindMulti(b.DisplayName, b.Bindings); } Global.ClientControls = controls; _autofireNullControls = new AutofireController(NullController.Instance.Definition, Emulator); } private void LoadMoviesFromRecent(string path) { if (File.Exists(path)) { var movie = MovieService.Get(path); Global.MovieSession.ReadOnly = true; StartNewMovie(movie, false); } else { Global.Config.RecentMovies.HandleLoadError(path); } } private void LoadRomFromRecent(string rom) { var ioa = OpenAdvancedSerializer.ParseWithLegacy(rom); var args = new LoadRomArgs { OpenAdvanced = ioa }; // if(ioa is this or that) - for more complex behaviour string romPath = ioa.SimplePath; if (!LoadRom(romPath, args)) { Global.Config.RecentRoms.HandleLoadError(romPath, rom); } } private void SetPauseStatusbarIcon() { if (IsTurboSeeking) { PauseStatusButton.Image = Properties.Resources.Lightning; PauseStatusButton.Visible = true; PauseStatusButton.ToolTipText = "Emulator is turbo seeking to frame " + PauseOnFrame.Value + " click to stop seek"; } else if (PauseOnFrame.HasValue) { PauseStatusButton.Image = Properties.Resources.YellowRight; PauseStatusButton.Visible = true; PauseStatusButton.ToolTipText = "Emulator is playing to frame " + PauseOnFrame.Value + " click to stop seek"; } else if (EmulatorPaused) { PauseStatusButton.Image = Properties.Resources.Pause; PauseStatusButton.Visible = true; PauseStatusButton.ToolTipText = "Emulator Paused"; } else { PauseStatusButton.Image = Properties.Resources.Blank; PauseStatusButton.Visible = false; PauseStatusButton.ToolTipText = ""; } } private void SyncThrottle() { // "unthrottled" = throttle was turned off with "Toggle Throttle" hotkey // "turbo" = throttle is off due to the "Turbo" hotkey being held // They are basically the same thing but one is a toggle and the other requires a // hotkey to be held. There is however slightly different behavior in that turbo // skips outputting the audio. There's also a third way which is when no throttle // method is selected, but the clock throttle determines that by itself and // everything appears normal here. var rewind = Global.Rewinder.RewindActive && (Global.ClientControls["Rewind"] || PressRewind); var fastForward = Global.ClientControls["Fast Forward"] || FastForward; var turbo = IsTurboing; int speedPercent = fastForward ? Global.Config.SpeedPercentAlternate : Global.Config.SpeedPercent; if (rewind) { speedPercent = Math.Max(speedPercent * Global.Config.RewindSpeedMultiplier / Global.Rewinder.RewindFrequency, 5); } Global.DisableSecondaryThrottling = _unthrottled || turbo || fastForward || rewind; // realtime throttle is never going to be so exact that using a double here is wrong _throttle.SetCoreFps(Emulator.VsyncRate()); _throttle.signal_paused = EmulatorPaused; _throttle.signal_unthrottle = _unthrottled || turbo; // zero 26-mar-2016 - vsync and vsync throttle here both is odd, but see comments elsewhere about triple buffering _throttle.signal_overrideSecondaryThrottle = (fastForward || rewind) && (Global.Config.SoundThrottle || Global.Config.VSyncThrottle || Global.Config.VSync); _throttle.SetSpeedPercent(speedPercent); } private void SetSpeedPercentAlternate(int value) { Global.Config.SpeedPercentAlternate = value; SyncThrottle(); GlobalWin.OSD.AddMessage("Alternate Speed: " + value + "%"); } private void SetSpeedPercent(int value) { Global.Config.SpeedPercent = value; SyncThrottle(); GlobalWin.OSD.AddMessage("Speed: " + value + "%"); } private void Shutdown() { if (_currAviWriter != null) { _currAviWriter.CloseFile(); _currAviWriter = null; } } private static void CheckMessages() { Application.DoEvents(); if (ActiveForm != null) { ScreenSaver.ResetTimerPeriodically(); } } private void AutohideCursor(bool hide) { if (hide && !_cursorHidden) { if (_blankCursor == null) { var ms = new MemoryStream(Properties.Resources.BlankCursor); _blankCursor = new Cursor(ms); } PresentationPanel.Control.Cursor = _blankCursor; _cursorHidden = true; } else if (!hide && _cursorHidden) { PresentationPanel.Control.Cursor = Cursors.Default; timerMouseIdle.Stop(); timerMouseIdle.Start(); _cursorHidden = false; } } private BitmapBuffer MakeScreenshotImage() { return GlobalWin.DisplayManager.RenderVideoProvider(_currentVideoProvider); } private void SaveSlotSelectedMessage() { int slot = Global.Config.SaveSlot; string emptypart = _stateSlots.HasSlot(slot) ? "" : " (empty)"; string message = $"Slot {slot}{emptypart} selected."; GlobalWin.OSD.AddMessage(message); } private void Render() { if (Global.Config.DispSpeedupFeatures == 0) { return; } var video = _currentVideoProvider; Size currVideoSize = new Size(video.BufferWidth, video.BufferHeight); Size currVirtualSize = new Size(video.VirtualWidth, video.VirtualHeight); bool resizeFramebuffer = false; if (currVideoSize != _lastVideoSize || currVirtualSize != _lastVirtualSize) resizeFramebuffer = true; bool isZero = false; if (currVideoSize.Width == 0 || currVideoSize.Height == 0 || currVirtualSize.Width == 0 || currVirtualSize.Height == 0) isZero = true; //don't resize if the new size is 0 somehow; we'll wait until we have a sensible size if(isZero) resizeFramebuffer = false; if(resizeFramebuffer) { _lastVideoSize = currVideoSize; _lastVirtualSize = currVirtualSize; FrameBufferResized(); } //rendering flakes out egregiously if we have a zero size //can we fix it later not to? if(isZero) GlobalWin.DisplayManager.Blank(); else GlobalWin.DisplayManager.UpdateSource(video); } // sends a simulation of a plain alt key keystroke private void SendPlainAltKey(int lparam) { var m = new Message { WParam = new IntPtr(0xF100), LParam = new IntPtr(lparam), Msg = 0x0112, HWnd = Handle }; base.WndProc(ref m); } // sends an alt+mnemonic combination private void SendAltKeyChar(char c) { typeof(ToolStrip).InvokeMember("ProcessMnemonicInternal", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.InvokeMethod | System.Reflection.BindingFlags.Instance, null, MainformMenu, new object[] { c }); } public static string FormatFilter(params string[] args) { var sb = new StringBuilder(); if (args.Length % 2 != 0) { throw new ArgumentException(); } var num = args.Length / 2; for (int i = 0; i < num; i++) { sb.AppendFormat("{0} ({1})|{1}", args[i * 2], args[(i * 2) + 1]); if (i != num - 1) { sb.Append('|'); } } var str = sb.ToString().Replace("%ARCH%", "*.zip;*.rar;*.7z;*.gz"); str = str.Replace(";", "; "); return str; } public static string RomFilter { get { if (VersionInfo.DeveloperBuild) { return FormatFilter( "Rom Files", "*.nes;*.fds;*.unf;*.sms;*.gg;*.sg;*.pce;*.sgx;*.bin;*.smd;*.rom;*.a26;*.a78;*.lnx;*.m3u;*.cue;*.ccd;*.exe;*.gb;*.gbc;*.gba;*.gen;*.md;*.32x;*.col;*.int;*.smc;*.sfc;*.prg;*.d64;*.g64;*.crt;*.tap;*.sgb;*.xml;*.z64;*.v64;*.n64;*.ws;*.wsc;*.dsk;*.do;*.po;*.vb;*.ngp;*.ngc;*.psf;*.minipsf;*.nsf;%ARCH%", "Music Files", "*.psf;*.minipsf;*.sid;*.nsf", "Disc Images", "*.cue;*.ccd;*.m3u", "NES", "*.nes;*.fds;*.unf;*.nsf;%ARCH%", "Super NES", "*.smc;*.sfc;*.xml;%ARCH%", "Master System", "*.sms;*.gg;*.sg;%ARCH%", "PC Engine", "*.pce;*.sgx;*.cue;*.ccd;%ARCH%", "TI-83", "*.rom;%ARCH%", "Archive Files", "%ARCH%", "Savestate", "*.state", "Atari 2600", "*.a26;*.bin;%ARCH%", "Atari 7800", "*.a78;*.bin;%ARCH%", "Atari Lynx", "*.lnx;%ARCH%", "Genesis", "*.gen;*.smd;*.bin;*.md;*.32x;*.cue;*.ccd;%ARCH%", "Gameboy", "*.gb;*.gbc;*.sgb;%ARCH%", "Gameboy Advance", "*.gba;%ARCH%", "Colecovision", "*.col;%ARCH%", "Intellivision", "*.int;*.bin;*.rom;%ARCH%", "PlayStation", "*.cue;*.ccd;*.m3u", "PSX Executables (experimental)", "*.exe", "PSF Playstation Sound File", "*.psf;*.minipsf", "Commodore 64", "*.prg; *.d64, *.g64; *.crt; *.tap;%ARCH%", "SID Commodore 64 Music File", "*.sid;%ARCH%", "Nintendo 64", "*.z64;*.v64;*.n64", "WonderSwan", "*.ws;*.wsc;%ARCH%", "Apple II", "*.dsk;*.do;*.po;%ARCH%", "Virtual Boy", "*.vb;%ARCH%", "Neo Geo Pocket", "*.ngp;*.ngc;%ARCH%", "All Files", "*.*"); } return FormatFilter( "Rom Files", "*.nes;*.fds;*.unf;*.sms;*.gg;*.sg;*.gb;*.gbc;*.gba;*.pce;*.sgx;*.bin;*.smd;*.gen;*.md;*.32x;*.smc;*.sfc;*.a26;*.a78;*.lnx;*.col;*.int;*.rom;*.m3u;*.cue;*.ccd;*.sgb;*.z64;*.v64;*.n64;*.ws;*.wsc;*.xml;*.dsk;*.do;*.po;*.psf;*.ngp;*.ngc;*.prg;*.d64;*.g64;*.minipsf;*.nsf;%ARCH%", "Disc Images", "*.cue;*.ccd;*.m3u", "NES", "*.nes;*.fds;*.unf;*.nsf;%ARCH%", "Super NES", "*.smc;*.sfc;*.xml;%ARCH%", "PlayStation", "*.cue;*.ccd;*.m3u", "PSF Playstation Sound File", "*.psf;*.minipsf", "Nintendo 64", "*.z64;*.v64;*.n64", "Gameboy", "*.gb;*.gbc;*.sgb;%ARCH%", "Gameboy Advance", "*.gba;%ARCH%", "Master System", "*.sms;*.gg;*.sg;%ARCH%", "PC Engine", "*.pce;*.sgx;*.cue;*.ccd;%ARCH%", "Atari 2600", "*.a26;%ARCH%", "Atari 7800", "*.a78;%ARCH%", "Atari Lynx", "*.lnx;%ARCH%", "Colecovision", "*.col;%ARCH%", "Intellivision", "*.int;*.bin;*.rom;%ARCH%", "TI-83", "*.rom;%ARCH%", "Archive Files", "%ARCH%", "Savestate", "*.state", "Genesis", "*.gen;*.md;*.smd;*.32x;*.bin;*.cue;*.ccd;%ARCH%", "WonderSwan", "*.ws;*.wsc;%ARCH%", "Apple II", "*.dsk;*.do;*.po;%ARCH%", "Virtual Boy", "*.vb;%ARCH%", "Neo Geo Pocket", "*.ngp;*.ngc;%ARCH%", "Commodore 64", "*.prg; *.d64, *.g64; *.crt; *.tap;%ARCH%", "All Files", "*.*"); } } private void OpenRom() { var ofd = new OpenFileDialog { InitialDirectory = PathManager.GetRomsPath(Emulator.SystemId), Filter = RomFilter, RestoreDirectory = false, FilterIndex = _lastOpenRomFilter }; var result = ofd.ShowHawkDialog(); if (result != DialogResult.OK) { return; } var file = new FileInfo(ofd.FileName); Global.Config.LastRomPath = file.DirectoryName; _lastOpenRomFilter = ofd.FilterIndex; var lra = new LoadRomArgs { OpenAdvanced = new OpenAdvanced_OpenRom { Path = file.FullName } }; LoadRom(file.FullName, lra); } private void CoreSyncSettings(object sender, RomLoader.SettingsLoadArgs e) { if (Global.MovieSession.QueuedMovie != null) { if (!string.IsNullOrWhiteSpace(Global.MovieSession.QueuedMovie.SyncSettingsJson)) { e.Settings = ConfigService.LoadWithType(Global.MovieSession.QueuedMovie.SyncSettingsJson); } else { e.Settings = Global.Config.GetCoreSyncSettings(e.Core); // adelikat: only show this nag if the core actually has sync settings, not all cores do if (e.Settings != null && !_supressSyncSettingsWarning) { MessageBox.Show( "No sync settings found, using currently configured settings for this core.", "No sync settings found", MessageBoxButtons.OK, MessageBoxIcon.Warning); } } } else { e.Settings = Global.Config.GetCoreSyncSettings(e.Core); } } private static void CoreSettings(object sender, RomLoader.SettingsLoadArgs e) { e.Settings = Global.Config.GetCoreSettings(e.Core); } /// <summary> /// send core settings to emu, setting reboot flag if needed /// </summary> public void PutCoreSettings(object o) { var settable = new SettingsAdapter(Emulator); if (settable.HasSettings && settable.PutSettings(o)) { FlagNeedsReboot(); } } /// <summary> /// send core sync settings to emu, setting reboot flag if needed /// </summary> public void PutCoreSyncSettings(object o) { var settable = new SettingsAdapter(Emulator); if (Global.MovieSession.Movie.IsActive) { GlobalWin.OSD.AddMessage("Attempt to change sync-relevant settings while recording BLOCKED."); } else if (settable.HasSyncSettings && settable.PutSyncSettings(o)) { FlagNeedsReboot(); } } private void SaveConfig(string path = "") { if (Global.Config.SaveWindowPosition) { if (Global.Config.MainWndx != -32000) // When minimized location is -32000, don't save this into the config file! { Global.Config.MainWndx = Location.X; } if (Global.Config.MainWndy != -32000) { Global.Config.MainWndy = Location.Y; } } else { Global.Config.MainWndx = -1; Global.Config.MainWndy = -1; } if (Global.Config.ShowLogWindow) { LogConsole.SaveConfigSettings(); } if (string.IsNullOrEmpty(path)) { path = PathManager.DefaultIniPath; } ConfigService.Save(path, Global.Config); } private static void ToggleFps() { Global.Config.DisplayFPS ^= true; } private static void ToggleFrameCounter() { Global.Config.DisplayFrameCounter ^= true; } private static void ToggleLagCounter() { Global.Config.DisplayLagCounter ^= true; } private static void ToggleInputDisplay() { Global.Config.DisplayInput ^= true; } private static void ToggleSound() { Global.Config.SoundEnabled ^= true; GlobalWin.Sound.StopSound(); GlobalWin.Sound.StartSound(); } private static void VolumeUp() { Global.Config.SoundVolume += 10; if (Global.Config.SoundVolume > 100) { Global.Config.SoundVolume = 100; } GlobalWin.OSD.AddMessage("Volume " + Global.Config.SoundVolume); } private static void VolumeDown() { Global.Config.SoundVolume -= 10; if (Global.Config.SoundVolume < 0) { Global.Config.SoundVolume = 0; } GlobalWin.OSD.AddMessage("Volume " + Global.Config.SoundVolume); } private void SoftReset() { // is it enough to run this for one frame? maybe.. if (Emulator.ControllerDefinition.BoolButtons.Contains("Reset")) { if (!Global.MovieSession.Movie.IsPlaying || Global.MovieSession.Movie.IsFinished) { Global.ClickyVirtualPadController.Click("Reset"); GlobalWin.OSD.AddMessage("Reset button pressed."); } } } private void HardReset() { // is it enough to run this for one frame? maybe.. if (Emulator.ControllerDefinition.BoolButtons.Contains("Power")) { if (!Global.MovieSession.Movie.IsPlaying || Global.MovieSession.Movie.IsFinished) { Global.ClickyVirtualPadController.Click("Power"); GlobalWin.OSD.AddMessage("Power button pressed."); } } } private void UpdateStatusSlots() { _stateSlots.Update(); Slot0StatusButton.ForeColor = _stateSlots.HasSlot(0) ? Global.Config.SaveSlot == 0 ? SystemColors.HighlightText : SystemColors.WindowText : SystemColors.GrayText; Slot1StatusButton.ForeColor = _stateSlots.HasSlot(1) ? Global.Config.SaveSlot == 1 ? SystemColors.HighlightText : SystemColors.WindowText : SystemColors.GrayText; Slot2StatusButton.ForeColor = _stateSlots.HasSlot(2) ? Global.Config.SaveSlot == 2 ? SystemColors.HighlightText : SystemColors.WindowText : SystemColors.GrayText; Slot3StatusButton.ForeColor = _stateSlots.HasSlot(3) ? Global.Config.SaveSlot == 3 ? SystemColors.HighlightText : SystemColors.WindowText : SystemColors.GrayText; Slot4StatusButton.ForeColor = _stateSlots.HasSlot(4) ? Global.Config.SaveSlot == 4 ? SystemColors.HighlightText : SystemColors.WindowText : SystemColors.GrayText; Slot5StatusButton.ForeColor = _stateSlots.HasSlot(5) ? Global.Config.SaveSlot == 5 ? SystemColors.HighlightText : SystemColors.WindowText : SystemColors.GrayText; Slot6StatusButton.ForeColor = _stateSlots.HasSlot(6) ? Global.Config.SaveSlot == 6 ? SystemColors.HighlightText : SystemColors.WindowText : SystemColors.GrayText; Slot7StatusButton.ForeColor = _stateSlots.HasSlot(7) ? Global.Config.SaveSlot == 7 ? SystemColors.HighlightText : SystemColors.WindowText : SystemColors.GrayText; Slot8StatusButton.ForeColor = _stateSlots.HasSlot(8) ? Global.Config.SaveSlot == 8 ? SystemColors.HighlightText : SystemColors.WindowText : SystemColors.GrayText; Slot9StatusButton.ForeColor = _stateSlots.HasSlot(9) ? Global.Config.SaveSlot == 9 ? SystemColors.HighlightText : SystemColors.WindowText : SystemColors.GrayText; Slot0StatusButton.BackColor = Global.Config.SaveSlot == 0 ? SystemColors.Highlight : SystemColors.Control; Slot1StatusButton.BackColor = Global.Config.SaveSlot == 1 ? SystemColors.Highlight : SystemColors.Control; Slot2StatusButton.BackColor = Global.Config.SaveSlot == 2 ? SystemColors.Highlight : SystemColors.Control; Slot3StatusButton.BackColor = Global.Config.SaveSlot == 3 ? SystemColors.Highlight : SystemColors.Control; Slot4StatusButton.BackColor = Global.Config.SaveSlot == 4 ? SystemColors.Highlight : SystemColors.Control; Slot5StatusButton.BackColor = Global.Config.SaveSlot == 5 ? SystemColors.Highlight : SystemColors.Control; Slot6StatusButton.BackColor = Global.Config.SaveSlot == 6 ? SystemColors.Highlight : SystemColors.Control; Slot7StatusButton.BackColor = Global.Config.SaveSlot == 7 ? SystemColors.Highlight : SystemColors.Control; Slot8StatusButton.BackColor = Global.Config.SaveSlot == 8 ? SystemColors.Highlight : SystemColors.Control; Slot9StatusButton.BackColor = Global.Config.SaveSlot == 9 ? SystemColors.Highlight : SystemColors.Control; SaveSlotsStatusLabel.Visible = Slot0StatusButton.Visible = Slot1StatusButton.Visible = Slot2StatusButton.Visible = Slot3StatusButton.Visible = Slot4StatusButton.Visible = Slot5StatusButton.Visible = Slot6StatusButton.Visible = Slot7StatusButton.Visible = Slot8StatusButton.Visible = Slot9StatusButton.Visible = Emulator.HasSavestates(); } public BitmapBuffer CaptureOSD() { var bb = GlobalWin.DisplayManager.RenderOffscreen(_currentVideoProvider, true); bb.DiscardAlpha(); return bb; } private void IncreaseWindowSize() { switch (Global.Config.TargetZoomFactors[Emulator.SystemId]) { case 1: Global.Config.TargetZoomFactors[Emulator.SystemId] = 2; break; case 2: Global.Config.TargetZoomFactors[Emulator.SystemId] = 3; break; case 3: Global.Config.TargetZoomFactors[Emulator.SystemId] = 4; break; case 4: Global.Config.TargetZoomFactors[Emulator.SystemId] = 5; break; case 5: Global.Config.TargetZoomFactors[Emulator.SystemId] = 10; break; case 10: return; } GlobalWin.OSD.AddMessage("Screensize set to " + Global.Config.TargetZoomFactors[Emulator.SystemId] + "x"); FrameBufferResized(); } private void DecreaseWindowSize() { switch (Global.Config.TargetZoomFactors[Emulator.SystemId]) { case 1: return; case 2: Global.Config.TargetZoomFactors[Emulator.SystemId] = 1; break; case 3: Global.Config.TargetZoomFactors[Emulator.SystemId] = 2; break; case 4: Global.Config.TargetZoomFactors[Emulator.SystemId] = 3; break; case 5: Global.Config.TargetZoomFactors[Emulator.SystemId] = 4; break; case 10: Global.Config.TargetZoomFactors[Emulator.SystemId] = 5; return; } GlobalWin.OSD.AddMessage("Screensize set to " + Global.Config.TargetZoomFactors[Emulator.SystemId] + "x"); FrameBufferResized(); } private void IncreaseSpeed() { if (!Global.Config.ClockThrottle) { GlobalWin.OSD.AddMessage("Unable to change speed, please switch to clock throttle"); return; } var oldp = Global.Config.SpeedPercent; int newp; if (oldp < 3) { newp = 3; } else if (oldp < 6) { newp = 6; } else if (oldp < 12) { newp = 12; } else if (oldp < 25) { newp = 25; } else if (oldp < 50) { newp = 50; } else if (oldp < 75) { newp = 75; } else if (oldp < 100) { newp = 100; } else if (oldp < 150) { newp = 150; } else if (oldp < 200) { newp = 200; } else if (oldp < 300) { newp = 300; } else if (oldp < 400) { newp = 400; } else if (oldp < 800) { newp = 800; } else if (oldp < 1600) { newp = 1600; } else if (oldp < 3200) { newp = 3200; } else { newp = 6400; } SetSpeedPercent(newp); } private void DecreaseSpeed() { if (!Global.Config.ClockThrottle) { GlobalWin.OSD.AddMessage("Unable to change speed, please switch to clock throttle"); return; } var oldp = Global.Config.SpeedPercent; int newp; if (oldp > 3200) { newp = 3200; } else if (oldp > 1600) { newp = 1600; } else if (oldp > 800) { newp = 800; } else if (oldp > 400) { newp = 400; } else if (oldp > 300) { newp = 300; } else if (oldp > 200) { newp = 200; } else if (oldp > 150) { newp = 150; } else if (oldp > 100) { newp = 100; } else if (oldp > 75) { newp = 75; } else if (oldp > 50) { newp = 50; } else if (oldp > 25) { newp = 25; } else if (oldp > 12) { newp = 12; } else if (oldp > 6) { newp = 6; } else if (oldp > 3) { newp = 3; } else { newp = 1; } SetSpeedPercent(newp); } private static void SaveMovie() { if (Global.MovieSession.Movie.IsActive) { Global.MovieSession.Movie.Save(); GlobalWin.OSD.AddMessage(Global.MovieSession.Movie.Filename + " saved."); } } private void HandleToggleLightAndLink() { if (MainStatusBar.Visible) { var hasDriveLight = Emulator.HasDriveLight() && Emulator.AsDriveLight().DriveLightEnabled; if (hasDriveLight) { if (!LedLightStatusLabel.Visible) { LedLightStatusLabel.Visible = true; } LedLightStatusLabel.Image = Emulator.AsDriveLight().DriveLightOn ? _statusBarDiskLightOnImage : _statusBarDiskLightOffImage; } else { if (LedLightStatusLabel.Visible) { LedLightStatusLabel.Visible = false; } } if (Emulator.UsesLinkCable()) { if (!LinkConnectStatusBarButton.Visible) { LinkConnectStatusBarButton.Visible = true; } LinkConnectStatusBarButton.Image = Emulator.AsLinkable().LinkConnected ? _linkCableOn : _linkCableOff; } else { if (LinkConnectStatusBarButton.Visible) { LinkConnectStatusBarButton.Visible = false; } } } } private void UpdateKeyPriorityIcon() { switch (Global.Config.Input_Hotkey_OverrideOptions) { default: case 0: KeyPriorityStatusLabel.Image = Properties.Resources.Both; KeyPriorityStatusLabel.ToolTipText = "Key priority: Allow both hotkeys and controller buttons"; break; case 1: KeyPriorityStatusLabel.Image = Properties.Resources.GameController; KeyPriorityStatusLabel.ToolTipText = "Key priority: Controller buttons will override hotkeys"; break; case 2: KeyPriorityStatusLabel.Image = Properties.Resources.HotKeys; KeyPriorityStatusLabel.ToolTipText = "Key priority: Hotkeys will override controller buttons"; break; } } private static void ToggleModePokeMode() { Global.Config.MoviePlaybackPokeMode ^= true; GlobalWin.OSD.AddMessage(Global.Config.MoviePlaybackPokeMode ? "Movie Poke mode enabled" : "Movie Poke mode disabled"); } private static void ToggleBackgroundInput() { Global.Config.AcceptBackgroundInput ^= true; GlobalWin.OSD.AddMessage(Global.Config.AcceptBackgroundInput ? "Background Input enabled" : "Background Input disabled"); } private static void VsyncMessage() { GlobalWin.OSD.AddMessage( "Display Vsync set to " + (Global.Config.VSync ? "on" : "off")); } private static bool StateErrorAskUser(string title, string message) { var result = MessageBox.Show( message, title, MessageBoxButtons.YesNo, MessageBoxIcon.Question); return result == DialogResult.Yes; } private void FdsInsertDiskMenuAdd(string name, string button, string msg) { FDSControlsMenuItem.DropDownItems.Add(name, null, delegate { if (Emulator.ControllerDefinition.BoolButtons.Contains(button)) { if (!Global.MovieSession.Movie.IsPlaying || Global.MovieSession.Movie.IsFinished) { Global.ClickyVirtualPadController.Click(button); GlobalWin.OSD.AddMessage(msg); } } }); } private const int WmDevicechange = 0x0219; // Alt key hacks protected override void WndProc(ref Message m) { switch (m.Msg) { case WmDevicechange: GamePad.Initialize(); GamePad360.Initialize(); break; } // this is necessary to trap plain alt keypresses so that only our hotkey system gets them if (m.Msg == 0x0112) // WM_SYSCOMMAND { if (m.WParam.ToInt32() == 0xF100) // SC_KEYMENU { return; } } base.WndProc(ref m); } protected override bool ProcessDialogChar(char charCode) { // this is necessary to trap alt+char combinations so that only our hotkey system gets them return (ModifierKeys & Keys.Alt) != 0 || base.ProcessDialogChar(charCode); } private void UpdateCoreStatusBarButton() { if (Emulator.IsNull()) { CoreNameStatusBarButton.Visible = false; return; } CoreNameStatusBarButton.Visible = true; var attributes = Emulator.Attributes(); CoreNameStatusBarButton.Text = Emulator.DisplayName(); CoreNameStatusBarButton.Image = Emulator.Icon(); CoreNameStatusBarButton.ToolTipText = attributes.Ported ? "(ported) " : ""; } private void ToggleKeyPriority() { Global.Config.Input_Hotkey_OverrideOptions++; if (Global.Config.Input_Hotkey_OverrideOptions > 2) { Global.Config.Input_Hotkey_OverrideOptions = 0; } UpdateKeyPriorityIcon(); switch (Global.Config.Input_Hotkey_OverrideOptions) { case 0: GlobalWin.OSD.AddMessage("Key priority set to Both Hotkey and Input"); break; case 1: GlobalWin.OSD.AddMessage("Key priority set to Input over Hotkey"); break; case 2: GlobalWin.OSD.AddMessage("Key priority set to Input"); break; } } #endregion #region Frame Loop private void StepRunLoop_Throttle() { SyncThrottle(); _throttle.signal_frameAdvance = _runloopFrameAdvance; _throttle.signal_continuousFrameAdvancing = _runloopFrameProgress; _throttle.Step(true, -1); } public void FrameAdvance() { PressFrameAdvance = true; StepRunLoop_Core(true); } public void SeekFrameAdvance() { PressFrameAdvance = true; StepRunLoop_Core(true); PressFrameAdvance = false; } public bool IsLagFrame { get { if (Emulator.CanPollInput()) { return Emulator.AsInputPollable().IsLagFrame; } return false; } } private void StepRunLoop_Core(bool force = false) { var runFrame = false; _runloopFrameAdvance = false; var currentTimestamp = Stopwatch.GetTimestamp(); double frameAdvanceTimestampDeltaMs = (double)(currentTimestamp - _frameAdvanceTimestamp) / Stopwatch.Frequency * 1000.0; bool frameProgressTimeElapsed = frameAdvanceTimestampDeltaMs >= Global.Config.FrameProgressDelayMs; if (Global.Config.SkipLagFrame && IsLagFrame && frameProgressTimeElapsed && Emulator.Frame > 0) { runFrame = true; } if (Global.ClientControls["Frame Advance"] || PressFrameAdvance || HoldFrameAdvance) { _runloopFrameAdvance = true; // handle the initial trigger of a frame advance if (_frameAdvanceTimestamp == 0) { PauseEmulator(); runFrame = true; _frameAdvanceTimestamp = currentTimestamp; } else { // handle the timed transition from countdown to FrameProgress if (frameProgressTimeElapsed) { runFrame = true; _runloopFrameProgress = true; UnpauseEmulator(); } } } else { // handle release of frame advance: do we need to deactivate FrameProgress? if (_runloopFrameProgress) { _runloopFrameProgress = false; PauseEmulator(); } _frameAdvanceTimestamp = 0; } if (!EmulatorPaused) { runFrame = true; } bool returnToRecording; bool isRewinding = Rewind(ref runFrame, currentTimestamp, out returnToRecording); float atten = 0; if (runFrame || force) { var isFastForwarding = Global.ClientControls["Fast Forward"] || IsTurboing; var isFastForwardingOrRewinding = isFastForwarding || isRewinding || _unthrottled; if (isFastForwardingOrRewinding != _lastFastForwardingOrRewinding) { InitializeFpsData(); } _lastFastForwardingOrRewinding = isFastForwardingOrRewinding; // client input-related duties GlobalWin.OSD.ClearGUIText(); Global.CheatList.Pulse(); // zero 03-may-2014 - moved this before call to UpdateToolsBefore(), since it seems to clear the state which a lua event.framestart is going to want to alter Global.ClickyVirtualPadController.FrameTick(); Global.LuaAndAdaptor.FrameTick(); if (GlobalWin.Tools.Has<LuaConsole>() && !SuppressLua) { GlobalWin.Tools.LuaConsole.LuaImp.CallFrameBeforeEvent(); } if (IsTurboing) { GlobalWin.Tools.FastUpdateBefore(); } else { GlobalWin.Tools.UpdateToolsBefore(); } _framesSinceLastFpsUpdate++; UpdateFpsDisplay(currentTimestamp, isRewinding, isFastForwarding); CaptureRewind(isRewinding); // Set volume, if enabled if (Global.Config.SoundEnabledNormal) { atten = Global.Config.SoundVolume / 100.0f; if (isFastForwardingOrRewinding) { if (Global.Config.SoundEnabledRWFF) { atten *= Global.Config.SoundVolumeRWFF / 100.0f; } else { atten = 0; } } // Mute if using Frame Advance/Frame Progress if (_runloopFrameAdvance && Global.Config.MuteFrameAdvance) { atten = 0; } } Global.MovieSession.HandleMovieOnFrameLoop(); if (Global.Config.AutosaveSaveRAM) { if (AutoFlushSaveRamIn-- <= 0) { FlushSaveRAM(true); } } // why not skip audio if the user doesnt want sound bool renderSound = (Global.Config.SoundEnabled && !IsTurboing) || (_currAviWriter?.UsesAudio ?? false); if (!renderSound) { atten = 0; } bool render = !_throttle.skipNextFrame || (_currAviWriter?.UsesVideo ?? false); Emulator.FrameAdvance(Global.ControllerOutput, render, renderSound); Global.MovieSession.HandleMovieAfterFrameLoop(); if (returnToRecording) { Global.MovieSession.Movie.SwitchToRecord(); } if (isRewinding && !IsRewindSlave && Global.MovieSession.Movie.IsRecording) { Global.MovieSession.Movie.Truncate(Global.Emulator.Frame); } Global.CheatList.Pulse(); if (!PauseAvi) { AvFrameAdvance(); } if (IsLagFrame && Global.Config.AutofireLagFrames) { Global.AutoFireController.IncrementStarts(); } Global.AutofireStickyXORAdapter.IncrementLoops(IsLagFrame); PressFrameAdvance = false; if (GlobalWin.Tools.Has<LuaConsole>() && !SuppressLua) { GlobalWin.Tools.LuaConsole.LuaImp.CallFrameAfterEvent(); } if (IsTurboing) { GlobalWin.Tools.FastUpdateAfter(); } else { UpdateToolsAfter(SuppressLua); } if (GlobalWin.Tools.IsLoaded<TAStudio>() && GlobalWin.Tools.TAStudio.LastPositionFrame == Emulator.Frame) { if (PauseOnFrame.HasValue && PauseOnFrame.Value <= GlobalWin.Tools.TAStudio.LastPositionFrame) { TasMovieRecord record = (Global.MovieSession.Movie as TasMovie)[Emulator.Frame]; if (!record.Lagged.HasValue && IsSeeking) { // haven't yet greenzoned the frame, hence it's after editing // then we want to pause here. taseditor fasion PauseEmulator(); } } } if (IsSeeking && Emulator.Frame == PauseOnFrame.Value) { PauseEmulator(); PauseOnFrame = null; if (GlobalWin.Tools.IsLoaded<TAStudio>()) { GlobalWin.Tools.TAStudio.StopSeeking(); } } } if (Global.ClientControls["Rewind"] || PressRewind) { UpdateToolsAfter(); } GlobalWin.Sound.UpdateSound(atten); } private void UpdateFpsDisplay(long currentTimestamp, bool isRewinding, bool isFastForwarding) { double elapsedSeconds = (currentTimestamp - _timestampLastFpsUpdate) / (double)Stopwatch.Frequency; if (elapsedSeconds < 1.0 / _fpsUpdatesPerSecond) { return; } if (_lastFps == 0) // Initial calculation { _lastFps = (_framesSinceLastFpsUpdate - 1) / elapsedSeconds; } else { _lastFps = (_lastFps + (_framesSinceLastFpsUpdate * _fpsSmoothing)) / (1.0 + (elapsedSeconds * _fpsSmoothing)); } _framesSinceLastFpsUpdate = 0; _timestampLastFpsUpdate = currentTimestamp; var fpsString = $"{_lastFps:0} fps"; if (isRewinding) { fpsString += IsTurboing || isFastForwarding ? " <<<<" : " <<"; } else if (isFastForwarding) { fpsString += IsTurboing ? " >>>>" : " >>"; } GlobalWin.OSD.FPS = fpsString; // need to refresh window caption in this case if (Global.Config.DispSpeedupFeatures == 0) { SetWindowText(); } } private void InitializeFpsData() { _lastFps = 0; _timestampLastFpsUpdate = Stopwatch.GetTimestamp(); _framesSinceLastFpsUpdate = 0; } #endregion #region AVI Stuff /// <summary> /// start AVI recording, unattended /// </summary> /// <param name="videowritername">match the short name of an <seealso cref="IVideoWriter"/></param> /// <param name="filename">filename to save to</param> private void RecordAv(string videowritername, string filename) { RecordAvBase(videowritername, filename, true); } /// <summary> /// start AV recording, asking user for filename and options /// </summary> private void RecordAv() { RecordAvBase(null, null, false); } /// <summary> /// start AV recording /// </summary> private void RecordAvBase(string videowritername, string filename, bool unattended) { if (_currAviWriter != null) { return; } // select IVideoWriter to use IVideoWriter aw; if (string.IsNullOrEmpty(videowritername) && !string.IsNullOrEmpty(Global.Config.VideoWriter)) { videowritername = Global.Config.VideoWriter; } _dumpaudiosync = Global.Config.VideoWriterAudioSync; if (unattended && !string.IsNullOrEmpty(videowritername)) { aw = VideoWriterInventory.GetVideoWriter(videowritername); } else { aw = VideoWriterChooserForm.DoVideoWriterChoserDlg(VideoWriterInventory.GetAllWriters(), this, out _avwriterResizew, out _avwriterResizeh, out _avwriterpad, ref _dumpaudiosync); } if (aw == null) { GlobalWin.OSD.AddMessage( unattended ? $"Couldn't start video writer \"{videowritername}\"" : "A/V capture canceled."); return; } try { bool usingAvi = aw is AviWriter; // SO GROSS! if (_dumpaudiosync) { aw = new VideoStretcher(aw); } else { aw = new AudioStretcher(aw); } aw.SetMovieParameters(Emulator.VsyncNumerator(), Emulator.VsyncDenominator()); if (_avwriterResizew > 0 && _avwriterResizeh > 0) { aw.SetVideoParameters(_avwriterResizew, _avwriterResizeh); } else { aw.SetVideoParameters(_currentVideoProvider.BufferWidth, _currentVideoProvider.BufferHeight); } aw.SetAudioParameters(44100, 2, 16); // select codec token // do this before save dialog because ffmpeg won't know what extension it wants until it's been configured if (unattended && !string.IsNullOrEmpty(filename)) { aw.SetDefaultVideoCodecToken(); } else { // THIS IS REALLY SLOPPY! // PLEASE REDO ME TO NOT CARE WHICH AVWRITER IS USED! if (usingAvi && !string.IsNullOrEmpty(Global.Config.AVICodecToken)) { aw.SetDefaultVideoCodecToken(); } var token = aw.AcquireVideoCodecToken(this); if (token == null) { GlobalWin.OSD.AddMessage("A/V capture canceled."); aw.Dispose(); return; } aw.SetVideoCodecToken(token); } // select file to save to if (unattended && !string.IsNullOrEmpty(filename)) { aw.OpenFile(filename); } else { string ext = aw.DesiredExtension(); string pathForOpenFile; // handle directories first if (ext == "<directory>") { var fbd = new FolderBrowserEx(); if (fbd.ShowDialog() == DialogResult.Cancel) { aw.Dispose(); return; } pathForOpenFile = fbd.SelectedPath; } else { var sfd = new SaveFileDialog(); if (Global.Game != null) { sfd.FileName = PathManager.FilesystemSafeName(Global.Game) + "." + ext; // dont use Path.ChangeExtension, it might wreck game names with dots in them sfd.InitialDirectory = PathManager.MakeAbsolutePath(Global.Config.PathEntries.AvPathFragment, null); } else { sfd.FileName = "NULL"; sfd.InitialDirectory = PathManager.MakeAbsolutePath(Global.Config.PathEntries.AvPathFragment, null); } sfd.Filter = string.Format("{0} (*.{0})|*.{0}|All Files|*.*", ext); var result = sfd.ShowHawkDialog(); if (result == DialogResult.Cancel) { aw.Dispose(); return; } pathForOpenFile = sfd.FileName; } aw.OpenFile(pathForOpenFile); } // commit the avi writing last, in case there were any errors earlier _currAviWriter = aw; GlobalWin.OSD.AddMessage("A/V capture started"); AVIStatusLabel.Image = Properties.Resources.AVI; AVIStatusLabel.ToolTipText = "A/V capture in progress"; AVIStatusLabel.Visible = true; } catch { GlobalWin.OSD.AddMessage("A/V capture failed!"); aw.Dispose(); throw; } if (_dumpaudiosync) { _currentSoundProvider.SetSyncMode(SyncSoundMode.Sync); } else { if (_currentSoundProvider.CanProvideAsync) { _currentSoundProvider.SetSyncMode(SyncSoundMode.Async); _aviSoundInputAsync = _currentSoundProvider; } else { _currentSoundProvider.SetSyncMode(SyncSoundMode.Sync); _aviSoundInputAsync = new SyncToAsyncProvider(_currentSoundProvider); } } _dumpProxy = new SimpleSyncSoundProvider(); RewireSound(); } private void AbortAv() { if (_currAviWriter == null) { _dumpProxy = null; RewireSound(); return; } _currAviWriter.Dispose(); _currAviWriter = null; GlobalWin.OSD.AddMessage("A/V capture aborted"); AVIStatusLabel.Image = Properties.Resources.Blank; AVIStatusLabel.ToolTipText = ""; AVIStatusLabel.Visible = false; _aviSoundInputAsync = null; _dumpProxy = null; // return to normal sound output RewireSound(); } private void StopAv() { if (_currAviWriter == null) { _dumpProxy = null; RewireSound(); return; } _currAviWriter.CloseFile(); _currAviWriter.Dispose(); _currAviWriter = null; GlobalWin.OSD.AddMessage("A/V capture stopped"); AVIStatusLabel.Image = Properties.Resources.Blank; AVIStatusLabel.ToolTipText = ""; AVIStatusLabel.Visible = false; _aviSoundInputAsync = null; _dumpProxy = null; // return to normal sound output RewireSound(); } private void AvFrameAdvance() { if (_currAviWriter != null) { // TODO ZERO - this code is pretty jacked. we'll want to frugalize buffers better for speedier dumping, and we might want to rely on the GL layer for padding try { // is this the best time to handle this? or deeper inside? if (argParse._currAviWriterFrameList != null) { if (!argParse._currAviWriterFrameList.Contains(Emulator.Frame)) { goto HANDLE_AUTODUMP; } } IVideoProvider output; IDisposable disposableOutput = null; if (_avwriterResizew > 0 && _avwriterResizeh > 0) { BitmapBuffer bbin = null; Bitmap bmpin = null; try { bbin = Global.Config.AVI_CaptureOSD ? CaptureOSD() : new BitmapBuffer(_currentVideoProvider.BufferWidth, _currentVideoProvider.BufferHeight, _currentVideoProvider.GetVideoBuffer()); bbin.DiscardAlpha(); var bmpout = new Bitmap(_avwriterResizew, _avwriterResizeh, PixelFormat.Format32bppArgb); bmpin = bbin.ToSysdrawingBitmap(); using (var g = Graphics.FromImage(bmpout)) { if (_avwriterpad) { g.Clear(Color.FromArgb(_currentVideoProvider.BackgroundColor)); g.DrawImageUnscaled(bmpin, (bmpout.Width - bmpin.Width) / 2, (bmpout.Height - bmpin.Height) / 2); } else { g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.NearestNeighbor; g.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.Half; g.DrawImage(bmpin, new Rectangle(0, 0, bmpout.Width, bmpout.Height)); } } output = new BmpVideoProvider(bmpout, _currentVideoProvider.VsyncNumerator, _currentVideoProvider.VsyncDenominator); disposableOutput = (IDisposable)output; } finally { bbin?.Dispose(); bmpin?.Dispose(); } } else { if (Global.Config.AVI_CaptureOSD) { output = new BitmapBufferVideoProvider(CaptureOSD()); disposableOutput = (IDisposable)output; } else { output = _currentVideoProvider; } } _currAviWriter.SetFrame(Emulator.Frame); short[] samp; int nsamp; if (_dumpaudiosync) { ((VideoStretcher)_currAviWriter).DumpAV(output, _currentSoundProvider, out samp, out nsamp); } else { ((AudioStretcher)_currAviWriter).DumpAV(output, _aviSoundInputAsync, out samp, out nsamp); } disposableOutput?.Dispose(); _dumpProxy.PutSamples(samp, nsamp); } catch (Exception e) { MessageBox.Show("Video dumping died:\n\n" + e); AbortAv(); } HANDLE_AUTODUMP: if (argParse._autoDumpLength > 0) { argParse._autoDumpLength--; if (argParse._autoDumpLength == 0) // finish { StopAv(); if (argParse._autoCloseOnDump) { _exit = true; } } } } } private int? LoadArhiveChooser(HawkFile file) { var ac = new ArchiveChooser(file); if (ac.ShowDialog(this) == DialogResult.OK) { return ac.SelectedMemberIndex; } return null; } #endregion #region Scheduled for refactor private void ShowMessageCoreComm(string message) { MessageBox.Show(this, message, "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning); } private void ShowLoadError(object sender, RomLoader.RomErrorArgs e) { if (e.Type == RomLoader.LoadErrorType.MissingFirmware) { var result = MessageBox.Show( "You are missing the needed firmware files to load this Rom\n\nWould you like to open the firmware manager now and configure your firmwares?", e.Message, MessageBoxButtons.YesNo, MessageBoxIcon.Error); if (result == DialogResult.Yes) { FirmwaresMenuItem_Click(null, e); if (e.Retry) { // Retry loading the ROM here. This leads to recursion, as the original call to LoadRom has not exited yet, // but unless the user tries and fails to set his firmware a lot of times, nothing should happen. // Refer to how RomLoader implemented its LoadRom method for a potential fix on this. LoadRom(e.RomPath, _currentLoadRomArgs); } } } else { string title = "load error"; if (e.AttemptedCoreLoad != null) { title = e.AttemptedCoreLoad + " load error"; } MessageBox.Show(this, e.Message, title, MessageBoxButtons.OK, MessageBoxIcon.Error); } } private void NotifyCoreComm(string message) { GlobalWin.OSD.AddMessage(message); } private string ChoosePlatformForRom(RomGame rom) { var platformChooser = new PlatformChooser { RomGame = rom }; platformChooser.ShowDialog(); return platformChooser.PlatformChoice; } public class LoadRomArgs { public bool? Deterministic { get; set; } public IOpenAdvanced OpenAdvanced { get; set; } } private LoadRomArgs _currentLoadRomArgs; // Still needs a good bit of refactoring public bool LoadRom(string path, LoadRomArgs args) { path = HawkFile.Util_ResolveLink(path); // default args if (args == null) { args = new LoadRomArgs(); } // if this is the first call to LoadRom (they will come in recursively) then stash the args bool firstCall = false; if (_currentLoadRomArgs == null) { firstCall = true; _currentLoadRomArgs = args; } else { args = _currentLoadRomArgs; } try { // If deterministic emulation is passed in, respect that value regardless, else determine a good value (currently that simply means movies require deterministic emulaton) bool deterministic = args.Deterministic ?? Global.MovieSession.QueuedMovie != null; if (!GlobalWin.Tools.AskSave()) { return false; } bool asLibretro = args.OpenAdvanced is OpenAdvanced_Libretro || args.OpenAdvanced is OpenAdvanced_LibretroNoGame; var loader = new RomLoader { ChooseArchive = LoadArhiveChooser, ChoosePlatform = ChoosePlatformForRom, Deterministic = deterministic, MessageCallback = GlobalWin.OSD.AddMessage, AsLibretro = asLibretro }; Global.FirmwareManager.RecentlyServed.Clear(); loader.OnLoadError += ShowLoadError; loader.OnLoadSettings += CoreSettings; loader.OnLoadSyncSettings += CoreSyncSettings; // this also happens in CloseGame(). But it needs to happen here since if we're restarting with the same core, // any settings changes that we made need to make it back to config before we try to instantiate that core with // the new settings objects CommitCoreSettingsToConfig(); // adelikat: I Think by reordering things, this isn't necessary anymore CloseGame(); var nextComm = CreateCoreComm(); // we need to inform LoadRom which Libretro core to use... IOpenAdvanced ioa = args.OpenAdvanced; if (ioa is IOpenAdvancedLibretro) { var ioaretro = (IOpenAdvancedLibretro)ioa; // prepare a core specification // if it wasnt already specified, use the current default if (ioaretro.CorePath == null) { ioaretro.CorePath = Global.Config.LibretroCore; } nextComm.LaunchLibretroCore = ioaretro.CorePath; if (nextComm.LaunchLibretroCore == null) { throw new InvalidOperationException("Can't load a file via Libretro until a core is specified"); } } if (ioa is OpenAdvanced_OpenRom) { var ioa_openrom = (OpenAdvanced_OpenRom)ioa; path = ioa_openrom.Path; } CoreFileProvider.SyncCoreCommInputSignals(nextComm); var result = loader.LoadRom(path, nextComm); // we need to replace the path in the OpenAdvanced with the canonical one the user chose. // It can't be done until loder.LoadRom happens (for CanonicalFullPath) // i'm not sure this needs to be more abstractly engineered yet until we have more OpenAdvanced examples if (ioa is OpenAdvanced_Libretro) { var oaretro = ioa as OpenAdvanced_Libretro; oaretro.token.Path = loader.CanonicalFullPath; } if (ioa is OpenAdvanced_OpenRom) { ((OpenAdvanced_OpenRom)ioa).Path = loader.CanonicalFullPath; } if (result) { string loaderName = "*" + OpenAdvancedSerializer.Serialize(ioa); Emulator = loader.LoadedEmulator; Global.Game = loader.Game; CoreFileProvider.SyncCoreCommInputSignals(nextComm); InputManager.SyncControls(); if (Emulator is TI83 && Global.Config.TI83autoloadKeyPad) { GlobalWin.Tools.Load<TI83KeyPad>(); } if (loader.LoadedEmulator is NES) { var nes = (NES)loader.LoadedEmulator; if (!string.IsNullOrWhiteSpace(nes.GameName)) { Global.Game.Name = nes.GameName; } Global.Game.Status = nes.RomStatus; } else if (loader.LoadedEmulator is QuickNES) { var qns = (QuickNES)loader.LoadedEmulator; if (!string.IsNullOrWhiteSpace(qns.BootGodName)) { Global.Game.Name = qns.BootGodName; } if (qns.BootGodStatus.HasValue) { Global.Game.Status = qns.BootGodStatus.Value; } } if (Emulator.CoreComm.RomStatusDetails == null && loader.Rom != null) { Emulator.CoreComm.RomStatusDetails = $"{loader.Game.Name}\r\nSHA1:{loader.Rom.RomData.HashSHA1()}\r\nMD5:{loader.Rom.RomData.HashMD5()}\r\n"; } if (Emulator.HasBoardInfo()) { Console.WriteLine("Core reported BoardID: \"{0}\"", Emulator.AsBoardInfo().BoardName); } // restarts the lua console if a different rom is loaded. // im not really a fan of how this is done.. if (Global.Config.RecentRoms.Empty || Global.Config.RecentRoms.MostRecent != loaderName) { GlobalWin.Tools.Restart<LuaConsole>(); } Global.Config.RecentRoms.Add(loaderName); JumpLists.AddRecentItem(loaderName, ioa.DisplayName); // Don't load Save Ram if a movie is being loaded if (!Global.MovieSession.MovieIsQueued) { if (File.Exists(PathManager.SaveRamPath(loader.Game))) { LoadSaveRam(); } else if (Global.Config.AutosaveSaveRAM && File.Exists(PathManager.AutoSaveRamPath(loader.Game))) { GlobalWin.OSD.AddMessage("AutoSaveRAM found, but SaveRAM was not saved"); } } GlobalWin.Tools.Restart(); if (Global.Config.LoadCheatFileByGame) { Global.CheatList.SetDefaultFileName(ToolManager.GenerateDefaultCheatFilename()); if (Global.CheatList.AttemptToLoadCheatFile()) { GlobalWin.OSD.AddMessage("Cheats file loaded"); } else if (Global.CheatList.Any()) { Global.CheatList.Clear(); } } SetWindowText(); _currentlyOpenRomPoopForAdvancedLoaderPleaseRefactorMe = loaderName; CurrentlyOpenRom = loaderName.Replace("*OpenRom*", ""); // POOP HandlePlatformMenus(); _stateSlots.Clear(); UpdateCoreStatusBarButton(); UpdateDumpIcon(); SetMainformMovieInfo(); CurrentlyOpenRomArgs = args; GlobalWin.DisplayManager.Blank(); Global.Rewinder.Initialize(); Global.StickyXORAdapter.ClearStickies(); Global.StickyXORAdapter.ClearStickyFloats(); Global.AutofireStickyXORAdapter.ClearStickies(); RewireSound(); ToolFormBase.UpdateCheatRelatedTools(null, null); if (Global.Config.AutoLoadLastSaveSlot && _stateSlots.HasSlot(Global.Config.SaveSlot)) { LoadQuickSave("QuickSave" + Global.Config.SaveSlot); } if (Global.FirmwareManager.RecentlyServed.Count > 0) { Console.WriteLine("Active Firmwares:"); foreach (var f in Global.FirmwareManager.RecentlyServed) { Console.WriteLine(" {0} : {1}", f.FirmwareId, f.Hash); } } ClientApi.OnRomLoaded(); return true; } else { // This shows up if there's a problem // TODO: put all these in a single method or something // The ROM has been loaded by a recursive invocation of the LoadROM method. if (!(Emulator is NullEmulator)) { ClientApi.OnRomLoaded(); return true; } HandlePlatformMenus(); _stateSlots.Clear(); UpdateStatusSlots(); UpdateCoreStatusBarButton(); UpdateDumpIcon(); SetMainformMovieInfo(); SetWindowText(); return false; } } finally { if (firstCall) { _currentLoadRomArgs = null; } } } private string _currentlyOpenRomPoopForAdvancedLoaderPleaseRefactorMe = ""; private void CommitCoreSettingsToConfig() { // save settings object var t = Emulator.GetType(); var settable = new SettingsAdapter(Emulator); if (settable.HasSettings) { Global.Config.PutCoreSettings(settable.GetSettings(), t); } if (settable.HasSyncSettings && !Global.MovieSession.Movie.IsActive) { // don't trample config with loaded-from-movie settings Global.Config.PutCoreSyncSettings(settable.GetSyncSettings(), t); } } // whats the difference between these two methods?? // its very tricky. rename to be more clear or combine them. // This gets called whenever a core related thing is changed. // Like reboot core. private void CloseGame(bool clearSram = false) { GameIsClosing = true; if (clearSram) { var path = PathManager.SaveRamPath(Global.Game); if (File.Exists(path)) { File.Delete(path); GlobalWin.OSD.AddMessage("SRAM cleared."); } } else if (Emulator.HasSaveRam() && Emulator.AsSaveRam().SaveRamModified) { FlushSaveRAM(); } StopAv(); CommitCoreSettingsToConfig(); if (Global.MovieSession.Movie.IsActive) // Note: this must be called after CommitCoreSettingsToConfig() { StopMovie(); } Global.Rewinder.Uninitialize(); if (GlobalWin.Tools.IsLoaded<TraceLogger>()) { GlobalWin.Tools.Get<TraceLogger>().Restart(); } Global.CheatList.SaveOnClose(); Emulator.Dispose(); var coreComm = CreateCoreComm(); CoreFileProvider.SyncCoreCommInputSignals(coreComm); Emulator = new NullEmulator(coreComm, Global.Config.GetCoreSettings<NullEmulator>()); Global.ActiveController = new Controller(NullController.Instance.Definition); Global.AutoFireController = _autofireNullControls; RewireSound(); RebootStatusBarIcon.Visible = false; GameIsClosing = false; } public bool GameIsClosing { get; private set; } // Lets tools make better decisions when being called by CloseGame public void CloseRom(bool clearSram = false) { // This gets called after Close Game gets called. // Tested with NESHawk and SMB3 (U) if (GlobalWin.Tools.AskSave()) { CloseGame(clearSram); var coreComm = CreateCoreComm(); CoreFileProvider.SyncCoreCommInputSignals(coreComm); Emulator = new NullEmulator(coreComm, Global.Config.GetCoreSettings<NullEmulator>()); Global.Game = GameInfo.NullInstance; GlobalWin.Tools.Restart(); RewireSound(); Text = "BizHawk" + (VersionInfo.DeveloperBuild ? " (interim) " : ""); HandlePlatformMenus(); _stateSlots.Clear(); UpdateDumpIcon(); UpdateCoreStatusBarButton(); ClearHolds(); PauseOnFrame = null; ToolFormBase.UpdateCheatRelatedTools(null, null); UpdateStatusSlots(); CurrentlyOpenRom = null; CurrentlyOpenRomArgs = null; } } private static void ShowConversionError(string errorMsg) { MessageBox.Show(errorMsg, "Conversion error", MessageBoxButtons.OK, MessageBoxIcon.Error); } private static void ProcessMovieImport(string fn) { MovieImport.ProcessMovieImport(fn, ShowConversionError, GlobalWin.OSD.AddMessage); } public void EnableRewind(bool enabled) { Global.Rewinder.SuspendRewind = !enabled; GlobalWin.OSD.AddMessage("Rewind " + (enabled ? "enabled" : "suspended")); } public void ClearRewindData() { Global.Rewinder.Clear(); } #endregion #region Tool Control API // TODO: move me public IControlMainform Master { get; private set; } private bool IsSlave => Master != null; private bool IsSavestateSlave => IsSlave && Master.WantsToControlSavestates; private bool IsRewindSlave => IsSlave && Master.WantsToControlRewind; public void RelinquishControl(IControlMainform master) { Master = master; } public void TakeBackControl() { Master = null; } private int SlotToInt(string slot) { return int.Parse(slot.Substring(slot.Length - 1, 1)); } public void LoadState(string path, string userFriendlyStateName, bool fromLua = false, bool supressOSD = false) // Move to client.common { if (!Emulator.HasSavestates()) { return; } if (IsSavestateSlave) { Master.LoadState(); return; } // If from lua, disable counting rerecords bool wasCountingRerecords = Global.MovieSession.Movie.IsCountingRerecords; if (fromLua) { Global.MovieSession.Movie.IsCountingRerecords = false; } if (SavestateManager.LoadStateFile(path, userFriendlyStateName)) { GlobalWin.OSD.ClearGUIText(); ClientApi.OnStateLoaded(this, userFriendlyStateName); if (GlobalWin.Tools.Has<LuaConsole>()) { GlobalWin.Tools.LuaConsole.LuaImp.CallLoadStateEvent(userFriendlyStateName); } SetMainformMovieInfo(); GlobalWin.Tools.UpdateToolsBefore(fromLua); UpdateToolsAfter(fromLua); UpdateToolsLoadstate(); Global.AutoFireController.ClearStarts(); if (!IsRewindSlave && Global.MovieSession.Movie.IsActive) { ClearRewindData(); } if (!supressOSD) { GlobalWin.OSD.AddMessage("Loaded state: " + userFriendlyStateName); } } else { GlobalWin.OSD.AddMessage("Loadstate error!"); } Global.MovieSession.Movie.IsCountingRerecords = wasCountingRerecords; } public void LoadQuickSave(string quickSlotName, bool fromLua = false, bool supressOSD = false) { if (!Emulator.HasSavestates()) { return; } bool handled; ClientApi.OnBeforeQuickLoad(this, quickSlotName, out handled); if (handled) { return; } if (IsSavestateSlave) { Master.LoadQuickSave(SlotToInt(quickSlotName)); return; } var path = PathManager.SaveStatePrefix(Global.Game) + "." + quickSlotName + ".State"; if (!File.Exists(path)) { GlobalWin.OSD.AddMessage("Unable to load " + quickSlotName + ".State"); return; } LoadState(path, quickSlotName, fromLua, supressOSD); } public void SaveState(string path, string userFriendlyStateName, bool fromLua) { if (!Emulator.HasSavestates()) { return; } if (IsSavestateSlave) { Master.SaveState(); return; } try { SavestateManager.SaveStateFile(path, userFriendlyStateName); ClientApi.OnStateSaved(this, userFriendlyStateName); GlobalWin.OSD.AddMessage("Saved state: " + userFriendlyStateName); } catch (IOException) { GlobalWin.OSD.AddMessage("Unable to save state " + path); } if (!fromLua) { UpdateStatusSlots(); } } // TODO: should backup logic be stuffed in into Client.Common.SaveStateManager? public void SaveQuickSave(string quickSlotName) { if (!Emulator.HasSavestates()) { return; } bool handled; ClientApi.OnBeforeQuickSave(this, quickSlotName, out handled); if (handled) { return; } if (IsSavestateSlave) { Master.SaveQuickSave(SlotToInt(quickSlotName)); return; } var path = PathManager.SaveStatePrefix(Global.Game) + "." + quickSlotName + ".State"; var file = new FileInfo(path); if (file.Directory != null && !file.Directory.Exists) { file.Directory.Create(); } // Make backup first if (Global.Config.BackupSavestates) { Util.TryMoveBackupFile(path, path + ".bak"); } SaveState(path, quickSlotName, false); if (GlobalWin.Tools.Has<LuaConsole>()) { GlobalWin.Tools.LuaConsole.LuaImp.CallSaveStateEvent(quickSlotName); } } private void SaveStateAs() { if (!Emulator.HasSavestates()) { return; } // allow named state export for tastudio, since it's safe, unlike loading one // todo: make it not save laglog in that case if (GlobalWin.Tools.IsLoaded<TAStudio>()) { GlobalWin.Tools.TAStudio.NamedStatePending = true; } if (IsSavestateSlave) { Master.SaveStateAs(); return; } var path = PathManager.GetSaveStatePath(Global.Game); var file = new FileInfo(path); if (file.Directory != null && !file.Directory.Exists) { file.Directory.Create(); } var sfd = new SaveFileDialog { AddExtension = true, DefaultExt = "State", Filter = "Save States (*.State)|*.State|All Files|*.*", InitialDirectory = path, FileName = PathManager.SaveStatePrefix(Global.Game) + "." + "QuickSave0.State" }; var result = sfd.ShowHawkDialog(); if (result == DialogResult.OK) { SaveState(sfd.FileName, sfd.FileName, false); } if (GlobalWin.Tools.IsLoaded<TAStudio>()) { GlobalWin.Tools.TAStudio.NamedStatePending = false; } } private void LoadStateAs() { if (!Emulator.HasSavestates()) { return; } if (IsSavestateSlave) { Master.LoadStateAs(); return; } var ofd = new OpenFileDialog { InitialDirectory = PathManager.GetSaveStatePath(Global.Game), Filter = "Save States (*.State)|*.State|All Files|*.*", RestoreDirectory = true }; var result = ofd.ShowHawkDialog(); if (result != DialogResult.OK) { return; } if (!File.Exists(ofd.FileName)) { return; } LoadState(ofd.FileName, Path.GetFileName(ofd.FileName)); } private void SelectSlot(int slot) { if (Emulator.HasSavestates()) { if (IsSavestateSlave) { Master.SelectSlot(slot); return; } Global.Config.SaveSlot = slot; SaveSlotSelectedMessage(); UpdateStatusSlots(); } } private void PreviousSlot() { if (Emulator.HasSavestates()) { if (IsSavestateSlave) { Master.PreviousSlot(); return; } if (Global.Config.SaveSlot == 0) { Global.Config.SaveSlot = 9; // Wrap to end of slot list } else if (Global.Config.SaveSlot > 9) { Global.Config.SaveSlot = 9; // Meh, just in case } else { Global.Config.SaveSlot--; } SaveSlotSelectedMessage(); UpdateStatusSlots(); } } private void NextSlot() { if (Emulator.HasSavestates()) { if (IsSavestateSlave) { Master.NextSlot(); return; } if (Global.Config.SaveSlot >= 9) { Global.Config.SaveSlot = 0; // Wrap to beginning of slot list } else if (Global.Config.SaveSlot < 0) { Global.Config.SaveSlot = 0; // Meh, just in case } else { Global.Config.SaveSlot++; } SaveSlotSelectedMessage(); UpdateStatusSlots(); } } private void ToggleReadOnly() { if (IsSlave && Master.WantsToControlReadOnly) { Master.ToggleReadOnly(); } else { if (Global.MovieSession.Movie.IsActive) { Global.MovieSession.ReadOnly ^= true; GlobalWin.OSD.AddMessage(Global.MovieSession.ReadOnly ? "Movie read-only mode" : "Movie read+write mode"); } else { GlobalWin.OSD.AddMessage("No movie active"); } } } private void StopMovie(bool saveChanges = true) { if (IsSlave && Master.WantsToControlStopMovie) { Master.StopMovie(!saveChanges); } else { Global.MovieSession.StopMovie(saveChanges); SetMainformMovieInfo(); UpdateStatusSlots(); } } private void GBAcoresettingsToolStripMenuItem1_Click(object sender, EventArgs e) { GenericCoreConfig.DoDialog(this, "Gameboy Advance Settings"); } private void CaptureRewind(bool suppressCaptureRewind) { if (IsRewindSlave) { Master.CaptureRewind(); } else if (!suppressCaptureRewind && Global.Rewinder.RewindActive) { Global.Rewinder.Capture(); } } private void preferencesToolStripMenuItem1_Click(object sender, EventArgs e) { GenericCoreConfig.DoDialog(this, "VirtualBoy Settings"); } private void preferencesToolStripMenuItem_Click(object sender, EventArgs e) { GenericCoreConfig.DoDialog(this, "Snes9x Settings"); } private void preferencesToolStripMenuItem2_Click(object sender, EventArgs e) { GenericCoreConfig.DoDialog(this, "NeoPop Settings"); } private void preferencesToolStripMenuItem3_Click(object sender, EventArgs e) { GenericCoreConfig.DoDialog(this, "PC-FX Settings"); } private bool Rewind(ref bool runFrame, long currentTimestamp, out bool returnToRecording) { var isRewinding = false; returnToRecording = false; if (IsRewindSlave) { if (Global.ClientControls["Rewind"] || PressRewind) { if (_frameRewindTimestamp == 0) { isRewinding = true; _frameRewindTimestamp = currentTimestamp; _frameRewindWasPaused = EmulatorPaused; } else { double timestampDeltaMs = (double)(currentTimestamp - _frameRewindTimestamp) / Stopwatch.Frequency * 1000.0; isRewinding = timestampDeltaMs >= Global.Config.FrameProgressDelayMs; // clear this flag once we get out of the progress stage if (isRewinding) { _frameRewindWasPaused = false; } // if we're freely running, there's no need for reverse frame progress semantics (that may be debateable though) if (!EmulatorPaused) { isRewinding = true; } if (_frameRewindWasPaused) { if (IsSeeking) { isRewinding = false; } } } if (isRewinding) { runFrame = true; // TODO: the master should be deciding this! Master.Rewind(); } } else { _frameRewindTimestamp = 0; } return isRewinding; } if (Global.Rewinder.RewindActive && (Global.ClientControls["Rewind"] || PressRewind)) { if (EmulatorPaused) { if (_frameRewindTimestamp == 0) { isRewinding = true; _frameRewindTimestamp = currentTimestamp; } else { double timestampDeltaMs = (double)(currentTimestamp - _frameRewindTimestamp) / Stopwatch.Frequency * 1000.0; isRewinding = timestampDeltaMs >= Global.Config.FrameProgressDelayMs; } } else { isRewinding = true; } if (isRewinding) { runFrame = Global.Rewinder.Rewind(1); if (runFrame && Global.MovieSession.Movie.IsRecording) { Global.MovieSession.Movie.SwitchToPlay(); returnToRecording = true; } } } else { _frameRewindTimestamp = 0; } return isRewinding; } #endregion } }
26.464551
318
0.666871
[ "MIT" ]
CognitiaAI/StreetFighterRL
emulator/Bizhawk/BizHawk-master/BizHawk.Client.EmuHawk/MainForm.cs
117,582
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. using Microsoft.MixedReality.Toolkit.Utilities; using UnityEditor; namespace Microsoft.MixedReality.Toolkit.Input.Editor { [CustomEditor(typeof(ControllerPoseSynchronizer))] public class ControllerPoseSynchronizerInspector : UnityEditor.Editor { private const string SynchronizationSettingsKey = "MRTK_Inspector_SynchronizationSettingsFoldout"; private static readonly string[] HandednessLabels = { "Left", "Right" }; private static bool synchronizationSettingsFoldout = true; private SerializedProperty handedness; private SerializedProperty useSourcePoseData; private SerializedProperty poseAction; protected bool DrawHandednessProperty = true; protected virtual void OnEnable() { synchronizationSettingsFoldout = SessionState.GetBool(SynchronizationSettingsKey, synchronizationSettingsFoldout); handedness = serializedObject.FindProperty("handedness"); useSourcePoseData = serializedObject.FindProperty("useSourcePoseData"); poseAction = serializedObject.FindProperty("poseAction"); } public override void OnInspectorGUI() { serializedObject.Update(); EditorGUILayout.Space(); EditorGUI.BeginChangeCheck(); synchronizationSettingsFoldout = EditorGUILayout.Foldout(synchronizationSettingsFoldout, "Synchronization Settings", true); if (EditorGUI.EndChangeCheck()) { SessionState.SetBool(SynchronizationSettingsKey, synchronizationSettingsFoldout); } if (!synchronizationSettingsFoldout) { return; } EditorGUI.indentLevel++; if (DrawHandednessProperty) { var currentHandedness = (Handedness)handedness.enumValueIndex; var handIndex = currentHandedness == Handedness.Right ? 1 : 0; EditorGUI.BeginChangeCheck(); var newHandednessIndex = EditorGUILayout.Popup(handedness.displayName, handIndex, HandednessLabels); if (EditorGUI.EndChangeCheck()) { currentHandedness = newHandednessIndex == 0 ? Handedness.Left : Handedness.Right; handedness.enumValueIndex = (int)currentHandedness; } } EditorGUILayout.PropertyField(useSourcePoseData); if (!useSourcePoseData.boolValue) { EditorGUILayout.PropertyField(poseAction); } EditorGUI.indentLevel--; serializedObject.ApplyModifiedProperties(); } } }
39.22973
136
0.645195
[ "MIT" ]
AzureMentor/MapsSDK-Unity
SampleProject/Assets/MixedRealityToolkit.SDK/Inspectors/Input/Handlers/ControllerPoseSynchronizerInspector.cs
2,907
C#
using MeatExpress.Models; using MeatExpress.Services; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; using Xamarin.Forms.Xaml; namespace MeatExpress.Views { [XamlCompilation(XamlCompilationOptions.Compile)] public partial class MenuView : ContentPage { private ObservableCollection<CarnePronta> MeatExpresss; public MenuView() { InitializeComponent(); } protected override void OnAppearing() { MeatExpresss = GetTodosMeatExpresss(); carneListView.ItemsSource = MeatExpresss; base.OnAppearing(); } public ObservableCollection<CarnePronta> GetTodosMeatExpresss() { CarneDAO dao = new CarneDAO(); return new ObservableCollection<CarnePronta>(dao.GetTodos()); } private void OncarneSelecionado(object sender, SelectedItemChangedEventArgs e) { Application.Current.MainPage = new NavigationPage(new PagamentoPage()); } private void OncarneProcurado(object sender, TextChangedEventArgs e) { string texto = carneSearchBar.Text; carneListView.ItemsSource = MeatExpresss.Where( x => x.Descricao.ToLowerInvariant().Contains(texto.ToLowerInvariant()) ); } private void OnHelp(object sender, EventArgs e) { Application.Current.MainPage = new NavigationPage(new HelpPage()); } } }
27.627119
86
0.646626
[ "MIT" ]
Goleyzinho/Meat-Express-Xamarin
MeatExpress/ObjetosEmprestado/ObjetosEmprestado/Views/MenuView.xaml.cs
1,632
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using System.Runtime.InteropServices; using System.Windows.Forms.Layout; using static Interop; namespace System.Windows.Forms { public sealed partial class Application { /// <summary> /// This class embodies our parking window, which we create when the /// first message loop is pushed onto the thread. /// </summary> internal sealed class ParkingWindow : ContainerControl, IArrangedElement { // In .NET 2.0 we now aggressively tear down the parking window // when the last control has been removed off of it. private const int WM_CHECKDESTROY = Interop.WindowMessages.WM_USER + 0x01; private int _childCount = 0; public ParkingWindow() { SetExtendedState(ExtendedStates.InterestedInUserPreferenceChanged, false); SetState(States.TopLevel, true); Text = "WindowsFormsParkingWindow"; Visible = false; DpiHelper.FirstParkingWindowCreated = true; } protected override CreateParams CreateParams { get { CreateParams cp = base.CreateParams; // Message only windows are cheaper and have fewer issues than // full blown invisible windows. cp.Parent = User32.HWND_MESSAGE; return cp; } } internal override void AddReflectChild() { if (_childCount < 0) { Debug.Fail("How did parkingwindow childcount go negative???"); _childCount = 0; } _childCount++; } internal override void RemoveReflectChild() { if (--_childCount < 0) { Debug.Fail("How did parkingwindow childcount go negative???"); _childCount = 0; } if (_childCount != 0 || !IsHandleCreated) { return; } // Check to see if we are running on the thread that owns the parkingwindow. // If so, we can destroy immediately. // // This is important for scenarios where apps leak controls until after the // messagepump is gone and then decide to clean them up. We should clean // up the parkingwindow in this case and a postmessage won't do it. uint id = User32.GetWindowThreadProcessId(this, out _); ThreadContext context = ThreadContext.FromId(id); // We only do this if the ThreadContext tells us that we are currently // handling a window message. if (context == null || !ReferenceEquals(context, ThreadContext.FromCurrent())) { UnsafeNativeMethods.PostMessage(new HandleRef(this, HandleInternal), WM_CHECKDESTROY, IntPtr.Zero, IntPtr.Zero); } else { CheckDestroy(); } } private void CheckDestroy() { if (_childCount != 0) return; IntPtr hwndChild = UnsafeNativeMethods.GetWindow(new HandleRef(this, Handle), NativeMethods.GW_CHILD); if (hwndChild == IntPtr.Zero) { DestroyHandle(); } } public void Destroy() { DestroyHandle(); } /// <summary> /// "Parks" the given HWND to a temporary HWND. This allows WS_CHILD windows to /// be parked. /// </summary> internal void ParkHandle(HandleRef handle) { if (!IsHandleCreated) { CreateHandle(); } UnsafeNativeMethods.SetParent(handle, new HandleRef(this, Handle)); } /// <summary> /// "Unparks" the given HWND to a temporary HWND. This allows WS_CHILD windows to /// be parked. /// </summary> internal void UnparkHandle(HandleRef handle) { if (!IsHandleCreated) return; Debug.Assert( UnsafeNativeMethods.GetParent(handle) != Handle, "Always set the handle's parent to someone else before calling UnparkHandle"); // If there are no child windows in this handle any longer, destroy the parking window. CheckDestroy(); } // Do nothing on layout to reduce the calls into the LayoutEngine while debugging. protected override void OnLayout(LayoutEventArgs levent) { } void IArrangedElement.PerformLayout(IArrangedElement affectedElement, string affectedProperty) { } protected override void WndProc(ref Message m) { if (m.Msg == Interop.WindowMessages.WM_SHOWWINDOW) return; base.WndProc(ref m); switch (m.Msg) { case Interop.WindowMessages.WM_PARENTNOTIFY: if (NativeMethods.Util.LOWORD(unchecked((int)(long)m.WParam)) == Interop.WindowMessages.WM_DESTROY) { UnsafeNativeMethods.PostMessage(new HandleRef(this, Handle), WM_CHECKDESTROY, IntPtr.Zero, IntPtr.Zero); } break; case WM_CHECKDESTROY: CheckDestroy(); break; } } } } }
36.633136
132
0.514133
[ "MIT" ]
15835229565/winforms-1
src/System.Windows.Forms/src/System/Windows/Forms/Application.ParkingWindow.cs
6,193
C#
using System; using Cnblogs.Academy.Common; using MediatR; namespace Cnblogs.Academy.Application.Commands { public class UndoItemCommand : IRequest<BooleanResult> { public long ScheduleId { get; set; } public long ItemId { get; set; } public Guid UserId { get; set; } public UndoItemCommand(long scheduleId, long itemId, Guid userId) { ScheduleId = scheduleId; ItemId = itemId; UserId = userId; } } }
23.761905
73
0.613226
[ "Apache-2.0" ]
cnblogs/learning-schedule
src/Application/Cnblogs.Academy.Commands/ItemCommands/UndoItemCommand.cs
499
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("03.DecimalToHexadecimal")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("03.DecimalToHexadecimal")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("c3d55783-3e24-4564-918e-87c30dfc5407")] // 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.351351
84
0.74771
[ "MIT" ]
ztodorova/Telerik-Academy
C#-part2/NumeralSystems/03.DecimalToHexadecimal/Properties/AssemblyInfo.cs
1,422
C#
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="BooleanToOppositeBooleanConverterTest.cs" company="Catel development team"> // Copyright (c) 2008 - 2014 Catel development team. All rights reserved. // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Catel.Test.MVVM.Converters { using System.Globalization; using Catel.MVVM.Converters; using NUnit.Framework; [TestFixture] public class BooleanToOppositeBooleanConverterTest { #region Methods [TestCase] public void Convert_Null() { var converter = new BooleanToOppositeBooleanConverter(); Assert.AreEqual(null, converter.Convert(null, typeof (bool), null, (CultureInfo)null)); } [TestCase] public void Convert_NonBoolean() { var converter = new BooleanToOppositeBooleanConverter(); Assert.AreEqual(null, converter.Convert("test", typeof(bool), null, (CultureInfo)null)); } [TestCase] public void Convert_True() { var converter = new BooleanToOppositeBooleanConverter(); Assert.AreEqual(false, converter.Convert(true, typeof(bool), null, (CultureInfo)null)); } [TestCase] public void Convert_False() { var converter = new BooleanToOppositeBooleanConverter(); Assert.AreEqual(true, converter.Convert(false, typeof(bool), null, (CultureInfo)null)); } [TestCase] public void ConvertBack_Null() { var converter = new BooleanToOppositeBooleanConverter(); Assert.AreEqual(null, converter.ConvertBack(null, typeof(bool), null, (CultureInfo)null)); } [TestCase] public void ConvertBack_NonBoolean() { var converter = new BooleanToOppositeBooleanConverter(); Assert.AreEqual(null, converter.ConvertBack("test", typeof(bool), null, (CultureInfo)null)); } [TestCase] public void ConvertBack_True() { var converter = new BooleanToOppositeBooleanConverter(); Assert.AreEqual(false, converter.ConvertBack(true, typeof(bool), null, (CultureInfo)null)); } [TestCase] public void ConvertBack_False() { var converter = new BooleanToOppositeBooleanConverter(); Assert.AreEqual(true, converter.ConvertBack(false, typeof(bool), null, (CultureInfo)null)); } #endregion } }
36.337838
120
0.5701
[ "MIT" ]
IvanKupriyanov/Catel
src/Catel.Test/Catel.Test.Shared/MVVM/Converters/BooleanToOppositeBooleanConverterTest.cs
2,691
C#
/* * Copyright 2019 GridGain Systems, Inc. and Contributors. * * Licensed under the GridGain Community Edition License (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.gridgain.com/products/software/community-edition/gridgain-community-edition-license * * 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. */ // ReSharper disable UnusedAutoPropertyAccessor.Global // ReSharper disable MemberCanBePrivate.Global #pragma warning disable 618 namespace Apache.Ignite.Core.Tests { using System; using System.Collections.Generic; using System.Configuration; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; using System.Text; using System.Threading; using System.Xml; using System.Xml.Linq; using System.Xml.Schema; using Apache.Ignite.Core.Binary; using Apache.Ignite.Core.Cache.Affinity.Rendezvous; using Apache.Ignite.Core.Cache.Configuration; using Apache.Ignite.Core.Cache.Eviction; using Apache.Ignite.Core.Cache.Expiry; using Apache.Ignite.Core.Cache.Store; using Apache.Ignite.Core.Ssl; using Apache.Ignite.Core.Common; using Apache.Ignite.Core.Communication.Tcp; using Apache.Ignite.Core.Configuration; using Apache.Ignite.Core.DataStructures.Configuration; using Apache.Ignite.Core.Deployment; using Apache.Ignite.Core.Discovery.Tcp; using Apache.Ignite.Core.Discovery.Tcp.Multicast; using Apache.Ignite.Core.Events; using Apache.Ignite.Core.Failure; using Apache.Ignite.Core.Lifecycle; using Apache.Ignite.Core.Log; using Apache.Ignite.Core.PersistentStore; using Apache.Ignite.Core.Plugin.Cache; using Apache.Ignite.Core.Tests.Binary; using Apache.Ignite.Core.Tests.Plugin; using Apache.Ignite.Core.Transactions; using Apache.Ignite.NLog; using NUnit.Framework; using CheckpointWriteOrder = Apache.Ignite.Core.PersistentStore.CheckpointWriteOrder; using DataPageEvictionMode = Apache.Ignite.Core.Cache.Configuration.DataPageEvictionMode; using WalMode = Apache.Ignite.Core.PersistentStore.WalMode; /// <summary> /// Tests <see cref="IgniteConfiguration"/> serialization. /// </summary> public class IgniteConfigurationSerializerTest { /// <summary> /// Tests the predefined XML. /// </summary> [Test] public void TestPredefinedXml() { var xml = File.ReadAllText("Config\\full-config.xml"); var cfg = IgniteConfiguration.FromXml(xml); Assert.AreEqual("c:", cfg.WorkDirectory); Assert.AreEqual("127.1.1.1", cfg.Localhost); Assert.IsTrue(cfg.IsDaemon); Assert.AreEqual(1024, cfg.JvmMaxMemoryMb); Assert.AreEqual(TimeSpan.FromSeconds(10), cfg.MetricsLogFrequency); Assert.AreEqual(TimeSpan.FromMinutes(1), ((TcpDiscoverySpi)cfg.DiscoverySpi).JoinTimeout); Assert.AreEqual("192.168.1.1", ((TcpDiscoverySpi)cfg.DiscoverySpi).LocalAddress); Assert.AreEqual(6655, ((TcpDiscoverySpi)cfg.DiscoverySpi).LocalPort); Assert.AreEqual(7, ((TcpDiscoveryMulticastIpFinder) ((TcpDiscoverySpi) cfg.DiscoverySpi).IpFinder).AddressRequestAttempts); Assert.AreEqual(new[] { "-Xms1g", "-Xmx4g" }, cfg.JvmOptions); Assert.AreEqual(15, ((LifecycleBean) cfg.LifecycleHandlers.Single()).Foo); Assert.AreEqual("testBar", ((NameMapper) cfg.BinaryConfiguration.NameMapper).Bar); Assert.AreEqual( "Apache.Ignite.Core.Tests.IgniteConfigurationSerializerTest+FooClass, Apache.Ignite.Core.Tests", cfg.BinaryConfiguration.Types.Single()); Assert.IsFalse(cfg.BinaryConfiguration.CompactFooter); Assert.AreEqual(new[] {42, EventType.TaskFailed, EventType.JobFinished}, cfg.IncludedEventTypes); Assert.AreEqual(@"c:\myconfig.xml", cfg.SpringConfigUrl); Assert.IsTrue(cfg.AutoGenerateIgniteInstanceName); Assert.AreEqual(new TimeSpan(1, 2, 3), cfg.LongQueryWarningTimeout); Assert.IsFalse(cfg.IsActiveOnStart); Assert.IsTrue(cfg.AuthenticationEnabled); Assert.AreEqual(10000, cfg.MvccVacuumFrequency); Assert.AreEqual(4, cfg.MvccVacuumThreadCount); Assert.AreEqual(123, cfg.SqlQueryHistorySize); Assert.IsNotNull(cfg.SqlSchemas); Assert.AreEqual(2, cfg.SqlSchemas.Count); Assert.IsTrue(cfg.SqlSchemas.Contains("SCHEMA_1")); Assert.IsTrue(cfg.SqlSchemas.Contains("schema_2")); Assert.AreEqual("someId012", cfg.ConsistentId); Assert.IsFalse(cfg.RedirectJavaConsoleOutput); Assert.AreEqual("secondCache", cfg.CacheConfiguration.Last().Name); var cacheCfg = cfg.CacheConfiguration.First(); Assert.AreEqual(CacheMode.Replicated, cacheCfg.CacheMode); Assert.IsTrue(cacheCfg.ReadThrough); Assert.IsTrue(cacheCfg.WriteThrough); Assert.IsInstanceOf<MyPolicyFactory>(cacheCfg.ExpiryPolicyFactory); Assert.IsTrue(cacheCfg.EnableStatistics); Assert.IsFalse(cacheCfg.WriteBehindCoalescing); Assert.AreEqual(PartitionLossPolicy.ReadWriteAll, cacheCfg.PartitionLossPolicy); Assert.AreEqual("fooGroup", cacheCfg.GroupName); Assert.AreEqual("bar", cacheCfg.KeyConfiguration.Single().AffinityKeyFieldName); Assert.AreEqual("foo", cacheCfg.KeyConfiguration.Single().TypeName); Assert.IsTrue(cacheCfg.OnheapCacheEnabled); Assert.AreEqual(8, cacheCfg.StoreConcurrentLoadAllThreshold); Assert.AreEqual(9, cacheCfg.RebalanceOrder); Assert.AreEqual(10, cacheCfg.RebalanceBatchesPrefetchCount); Assert.AreEqual(11, cacheCfg.MaxQueryIteratorsCount); Assert.AreEqual(12, cacheCfg.QueryDetailMetricsSize); Assert.AreEqual(13, cacheCfg.QueryParallelism); Assert.AreEqual("mySchema", cacheCfg.SqlSchema); var queryEntity = cacheCfg.QueryEntities.Single(); Assert.AreEqual(typeof(int), queryEntity.KeyType); Assert.AreEqual(typeof(string), queryEntity.ValueType); Assert.AreEqual("myTable", queryEntity.TableName); Assert.AreEqual("length", queryEntity.Fields.Single().Name); Assert.AreEqual(typeof(int), queryEntity.Fields.Single().FieldType); Assert.IsTrue(queryEntity.Fields.Single().IsKeyField); Assert.IsTrue(queryEntity.Fields.Single().NotNull); Assert.AreEqual(3.456d, (double)queryEntity.Fields.Single().DefaultValue); Assert.AreEqual("somefield.field", queryEntity.Aliases.Single().FullName); Assert.AreEqual("shortField", queryEntity.Aliases.Single().Alias); var queryIndex = queryEntity.Indexes.Single(); Assert.AreEqual(QueryIndexType.Geospatial, queryIndex.IndexType); Assert.AreEqual("indexFld", queryIndex.Fields.Single().Name); Assert.AreEqual(true, queryIndex.Fields.Single().IsDescending); Assert.AreEqual(123, queryIndex.InlineSize); var nearCfg = cacheCfg.NearConfiguration; Assert.IsNotNull(nearCfg); Assert.AreEqual(7, nearCfg.NearStartSize); var plc = nearCfg.EvictionPolicy as FifoEvictionPolicy; Assert.IsNotNull(plc); Assert.AreEqual(10, plc.BatchSize); Assert.AreEqual(20, plc.MaxSize); Assert.AreEqual(30, plc.MaxMemorySize); var plc2 = cacheCfg.EvictionPolicy as LruEvictionPolicy; Assert.IsNotNull(plc2); Assert.AreEqual(1, plc2.BatchSize); Assert.AreEqual(2, plc2.MaxSize); Assert.AreEqual(3, plc2.MaxMemorySize); var af = cacheCfg.AffinityFunction as RendezvousAffinityFunction; Assert.IsNotNull(af); Assert.AreEqual(99, af.Partitions); Assert.IsTrue(af.ExcludeNeighbors); Assert.AreEqual(new Dictionary<string, object> { {"myNode", "true"}, {"foo", new FooClass {Bar = "Baz"}} }, cfg.UserAttributes); var atomicCfg = cfg.AtomicConfiguration; Assert.AreEqual(2, atomicCfg.Backups); Assert.AreEqual(CacheMode.Local, atomicCfg.CacheMode); Assert.AreEqual(250, atomicCfg.AtomicSequenceReserveSize); var tx = cfg.TransactionConfiguration; Assert.AreEqual(TransactionConcurrency.Optimistic, tx.DefaultTransactionConcurrency); Assert.AreEqual(TransactionIsolation.RepeatableRead, tx.DefaultTransactionIsolation); Assert.AreEqual(new TimeSpan(0,1,2), tx.DefaultTimeout); Assert.AreEqual(15, tx.PessimisticTransactionLogSize); Assert.AreEqual(TimeSpan.FromSeconds(33), tx.PessimisticTransactionLogLinger); var comm = cfg.CommunicationSpi as TcpCommunicationSpi; Assert.IsNotNull(comm); Assert.AreEqual(33, comm.AckSendThreshold); Assert.AreEqual(new TimeSpan(0, 1, 2), comm.IdleConnectionTimeout); Assert.IsInstanceOf<TestLogger>(cfg.Logger); var binType = cfg.BinaryConfiguration.TypeConfigurations.Single(); Assert.AreEqual("typeName", binType.TypeName); Assert.AreEqual("affKeyFieldName", binType.AffinityKeyFieldName); Assert.IsTrue(binType.IsEnum); Assert.AreEqual(true, binType.KeepDeserialized); Assert.IsInstanceOf<IdMapper>(binType.IdMapper); Assert.IsInstanceOf<NameMapper>(binType.NameMapper); Assert.IsInstanceOf<TestSerializer>(binType.Serializer); var plugins = cfg.PluginConfigurations; Assert.IsNotNull(plugins); Assert.IsNotNull(plugins.Cast<TestIgnitePluginConfiguration>().SingleOrDefault()); Assert.IsNotNull(cacheCfg.PluginConfigurations.Cast<MyPluginConfiguration>().SingleOrDefault()); var eventStorage = cfg.EventStorageSpi as MemoryEventStorageSpi; Assert.IsNotNull(eventStorage); Assert.AreEqual(23.45, eventStorage.ExpirationTimeout.TotalSeconds); Assert.AreEqual(129, eventStorage.MaxEventCount); var memCfg = cfg.MemoryConfiguration; Assert.IsNotNull(memCfg); Assert.AreEqual(3, memCfg.ConcurrencyLevel); Assert.AreEqual("dfPlc", memCfg.DefaultMemoryPolicyName); Assert.AreEqual(45, memCfg.PageSize); Assert.AreEqual(67, memCfg.SystemCacheInitialSize); Assert.AreEqual(68, memCfg.SystemCacheMaxSize); var memPlc = memCfg.MemoryPolicies.Single(); Assert.AreEqual(1, memPlc.EmptyPagesPoolSize); Assert.AreEqual(0.2, memPlc.EvictionThreshold); Assert.AreEqual("dfPlc", memPlc.Name); Assert.AreEqual(DataPageEvictionMode.RandomLru, memPlc.PageEvictionMode); Assert.AreEqual("abc", memPlc.SwapFilePath); Assert.AreEqual(89, memPlc.InitialSize); Assert.AreEqual(98, memPlc.MaxSize); Assert.IsTrue(memPlc.MetricsEnabled); Assert.AreEqual(9, memPlc.SubIntervals); Assert.AreEqual(TimeSpan.FromSeconds(62), memPlc.RateTimeInterval); Assert.AreEqual(PeerAssemblyLoadingMode.CurrentAppDomain, cfg.PeerAssemblyLoadingMode); var sql = cfg.SqlConnectorConfiguration; Assert.IsNotNull(sql); Assert.AreEqual("bar", sql.Host); Assert.AreEqual(10, sql.Port); Assert.AreEqual(11, sql.PortRange); Assert.AreEqual(12, sql.SocketSendBufferSize); Assert.AreEqual(13, sql.SocketReceiveBufferSize); Assert.IsTrue(sql.TcpNoDelay); Assert.AreEqual(14, sql.MaxOpenCursorsPerConnection); Assert.AreEqual(15, sql.ThreadPoolSize); var client = cfg.ClientConnectorConfiguration; Assert.IsNotNull(client); Assert.AreEqual("bar", client.Host); Assert.AreEqual(10, client.Port); Assert.AreEqual(11, client.PortRange); Assert.AreEqual(12, client.SocketSendBufferSize); Assert.AreEqual(13, client.SocketReceiveBufferSize); Assert.IsTrue(client.TcpNoDelay); Assert.AreEqual(14, client.MaxOpenCursorsPerConnection); Assert.AreEqual(15, client.ThreadPoolSize); Assert.AreEqual(19, client.IdleTimeout.TotalSeconds); var pers = cfg.PersistentStoreConfiguration; Assert.AreEqual(true, pers.AlwaysWriteFullPages); Assert.AreEqual(TimeSpan.FromSeconds(1), pers.CheckpointingFrequency); Assert.AreEqual(2, pers.CheckpointingPageBufferSize); Assert.AreEqual(3, pers.CheckpointingThreads); Assert.AreEqual(TimeSpan.FromSeconds(4), pers.LockWaitTime); Assert.AreEqual("foo", pers.PersistentStorePath); Assert.AreEqual(5, pers.TlbSize); Assert.AreEqual("bar", pers.WalArchivePath); Assert.AreEqual(TimeSpan.FromSeconds(6), pers.WalFlushFrequency); Assert.AreEqual(7, pers.WalFsyncDelayNanos); Assert.AreEqual(8, pers.WalHistorySize); Assert.AreEqual(WalMode.None, pers.WalMode); Assert.AreEqual(9, pers.WalRecordIteratorBufferSize); Assert.AreEqual(10, pers.WalSegments); Assert.AreEqual(11, pers.WalSegmentSize); Assert.AreEqual("baz", pers.WalStorePath); Assert.IsTrue(pers.MetricsEnabled); Assert.AreEqual(3, pers.SubIntervals); Assert.AreEqual(TimeSpan.FromSeconds(6), pers.RateTimeInterval); Assert.AreEqual(CheckpointWriteOrder.Random, pers.CheckpointWriteOrder); Assert.IsTrue(pers.WriteThrottlingEnabled); var listeners = cfg.LocalEventListeners; Assert.AreEqual(2, listeners.Count); var rebalListener = (LocalEventListener<CacheRebalancingEvent>) listeners.First(); Assert.AreEqual(new[] {EventType.CacheObjectPut, 81}, rebalListener.EventTypes); Assert.AreEqual("Apache.Ignite.Core.Tests.EventsTestLocalListeners+Listener`1" + "[Apache.Ignite.Core.Events.CacheRebalancingEvent]", rebalListener.Listener.GetType().ToString()); var ds = cfg.DataStorageConfiguration; Assert.IsFalse(ds.AlwaysWriteFullPages); Assert.AreEqual(TimeSpan.FromSeconds(1), ds.CheckpointFrequency); Assert.AreEqual(3, ds.CheckpointThreads); Assert.AreEqual(4, ds.ConcurrencyLevel); Assert.AreEqual(TimeSpan.FromSeconds(5), ds.LockWaitTime); Assert.IsTrue(ds.MetricsEnabled); Assert.AreEqual(6, ds.PageSize); Assert.AreEqual("cde", ds.StoragePath); Assert.AreEqual(TimeSpan.FromSeconds(7), ds.MetricsRateTimeInterval); Assert.AreEqual(8, ds.MetricsSubIntervalCount); Assert.AreEqual(9, ds.SystemRegionInitialSize); Assert.AreEqual(10, ds.SystemRegionMaxSize); Assert.AreEqual(11, ds.WalThreadLocalBufferSize); Assert.AreEqual("abc", ds.WalArchivePath); Assert.AreEqual(TimeSpan.FromSeconds(12), ds.WalFlushFrequency); Assert.AreEqual(13, ds.WalFsyncDelayNanos); Assert.AreEqual(14, ds.WalHistorySize); Assert.AreEqual(Core.Configuration.WalMode.Background, ds.WalMode); Assert.AreEqual(15, ds.WalRecordIteratorBufferSize); Assert.AreEqual(16, ds.WalSegments); Assert.AreEqual(17, ds.WalSegmentSize); Assert.AreEqual("wal-store", ds.WalPath); Assert.AreEqual(TimeSpan.FromSeconds(18), ds.WalAutoArchiveAfterInactivity); Assert.IsTrue(ds.WriteThrottlingEnabled); Assert.AreEqual(DiskPageCompression.Zstd, ds.WalPageCompression); var dr = ds.DataRegionConfigurations.Single(); Assert.AreEqual(1, dr.EmptyPagesPoolSize); Assert.AreEqual(2, dr.EvictionThreshold); Assert.AreEqual(3, dr.InitialSize); Assert.AreEqual(4, dr.MaxSize); Assert.AreEqual("reg2", dr.Name); Assert.AreEqual(Core.Configuration.DataPageEvictionMode.RandomLru, dr.PageEvictionMode); Assert.AreEqual(TimeSpan.FromSeconds(1), dr.MetricsRateTimeInterval); Assert.AreEqual(5, dr.MetricsSubIntervalCount); Assert.AreEqual("swap", dr.SwapPath); Assert.IsTrue(dr.MetricsEnabled); Assert.AreEqual(7, dr.CheckpointPageBufferSize); dr = ds.DefaultDataRegionConfiguration; Assert.AreEqual(2, dr.EmptyPagesPoolSize); Assert.AreEqual(3, dr.EvictionThreshold); Assert.AreEqual(4, dr.InitialSize); Assert.AreEqual(5, dr.MaxSize); Assert.AreEqual("reg1", dr.Name); Assert.AreEqual(Core.Configuration.DataPageEvictionMode.Disabled, dr.PageEvictionMode); Assert.AreEqual(TimeSpan.FromSeconds(3), dr.MetricsRateTimeInterval); Assert.AreEqual(6, dr.MetricsSubIntervalCount); Assert.AreEqual("swap2", dr.SwapPath); Assert.IsFalse(dr.MetricsEnabled); Assert.IsInstanceOf<SslContextFactory>(cfg.SslContextFactory); Assert.IsInstanceOf<StopNodeOrHaltFailureHandler>(cfg.FailureHandler); var failureHandler = (StopNodeOrHaltFailureHandler)cfg.FailureHandler; Assert.IsTrue(failureHandler.TryStop); Assert.AreEqual(TimeSpan.Parse("0:1:0"), failureHandler.Timeout); } /// <summary> /// Tests the serialize deserialize. /// </summary> [Test] public void TestSerializeDeserialize() { // Test custom CheckSerializeDeserialize(GetTestConfig()); // Test custom with different culture to make sure numbers are serialized properly RunWithCustomCulture(() => CheckSerializeDeserialize(GetTestConfig())); // Test default CheckSerializeDeserialize(new IgniteConfiguration()); } /// <summary> /// Tests that all properties are present in the schema. /// </summary> [Test] public void TestAllPropertiesArePresentInSchema() { CheckAllPropertiesArePresentInSchema("IgniteConfigurationSection.xsd", "igniteConfiguration", typeof(IgniteConfiguration)); } /// <summary> /// Checks that all properties are present in schema. /// </summary> [SuppressMessage("ReSharper", "PossibleNullReferenceException")] public static void CheckAllPropertiesArePresentInSchema(string xsd, string sectionName, Type type) { var schema = XDocument.Load(xsd) .Root.Elements() .Single(x => x.Attribute("name").Value == sectionName); CheckPropertyIsPresentInSchema(type, schema); } /// <summary> /// Checks the property is present in schema. /// </summary> // ReSharper disable once UnusedParameter.Local // ReSharper disable once ParameterOnlyUsedForPreconditionCheck.Local private static void CheckPropertyIsPresentInSchema(Type type, XElement schema) { Func<string, string> toLowerCamel = x => char.ToLowerInvariant(x[0]) + x.Substring(1); foreach (var prop in type.GetProperties()) { if (!prop.CanWrite) continue; // Read-only properties are not configured in XML. if (prop.GetCustomAttributes(typeof(ObsoleteAttribute), true).Any()) continue; // Skip deprecated. var propType = prop.PropertyType; var isCollection = propType.IsGenericType && propType.GetGenericTypeDefinition() == typeof(ICollection<>); if (isCollection) propType = propType.GetGenericArguments().First(); var propName = toLowerCamel(prop.Name); Assert.IsTrue(schema.Descendants().Select(x => x.Attribute("name")) .Any(x => x != null && x.Value == propName), "Property is missing in XML schema: " + propName); var isComplexProp = propType.Namespace != null && propType.Namespace.StartsWith("Apache.Ignite.Core"); if (isComplexProp) CheckPropertyIsPresentInSchema(propType, schema); } } /// <summary> /// Tests the schema validation. /// </summary> [Test] public void TestSchemaValidation() { CheckSchemaValidation(); RunWithCustomCulture(CheckSchemaValidation); // Check invalid xml const string invalidXml = @"<igniteConfiguration xmlns='http://ignite.apache.org/schema/dotnet/IgniteConfigurationSection'> <binaryConfiguration /><binaryConfiguration /> </igniteConfiguration>"; Assert.Throws<XmlSchemaValidationException>(() => CheckSchemaValidation(invalidXml)); } /// <summary> /// Tests the XML conversion. /// </summary> [Test] public void TestToXml() { // Empty config Assert.AreEqual("<?xml version=\"1.0\" encoding=\"utf-16\"?>\r\n<igniteConfiguration " + "xmlns=\"http://ignite.apache.org/schema/dotnet/IgniteConfigurationSection\" />", new IgniteConfiguration().ToXml()); // Some properties var cfg = new IgniteConfiguration { IgniteInstanceName = "myGrid", ClientMode = true, CacheConfiguration = new[] { new CacheConfiguration("myCache") { CacheMode = CacheMode.Replicated, QueryEntities = new[] { new QueryEntity(typeof(int)), new QueryEntity(typeof(int), typeof(string)) } } }, IncludedEventTypes = new[] { EventType.CacheEntryCreated, EventType.CacheNodesLeft } }; Assert.AreEqual(FixLineEndings(@"<?xml version=""1.0"" encoding=""utf-16""?> <igniteConfiguration clientMode=""true"" igniteInstanceName=""myGrid"" xmlns=""http://ignite.apache.org/schema/dotnet/IgniteConfigurationSection""> <cacheConfiguration> <cacheConfiguration cacheMode=""Replicated"" name=""myCache""> <queryEntities> <queryEntity valueType=""System.Int32"" valueTypeName=""java.lang.Integer"" /> <queryEntity keyType=""System.Int32"" keyTypeName=""java.lang.Integer"" valueType=""System.String"" valueTypeName=""java.lang.String"" /> </queryEntities> </cacheConfiguration> </cacheConfiguration> <includedEventTypes> <int>CacheEntryCreated</int> <int>CacheNodesLeft</int> </includedEventTypes> </igniteConfiguration>"), cfg.ToXml()); // Custom section name and indent var sb = new StringBuilder(); var settings = new XmlWriterSettings { Indent = true, IndentChars = " " }; using (var xmlWriter = XmlWriter.Create(sb, settings)) { cfg.ToXml(xmlWriter, "igCfg"); } Assert.AreEqual(FixLineEndings(@"<?xml version=""1.0"" encoding=""utf-16""?> <igCfg clientMode=""true"" igniteInstanceName=""myGrid"" xmlns=""http://ignite.apache.org/schema/dotnet/IgniteConfigurationSection""> <cacheConfiguration> <cacheConfiguration cacheMode=""Replicated"" name=""myCache""> <queryEntities> <queryEntity valueType=""System.Int32"" valueTypeName=""java.lang.Integer"" /> <queryEntity keyType=""System.Int32"" keyTypeName=""java.lang.Integer"" valueType=""System.String"" valueTypeName=""java.lang.String"" /> </queryEntities> </cacheConfiguration> </cacheConfiguration> <includedEventTypes> <int>CacheEntryCreated</int> <int>CacheNodesLeft</int> </includedEventTypes> </igCfg>"), sb.ToString()); } /// <summary> /// Tests the deserialization. /// </summary> [Test] public void TestFromXml() { // Empty section. var cfg = IgniteConfiguration.FromXml("<x />"); AssertExtensions.ReflectionEqual(new IgniteConfiguration(), cfg); // Empty section with XML header. cfg = IgniteConfiguration.FromXml("<?xml version=\"1.0\" encoding=\"utf-16\"?><x />"); AssertExtensions.ReflectionEqual(new IgniteConfiguration(), cfg); // Simple test. cfg = IgniteConfiguration.FromXml(@"<igCfg igniteInstanceName=""myGrid"" clientMode=""true"" />"); AssertExtensions.ReflectionEqual(new IgniteConfiguration {IgniteInstanceName = "myGrid", ClientMode = true}, cfg); // Invalid xml. var ex = Assert.Throws<ConfigurationErrorsException>(() => IgniteConfiguration.FromXml(@"<igCfg foo=""bar"" />")); Assert.AreEqual("Invalid IgniteConfiguration attribute 'foo=bar', there is no such property " + "on 'Apache.Ignite.Core.IgniteConfiguration'", ex.Message); // Xml reader. using (var xmlReader = XmlReader.Create( new StringReader(@"<igCfg igniteInstanceName=""myGrid"" clientMode=""true"" />"))) { cfg = IgniteConfiguration.FromXml(xmlReader); } AssertExtensions.ReflectionEqual(new IgniteConfiguration { IgniteInstanceName = "myGrid", ClientMode = true }, cfg); } /// <summary> /// Ensures windows-style \r\n line endings in a string literal. /// Git settings may cause string literals in both styles. /// </summary> private static string FixLineEndings(string s) { return s.Split('\n').Select(x => x.TrimEnd('\r')) .Aggregate((acc, x) => string.Format("{0}\r\n{1}", acc, x)); } /// <summary> /// Checks the schema validation. /// </summary> private static void CheckSchemaValidation() { CheckSchemaValidation(GetTestConfig().ToXml()); } /// <summary> /// Checks the schema validation. /// </summary> private static void CheckSchemaValidation(string xml) { var xmlns = "http://ignite.apache.org/schema/dotnet/IgniteConfigurationSection"; var schemaFile = "IgniteConfigurationSection.xsd"; CheckSchemaValidation(xml, xmlns, schemaFile); } /// <summary> /// Checks the schema validation. /// </summary> public static void CheckSchemaValidation(string xml, string xmlns, string schemaFile) { var document = new XmlDocument(); document.Schemas.Add(xmlns, XmlReader.Create(schemaFile)); document.Load(new StringReader(xml)); document.Validate(null); } /// <summary> /// Checks the serialize deserialize. /// </summary> /// <param name="cfg">The config.</param> private static void CheckSerializeDeserialize(IgniteConfiguration cfg) { var resCfg = SerializeDeserialize(cfg); AssertExtensions.ReflectionEqual(cfg, resCfg); } /// <summary> /// Serializes and deserializes a config. /// </summary> private static IgniteConfiguration SerializeDeserialize(IgniteConfiguration cfg) { var xml = cfg.ToXml(); return IgniteConfiguration.FromXml(xml); } /// <summary> /// Gets the test configuration. /// </summary> private static IgniteConfiguration GetTestConfig() { return new IgniteConfiguration { IgniteInstanceName = "gridName", JvmOptions = new[] {"1", "2"}, Localhost = "localhost11", JvmClasspath = "classpath", Assemblies = new[] {"asm1", "asm2", "asm3"}, BinaryConfiguration = new BinaryConfiguration { TypeConfigurations = new[] { new BinaryTypeConfiguration { IsEnum = true, KeepDeserialized = true, AffinityKeyFieldName = "affKeyFieldName", TypeName = "typeName", IdMapper = new IdMapper(), NameMapper = new NameMapper(), Serializer = new TestSerializer() }, new BinaryTypeConfiguration { IsEnum = false, KeepDeserialized = false, AffinityKeyFieldName = "affKeyFieldName", TypeName = "typeName2", Serializer = new BinaryReflectiveSerializer() } }, Types = new[] {typeof(string).FullName}, IdMapper = new IdMapper(), KeepDeserialized = true, NameMapper = new NameMapper(), Serializer = new TestSerializer() }, CacheConfiguration = new[] { new CacheConfiguration("cacheName") { AtomicityMode = CacheAtomicityMode.Transactional, Backups = 15, CacheMode = CacheMode.Replicated, CacheStoreFactory = new TestCacheStoreFactory(), CopyOnRead = false, EagerTtl = false, Invalidate = true, KeepBinaryInStore = true, LoadPreviousValue = true, LockTimeout = TimeSpan.FromSeconds(56), MaxConcurrentAsyncOperations = 24, QueryEntities = new[] { new QueryEntity { Fields = new[] { new QueryField("field", typeof(int)) { IsKeyField = true, NotNull = true, DefaultValue = "foo" } }, Indexes = new[] { new QueryIndex("field") { IndexType = QueryIndexType.FullText, InlineSize = 32 } }, Aliases = new[] { new QueryAlias("field.field", "fld") }, KeyType = typeof(string), ValueType = typeof(long), TableName = "table-1", KeyFieldName = "k", ValueFieldName = "v" }, }, ReadFromBackup = false, RebalanceBatchSize = 33, RebalanceDelay = TimeSpan.MaxValue, RebalanceMode = CacheRebalanceMode.Sync, RebalanceThrottle = TimeSpan.FromHours(44), RebalanceTimeout = TimeSpan.FromMinutes(8), SqlEscapeAll = true, WriteBehindBatchSize = 45, WriteBehindEnabled = true, WriteBehindFlushFrequency = TimeSpan.FromSeconds(55), WriteBehindFlushSize = 66, WriteBehindFlushThreadCount = 2, WriteBehindCoalescing = false, WriteSynchronizationMode = CacheWriteSynchronizationMode.FullAsync, NearConfiguration = new NearCacheConfiguration { NearStartSize = 5, EvictionPolicy = new FifoEvictionPolicy { BatchSize = 19, MaxMemorySize = 1024, MaxSize = 555 } }, EvictionPolicy = new LruEvictionPolicy { BatchSize = 18, MaxMemorySize = 1023, MaxSize = 554 }, AffinityFunction = new RendezvousAffinityFunction { ExcludeNeighbors = true, Partitions = 48 }, ExpiryPolicyFactory = new MyPolicyFactory(), EnableStatistics = true, PluginConfigurations = new[] { new MyPluginConfiguration() }, MemoryPolicyName = "somePolicy", PartitionLossPolicy = PartitionLossPolicy.ReadOnlyAll, GroupName = "abc", SqlIndexMaxInlineSize = 24, KeyConfiguration = new[] { new CacheKeyConfiguration { AffinityKeyFieldName = "abc", TypeName = "def" }, }, OnheapCacheEnabled = true, StoreConcurrentLoadAllThreshold = 7, RebalanceOrder = 3, RebalanceBatchesPrefetchCount = 4, MaxQueryIteratorsCount = 512, QueryDetailMetricsSize = 100, QueryParallelism = 16, SqlSchema = "foo" } }, ClientMode = true, DiscoverySpi = new TcpDiscoverySpi { NetworkTimeout = TimeSpan.FromSeconds(1), SocketTimeout = TimeSpan.FromSeconds(2), AckTimeout = TimeSpan.FromSeconds(3), JoinTimeout = TimeSpan.FromSeconds(4), MaxAckTimeout = TimeSpan.FromSeconds(5), IpFinder = new TcpDiscoveryMulticastIpFinder { TimeToLive = 110, MulticastGroup = "multicastGroup", AddressRequestAttempts = 10, MulticastPort = 987, ResponseTimeout = TimeSpan.FromDays(1), LocalAddress = "127.0.0.2", Endpoints = new[] {"", "abc"} }, ClientReconnectDisabled = true, ForceServerMode = true, IpFinderCleanFrequency = TimeSpan.FromMinutes(7), LocalAddress = "127.0.0.1", LocalPort = 49900, LocalPortRange = 13, ReconnectCount = 11, StatisticsPrintFrequency = TimeSpan.FromSeconds(20), ThreadPriority = 6, TopologyHistorySize = 1234567 }, IgniteHome = "igniteHome", IncludedEventTypes = EventType.CacheQueryAll, JvmDllPath = @"c:\jvm", JvmInitialMemoryMb = 1024, JvmMaxMemoryMb = 2048, LifecycleHandlers = new[] {new LifecycleBean(), new LifecycleBean()}, MetricsExpireTime = TimeSpan.FromSeconds(15), MetricsHistorySize = 45, MetricsLogFrequency = TimeSpan.FromDays(2), MetricsUpdateFrequency = TimeSpan.MinValue, NetworkSendRetryCount = 7, NetworkSendRetryDelay = TimeSpan.FromSeconds(98), NetworkTimeout = TimeSpan.FromMinutes(4), SuppressWarnings = true, WorkDirectory = @"c:\work", IsDaemon = true, UserAttributes = Enumerable.Range(1, 10).ToDictionary(x => x.ToString(), x => x % 2 == 0 ? (object) x : new FooClass {Bar = x.ToString()}), AtomicConfiguration = new AtomicConfiguration { CacheMode = CacheMode.Replicated, AtomicSequenceReserveSize = 200, Backups = 2 }, TransactionConfiguration = new TransactionConfiguration { PessimisticTransactionLogSize = 23, DefaultTransactionIsolation = TransactionIsolation.ReadCommitted, DefaultTimeout = TimeSpan.FromDays(2), DefaultTransactionConcurrency = TransactionConcurrency.Optimistic, PessimisticTransactionLogLinger = TimeSpan.FromHours(3) }, CommunicationSpi = new TcpCommunicationSpi { LocalPort = 47501, MaxConnectTimeout = TimeSpan.FromSeconds(34), MessageQueueLimit = 15, ConnectTimeout = TimeSpan.FromSeconds(17), IdleConnectionTimeout = TimeSpan.FromSeconds(19), SelectorsCount = 8, ReconnectCount = 33, SocketReceiveBufferSize = 512, AckSendThreshold = 99, DirectBuffer = false, DirectSendBuffer = true, LocalPortRange = 45, LocalAddress = "127.0.0.1", TcpNoDelay = false, SlowClientQueueLimit = 98, SocketSendBufferSize = 2045, UnacknowledgedMessagesBufferSize = 3450 }, SpringConfigUrl = "test", Logger = new IgniteNLogLogger(), FailureDetectionTimeout = TimeSpan.FromMinutes(2), ClientFailureDetectionTimeout = TimeSpan.FromMinutes(3), LongQueryWarningTimeout = TimeSpan.FromDays(4), PluginConfigurations = new[] {new TestIgnitePluginConfiguration()}, EventStorageSpi = new MemoryEventStorageSpi { ExpirationTimeout = TimeSpan.FromMilliseconds(12345), MaxEventCount = 257 }, MemoryConfiguration = new MemoryConfiguration { ConcurrencyLevel = 3, DefaultMemoryPolicyName = "somePolicy", PageSize = 4, SystemCacheInitialSize = 5, SystemCacheMaxSize = 6, MemoryPolicies = new[] { new MemoryPolicyConfiguration { Name = "myDefaultPlc", PageEvictionMode = DataPageEvictionMode.Random2Lru, InitialSize = 245 * 1024 * 1024, MaxSize = 345 * 1024 * 1024, EvictionThreshold = 0.88, EmptyPagesPoolSize = 77, SwapFilePath = "myPath1", RateTimeInterval = TimeSpan.FromSeconds(22), SubIntervals = 99 }, new MemoryPolicyConfiguration { Name = "customPlc", PageEvictionMode = DataPageEvictionMode.RandomLru, EvictionThreshold = 0.77, EmptyPagesPoolSize = 66, SwapFilePath = "somePath2", MetricsEnabled = true } } }, PeerAssemblyLoadingMode = PeerAssemblyLoadingMode.CurrentAppDomain, ClientConnectorConfiguration = new ClientConnectorConfiguration { Host = "foo", Port = 2, PortRange = 3, MaxOpenCursorsPerConnection = 4, SocketReceiveBufferSize = 5, SocketSendBufferSize = 6, TcpNoDelay = false, ThinClientEnabled = false, OdbcEnabled = false, JdbcEnabled = false, ThreadPoolSize = 7, IdleTimeout = TimeSpan.FromMinutes(5) }, PersistentStoreConfiguration = new PersistentStoreConfiguration { AlwaysWriteFullPages = true, CheckpointingFrequency = TimeSpan.FromSeconds(25), CheckpointingPageBufferSize = 28 * 1024 * 1024, CheckpointingThreads = 2, LockWaitTime = TimeSpan.FromSeconds(5), PersistentStorePath = Path.GetTempPath(), TlbSize = 64 * 1024, WalArchivePath = Path.GetTempPath(), WalFlushFrequency = TimeSpan.FromSeconds(3), WalFsyncDelayNanos = 3, WalHistorySize = 10, WalMode = WalMode.Background, WalRecordIteratorBufferSize = 32 * 1024 * 1024, WalSegments = 6, WalSegmentSize = 5 * 1024 * 1024, WalStorePath = Path.GetTempPath(), SubIntervals = 25, MetricsEnabled = true, RateTimeInterval = TimeSpan.FromDays(1), CheckpointWriteOrder = CheckpointWriteOrder.Random, WriteThrottlingEnabled = true }, IsActiveOnStart = false, ConsistentId = "myId123", LocalEventListeners = new[] { new LocalEventListener<IEvent> { EventTypes = new[] {1, 2}, Listener = new MyEventListener() } }, DataStorageConfiguration = new DataStorageConfiguration { AlwaysWriteFullPages = true, CheckpointFrequency = TimeSpan.FromSeconds(25), CheckpointThreads = 2, LockWaitTime = TimeSpan.FromSeconds(5), StoragePath = Path.GetTempPath(), WalThreadLocalBufferSize = 64 * 1024, WalArchivePath = Path.GetTempPath(), WalFlushFrequency = TimeSpan.FromSeconds(3), WalFsyncDelayNanos = 3, WalHistorySize = 10, WalMode = Core.Configuration.WalMode.None, WalRecordIteratorBufferSize = 32 * 1024 * 1024, WalSegments = 6, WalSegmentSize = 5 * 1024 * 1024, WalPath = Path.GetTempPath(), MetricsEnabled = true, MetricsSubIntervalCount = 7, MetricsRateTimeInterval = TimeSpan.FromSeconds(9), CheckpointWriteOrder = Core.Configuration.CheckpointWriteOrder.Sequential, WriteThrottlingEnabled = true, SystemRegionInitialSize = 64 * 1024 * 1024, SystemRegionMaxSize = 128 * 1024 * 1024, ConcurrencyLevel = 1, PageSize = 5 * 1024, WalAutoArchiveAfterInactivity = TimeSpan.FromSeconds(19), WalPageCompression = DiskPageCompression.Lz4, WalPageCompressionLevel = 10, DefaultDataRegionConfiguration = new DataRegionConfiguration { Name = "reg1", EmptyPagesPoolSize = 50, EvictionThreshold = 0.8, InitialSize = 100 * 1024 * 1024, MaxSize = 150 * 1024 * 1024, MetricsEnabled = true, PageEvictionMode = Core.Configuration.DataPageEvictionMode.RandomLru, PersistenceEnabled = false, MetricsRateTimeInterval = TimeSpan.FromMinutes(2), MetricsSubIntervalCount = 6, SwapPath = Path.GetTempPath(), CheckpointPageBufferSize = 7 }, DataRegionConfigurations = new[] { new DataRegionConfiguration { Name = "reg2", EmptyPagesPoolSize = 51, EvictionThreshold = 0.7, InitialSize = 101 * 1024 * 1024, MaxSize = 151 * 1024 * 1024, MetricsEnabled = false, PageEvictionMode = Core.Configuration.DataPageEvictionMode.RandomLru, PersistenceEnabled = false, MetricsRateTimeInterval = TimeSpan.FromMinutes(3), MetricsSubIntervalCount = 7, SwapPath = Path.GetTempPath() } } }, SslContextFactory = new SslContextFactory(), FailureHandler = new StopNodeOrHaltFailureHandler { TryStop = false, Timeout = TimeSpan.FromSeconds(10) }, SqlQueryHistorySize = 345 }; } /// <summary> /// Runs the with custom culture. /// </summary> /// <param name="action">The action.</param> private static void RunWithCustomCulture(Action action) { RunWithCulture(action, CultureInfo.InvariantCulture); RunWithCulture(action, CultureInfo.GetCultureInfo("ru-RU")); } /// <summary> /// Runs the with culture. /// </summary> /// <param name="action">The action.</param> /// <param name="cultureInfo">The culture information.</param> private static void RunWithCulture(Action action, CultureInfo cultureInfo) { var oldCulture = Thread.CurrentThread.CurrentCulture; try { Thread.CurrentThread.CurrentCulture = cultureInfo; action(); } finally { Thread.CurrentThread.CurrentCulture = oldCulture; } } /// <summary> /// Test bean. /// </summary> public class LifecycleBean : ILifecycleHandler { /// <summary> /// Gets or sets the foo. /// </summary> /// <value> /// The foo. /// </value> public int Foo { get; set; } /// <summary> /// This method is called when lifecycle event occurs. /// </summary> /// <param name="evt">Lifecycle event.</param> public void OnLifecycleEvent(LifecycleEventType evt) { // No-op. } } /// <summary> /// Test mapper. /// </summary> public class NameMapper : IBinaryNameMapper { /// <summary> /// Gets or sets the bar. /// </summary> /// <value> /// The bar. /// </value> public string Bar { get; set; } /// <summary> /// Gets the type name. /// </summary> /// <param name="name">The name.</param> /// <returns> /// Type name. /// </returns> public string GetTypeName(string name) { return name; } /// <summary> /// Gets the field name. /// </summary> /// <param name="name">The name.</param> /// <returns> /// Field name. /// </returns> public string GetFieldName(string name) { return name; } } /// <summary> /// Serializer. /// </summary> public class TestSerializer : IBinarySerializer { /** <inheritdoc /> */ public void WriteBinary(object obj, IBinaryWriter writer) { // No-op. } /** <inheritdoc /> */ public void ReadBinary(object obj, IBinaryReader reader) { // No-op. } } /// <summary> /// Test class. /// </summary> public class FooClass { public string Bar { get; set; } public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; if (obj.GetType() != GetType()) return false; return string.Equals(Bar, ((FooClass) obj).Bar); } public override int GetHashCode() { return Bar != null ? Bar.GetHashCode() : 0; } public static bool operator ==(FooClass left, FooClass right) { return Equals(left, right); } public static bool operator !=(FooClass left, FooClass right) { return !Equals(left, right); } } /// <summary> /// Test factory. /// </summary> public class TestCacheStoreFactory : IFactory<ICacheStore> { /// <summary> /// Creates an instance of the cache store. /// </summary> /// <returns> /// New instance of the cache store. /// </returns> public ICacheStore CreateInstance() { return null; } } /// <summary> /// Test logger. /// </summary> public class TestLogger : ILogger { /** <inheritdoc /> */ public void Log(LogLevel level, string message, object[] args, IFormatProvider formatProvider, string category, string nativeErrorInfo, Exception ex) { throw new NotImplementedException(); } /** <inheritdoc /> */ public bool IsEnabled(LogLevel level) { throw new NotImplementedException(); } } /// <summary> /// Test factory. /// </summary> public class MyPolicyFactory : IFactory<IExpiryPolicy> { /** <inheritdoc /> */ public IExpiryPolicy CreateInstance() { throw new NotImplementedException(); } } public class MyPluginConfiguration : ICachePluginConfiguration { int? ICachePluginConfiguration.CachePluginConfigurationClosureFactoryId { get { return 0; } } void ICachePluginConfiguration.WriteBinary(IBinaryRawWriter writer) { throw new NotImplementedException(); } } public class MyEventListener : IEventListener<IEvent> { public bool Invoke(IEvent evt) { throw new NotImplementedException(); } } } }
43.333868
147
0.538949
[ "CC0-1.0" ]
Diffblue-benchmarks/Gridgain-gridgain
modules/platforms/dotnet/Apache.Ignite.Core.Tests/IgniteConfigurationSerializerTest.cs
53,994
C#
// <auto-generated> // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/ads/googleads/v7/enums/policy_topic_evidence_destination_not_working_device.proto // </auto-generated> #pragma warning disable 1591, 0612, 3021 #region Designer generated code using pb = global::Google.Protobuf; using pbc = global::Google.Protobuf.Collections; using pbr = global::Google.Protobuf.Reflection; using scg = global::System.Collections.Generic; namespace Google.Ads.GoogleAds.V7.Enums { /// <summary>Holder for reflection information generated from google/ads/googleads/v7/enums/policy_topic_evidence_destination_not_working_device.proto</summary> public static partial class PolicyTopicEvidenceDestinationNotWorkingDeviceReflection { #region Descriptor /// <summary>File descriptor for google/ads/googleads/v7/enums/policy_topic_evidence_destination_not_working_device.proto</summary> public static pbr::FileDescriptor Descriptor { get { return descriptor; } } private static pbr::FileDescriptor descriptor; static PolicyTopicEvidenceDestinationNotWorkingDeviceReflection() { byte[] descriptorData = global::System.Convert.FromBase64String( string.Concat( "Clhnb29nbGUvYWRzL2dvb2dsZWFkcy92Ny9lbnVtcy9wb2xpY3lfdG9waWNf", "ZXZpZGVuY2VfZGVzdGluYXRpb25fbm90X3dvcmtpbmdfZGV2aWNlLnByb3Rv", "Eh1nb29nbGUuYWRzLmdvb2dsZWFkcy52Ny5lbnVtcxocZ29vZ2xlL2FwaS9h", "bm5vdGF0aW9ucy5wcm90byKnAQoyUG9saWN5VG9waWNFdmlkZW5jZURlc3Rp", "bmF0aW9uTm90V29ya2luZ0RldmljZUVudW0icQouUG9saWN5VG9waWNFdmlk", "ZW5jZURlc3RpbmF0aW9uTm90V29ya2luZ0RldmljZRIPCgtVTlNQRUNJRklF", "RBAAEgsKB1VOS05PV04QARILCgdERVNLVE9QEAISCwoHQU5EUk9JRBADEgcK", "A0lPUxAEQogCCiFjb20uZ29vZ2xlLmFkcy5nb29nbGVhZHMudjcuZW51bXNC", "M1BvbGljeVRvcGljRXZpZGVuY2VEZXN0aW5hdGlvbk5vdFdvcmtpbmdEZXZp", "Y2VQcm90b1ABWkJnb29nbGUuZ29sYW5nLm9yZy9nZW5wcm90by9nb29nbGVh", "cGlzL2Fkcy9nb29nbGVhZHMvdjcvZW51bXM7ZW51bXOiAgNHQUGqAh1Hb29n", "bGUuQWRzLkdvb2dsZUFkcy5WNy5FbnVtc8oCHUdvb2dsZVxBZHNcR29vZ2xl", "QWRzXFY3XEVudW1z6gIhR29vZ2xlOjpBZHM6Okdvb2dsZUFkczo6Vjc6OkVu", "dW1zYgZwcm90bzM=")); descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, new pbr::FileDescriptor[] { global::Google.Api.AnnotationsReflection.Descriptor, }, new pbr::GeneratedClrTypeInfo(null, null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::Google.Ads.GoogleAds.V7.Enums.PolicyTopicEvidenceDestinationNotWorkingDeviceEnum), global::Google.Ads.GoogleAds.V7.Enums.PolicyTopicEvidenceDestinationNotWorkingDeviceEnum.Parser, null, null, new[]{ typeof(global::Google.Ads.GoogleAds.V7.Enums.PolicyTopicEvidenceDestinationNotWorkingDeviceEnum.Types.PolicyTopicEvidenceDestinationNotWorkingDevice) }, null, null) })); } #endregion } #region Messages /// <summary> /// Container for enum describing possible policy topic evidence destination not /// working devices. /// </summary> public sealed partial class PolicyTopicEvidenceDestinationNotWorkingDeviceEnum : pb::IMessage<PolicyTopicEvidenceDestinationNotWorkingDeviceEnum> #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE , pb::IBufferMessage #endif { private static readonly pb::MessageParser<PolicyTopicEvidenceDestinationNotWorkingDeviceEnum> _parser = new pb::MessageParser<PolicyTopicEvidenceDestinationNotWorkingDeviceEnum>(() => new PolicyTopicEvidenceDestinationNotWorkingDeviceEnum()); private pb::UnknownFieldSet _unknownFields; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<PolicyTopicEvidenceDestinationNotWorkingDeviceEnum> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Ads.GoogleAds.V7.Enums.PolicyTopicEvidenceDestinationNotWorkingDeviceReflection.Descriptor.MessageTypes[0]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public PolicyTopicEvidenceDestinationNotWorkingDeviceEnum() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public PolicyTopicEvidenceDestinationNotWorkingDeviceEnum(PolicyTopicEvidenceDestinationNotWorkingDeviceEnum other) : this() { _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public PolicyTopicEvidenceDestinationNotWorkingDeviceEnum Clone() { return new PolicyTopicEvidenceDestinationNotWorkingDeviceEnum(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as PolicyTopicEvidenceDestinationNotWorkingDeviceEnum); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(PolicyTopicEvidenceDestinationNotWorkingDeviceEnum other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } return Equals(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (_unknownFields != null) { hash ^= _unknownFields.GetHashCode(); } return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE output.WriteRawMessage(this); #else if (_unknownFields != null) { _unknownFields.WriteTo(output); } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { if (_unknownFields != null) { _unknownFields.WriteTo(ref output); } } #endif [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (_unknownFields != null) { size += _unknownFields.CalculateSize(); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(PolicyTopicEvidenceDestinationNotWorkingDeviceEnum other) { if (other == null) { return; } _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE input.ReadRawMessage(this); #else uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); break; } } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); break; } } } #endif #region Nested types /// <summary>Container for nested types declared in the PolicyTopicEvidenceDestinationNotWorkingDeviceEnum message type.</summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static partial class Types { /// <summary> /// The possible policy topic evidence destination not working devices. /// </summary> public enum PolicyTopicEvidenceDestinationNotWorkingDevice { /// <summary> /// No value has been specified. /// </summary> [pbr::OriginalName("UNSPECIFIED")] Unspecified = 0, /// <summary> /// The received value is not known in this version. /// /// This is a response-only value. /// </summary> [pbr::OriginalName("UNKNOWN")] Unknown = 1, /// <summary> /// Landing page doesn't work on desktop device. /// </summary> [pbr::OriginalName("DESKTOP")] Desktop = 2, /// <summary> /// Landing page doesn't work on Android device. /// </summary> [pbr::OriginalName("ANDROID")] Android = 3, /// <summary> /// Landing page doesn't work on iOS device. /// </summary> [pbr::OriginalName("IOS")] Ios = 4, } } #endregion } #endregion } #endregion Designer generated code
40.268398
420
0.719523
[ "Apache-2.0" ]
deni-skaraudio/google-ads-dotnet
src/V7/Types/PolicyTopicEvidenceDestinationNotWorkingDevice.cs
9,302
C#
using Amazon.JSII.Runtime.Deputy; #pragma warning disable CS0672,CS0809,CS1591 namespace aws { [JsiiInterface(nativeType: typeof(IElasticsearchDomainClusterConfigZoneAwarenessConfig), fullyQualifiedName: "aws.ElasticsearchDomainClusterConfigZoneAwarenessConfig")] public interface IElasticsearchDomainClusterConfigZoneAwarenessConfig { [JsiiProperty(name: "availabilityZoneCount", typeJson: "{\"primitive\":\"number\"}", isOptional: true)] [Amazon.JSII.Runtime.Deputy.JsiiOptional] double? AvailabilityZoneCount { get { return null; } } [JsiiTypeProxy(nativeType: typeof(IElasticsearchDomainClusterConfigZoneAwarenessConfig), fullyQualifiedName: "aws.ElasticsearchDomainClusterConfigZoneAwarenessConfig")] internal sealed class _Proxy : DeputyBase, aws.IElasticsearchDomainClusterConfigZoneAwarenessConfig { private _Proxy(ByRefValue reference): base(reference) { } [JsiiOptional] [JsiiProperty(name: "availabilityZoneCount", typeJson: "{\"primitive\":\"number\"}", isOptional: true)] public double? AvailabilityZoneCount { get => GetInstanceProperty<double?>(); } } } }
36.861111
176
0.664657
[ "MIT" ]
scottenriquez/cdktf-alpha-csharp-testing
resources/.gen/aws/aws/IElasticsearchDomainClusterConfigZoneAwarenessConfig.cs
1,327
C#
#region MigraDoc - Creating Documents on the Fly // // Authors: // Stefan Lange (mailto:Stefan.Lange@PdfSharpCore.com) // Klaus Potzesny (mailto:Klaus.Potzesny@PdfSharpCore.com) // David Stephensen (mailto:David.Stephensen@PdfSharpCore.com) // // Copyright (c) 2001-2009 empira Software GmbH, Cologne (Germany) // // http://www.PdfSharpCore.com // http://www.migradoc.com // http://sourceforge.net/projects/pdfsharp // // 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 MigraDocCore.DocumentObjectModel.Internals; using MigraDocCore.DocumentObjectModel.Shapes.Charts; using MigraDocCore.DocumentObjectModel.Tables; using MigraDocCore.DocumentObjectModel.Visitors; using static MigraDocCore.DocumentObjectModel.MigraDoc.DocumentObjectModel.Shapes.ImageSource; namespace MigraDocCore.DocumentObjectModel.Shapes { /// <summary> /// Represents a text frame that can be freely placed. /// </summary> public class TextFrame : Shape, IVisitable { /// <summary> /// Initializes a new instance of the TextFrame class. /// </summary> public TextFrame() { } /// <summary> /// Initializes a new instance of the TextFrame class with the specified parent. /// </summary> internal TextFrame(DocumentObject parent) : base(parent) { } /// <summary> /// Allows the visitor object to visit the document object and it's child objects. /// </summary> void IVisitable.AcceptVisitor(DocumentObjectVisitor visitor, bool visitChildren) { visitor.VisitTextFrame(this); if (visitChildren && elements != null) ((IVisitable) elements).AcceptVisitor(visitor, visitChildren); } #region Methods /// <summary> /// Creates a deep copy of this object. /// </summary> public new TextFrame Clone() { return (TextFrame) DeepCopy(); } /// <summary> /// Implements the deep copy of the object. /// </summary> protected override object DeepCopy() { var textFrame = (TextFrame) base.DeepCopy(); if (textFrame.elements != null) { textFrame.elements = textFrame.elements.Clone(); textFrame.elements.parent = textFrame; } return textFrame; } /// <summary> /// Adds a new paragraph to the text frame. /// </summary> public Paragraph AddParagraph() { return Elements.AddParagraph(); } /// <summary> /// Adds a new paragraph with the specified text to the text frame. /// </summary> public Paragraph AddParagraph(string paragraphText) { return Elements.AddParagraph(paragraphText); } /// <summary> /// Adds a new chart with the specified type to the text frame. /// </summary> public Chart AddChart(ChartType type) { return Elements.AddChart(type); } /// <summary> /// Adds a new chart to the text frame. /// </summary> public Chart AddChart() { return Elements.AddChart(); } /// <summary> /// Adds a new table to the text frame. /// </summary> public Table AddTable() { return Elements.AddTable(); } /// <summary> /// Adds a new Image to the text frame. /// </summary> public Image AddImage(IImageSource imageSource) { return Elements.AddImage(imageSource); } /// <summary> /// Adds a new paragraph to the text frame. /// </summary> public void Add(Paragraph paragraph) { Elements.Add(paragraph); } /// <summary> /// Adds a new chart to the text frame. /// </summary> public void Add(Chart chart) { Elements.Add(chart); } /// <summary> /// Adds a new table to the text frame. /// </summary> public void Add(Table table) { Elements.Add(table); } /// <summary> /// Adds a new image to the text frame. /// </summary> public void Add(Image image) { Elements.Add(image); } #endregion #region Properties /// <summary> /// Gets or sets the Margin between the textframes content and its left edge. /// </summary> public Unit MarginLeft { get => marginLeft; set => marginLeft = value; } [Dv] internal Unit marginLeft = Unit.NullValue; /// <summary> /// Gets or sets the Margin between the textframes content and its right edge. /// </summary> public Unit MarginRight { get => marginRight; set => marginRight = value; } [Dv] internal Unit marginRight = Unit.NullValue; /// <summary> /// Gets or sets the Margin between the textframes content and its top edge. /// </summary> public Unit MarginTop { get => marginTop; set => marginTop = value; } [Dv] internal Unit marginTop = Unit.NullValue; /// <summary> /// Gets or sets the Margin between the textframes content and its bottom edge. /// </summary> public Unit MarginBottom { get => marginBottom; set => marginBottom = value; } [Dv] internal Unit marginBottom = Unit.NullValue; /// <summary> /// Gets or sets the text orientation for the texframe content. /// </summary> public TextOrientation Orientation { get => (TextOrientation) orientation.Value; set => orientation.Value = (int) value; } [Dv(Type = typeof(TextOrientation))] internal NEnum orientation = NEnum.NullValue(typeof(TextOrientation)); /// <summary> /// The document elements that build the textframe's content. /// </summary> public DocumentElements Elements { get { if (elements == null) elements = new DocumentElements(this); return elements; } set { SetParent(value); elements = value; } } [Dv(ItemType = typeof(DocumentObject))] protected DocumentElements elements; #endregion #region Internal /// <summary> /// Converts TextFrame into DDL. /// </summary> internal override void Serialize(Serializer serializer) { serializer.WriteLine("\\textframe"); var pos = serializer.BeginAttributes(); base.Serialize(serializer); if (!marginLeft.IsNull) serializer.WriteSimpleAttribute("MarginLeft", MarginLeft); if (!marginRight.IsNull) serializer.WriteSimpleAttribute("MarginRight", MarginRight); if (!marginTop.IsNull) serializer.WriteSimpleAttribute("MarginTop", MarginTop); if (!marginBottom.IsNull) serializer.WriteSimpleAttribute("MarginBottom", MarginBottom); if (!orientation.IsNull) serializer.WriteSimpleAttribute("Orientation", Orientation); serializer.EndAttributes(pos); serializer.BeginContent(); if (elements != null) elements.Serialize(serializer); serializer.EndContent(); } /// <summary> /// Returns the meta object of this instance. /// </summary> internal override Meta Meta { get { if (_meta == null) _meta = new Meta(typeof(TextFrame)); return _meta; } } private static Meta _meta; #endregion } }
30.607843
115
0.563314
[ "MIT" ]
aavilaco/PdfSharpCore
MigraDocCore.DocumentObjectModel/MigraDoc.DocumentObjectModel.Shapes/TextFrame.cs
9,366
C#
using System.Text; using System; namespace HotChocolate.Language { #if netstandard1_4 [Serializable] #endif public class SyntaxException : Exception { internal SyntaxException(Utf8GraphQLReader reader, string message) : base(message) { Position = reader.Position; Line = reader.Line; Column = reader.Column; SourceText = Encoding.UTF8.GetString(reader.GraphQLData.ToArray()); } internal SyntaxException(LexerState context, string message) : base(message) { Position = context.Position; Line = context.Line; Column = context.Column; SourceText = context.SourceText; } internal SyntaxException(LexerState context, string message, Exception innerException) : base(message, innerException) { Position = context.Position; Line = context.Line; Column = context.Column; SourceText = context.SourceText; } internal SyntaxException(ParserContext context, string message) : base(message) { Position = context.Current.Start; Line = context.Current.Line; Column = context.Current.Column; SourceText = context.Source.Text; } internal SyntaxException( ParserContext context, SyntaxToken token, string message) : base(message) { Position = token.Start; Line = token.Line; Column = token.Column; SourceText = context.Source.Text; } internal SyntaxException( SyntaxToken token, string message) : base(message) { Position = token.Start; Line = token.Line; Column = token.Column; } public int Position { get; } public int Line { get; } public int Column { get; } public string SourceText { get; } } }
28.39726
79
0.555716
[ "MIT" ]
PascalSenn/hotchocolate
src/Core/Language/SyntaxException.cs
2,075
C#
using System.Collections.Generic; using System.Runtime.Serialization; namespace WowSharp.BattleNet.Api.Wow.Community.Wow { /// <summary> /// Represents an achievement /// </summary> [DataContract] public class Achievement : ApiResponse { /// <summary> /// Gets or sets the achievement id /// </summary> [DataMember(Name = "id", IsRequired = true)] public int Id { get; internal set; } /// <summary> /// Gets or sets the achievement title /// </summary> [DataMember(Name = "title", IsRequired = true)] public string Title { get; internal set; } /// <summary> /// Gets or sets the achievement's icon /// </summary> [DataMember(Name = "icon", IsRequired = false)] public string Icon { get; internal set; } /// <summary> /// Gets or sets the achievement points /// </summary> [DataMember(Name = "points", IsRequired = false)] public int Points { get; internal set; } /// <summary> /// Gets or sets the achievement description /// </summary> [DataMember(Name = "description", IsRequired = true)] public string Description { get; internal set; } /// <summary> /// Gets or sets the achievement's reward /// </summary> [DataMember(Name = "reward", IsRequired = false)] public string Reward { get; internal set; } /// <summary> /// Gets or sets the achievement's reward item /// </summary> [DataMember(Name = "rewardItems", IsRequired = false)] public IList<RewardItem> RewardItems { get; internal set; } /// <summary> /// gets or sets Criteria for the achievement /// </summary> [DataMember(Name = "criteria", IsRequired = false)] public IList<AchievementCriterion> Criteria { get; internal set; } /// <summary> /// Gets or sets whether the achievement is account wide /// </summary> [DataMember(Name = "accountWide", IsRequired = false)] public bool AccountWide { get; internal set; } /// <summary> /// Achievement's faction /// </summary> [DataMember(Name = "factionId", IsRequired = true)] public Faction Faction { get; internal set; } /// <summary> /// Gets string representation (for debugging purposes) /// </summary> /// <returns> Gets string representation (for debugging purposes) </returns> public override string ToString() { return Title; } } }
25.347107
84
0.490708
[ "MIT" ]
bitobrian/Blizzard.net-API
WOWSharp.Community/Wow/Achievements/Achievement.cs
3,069
C#
using System.Linq; using Content.Client.Eui; using Content.Shared.Eui; using Content.Shared.Ghost.Roles; using JetBrains.Annotations; namespace Content.Client.Ghost.Roles.UI { [UsedImplicitly] public sealed class GhostRolesEui : BaseEui { private readonly GhostRolesWindow _window; private GhostRoleRulesWindow? _windowRules = null; private uint _windowRulesId = 0; public GhostRolesEui() { _window = new GhostRolesWindow(); _window.OnRoleRequested += info => { if (_windowRules != null) _windowRules.Close(); _windowRules = new GhostRoleRulesWindow(info.Rules, _ => { SendMessage(new GhostRoleTakeoverRequestMessage(info.Identifier)); }); _windowRulesId = info.Identifier; _windowRules.OnClose += () => { _windowRules = null; }; _windowRules.OpenCentered(); }; _window.OnRoleFollow += info => { SendMessage(new GhostRoleFollowRequestMessage(info.Identifier)); }; _window.OnClose += () => { SendMessage(new GhostRoleWindowCloseMessage()); }; } public override void Opened() { base.Opened(); _window.OpenCentered(); } public override void Closed() { base.Closed(); _window.Close(); _windowRules?.Close(); } public override void HandleState(EuiStateBase state) { base.HandleState(state); if (state is not GhostRolesEuiState ghostState) return; _window.ClearEntries(); var groupedRoles = ghostState.GhostRoles.GroupBy( role => (role.Name, role.Description)); foreach (var group in groupedRoles) { var name = group.Key.Name; var description = group.Key.Description; _window.AddEntry(name, description, group); } var closeRulesWindow = ghostState.GhostRoles.All(role => role.Identifier != _windowRulesId); if (closeRulesWindow) { _windowRules?.Close(); } } } }
28.611765
104
0.52426
[ "MIT" ]
14th-Batallion-Marine-Corps/14-Marine-Corps
Content.Client/Ghost/Roles/UI/GhostRolesEui.cs
2,432
C#
using System; using System.Collections.Generic; namespace PDSI.SmarterTrackClient { public partial class StEventProfiles { public int EventProfileId { get; set; } public int? UserId { get; set; } public string Name { get; set; } public bool DoPopup { get; set; } public bool DoEmail { get; set; } public bool DoSms { get; set; } public bool DoMsn { get; set; } public string EmailAddress { get; set; } public string SmsAddress { get; set; } public string MsnAddress { get; set; } public bool IsDefaultProfile { get; set; } public StUsers User { get; set; } } }
29.217391
50
0.602679
[ "MIT" ]
provisiondata/pdsi.mcp.ticketsync
PDSI.SmarterTrackClient/StEventProfiles.cs
674
C#
using ESFA.DAS.ProvideFeedback.Apprentice.Core.Exceptions; using ESFA.DAS.ProvideFeedback.Apprentice.Core.Interfaces; using System.Threading; using System.Threading.Tasks; namespace ESFA.DAS.ProvideFeedback.Apprentice.Services.FeedbackService.Commands.SendSms { public class SendSmsCommandHandlerWithLocking : ICommandHandlerAsync<SendSmsCommand> { private readonly ICommandHandlerAsync<SendSmsCommand> _handler; private readonly IDistributedLockProvider _lockProvider; public SendSmsCommandHandlerWithLocking(ICommandHandlerAsync<SendSmsCommand> handler, IDistributedLockProvider lockProvider) { _handler = handler; _lockProvider = lockProvider; } public void Handle(SendSmsCommand command) { _handler.Handle(command); } public async Task HandleAsync(SendSmsCommand command, CancellationToken cancellationToken = default(CancellationToken)) { await _lockProvider.Start(); try { var conversation = command.Message.Conversation.ToConversation(); var lockId = conversation.Id.ToString(); try { if (!await _lockProvider.AcquireLock(lockId, cancellationToken)) { throw new ConversationLockedException($"A message for conversation {lockId} is already being processed."); } await _handler.HandleAsync(command); } finally { await _lockProvider.ReleaseLock(lockId); } } finally { await _lockProvider.Stop(); } } } }
33.537037
132
0.600773
[ "MIT" ]
SkillsFundingAgency/das-provide-feedback-apprentice
src/Apprentice.Services.FeedbackService/Commands/SendSms/SendSmsCommandHandlerWithLocking.cs
1,813
C#
// This file is auto-generated, don't edit it. Thanks. using System; using System.Collections.Generic; using System.IO; using Tea; namespace AlibabaCloud.SDK.Rds20140815.Models { public class CreateDdrInstanceResponse : TeaModel { [NameInMap("RequestId")] [Validation(Required=true)] public string RequestId { get; set; } [NameInMap("DBInstanceId")] [Validation(Required=true)] public string DBInstanceId { get; set; } [NameInMap("OrderId")] [Validation(Required=true)] public string OrderId { get; set; } [NameInMap("ConnectionString")] [Validation(Required=true)] public string ConnectionString { get; set; } [NameInMap("Port")] [Validation(Required=true)] public string Port { get; set; } } }
23.8
55
0.631453
[ "Apache-2.0" ]
atptro/alibabacloud-sdk
rds-20140815/csharp/core/Models/CreateDdrInstanceResponse.cs
833
C#
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AzureNative.Network.V20200701 { /// <summary> /// Custom IP prefix resource. /// </summary> [AzureNativeResourceType("azure-native:network/v20200701:CustomIPPrefix")] public partial class CustomIPPrefix : Pulumi.CustomResource { /// <summary> /// The prefix range in CIDR notation. Should include the start address and the prefix length. /// </summary> [Output("cidr")] public Output<string?> Cidr { get; private set; } = null!; /// <summary> /// The commissioned state of the Custom IP Prefix. /// </summary> [Output("commissionedState")] public Output<string?> CommissionedState { get; private set; } = null!; /// <summary> /// A unique read-only string that changes whenever the resource is updated. /// </summary> [Output("etag")] public Output<string> Etag { get; private set; } = null!; /// <summary> /// Resource location. /// </summary> [Output("location")] public Output<string?> Location { get; private set; } = null!; /// <summary> /// Resource name. /// </summary> [Output("name")] public Output<string> Name { get; private set; } = null!; /// <summary> /// The provisioning state of the custom IP prefix resource. /// </summary> [Output("provisioningState")] public Output<string> ProvisioningState { get; private set; } = null!; /// <summary> /// The list of all referenced PublicIpPrefixes. /// </summary> [Output("publicIpPrefixes")] public Output<ImmutableArray<Outputs.SubResourceResponse>> PublicIpPrefixes { get; private set; } = null!; /// <summary> /// The resource GUID property of the custom IP prefix resource. /// </summary> [Output("resourceGuid")] public Output<string> ResourceGuid { get; private set; } = null!; /// <summary> /// Resource tags. /// </summary> [Output("tags")] public Output<ImmutableDictionary<string, string>?> Tags { get; private set; } = null!; /// <summary> /// Resource type. /// </summary> [Output("type")] public Output<string> Type { get; private set; } = null!; /// <summary> /// A list of availability zones denoting the IP allocated for the resource needs to come from. /// </summary> [Output("zones")] public Output<ImmutableArray<string>> Zones { get; private set; } = null!; /// <summary> /// Create a CustomIPPrefix resource with the given unique name, arguments, and options. /// </summary> /// /// <param name="name">The unique name of the resource</param> /// <param name="args">The arguments used to populate this resource's properties</param> /// <param name="options">A bag of options that control this resource's behavior</param> public CustomIPPrefix(string name, CustomIPPrefixArgs args, CustomResourceOptions? options = null) : base("azure-native:network/v20200701:CustomIPPrefix", name, args ?? new CustomIPPrefixArgs(), MakeResourceOptions(options, "")) { } private CustomIPPrefix(string name, Input<string> id, CustomResourceOptions? options = null) : base("azure-native:network/v20200701:CustomIPPrefix", name, null, MakeResourceOptions(options, id)) { } private static CustomResourceOptions MakeResourceOptions(CustomResourceOptions? options, Input<string>? id) { var defaultOptions = new CustomResourceOptions { Version = Utilities.Version, Aliases = { new Pulumi.Alias { Type = "azure-nextgen:network/v20200701:CustomIPPrefix"}, new Pulumi.Alias { Type = "azure-native:network:CustomIPPrefix"}, new Pulumi.Alias { Type = "azure-nextgen:network:CustomIPPrefix"}, new Pulumi.Alias { Type = "azure-native:network/v20200601:CustomIPPrefix"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20200601:CustomIPPrefix"}, new Pulumi.Alias { Type = "azure-native:network/v20200801:CustomIPPrefix"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20200801:CustomIPPrefix"}, new Pulumi.Alias { Type = "azure-native:network/v20201101:CustomIPPrefix"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20201101:CustomIPPrefix"}, new Pulumi.Alias { Type = "azure-native:network/v20210201:CustomIPPrefix"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20210201:CustomIPPrefix"}, new Pulumi.Alias { Type = "azure-native:network/v20210301:CustomIPPrefix"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20210301:CustomIPPrefix"}, }, }; var merged = CustomResourceOptions.Merge(defaultOptions, options); // Override the ID if one was specified for consistency with other language SDKs. merged.Id = id ?? merged.Id; return merged; } /// <summary> /// Get an existing CustomIPPrefix resource's state with the given name, ID, and optional extra /// properties used to qualify the lookup. /// </summary> /// /// <param name="name">The unique name of the resulting resource.</param> /// <param name="id">The unique provider ID of the resource to lookup.</param> /// <param name="options">A bag of options that control this resource's behavior</param> public static CustomIPPrefix Get(string name, Input<string> id, CustomResourceOptions? options = null) { return new CustomIPPrefix(name, id, options); } } public sealed class CustomIPPrefixArgs : Pulumi.ResourceArgs { /// <summary> /// The prefix range in CIDR notation. Should include the start address and the prefix length. /// </summary> [Input("cidr")] public Input<string>? Cidr { get; set; } /// <summary> /// The commissioned state of the Custom IP Prefix. /// </summary> [Input("commissionedState")] public InputUnion<string, Pulumi.AzureNative.Network.V20200701.CommissionedState>? CommissionedState { get; set; } /// <summary> /// The name of the custom IP prefix. /// </summary> [Input("customIpPrefixName")] public Input<string>? CustomIpPrefixName { get; set; } /// <summary> /// Resource ID. /// </summary> [Input("id")] public Input<string>? Id { get; set; } /// <summary> /// Resource location. /// </summary> [Input("location")] public Input<string>? Location { get; set; } /// <summary> /// The name of the resource group. /// </summary> [Input("resourceGroupName", required: true)] public Input<string> ResourceGroupName { get; set; } = null!; [Input("tags")] private InputMap<string>? _tags; /// <summary> /// Resource tags. /// </summary> public InputMap<string> Tags { get => _tags ?? (_tags = new InputMap<string>()); set => _tags = value; } [Input("zones")] private InputList<string>? _zones; /// <summary> /// A list of availability zones denoting the IP allocated for the resource needs to come from. /// </summary> public InputList<string> Zones { get => _zones ?? (_zones = new InputList<string>()); set => _zones = value; } public CustomIPPrefixArgs() { } } }
39.67619
141
0.583533
[ "Apache-2.0" ]
polivbr/pulumi-azure-native
sdk/dotnet/Network/V20200701/CustomIPPrefix.cs
8,332
C#
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace Microsoft.DocAsCode.Build.ManagedReference { using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using Microsoft.DocAsCode.Build.Common; using Microsoft.DocAsCode.DataContracts.Common; using Microsoft.DocAsCode.DataContracts.ManagedReference; using Microsoft.DocAsCode.Plugins; public class MergeManagedReferenceDocument : BaseDocumentBuildStep { public override int BuildOrder => 0xff; public override string Name => nameof(MergeManagedReferenceDocument); public override IEnumerable<FileModel> Prebuild(ImmutableList<FileModel> models, IHostService host) { host.LogInfo("Merging platform..."); var processedUid = new HashSet<string>(); var merged = models.RunAll(m => { if (m.Type != DocumentType.Article) { return m; } if (m.Uids.Length == 0) { host.LogWarning("Unknown model without uid.", file: m.File); return m; } var mainUid = m.Uids[0].Name; if (processedUid.Contains(mainUid)) { return null; } var sameTopics = host.LookupByUid(mainUid); if (sameTopics.Count == 1) { return m; } processedUid.Add(mainUid); var vm = (PageViewModel)m.Content; m.Content = MergeCore( mainUid, m, from topic in sameTopics where topic != m where topic.Type == DocumentType.Article select topic, host); return m; }); host.LogInfo("Platform merged."); return from p in merged where p != null select p; } private object MergeCore(string majorUid, FileModel model, IEnumerable<FileModel> others, IHostService host) { var item = CreateMergeItem(majorUid, model, host); if (item == null) { return model.Content; } foreach (var other in others) { var otherItem = CreateMergeItem(majorUid, other, host); if (otherItem == null) { continue; } MergeCore(item, otherItem); } return ConvertToVM(item); } private static MergeItem CreateMergeItem(string majorUid, FileModel model, IHostService host) { var vm = (PageViewModel)model.Content; var majorItem = vm.Items.Find(item => item.Uid == majorUid); if (majorItem == null) { host.LogError("Cannot find uid in model.", file: model.File); return null; } return CreateMergeItemCore(majorItem, vm); } private static MergeItem CreateMergeItemCore(ItemViewModel majorItem, PageViewModel page) { return new MergeItem { MajorItem = majorItem, AssemblyNameList = new SortedSet<string>(majorItem.AssemblyNameList ?? Enumerable.Empty<string>()), Children = new SortedSet<string>(majorItem.Children ?? Enumerable.Empty<string>()), Platform = new SortedSet<string>(majorItem.Platform ?? Enumerable.Empty<string>()), MinorItems = page?.Items.Where(x => x.Uid != majorItem.Uid).ToDictionary(item => item.Uid, item => CreateMergeItemCore(item, null)), References = page?.References.ToDictionary(item => item.Uid), Metadata = page?.Metadata, }; } private void MergeCore(MergeItem item, MergeItem otherItem) { item.AssemblyNameList.UnionWith(otherItem.AssemblyNameList); item.Children.UnionWith(otherItem.Children); item.Platform.UnionWith(otherItem.Platform); MergeMinorItems(item, otherItem); MergeReferences(item, otherItem); } private void MergeMinorItems(MergeItem item, MergeItem otherItem) { if (item.MinorItems != null) { if (otherItem.MinorItems != null) { MergeMinorItemsCore(item.MinorItems, otherItem.MinorItems); } } else if (otherItem.MinorItems != null) { item.MinorItems = otherItem.MinorItems; } } private void MergeMinorItemsCore( Dictionary<string, MergeItem> mergeTo, Dictionary<string, MergeItem> mergeFrom) { foreach (var pair in mergeTo) { MergeItem item; if (mergeFrom.TryGetValue(pair.Key, out item)) { MergeCore(pair.Value, item); mergeFrom.Remove(pair.Key); } } foreach (var pair in mergeFrom) { mergeTo[pair.Key] = pair.Value; } } private void MergeReferences(MergeItem item, MergeItem otherItem) { if (item.References != null) { if (otherItem.References != null) { MergeReferencesCore(item.References, otherItem.References); } } else if (otherItem.References != null) { item.References = otherItem.References; } } private void MergeReferencesCore( Dictionary<string, ReferenceViewModel> mergeTo, Dictionary<string, ReferenceViewModel> mergeFrom) { foreach (var pair in mergeFrom) { if (!mergeTo.ContainsKey(pair.Key)) { mergeTo[pair.Key] = pair.Value; } } } private PageViewModel ConvertToVM(MergeItem mergeItem) { var vm = new PageViewModel { Items = new List<ItemViewModel>(), References = mergeItem.References?.Values.ToList(), Metadata = mergeItem.Metadata, }; ConvertToVMCore(vm, mergeItem); return vm; } private void ConvertToVMCore(PageViewModel vm, MergeItem mergeItem) { if (mergeItem.AssemblyNameList.Count > 0) { mergeItem.MajorItem.AssemblyNameList = mergeItem.AssemblyNameList.ToList(); } if (mergeItem.Children.Count > 0) { mergeItem.MajorItem.Children = mergeItem.Children.ToList(); } if (mergeItem.Platform.Count > 0) { mergeItem.MajorItem.Platform = mergeItem.Platform.ToList(); } vm.Items.Add(mergeItem.MajorItem); if (mergeItem.MinorItems != null) { foreach (var item in mergeItem.MinorItems.Values) { ConvertToVMCore(vm, item); } } } private sealed class MergeItem { public ItemViewModel MajorItem { get; set; } public SortedSet<string> AssemblyNameList { get; set; } public SortedSet<string> Children { get; set; } public SortedSet<string> Platform { get; set; } public Dictionary<string, MergeItem> MinorItems { get; set; } public Dictionary<string, ReferenceViewModel> References { get; set; } public Dictionary<string, object> Metadata { get; set; } } } }
35.526087
148
0.519153
[ "MIT" ]
MorganOBN/KoA-Story
src/Microsoft.DocAsCode.Build.ManagedReference/MergeManagedReferenceDocument.cs
8,173
C#
namespace SimpleDICOMToolkit.Client { using System.Threading.Tasks; public interface IVerifySCU { /// <summary> /// Verify remote SCP /// Send C-ECHO request /// </summary> /// <param name="serverIp">Server IP</param> /// <param name="serverPort">Server Port</param> /// <param name="serverAET">Server AET</param> /// <param name="localAET">Local AET</param> /// <returns>True if success</returns> ValueTask<bool> VerifyAsync(string serverIp, int serverPort, string serverAET, string localAET); } }
31.421053
104
0.60469
[ "MIT" ]
kira-96/dicom-toolkit
src/DicomNetwork/Client/Interfaces/IVerifySCU.cs
599
C#
using System; using System.Collections.Generic; using System.Diagnostics; namespace Tera.Game { // Tera often uses a this tuple of Race, Gender and Class. For example for looking up skills public struct RaceGenderClass { public Race Race { get; private set; } public Gender Gender { get; private set; } public PlayerClass Class { get; private set; } public int Raw { get { if ((byte) Race >= 50 || (byte) Gender >= 2 || (byte) Class >= 100) return 0; //throw new InvalidOperationException(); return 10200 + 200*(int) Race - 100*(int) Gender + (int) Class; } private set { if (value/10000 != 1) throw new ArgumentException($"Unexpected raw value for RaceGenderClass {value}"); Race = (Race) ((value - 100)/200%50); Gender = (Gender) (value/100%2); Class = (PlayerClass) (value%100); Debug.Assert(Raw == value); } } private static T ParseEnum<T>(string s) { return (T) Enum.Parse(typeof(T), s); } public string GameRace => Race == Race.Popori && Gender == Gender.Female ? "Elin" : Race.ToString(); public RaceGenderClass(string race, string gender, string @class) : this() { Race = ParseEnum<Race>(race); Gender = ParseEnum<Gender>(gender); Class = ParseEnum<PlayerClass>(@class); } public RaceGenderClass(Race race, Gender gender, PlayerClass @class) : this() { Race = race; Gender = gender; Class = @class; } public RaceGenderClass(int raw) : this() { Raw = raw; } public IEnumerable<RaceGenderClass> Fallbacks() { yield return this; yield return new RaceGenderClass(Race.Common, Gender.Common, Class); yield return new RaceGenderClass(Race, Gender, PlayerClass.Common); yield return new RaceGenderClass(Race, Gender.Common, PlayerClass.Common); yield return new RaceGenderClass(Race.Common, Gender.Common, PlayerClass.Common); } public override bool Equals(object obj) { if (!(obj is RaceGenderClass)) return false; var other = (RaceGenderClass) obj; return (Race == other.Race) && (Gender == other.Gender) && (Class == other.Class); } public override int GetHashCode() { return (int) Race << 16 | (int) Gender << 8 | (int) Class; } public override string ToString() { return $"{GameRace} {Gender} {Class}"; } } }
32.613636
108
0.528571
[ "MIT" ]
menmaa/ShinraMeter
TeraCommon/Game/RaceGenderClass.cs
2,872
C#
using System; using System.Collections.Generic; namespace p07_PrimesInGivenrange { class p07_PrimesInGivenrange { static void Main(string[] args) { int start = int.Parse(Console.ReadLine()); int end = int.Parse(Console.ReadLine()); var primes = FindPrimesInRange(start, end); for (int i = 0; i < primes.Count; i++) { if (i < primes.Count - 1) { Console.Write(primes[i] + ", "); } else { Console.WriteLine(primes[i]); } } } static bool IsPrime(int number) { if (number < 2) { return false; } for (int i = 2; i <= Math.Sqrt(number); i++) { if (number % i == 0) { return false; } } return true; } static List<int> FindPrimesInRange(int startNum, int endNum) { List<int> primes = new List<int>(); for (int currentNum = startNum; currentNum <= endNum; currentNum++) { bool isPrime = IsPrime(currentNum); if (isPrime) { primes.Add(currentNum); } } return primes; } } }
23.564516
79
0.403833
[ "MIT" ]
Packo0/SoftUniProgrammingFundamentals
exercise/t06_MethodsDebuggingAndTroubleshootingCode/p07_PrimesInGivenrange/p07_PrimesInGivenrange.cs
1,463
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Toggl.Phoebe.Analytics; using Toggl.Phoebe.Data.DataObjects; using Toggl.Phoebe.Data.Utils; using XPlatUtils; namespace Toggl.Phoebe.Data.ViewModels { public interface IOnTagSelectedHandler { void OnCreateNewTag (TagData newTagData); void OnModifyTagList (List<TagData> newTagList); } public class TagListViewModel : IDisposable { // This viewMode is apparently simple but // it needs the code related with the update of // the list. (subscription and reload of data // everytime a tag is changed/created/deleted private readonly Guid workspaceId; private readonly List<Guid> previousSelectedIds; TagListViewModel (Guid workspaceId, List<Guid> previousSelectedIds) { this.previousSelectedIds = previousSelectedIds; this.workspaceId = workspaceId; ServiceContainer.Resolve<ITracker> ().CurrentScreen = "Select Tags"; } public static async Task<TagListViewModel> Init (Guid workspaceId, List<Guid> previousSelectedIds) { var vm = new TagListViewModel (workspaceId, previousSelectedIds); await vm.LoadTagsAsync (); return vm; } public void Dispose () { TagCollection = null; } public ObservableRangeCollection<TagData> TagCollection { get; set; } private async Task LoadTagsAsync () { TagCollection = new ObservableRangeCollection<TagData> (); var store = ServiceContainer.Resolve<IDataStore> (); var workspaceTags = await store.Table<TagData> () .Where (r => r.DeletedAt == null && r.WorkspaceId == workspaceId) .ToListAsync(); var currentSelectedTags = await store.Table<TagData> () .Where (r => r.DeletedAt == null && previousSelectedIds.Contains (r.Id)) .ToListAsync(); // TODO: // There is an strange case, tags are created again across // workspaces. To avoid display similar names // on the list the diff and corrupt data, the filter is done by // names. The bad point is that tags will appears unselected. var diff = currentSelectedTags.Where (sTag => workspaceTags.All (wTag => sTag.Name != wTag.Name)); workspaceTags.AddRange (diff); workspaceTags.Sort ((a, b) => { var aName = a != null ? (a.Name ?? String.Empty) : String.Empty; var bName = b != null ? (b.Name ?? String.Empty) : String.Empty; return String.Compare (aName, bName, StringComparison.Ordinal); }); TagCollection.AddRange (workspaceTags); } } }
35.771084
110
0.599865
[ "BSD-3-Clause" ]
opensourceios/toggle-mobile
Phoebe/Data/ViewModels/TagListViewModel.cs
2,971
C#
using Abp.MultiTenancy; using iMasterEnglishNG.Authorization.Users; namespace iMasterEnglishNG.MultiTenancy { public class Tenant : AbpTenant<User> { public Tenant() { } public Tenant(string tenancyName, string name) : base(tenancyName, name) { } } }
18.777778
54
0.579882
[ "MIT" ]
RenJieJiang/iMasterEnglishNG
aspnet-core/src/iMasterEnglishNG.Core/MultiTenancy/Tenant.cs
340
C#
using System; using System.Data.Entity; using Infrastructure.Services.DataAccess; namespace Infrastructure.DataAccess.Services { public class DatabaseTransaction : IDatabaseTransaction { private readonly DbContextTransaction _transaction; public DatabaseTransaction(DbContextTransaction transaction) { _transaction = transaction ?? throw new ArgumentNullException(nameof(transaction)); } public void Commit() { _transaction.Commit(); } public void Rollback() { _transaction.Rollback(); } public void Dispose() { _transaction?.Dispose(); } } }
22.28125
95
0.617111
[ "MPL-2.0", "MPL-2.0-no-copyleft-exception" ]
Strongminds/kitos
Infrastructure.DataAccess/Services/DatabaseTransaction.cs
715
C#
namespace UniGame.UniNodes.Nodes.Runtime.Commands { using System; using System.Collections; using Cysharp.Threading.Tasks; using UniModules.GameFlow.Runtime.Interfaces; using UniModules.UniCore.Runtime.DataFlow.Interfaces; using UniModules.UniCore.Runtime.Rx.Extensions; using UniModules.UniRoutine.Runtime; using UniModules.UniRoutine.Runtime.Extension; using UniModules.UniGame.Core.Runtime.DataFlow.Interfaces; using UniModules.UniGame.Core.Runtime.Interfaces; using UniRx; [Serializable] public class PortValuePreTransferCommand : ILifeTimeCommand,IContextWriter { private readonly Func<IContext,IMessagePublisher,IEnumerator> action; private readonly IBroadcaster<IMessagePublisher> connector; private readonly IContext sourceContext; private readonly IMessagePublisher target; private RoutineHandle handler; public PortValuePreTransferCommand( Func<IContext,IMessagePublisher,IEnumerator> action, IBroadcaster<IMessagePublisher> connector, IContext sourceContext, IMessagePublisher target) { this.action = action; this.connector = connector; this.sourceContext = sourceContext; this.target = target; } public UniTask Execute(ILifeTime lifeTime) { connector.Broadcast(this). AddTo(lifeTime); lifeTime.AddCleanUpAction(() => handler.Cancel()); return UniTask.CompletedTask; } public void Publish<T>(T message) { handler = OnPublish(message).Execute(); } public bool Remove<TData>() => true; public void CleanUp() {} private IEnumerator OnPublish<T>(T message) { yield return action(sourceContext, target); target.Publish(message); } } }
33.311475
84
0.626476
[ "MIT" ]
Mefodei/UniGameFlow
Runtime/Nodes/Commands/PortValuePreTransferCommand.cs
2,034
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ERP.BLL { public class Class1 { } }
12.166667
33
0.69863
[ "Apache-2.0" ]
sbawani2007/GITest
SimpleERP/ERP.BLL/Class1.cs
148
C#
using System; namespace IntegralEngine.Shading { public class BasicShader : Shader { public BasicShader() : base("Res/Shaders/basicVertex", "Res/Shaders/basicFragment") { } protected override void BindAttributes() { BindAttribute(0,"vPosition"); BindAttribute(1, "vTextCoords"); } protected override void GetUniformLocations() { base.GetUniformLocations(); } } }
21.73913
91
0.56
[ "MIT" ]
iceklue/Integral
IntegralEngine/IntegralEngine/Src/Shading/BasicShader.cs
502
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; using Sirenix.OdinInspector; public class HealthPowerUp : PowerUpBase { public override IEnumerator ExecuteCo() { throw new System.NotImplementedException(); } public override void Use() { CharacterManager.Instance.Player.HealCharacter(); Instantiate(PowerUpDisplayPrefab, CharacterManager.Instance.Player.transform.position, Quaternion.identity, CharacterManager.Instance.Player.transform); Dispose(); } }
23.791667
94
0.707531
[ "MIT" ]
denoboi/KodluyoruzEducationalProject-Final
Assets/Kodluyoruz/Projects/EndlessRunner/Scripts/PowerUps/HealthPowerUp.cs
573
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. using IdentityModel; using IdNet6.Extensions; using System; using System.Collections.Generic; using System.Linq; using System.Security.Cryptography; using System.Text; #pragma warning disable 1591 namespace IdNet6.Validation { public static class ValidatedAuthorizeRequestExtensions { public static void RemovePrompt(this ValidatedAuthorizeRequest request) { request.PromptModes = Enumerable.Empty<string>(); request.Raw.Remove(OidcConstants.AuthorizeRequest.Prompt); } public static string GetPrefixedAcrValue(this ValidatedAuthorizeRequest request, string prefix) { var value = request.AuthenticationContextReferenceClasses .FirstOrDefault(x => x.StartsWith(prefix)); if (value != null) { value = value.Substring(prefix.Length); } return value; } public static void RemovePrefixedAcrValue(this ValidatedAuthorizeRequest request, string prefix) { request.AuthenticationContextReferenceClasses.RemoveAll(acr => acr.StartsWith(prefix, StringComparison.Ordinal)); var acr_values = request.AuthenticationContextReferenceClasses.ToSpaceSeparatedString(); if (acr_values.IsPresent()) { request.Raw[OidcConstants.AuthorizeRequest.AcrValues] = acr_values; } else { request.Raw.Remove(OidcConstants.AuthorizeRequest.AcrValues); } } public static string GetIdP(this ValidatedAuthorizeRequest request) { return request.GetPrefixedAcrValue(Constants.KnownAcrValues.HomeRealm); } public static void RemoveIdP(this ValidatedAuthorizeRequest request) { request.RemovePrefixedAcrValue(Constants.KnownAcrValues.HomeRealm); } public static string GetTenant(this ValidatedAuthorizeRequest request) { return request.GetPrefixedAcrValue(Constants.KnownAcrValues.Tenant); } public static IEnumerable<string> GetAcrValues(this ValidatedAuthorizeRequest request) { return request .AuthenticationContextReferenceClasses .Where(acr => !Constants.KnownAcrValues.All.Any(well_known => acr.StartsWith(well_known))) .Distinct() .ToArray(); } public static void RemoveAcrValue(this ValidatedAuthorizeRequest request, string value) { request.AuthenticationContextReferenceClasses.RemoveAll(x => x.Equals(value, StringComparison.Ordinal)); var acr_values = request.AuthenticationContextReferenceClasses.ToSpaceSeparatedString(); if (acr_values.IsPresent()) { request.Raw[OidcConstants.AuthorizeRequest.AcrValues] = acr_values; } else { request.Raw.Remove(OidcConstants.AuthorizeRequest.AcrValues); } } public static void AddAcrValue(this ValidatedAuthorizeRequest request, string value) { if (String.IsNullOrWhiteSpace(value)) throw new ArgumentNullException(nameof(value)); request.AuthenticationContextReferenceClasses.Add(value); var acr_values = request.AuthenticationContextReferenceClasses.ToSpaceSeparatedString(); request.Raw[OidcConstants.AuthorizeRequest.AcrValues] = acr_values; } public static string GenerateSessionStateValue(this ValidatedAuthorizeRequest request) { if (request == null) return null; if (!request.IsOpenIdRequest) return null; if (request.SessionId == null) return null; if (request.ClientId.IsMissing()) return null; if (request.RedirectUri.IsMissing()) return null; var clientId = request.ClientId; var sessionId = request.SessionId; var salt = CryptoRandom.CreateUniqueId(16, CryptoRandom.OutputFormat.Hex); var uri = new Uri(request.RedirectUri); var origin = uri.Scheme + "://" + uri.Host; if (!uri.IsDefaultPort) { origin += ":" + uri.Port; } var bytes = Encoding.UTF8.GetBytes(clientId + origin + sessionId + salt); byte[] hash; using (var sha = SHA256.Create()) { hash = sha.ComputeHash(bytes); } return Base64Url.Encode(hash) + "." + salt; } } }
36.70229
125
0.630824
[ "Apache-2.0" ]
simple0x47/IdNet6
src/IdNet6/src/Extensions/ValidatedAuthorizeRequestExtensions.cs
4,808
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 application-autoscaling-2016-02-06.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.ApplicationAutoScaling.Model { /// <summary> /// Container for the parameters to the DeleteScheduledAction operation. /// Deletes the specified scheduled action for an Application Auto Scaling scalable target. /// /// /// <para> /// For more information, see <a href="https://docs.aws.amazon.com/autoscaling/application/userguide/scheduled-scaling-additional-cli-commands.html#delete-scheduled-action">Delete /// a scheduled action</a> in the <i>Application Auto Scaling User Guide</i>. /// </para> /// </summary> public partial class DeleteScheduledActionRequest : AmazonApplicationAutoScalingRequest { private string _resourceId; private ScalableDimension _scalableDimension; private string _scheduledActionName; private ServiceNamespace _serviceNamespace; /// <summary> /// Gets and sets the property ResourceId. /// <para> /// The identifier of the resource associated with the scheduled action. This string consists /// of the resource type and unique identifier. /// </para> /// <ul> <li> /// <para> /// ECS service - The resource type is <code>service</code> and the unique identifier /// is the cluster name and service name. Example: <code>service/default/sample-webapp</code>. /// </para> /// </li> <li> /// <para> /// Spot Fleet request - The resource type is <code>spot-fleet-request</code> and the /// unique identifier is the Spot Fleet request ID. Example: <code>spot-fleet-request/sfr-73fbd2ce-aa30-494c-8788-1cee4EXAMPLE</code>. /// </para> /// </li> <li> /// <para> /// EMR cluster - The resource type is <code>instancegroup</code> and the unique identifier /// is the cluster ID and instance group ID. Example: <code>instancegroup/j-2EEZNYKUA1NTV/ig-1791Y4E1L8YI0</code>. /// </para> /// </li> <li> /// <para> /// AppStream 2.0 fleet - The resource type is <code>fleet</code> and the unique identifier /// is the fleet name. Example: <code>fleet/sample-fleet</code>. /// </para> /// </li> <li> /// <para> /// DynamoDB table - The resource type is <code>table</code> and the unique identifier /// is the table name. Example: <code>table/my-table</code>. /// </para> /// </li> <li> /// <para> /// DynamoDB global secondary index - The resource type is <code>index</code> and the /// unique identifier is the index name. Example: <code>table/my-table/index/my-table-index</code>. /// </para> /// </li> <li> /// <para> /// Aurora DB cluster - The resource type is <code>cluster</code> and the unique identifier /// is the cluster name. Example: <code>cluster:my-db-cluster</code>. /// </para> /// </li> <li> /// <para> /// Amazon SageMaker endpoint variant - The resource type is <code>variant</code> and /// the unique identifier is the resource ID. Example: <code>endpoint/my-end-point/variant/KMeansClustering</code>. /// </para> /// </li> <li> /// <para> /// Custom resources are not supported with a resource type. This parameter must specify /// the <code>OutputValue</code> from the CloudFormation template stack used to access /// the resources. The unique identifier is defined by the service provider. More information /// is available in our <a href="https://github.com/aws/aws-auto-scaling-custom-resource">GitHub /// repository</a>. /// </para> /// </li> <li> /// <para> /// Amazon Comprehend document classification endpoint - The resource type and unique /// identifier are specified using the endpoint ARN. Example: <code>arn:aws:comprehend:us-west-2:123456789012:document-classifier-endpoint/EXAMPLE</code>. /// </para> /// </li> <li> /// <para> /// Amazon Comprehend entity recognizer endpoint - The resource type and unique identifier /// are specified using the endpoint ARN. Example: <code>arn:aws:comprehend:us-west-2:123456789012:entity-recognizer-endpoint/EXAMPLE</code>. /// </para> /// </li> <li> /// <para> /// Lambda provisioned concurrency - The resource type is <code>function</code> and the /// unique identifier is the function name with a function version or alias name suffix /// that is not <code>$LATEST</code>. Example: <code>function:my-function:prod</code> /// or <code>function:my-function:1</code>. /// </para> /// </li> <li> /// <para> /// Amazon Keyspaces table - The resource type is <code>table</code> and the unique identifier /// is the table name. Example: <code>keyspace/mykeyspace/table/mytable</code>. /// </para> /// </li> <li> /// <para> /// Amazon MSK cluster - The resource type and unique identifier are specified using the /// cluster ARN. Example: <code>arn:aws:kafka:us-east-1:123456789012:cluster/demo-cluster-1/6357e0b2-0e6a-4b86-a0b4-70df934c2e31-5</code>. /// </para> /// </li> </ul> /// </summary> [AWSProperty(Required=true, Min=1, Max=1600)] public string ResourceId { get { return this._resourceId; } set { this._resourceId = value; } } // Check to see if ResourceId property is set internal bool IsSetResourceId() { return this._resourceId != null; } /// <summary> /// Gets and sets the property ScalableDimension. /// <para> /// The scalable dimension. This string consists of the service namespace, resource type, /// and scaling property. /// </para> /// <ul> <li> /// <para> /// <code>ecs:service:DesiredCount</code> - The desired task count of an ECS service. /// </para> /// </li> <li> /// <para> /// <code>ec2:spot-fleet-request:TargetCapacity</code> - The target capacity of a Spot /// Fleet request. /// </para> /// </li> <li> /// <para> /// <code>elasticmapreduce:instancegroup:InstanceCount</code> - The instance count of /// an EMR Instance Group. /// </para> /// </li> <li> /// <para> /// <code>appstream:fleet:DesiredCapacity</code> - The desired capacity of an AppStream /// 2.0 fleet. /// </para> /// </li> <li> /// <para> /// <code>dynamodb:table:ReadCapacityUnits</code> - The provisioned read capacity for /// a DynamoDB table. /// </para> /// </li> <li> /// <para> /// <code>dynamodb:table:WriteCapacityUnits</code> - The provisioned write capacity for /// a DynamoDB table. /// </para> /// </li> <li> /// <para> /// <code>dynamodb:index:ReadCapacityUnits</code> - The provisioned read capacity for /// a DynamoDB global secondary index. /// </para> /// </li> <li> /// <para> /// <code>dynamodb:index:WriteCapacityUnits</code> - The provisioned write capacity for /// a DynamoDB global secondary index. /// </para> /// </li> <li> /// <para> /// <code>rds:cluster:ReadReplicaCount</code> - The count of Aurora Replicas in an Aurora /// DB cluster. Available for Aurora MySQL-compatible edition and Aurora PostgreSQL-compatible /// edition. /// </para> /// </li> <li> /// <para> /// <code>sagemaker:variant:DesiredInstanceCount</code> - The number of EC2 instances /// for an Amazon SageMaker model endpoint variant. /// </para> /// </li> <li> /// <para> /// <code>custom-resource:ResourceType:Property</code> - The scalable dimension for a /// custom resource provided by your own application or service. /// </para> /// </li> <li> /// <para> /// <code>comprehend:document-classifier-endpoint:DesiredInferenceUnits</code> - The /// number of inference units for an Amazon Comprehend document classification endpoint. /// </para> /// </li> <li> /// <para> /// <code>comprehend:entity-recognizer-endpoint:DesiredInferenceUnits</code> - The number /// of inference units for an Amazon Comprehend entity recognizer endpoint. /// </para> /// </li> <li> /// <para> /// <code>lambda:function:ProvisionedConcurrency</code> - The provisioned concurrency /// for a Lambda function. /// </para> /// </li> <li> /// <para> /// <code>cassandra:table:ReadCapacityUnits</code> - The provisioned read capacity for /// an Amazon Keyspaces table. /// </para> /// </li> <li> /// <para> /// <code>cassandra:table:WriteCapacityUnits</code> - The provisioned write capacity /// for an Amazon Keyspaces table. /// </para> /// </li> <li> /// <para> /// <code>kafka:broker-storage:VolumeSize</code> - The provisioned volume size (in GiB) /// for brokers in an Amazon MSK cluster. /// </para> /// </li> </ul> /// </summary> [AWSProperty(Required=true)] public ScalableDimension ScalableDimension { get { return this._scalableDimension; } set { this._scalableDimension = value; } } // Check to see if ScalableDimension property is set internal bool IsSetScalableDimension() { return this._scalableDimension != null; } /// <summary> /// Gets and sets the property ScheduledActionName. /// <para> /// The name of the scheduled action. /// </para> /// </summary> [AWSProperty(Required=true, Min=1, Max=1600)] public string ScheduledActionName { get { return this._scheduledActionName; } set { this._scheduledActionName = value; } } // Check to see if ScheduledActionName property is set internal bool IsSetScheduledActionName() { return this._scheduledActionName != null; } /// <summary> /// Gets and sets the property ServiceNamespace. /// <para> /// The namespace of the AWS service that provides the resource. For a resource provided /// by your own application or service, use <code>custom-resource</code> instead. /// </para> /// </summary> [AWSProperty(Required=true)] public ServiceNamespace ServiceNamespace { get { return this._serviceNamespace; } set { this._serviceNamespace = value; } } // Check to see if ServiceNamespace property is set internal bool IsSetServiceNamespace() { return this._serviceNamespace != null; } } }
42.113793
183
0.584295
[ "Apache-2.0" ]
ChristopherButtars/aws-sdk-net
sdk/src/Services/ApplicationAutoScaling/Generated/Model/DeleteScheduledActionRequest.cs
12,213
C#
using System; using System.Collections.Generic; using System.Linq; using DotVVM.Framework.ViewModel; using Microsoft.AspNetCore.Mvc.ModelBinding.Metadata; using Swashbuckle.AspNetCore.Swagger; using Swashbuckle.AspNetCore.SwaggerGen; namespace DotVVM.Framework.Api.Swashbuckle.AspNetCore.Filters { public class RemoveBindNoneFromUriParametersOperationFilter : IOperationFilter { public void Apply(Operation operation, OperationFilterContext context) { if (operation.Parameters != null) { foreach (var param in operation.Parameters.ToList()) { var description = context.ApiDescription.ParameterDescriptions.SingleOrDefault(p => p.Name == param.Name); var metadata = description?.ModelMetadata as DefaultModelMetadata; var bindAttribute = metadata?.Attributes.PropertyAttributes?.OfType<BindAttribute>().FirstOrDefault(); if (bindAttribute != null && !bindAttribute.Direction.HasFlag(Direction.ClientToServer)) { operation.Parameters.Remove(param); } } } } } }
39.516129
126
0.641633
[ "Apache-2.0" ]
GerardSmit/dotvvm
src/DotVVM.Framework.Api.Swashbuckle.AspNetCore/Filters/RemoveBindNoneFromUriParametersOperationFilter.cs
1,227
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. using System.Reflection; namespace IdentityServer4.Resources { public static class Scopes { public static string GetString(string name) { return typeof(Scopes).GetField(name)?.GetValue(null)?.ToString(); } public const string address_DisplayName = "Your postal address"; public const string all_claims_DisplayName = "All user information"; public const string email_DisplayName = "Your email address"; public const string offline_access_DisplayName = "Offline access"; public const string openid_DisplayName = "Your user identifier"; public const string phone_DisplayName = "Your phone number"; public const string profile_Description = "Your user profile information(first name, last name, etc.)"; public const string profile_DisplayName = "User profile"; public const string roles_DisplayName = "User roles"; } }
42.961538
111
0.706356
[ "Apache-2.0" ]
ajilantony/identityserver4
src/IdentityServer4/Resources/Scopes.cs
1,119
C#
using System; namespace SolidVehicles.Models { class SpeedBoat { private readonly ILogger _logger = new Logger(); public int MaxSpeedMph { get; } public string Colour { get; set; } public SpeedBoat() { MaxSpeedMph = 60; } public void Sail(Person person, int distance) { _logger.Log($"{person.Name} is sailing a {Colour} speed boat {distance} miles." + Environment.NewLine); } } }
19.086957
109
0.635535
[ "MIT" ]
chrispickford/SolidVehicles
SolidVehicles/Models/SpeedBoat.cs
441
C#
//------------------------------------------------------------------------------ // <auto-generated> // このコードはツールによって生成されました。 // ランタイム バージョン:4.0.30319.42000 // // このファイルへの変更は、以下の状況下で不正な動作の原因になったり、 // コードが再生成されるときに損失したりします。 // </auto-generated> //------------------------------------------------------------------------------ namespace MsgPack.Serialization.GeneratedSerializers { [System.CodeDom.Compiler.GeneratedCodeAttribute("MsgPack.Serialization.CodeDomSerializers.CodeDomSerializerBuilder", "0.9.0.0")] [System.Diagnostics.DebuggerNonUserCodeAttribute()] public class MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Normal_PrimitiveReadOnlyFieldAndConstructorSerializer : MsgPack.Serialization.MessagePackSerializer<MsgPack.Serialization.PolymorphicMemberTypeRuntimeType_Normal_PrimitiveReadOnlyFieldAndConstructor> { private MsgPack.Serialization.MessagePackSerializer<int> _serializer0; private System.Collections.Generic.IList<System.Action<MsgPack.Packer, MsgPack.Serialization.PolymorphicMemberTypeRuntimeType_Normal_PrimitiveReadOnlyFieldAndConstructor>> _packOperationList; private System.Collections.Generic.IDictionary<string, System.Action<MsgPack.Packer, MsgPack.Serialization.PolymorphicMemberTypeRuntimeType_Normal_PrimitiveReadOnlyFieldAndConstructor>> _packOperationTable; private System.Collections.Generic.IDictionary<string, System.Func<MsgPack.Serialization.PolymorphicMemberTypeRuntimeType_Normal_PrimitiveReadOnlyFieldAndConstructor, bool>> _nullCheckersTable; private System.Collections.Generic.IList<System.Func<MsgPack.Packer, MsgPack.Serialization.PolymorphicMemberTypeRuntimeType_Normal_PrimitiveReadOnlyFieldAndConstructor, System.Threading.CancellationToken, System.Threading.Tasks.Task>> _packOperationListAsync; private System.Collections.Generic.IDictionary<string, System.Func<MsgPack.Packer, MsgPack.Serialization.PolymorphicMemberTypeRuntimeType_Normal_PrimitiveReadOnlyFieldAndConstructor, System.Threading.CancellationToken, System.Threading.Tasks.Task>> _packOperationTableAsync; private System.Func<UnpackingContext, MsgPack.Serialization.PolymorphicMemberTypeRuntimeType_Normal_PrimitiveReadOnlyFieldAndConstructor> this_CreateInstanceFromContextDelegate; private System.Action<UnpackingContext, int> this_SetUnpackedValueOfPrimitiveDelegate; private System.Func<MsgPack.Unpacker, System.Type, string, int> MsgPack_Serialization_UnpackHelpers_UnpackInt32ValueDelegate; private System.Collections.Generic.IList<string> _memberNames; private System.Collections.Generic.IList<System.Action<MsgPack.Unpacker, UnpackingContext, int, int>> _unpackOperationList; private System.Collections.Generic.IDictionary<string, System.Action<MsgPack.Unpacker, UnpackingContext, int, int>> _unpackOperationTable; private System.Func<MsgPack.Unpacker, System.Type, string, System.Threading.CancellationToken, System.Threading.Tasks.Task<int>> MsgPack_Serialization_UnpackHelpers_UnpackInt32ValueAsyncDelegate; private System.Collections.Generic.IList<System.Func<MsgPack.Unpacker, UnpackingContext, int, int, System.Threading.CancellationToken, System.Threading.Tasks.Task>> _unpackOperationListAsync; private System.Collections.Generic.IDictionary<string, System.Func<MsgPack.Unpacker, UnpackingContext, int, int, System.Threading.CancellationToken, System.Threading.Tasks.Task>> _unpackOperationTableAsync; public MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Normal_PrimitiveReadOnlyFieldAndConstructorSerializer(MsgPack.Serialization.SerializationContext context) : base(context, (MsgPack.Serialization.SerializerCapabilities.PackTo | MsgPack.Serialization.SerializerCapabilities.UnpackFrom)) { MsgPack.Serialization.PolymorphismSchema schema0 = default(MsgPack.Serialization.PolymorphismSchema); schema0 = null; this._serializer0 = context.GetSerializer<int>(schema0); System.Action<MsgPack.Packer, MsgPack.Serialization.PolymorphicMemberTypeRuntimeType_Normal_PrimitiveReadOnlyFieldAndConstructor>[] packOperationList = default(System.Action<MsgPack.Packer, MsgPack.Serialization.PolymorphicMemberTypeRuntimeType_Normal_PrimitiveReadOnlyFieldAndConstructor>[]); packOperationList = new System.Action<MsgPack.Packer, MsgPack.Serialization.PolymorphicMemberTypeRuntimeType_Normal_PrimitiveReadOnlyFieldAndConstructor>[1]; packOperationList[0] = new System.Action<MsgPack.Packer, MsgPack.Serialization.PolymorphicMemberTypeRuntimeType_Normal_PrimitiveReadOnlyFieldAndConstructor>(this.PackValueOfPrimitive); this._packOperationList = packOperationList; System.Func<MsgPack.Packer, MsgPack.Serialization.PolymorphicMemberTypeRuntimeType_Normal_PrimitiveReadOnlyFieldAndConstructor, System.Threading.CancellationToken, System.Threading.Tasks.Task>[] packOperationListAsync = default(System.Func<MsgPack.Packer, MsgPack.Serialization.PolymorphicMemberTypeRuntimeType_Normal_PrimitiveReadOnlyFieldAndConstructor, System.Threading.CancellationToken, System.Threading.Tasks.Task>[]); packOperationListAsync = new System.Func<MsgPack.Packer, MsgPack.Serialization.PolymorphicMemberTypeRuntimeType_Normal_PrimitiveReadOnlyFieldAndConstructor, System.Threading.CancellationToken, System.Threading.Tasks.Task>[1]; packOperationListAsync[0] = new System.Func<MsgPack.Packer, MsgPack.Serialization.PolymorphicMemberTypeRuntimeType_Normal_PrimitiveReadOnlyFieldAndConstructor, System.Threading.CancellationToken, System.Threading.Tasks.Task>(this.PackValueOfPrimitiveAsync); this._packOperationListAsync = packOperationListAsync; System.Collections.Generic.Dictionary<string, System.Action<MsgPack.Packer, MsgPack.Serialization.PolymorphicMemberTypeRuntimeType_Normal_PrimitiveReadOnlyFieldAndConstructor>> packOperationTable = default(System.Collections.Generic.Dictionary<string, System.Action<MsgPack.Packer, MsgPack.Serialization.PolymorphicMemberTypeRuntimeType_Normal_PrimitiveReadOnlyFieldAndConstructor>>); packOperationTable = new System.Collections.Generic.Dictionary<string, System.Action<MsgPack.Packer, MsgPack.Serialization.PolymorphicMemberTypeRuntimeType_Normal_PrimitiveReadOnlyFieldAndConstructor>>(1); packOperationTable["Primitive"] = new System.Action<MsgPack.Packer, MsgPack.Serialization.PolymorphicMemberTypeRuntimeType_Normal_PrimitiveReadOnlyFieldAndConstructor>(this.PackValueOfPrimitive); this._packOperationTable = packOperationTable; System.Collections.Generic.Dictionary<string, System.Func<MsgPack.Packer, MsgPack.Serialization.PolymorphicMemberTypeRuntimeType_Normal_PrimitiveReadOnlyFieldAndConstructor, System.Threading.CancellationToken, System.Threading.Tasks.Task>> packOperationTableAsync = default(System.Collections.Generic.Dictionary<string, System.Func<MsgPack.Packer, MsgPack.Serialization.PolymorphicMemberTypeRuntimeType_Normal_PrimitiveReadOnlyFieldAndConstructor, System.Threading.CancellationToken, System.Threading.Tasks.Task>>); packOperationTableAsync = new System.Collections.Generic.Dictionary<string, System.Func<MsgPack.Packer, MsgPack.Serialization.PolymorphicMemberTypeRuntimeType_Normal_PrimitiveReadOnlyFieldAndConstructor, System.Threading.CancellationToken, System.Threading.Tasks.Task>>(1); packOperationTableAsync["Primitive"] = new System.Func<MsgPack.Packer, MsgPack.Serialization.PolymorphicMemberTypeRuntimeType_Normal_PrimitiveReadOnlyFieldAndConstructor, System.Threading.CancellationToken, System.Threading.Tasks.Task>(this.PackValueOfPrimitiveAsync); this._packOperationTableAsync = packOperationTableAsync; System.Collections.Generic.Dictionary<string, System.Func<MsgPack.Serialization.PolymorphicMemberTypeRuntimeType_Normal_PrimitiveReadOnlyFieldAndConstructor, bool>> nullCheckerTable = default(System.Collections.Generic.Dictionary<string, System.Func<MsgPack.Serialization.PolymorphicMemberTypeRuntimeType_Normal_PrimitiveReadOnlyFieldAndConstructor, bool>>); nullCheckerTable = new System.Collections.Generic.Dictionary<string, System.Func<MsgPack.Serialization.PolymorphicMemberTypeRuntimeType_Normal_PrimitiveReadOnlyFieldAndConstructor, bool>>(0); this._nullCheckersTable = nullCheckerTable; System.Action<MsgPack.Unpacker, UnpackingContext, int, int>[] unpackOperationList = default(System.Action<MsgPack.Unpacker, UnpackingContext, int, int>[]); unpackOperationList = new System.Action<MsgPack.Unpacker, UnpackingContext, int, int>[1]; unpackOperationList[0] = new System.Action<MsgPack.Unpacker, UnpackingContext, int, int>(this.UnpackValueOfPrimitive); this._unpackOperationList = unpackOperationList; System.Func<MsgPack.Unpacker, UnpackingContext, int, int, System.Threading.CancellationToken, System.Threading.Tasks.Task>[] unpackOperationListAsync = default(System.Func<MsgPack.Unpacker, UnpackingContext, int, int, System.Threading.CancellationToken, System.Threading.Tasks.Task>[]); unpackOperationListAsync = new System.Func<MsgPack.Unpacker, UnpackingContext, int, int, System.Threading.CancellationToken, System.Threading.Tasks.Task>[1]; unpackOperationListAsync[0] = new System.Func<MsgPack.Unpacker, UnpackingContext, int, int, System.Threading.CancellationToken, System.Threading.Tasks.Task>(this.UnpackValueOfPrimitiveAsync); this._unpackOperationListAsync = unpackOperationListAsync; System.Collections.Generic.Dictionary<string, System.Action<MsgPack.Unpacker, UnpackingContext, int, int>> unpackOperationTable = default(System.Collections.Generic.Dictionary<string, System.Action<MsgPack.Unpacker, UnpackingContext, int, int>>); unpackOperationTable = new System.Collections.Generic.Dictionary<string, System.Action<MsgPack.Unpacker, UnpackingContext, int, int>>(1); unpackOperationTable["Primitive"] = new System.Action<MsgPack.Unpacker, UnpackingContext, int, int>(this.UnpackValueOfPrimitive); this._unpackOperationTable = unpackOperationTable; System.Collections.Generic.Dictionary<string, System.Func<MsgPack.Unpacker, UnpackingContext, int, int, System.Threading.CancellationToken, System.Threading.Tasks.Task>> unpackOperationTableAsync = default(System.Collections.Generic.Dictionary<string, System.Func<MsgPack.Unpacker, UnpackingContext, int, int, System.Threading.CancellationToken, System.Threading.Tasks.Task>>); unpackOperationTableAsync = new System.Collections.Generic.Dictionary<string, System.Func<MsgPack.Unpacker, UnpackingContext, int, int, System.Threading.CancellationToken, System.Threading.Tasks.Task>>(1); unpackOperationTableAsync["Primitive"] = new System.Func<MsgPack.Unpacker, UnpackingContext, int, int, System.Threading.CancellationToken, System.Threading.Tasks.Task>(this.UnpackValueOfPrimitiveAsync); this._unpackOperationTableAsync = unpackOperationTableAsync; this._memberNames = new string[] { "Primitive"}; this.this_CreateInstanceFromContextDelegate = new System.Func<UnpackingContext, MsgPack.Serialization.PolymorphicMemberTypeRuntimeType_Normal_PrimitiveReadOnlyFieldAndConstructor>(this.CreateInstanceFromContext); this.this_SetUnpackedValueOfPrimitiveDelegate = new System.Action<UnpackingContext, int>(this.SetUnpackedValueOfPrimitive); this.MsgPack_Serialization_UnpackHelpers_UnpackInt32ValueDelegate = new System.Func<MsgPack.Unpacker, System.Type, string, int>(MsgPack.Serialization.UnpackHelpers.UnpackInt32Value); this.MsgPack_Serialization_UnpackHelpers_UnpackInt32ValueAsyncDelegate = new System.Func<MsgPack.Unpacker, System.Type, string, System.Threading.CancellationToken, System.Threading.Tasks.Task<int>>(MsgPack.Serialization.UnpackHelpers.UnpackInt32ValueAsync); } private void PackValueOfPrimitive(MsgPack.Packer packer, MsgPack.Serialization.PolymorphicMemberTypeRuntimeType_Normal_PrimitiveReadOnlyFieldAndConstructor objectTree) { this._serializer0.PackTo(packer, objectTree.Primitive); } protected internal override void PackToCore(MsgPack.Packer packer, MsgPack.Serialization.PolymorphicMemberTypeRuntimeType_Normal_PrimitiveReadOnlyFieldAndConstructor objectTree) { MsgPack.Serialization.PackToArrayParameters<MsgPack.Serialization.PolymorphicMemberTypeRuntimeType_Normal_PrimitiveReadOnlyFieldAndConstructor> packHelperParameters = default(MsgPack.Serialization.PackToArrayParameters<MsgPack.Serialization.PolymorphicMemberTypeRuntimeType_Normal_PrimitiveReadOnlyFieldAndConstructor>); packHelperParameters.Packer = packer; packHelperParameters.Target = objectTree; packHelperParameters.Operations = this._packOperationList; MsgPack.Serialization.PackToMapParameters<MsgPack.Serialization.PolymorphicMemberTypeRuntimeType_Normal_PrimitiveReadOnlyFieldAndConstructor> packHelperParameters0 = default(MsgPack.Serialization.PackToMapParameters<MsgPack.Serialization.PolymorphicMemberTypeRuntimeType_Normal_PrimitiveReadOnlyFieldAndConstructor>); packHelperParameters0.Packer = packer; packHelperParameters0.Target = objectTree; packHelperParameters0.Operations = this._packOperationTable; packHelperParameters0.SerializationContext = this.OwnerContext; packHelperParameters0.NullCheckers = this._nullCheckersTable; if ((this.OwnerContext.SerializationMethod == MsgPack.Serialization.SerializationMethod.Array)) { MsgPack.Serialization.PackHelpers.PackToArray(ref packHelperParameters); } else { MsgPack.Serialization.PackHelpers.PackToMap(ref packHelperParameters0); } } private System.Threading.Tasks.Task PackValueOfPrimitiveAsync(MsgPack.Packer packer, MsgPack.Serialization.PolymorphicMemberTypeRuntimeType_Normal_PrimitiveReadOnlyFieldAndConstructor objectTree, System.Threading.CancellationToken cancellationToken) { return this._serializer0.PackToAsync(packer, objectTree.Primitive, cancellationToken); } protected internal override System.Threading.Tasks.Task PackToAsyncCore(MsgPack.Packer packer, MsgPack.Serialization.PolymorphicMemberTypeRuntimeType_Normal_PrimitiveReadOnlyFieldAndConstructor objectTree, System.Threading.CancellationToken cancellationToken) { MsgPack.Serialization.PackToArrayAsyncParameters<MsgPack.Serialization.PolymorphicMemberTypeRuntimeType_Normal_PrimitiveReadOnlyFieldAndConstructor> packHelperParameters = default(MsgPack.Serialization.PackToArrayAsyncParameters<MsgPack.Serialization.PolymorphicMemberTypeRuntimeType_Normal_PrimitiveReadOnlyFieldAndConstructor>); packHelperParameters.Packer = packer; packHelperParameters.Target = objectTree; packHelperParameters.Operations = this._packOperationListAsync; packHelperParameters.CancellationToken = cancellationToken; MsgPack.Serialization.PackToMapAsyncParameters<MsgPack.Serialization.PolymorphicMemberTypeRuntimeType_Normal_PrimitiveReadOnlyFieldAndConstructor> packHelperParameters0 = default(MsgPack.Serialization.PackToMapAsyncParameters<MsgPack.Serialization.PolymorphicMemberTypeRuntimeType_Normal_PrimitiveReadOnlyFieldAndConstructor>); packHelperParameters0.Packer = packer; packHelperParameters0.Target = objectTree; packHelperParameters0.Operations = this._packOperationTableAsync; packHelperParameters0.SerializationContext = this.OwnerContext; packHelperParameters0.NullCheckers = this._nullCheckersTable; packHelperParameters0.CancellationToken = cancellationToken; if ((this.OwnerContext.SerializationMethod == MsgPack.Serialization.SerializationMethod.Array)) { return MsgPack.Serialization.PackHelpers.PackToArrayAsync(ref packHelperParameters); } else { return MsgPack.Serialization.PackHelpers.PackToMapAsync(ref packHelperParameters0); } } private MsgPack.Serialization.PolymorphicMemberTypeRuntimeType_Normal_PrimitiveReadOnlyFieldAndConstructor CreateInstanceFromContext(UnpackingContext unpackingContext) { MsgPack.Serialization.PolymorphicMemberTypeRuntimeType_Normal_PrimitiveReadOnlyFieldAndConstructor result = default(MsgPack.Serialization.PolymorphicMemberTypeRuntimeType_Normal_PrimitiveReadOnlyFieldAndConstructor); result = new MsgPack.Serialization.PolymorphicMemberTypeRuntimeType_Normal_PrimitiveReadOnlyFieldAndConstructor(unpackingContext.Primitive); return result; } private void SetUnpackedValueOfPrimitive(UnpackingContext unpackingContext, int unpackedValue) { unpackingContext.Primitive = unpackedValue; } private void UnpackValueOfPrimitive(MsgPack.Unpacker unpacker, UnpackingContext unpackingContext, int indexOfItem, int itemsCount) { MsgPack.Serialization.UnpackValueTypeValueParameters<UnpackingContext, int> unpackHelperParameters = default(MsgPack.Serialization.UnpackValueTypeValueParameters<UnpackingContext, int>); unpackHelperParameters.Unpacker = unpacker; unpackHelperParameters.UnpackingContext = unpackingContext; unpackHelperParameters.Serializer = this._serializer0; unpackHelperParameters.ItemsCount = itemsCount; unpackHelperParameters.Unpacked = indexOfItem; unpackHelperParameters.TargetObjectType = typeof(int); unpackHelperParameters.MemberName = "Primitive"; unpackHelperParameters.DirectRead = this.MsgPack_Serialization_UnpackHelpers_UnpackInt32ValueDelegate; unpackHelperParameters.Setter = this.this_SetUnpackedValueOfPrimitiveDelegate; MsgPack.Serialization.UnpackHelpers.UnpackValueTypeValue(ref unpackHelperParameters); } protected internal override MsgPack.Serialization.PolymorphicMemberTypeRuntimeType_Normal_PrimitiveReadOnlyFieldAndConstructor UnpackFromCore(MsgPack.Unpacker unpacker) { UnpackingContext unpackingContext = default(UnpackingContext); int ctorArg0 = default(int); ctorArg0 = 0; unpackingContext = new UnpackingContext(ctorArg0); if (unpacker.IsArrayHeader) { return MsgPack.Serialization.UnpackHelpers.UnpackFromArray(unpacker, unpackingContext, this.this_CreateInstanceFromContextDelegate, this._memberNames, this._unpackOperationList); } else { return MsgPack.Serialization.UnpackHelpers.UnpackFromMap(unpacker, unpackingContext, this.this_CreateInstanceFromContextDelegate, this._unpackOperationTable); } } private System.Threading.Tasks.Task UnpackValueOfPrimitiveAsync(MsgPack.Unpacker unpacker, UnpackingContext unpackingContext, int indexOfItem, int itemsCount, System.Threading.CancellationToken cancellationToken) { MsgPack.Serialization.UnpackValueTypeValueAsyncParameters<UnpackingContext, int> unpackHelperParameters = default(MsgPack.Serialization.UnpackValueTypeValueAsyncParameters<UnpackingContext, int>); unpackHelperParameters.Unpacker = unpacker; unpackHelperParameters.UnpackingContext = unpackingContext; unpackHelperParameters.Serializer = this._serializer0; unpackHelperParameters.ItemsCount = itemsCount; unpackHelperParameters.Unpacked = indexOfItem; unpackHelperParameters.TargetObjectType = typeof(int); unpackHelperParameters.MemberName = "Primitive"; unpackHelperParameters.DirectRead = this.MsgPack_Serialization_UnpackHelpers_UnpackInt32ValueAsyncDelegate; unpackHelperParameters.Setter = this.this_SetUnpackedValueOfPrimitiveDelegate; unpackHelperParameters.CancellationToken = cancellationToken; return MsgPack.Serialization.UnpackHelpers.UnpackValueTypeValueAsync(ref unpackHelperParameters); } protected internal override System.Threading.Tasks.Task<MsgPack.Serialization.PolymorphicMemberTypeRuntimeType_Normal_PrimitiveReadOnlyFieldAndConstructor> UnpackFromAsyncCore(MsgPack.Unpacker unpacker, System.Threading.CancellationToken cancellationToken) { UnpackingContext unpackingContext = default(UnpackingContext); int ctorArg0 = default(int); ctorArg0 = 0; unpackingContext = new UnpackingContext(ctorArg0); if (unpacker.IsArrayHeader) { return MsgPack.Serialization.UnpackHelpers.UnpackFromArrayAsync(unpacker, unpackingContext, this.this_CreateInstanceFromContextDelegate, this._memberNames, this._unpackOperationListAsync, cancellationToken); } else { return MsgPack.Serialization.UnpackHelpers.UnpackFromMapAsync(unpacker, unpackingContext, this.this_CreateInstanceFromContextDelegate, this._unpackOperationTableAsync, cancellationToken); } } public class UnpackingContext { public int Primitive; public UnpackingContext(int Primitive) { this.Primitive = Primitive; } } } }
99.817352
527
0.783989
[ "Apache-2.0" ]
KKL1982/msgpack-cli
test/MsgPack.UnitTest/gen/MsgPack_Serialization_PolymorphicMemberTypeRuntimeType_Normal_PrimitiveReadOnlyFieldAndConstructorSerializer.cs
22,034
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace _03.LastKNumbersSums { class LastKNumbersSums { static List<long> sequence = new List<long>(); static void AddToSequence(int numOfPrevious) { if(sequence.Count < numOfPrevious) { long sum = 0; foreach(long num in sequence) { sum += num; } sequence.Add(sum); } else { long sum = 0; for(int i = sequence.Count-1; i >= sequence.Count-numOfPrevious; i--) { sum += sequence[i]; } sequence.Add(sum); } } static void Main(string[] args) { int n = int.Parse(Console.ReadLine()); int k = int.Parse(Console.ReadLine()); sequence.Add(1); for(int i = 0; sequence.Count < n; i++) { AddToSequence(k); } foreach(long num in sequence) { Console.Write(num + " "); } } } }
23.072727
85
0.432624
[ "MIT" ]
MustafaAmish/All-Curses-in-SoftUni
02. Tech Module/Programming Fundamentals/13. Arrays/Arrays - Lab/03.LastKNumbersSums/LastKNumbersSums.cs
1,271
C#
using ServiceStack.DataAnnotations; namespace AptTool.Security { [Alias("package_notes")] public class PackageNotes { [Alias("id")] public int Id { get; set; } [Alias("bug_name")] public string BugName { get; set; } [Alias("package")] public string Package { get; set; } [Alias("fixed_version")] public string FixedVersion { get; set; } [Alias("fixed_version_id")] public int? FixedVersionId { get; set; } [Alias("release")] public string Release { get; set; } [Alias("package_kind")] public string PackageKind { get; set; } [Alias("urgency")] public string Urgency { get; set; } } }
24.71875
48
0.523388
[ "MIT" ]
adfernandes/apt-tool
src/AptTool/Security/PackageNotes.cs
791
C#
using System; using System.Collections.Generic; namespace Tauron.Application.Files.VirtualFiles.Core { public abstract class DirectoryBase<TInfo> : FileSystemNodeBase<TInfo>, IDirectory where TInfo : class { protected DirectoryBase(Func<IDirectory?> parentDirectory, string originalPath, string name) : base(parentDirectory, originalPath, name) { } public abstract IDirectory GetDirectory(string name); public abstract IEnumerable<IDirectory> Directories { get; } public abstract IEnumerable<IFile> Files { get; } public abstract IFile GetFile(string name); public abstract IDirectory MoveTo(string location); } }
37.052632
106
0.708807
[ "MIT" ]
augustoproiete-bot/Project-Manager-Akka
Tauron.Application.Files/VirtualFiles/Core/DirectoryBase.cs
706
C#
public interface IReader { string ReadLine(); }
7.714286
24
0.666667
[ "MIT" ]
Divelina/OOP_DependencyInjection
Contracts/IReader.cs
54
C#
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Threading.Tasks; namespace Sloth.Models.AccountViewModels { public class VerifyCodeViewModel { [Required] public string Provider { get; set; } [Required] public string Code { get; set; } public string ReturnUrl { get; set; } [Display(Name = "Remember this browser?")] public bool RememberBrowser { get; set; } [Display(Name = "Remember me?")] public bool RememberMe { get; set; } } }
23.038462
50
0.644407
[ "MIT" ]
simonmoreau/Sloth
Sloth/Models/AccountViewModels/VerifyCodeViewModel.cs
601
C#
using System; using System.Collections.Generic; using System.Linq; using MathParserNet.Exceptions; namespace MathParserNet { public delegate T Func<T, U> (U arg1); public delegate T Func<T, U, V> (U arg1, V arg2); public delegate T Func<T, U, V, W> (U arg1, V arg2, W arg3); public delegate T Func<T, U, V, W, X> (U arg1, V arg2, W arg3, X arg4); public delegate T Func<T, U, V, W, X, Y> (U arg1, V arg2, W arg3, X arg4, Y arg5); public class Parser { private readonly Queue<NumberClass> _outputQueue; private readonly Stack<string> _operatorStack; private readonly Dictionary<string, NumberClass> _variables; private readonly List<FunctionClass> _functions; private readonly Dictionary<string, Delegate> _customFunctions; public enum RoundingMethods { Round, RoundUp, RoundDown, Truncate } public Parser() { _outputQueue = new Queue<NumberClass>(); _operatorStack = new Stack<string>(); _variables = new Dictionary<string, NumberClass>(); _functions = new List<FunctionClass>(); _customFunctions = new Dictionary<string, Delegate>(); } public void UnregisterCustomFunction(string functionName) { try { _customFunctions.Remove(functionName); } catch (Exception) { throw new NoSuchFunctionException(); } } public void UnregisterAllCustomFunctions() { _customFunctions.Clear(); } public void RegisterCustomFunction(string functionName, Func<object, object> method) { _customFunctions.Add(functionName, method); } public void RegisterCustomFunction(string functionName, Func<object, object, object> method) { _customFunctions.Add(functionName, method); } public void RegisterCustomFunction(string functionName, Func<object, object, object, object> method) { _customFunctions.Add(functionName, method); } public void RegisterCustomFunction(string functionName, Func<object, object, object, object, object> method) { _customFunctions.Add(functionName, method); } public void RegisterCustomIntegerFunction(string functionName, Func<int, int> method) { _customFunctions.Add(functionName, method); } public void RegisterCustomIntegerFunction(string functionName, Func<int, int, int> method) { _customFunctions.Add(functionName, method); } public void RegisterCustomIntegerFunction(string functionName, Func<int, int, int, int> method) { _customFunctions.Add(functionName, method); } public void RegisterCustomIntegerFunction(string functionName, Func<int, int, int, int, int> method) { _customFunctions.Add(functionName, method); } public void RegisterCustomDoubleFunction(string functionName, Func<double, double> method) { _customFunctions.Add(functionName, method); } public void RegisterCustomDoubleFunction(string functionName, Func<double, double, double> method) { _customFunctions.Add(functionName, method); } public void RegisterCustomDoubleFunction(string functionName, Func<double, double, double, double> method) { _customFunctions.Add(functionName, method); } public void RegisterCustomDoubleFunction(string functionName, Func<double, double, double, double, double> method) { _customFunctions.Add(functionName, method); } public void RemoveFunction(string functionName) { bool found = false; foreach(var _f in _functions) { if(_f.Name.Equals(functionName)) { found = true; break; } } if (found) { int ndx = 0; while (ndx < _functions.Count) { if (_functions[ndx].Name.Equals(functionName)) break; ndx++; } _functions.RemoveAt(ndx); return; } throw new NoSuchFunctionException(StringResources.No_such_function_defined + ": " + functionName); } public void AddFunction(string functionName, FunctionArgumentList argList, string expression) { var fc = new FunctionClass { Arguments = argList, Expression = expression, Name = functionName }; var numClass = new NumberClass { NumberType = NumberClass.NumberTypes.Expression, Expression = expression }; EvaluateFunction(numClass, fc); _functions.Add(fc); } public void RemoveAllVariables() { _variables.Clear(); } public void RemoveAllFunctions() { _functions.Clear(); } public void Reset() { RemoveAllFunctions(); RemoveAllVariables(); UnregisterAllCustomFunctions(); } public void RemoveVariable(string varName) { if (_variables.ContainsKey(varName)) { _variables.Remove(varName); return; } throw new Exception(StringResources.Undefined_Variable + ": " + varName); } private void AddVariable(string varName, NumberClass valueType) { if (_variables.ContainsKey(varName)) { throw new VariableAlreadyDefinedException(StringResources.Variable_already_defined + ": " + varName); } if (valueType.NumberType == NumberClass.NumberTypes.Expression) { SimplificationReturnValue eeVal; eeVal = EvaluateExpression(valueType); if (eeVal.ReturnType == SimplificationReturnValue.ReturnTypes.Float) { AddVariable(varName, eeVal.DoubleValue); return; } if (eeVal.ReturnType == SimplificationReturnValue.ReturnTypes.Integer) { AddVariable(varName, eeVal.IntValue); return; } } _variables.Add(varName, valueType); } public void AddVariable(string varName, string value) { var nc = new NumberClass { NumberType = NumberClass.NumberTypes.Expression, Expression = value }; AddVariable(varName, nc); } public void AddVariable(string varName, double value) { var nc = new NumberClass { NumberType = NumberClass.NumberTypes.Float, FloatNumber = value }; AddVariable(varName, nc); } public void AddVariable(string varName, int value) { var nc = new NumberClass { NumberType = NumberClass.NumberTypes.Integer, IntNumber = value }; AddVariable(varName, nc); } private void EvaluateFunction(NumberClass expression, FunctionClass fc) { EvaluateFunction(expression, fc, new List<NumberClass> { new NumberClass {NumberType = NumberClass.NumberTypes.Integer, IntNumber = 0}}); } private SimplificationReturnValue EvaluateFunction(NumberClass expression, FunctionClass fc, IEnumerable<NumberClass> ncList2) { var parser = new Parser(); var ncList = new List<NumberClass>(ncList2); foreach (var cfr in _customFunctions) parser.AddCustomFunction(cfr.Key, cfr.Value); foreach (var v in _variables) { if (v.Value.NumberType == NumberClass.NumberTypes.Float) { parser.AddVariable(v.Key, v.Value.FloatNumber); } if (v.Value.NumberType == NumberClass.NumberTypes.Integer) { parser.AddVariable(v.Key, v.Value.IntNumber); } if (v.Value.NumberType == NumberClass.NumberTypes.Expression) { parser.AddVariable(v.Key, v.Value.Expression); } } foreach (var f in _functions) { parser.AddFunction(f.Name, f.Arguments, f.Expression); } int ndx = 0; foreach (var a in fc.Arguments) { NumberClass nc = ndx >= ncList.Count ? new NumberClass { NumberType = NumberClass.NumberTypes.Integer, IntNumber = 0 } : ncList[ndx]; if (nc.NumberType == NumberClass.NumberTypes.Float) { try { parser.AddVariable(a, nc.FloatNumber); } catch {} } if (nc.NumberType == NumberClass.NumberTypes.Integer) { try { parser.AddVariable(a, nc.IntNumber); }catch { } } if (nc.NumberType == NumberClass.NumberTypes.Expression) parser.AddVariable(a, nc.Expression); ndx++; } return parser.Simplify(expression.Expression); } protected void AddCustomFunction(string s, Delegate d) { _customFunctions.Add(s, d); } private SimplificationReturnValue EvaluateExpression(NumberClass expression) { var parser = new Parser(); foreach (var cfh in _customFunctions) parser.AddCustomFunction(cfh.Key,cfh.Value); foreach (var v in _variables) { if (v.Value.NumberType == NumberClass.NumberTypes.Float) { parser.AddVariable(v.Key, v.Value.FloatNumber); } if (v.Value.NumberType == NumberClass.NumberTypes.Integer) { parser.AddVariable(v.Key, v.Value.IntNumber); } if (v.Value.NumberType == NumberClass.NumberTypes.Expression) { parser.AddVariable(v.Key, v.Value.Expression); } } foreach (var f in _functions) { parser.AddFunction(f.Name, f.Arguments, f.Expression); } return parser.Simplify(expression.Expression); } public object SimplifyObject(string equation) { var retval = Simplify(equation); if (retval.ReturnType == SimplificationReturnValue.ReturnTypes.Integer) return retval.IntValue; return retval.DoubleValue; } public int SimplifyInt(string equation, RoundingMethods roundMethod) { SimplificationReturnValue retval = Simplify(equation); if (retval.ReturnType == SimplificationReturnValue.ReturnTypes.Integer) return retval.IntValue; if (roundMethod == RoundingMethods.RoundDown) return (int)Math.Floor(retval.DoubleValue); if (roundMethod == RoundingMethods.RoundUp) return (int)Math.Ceiling(retval.DoubleValue); if (roundMethod == RoundingMethods.Round) return (int)Math.Round(retval.DoubleValue); return (int)Math.Truncate(retval.DoubleValue); } public int SimplifyInt(string equation) { return SimplifyInt(equation, RoundingMethods.Round); } public double SimplifyDouble(string equation) { SimplificationReturnValue retval = Simplify(equation); if (retval.ReturnType == SimplificationReturnValue.ReturnTypes.Float) return retval.DoubleValue; return double.Parse(retval.IntValue.ToString()); } public SimplificationReturnValue Simplify(string equation) { var retval = new SimplificationReturnValue { OriginalEquation = equation }; if (equation.Trim().StartsWith("-") || equation.Trim().StartsWith("+")) equation = "0" + equation; equation = equation.Replace("(+", "(0+"); equation = equation.Replace("(-", "(0-"); equation = equation.Replace("( +", "( 0+"); equation = equation.Replace("( -", "( 0-"); equation = equation.Replace(",-", ",0-"); equation = equation.Replace(", -", ", 0-"); equation = equation.Replace(",+", ",0+"); equation = equation.Replace(", +", ", 0+"); var tp = new TokenParser(); foreach (var cf in _customFunctions) { tp.RegisterCustomFunction(cf.Key); } tp.InputString = equation; Token token = tp.GetToken(); _operatorStack.Clear(); _outputQueue.Clear(); while (token != null) { if (token.TokenName == TokenParser.Tokens.Sqrt) { string expression = token.TokenValue.Substring(4, token.TokenValue.Length - 4); SimplificationReturnValue rv = EvaluateExpression(new NumberClass { Expression = expression, NumberType = NumberClass.NumberTypes.Expression }); token.TokenName = TokenParser.Tokens.Float; switch (rv.ReturnType) { case SimplificationReturnValue.ReturnTypes.Integer: token.TokenValue = Math.Sqrt(rv.IntValue).ToString(); break; case SimplificationReturnValue.ReturnTypes.Float: token.TokenValue = Math.Sqrt(rv.DoubleValue).ToString(); break; } } if (token.TokenName == TokenParser.Tokens.Sin) { string expression = token.TokenValue.Substring(3, token.TokenValue.Length - 3); SimplificationReturnValue rv = EvaluateExpression(new NumberClass { Expression = expression, NumberType = NumberClass.NumberTypes.Expression }); token.TokenName = TokenParser.Tokens.Float; switch (rv.ReturnType) { case SimplificationReturnValue.ReturnTypes.Integer: token.TokenValue = Math.Sin(rv.IntValue).ToString(); break; case SimplificationReturnValue.ReturnTypes.Float: token.TokenValue = Math.Sin(rv.DoubleValue).ToString(); break; } } if (token.TokenName == TokenParser.Tokens.Log) { string expression = token.TokenValue.Substring(3, token.TokenValue.Length - 3); SimplificationReturnValue rv = EvaluateExpression(new NumberClass { Expression = expression, NumberType = NumberClass.NumberTypes.Expression }); token.TokenName = TokenParser.Tokens.Float; switch (rv.ReturnType) { case SimplificationReturnValue.ReturnTypes.Integer: token.TokenValue = Math.Log(rv.IntValue, 10).ToString(); break; case SimplificationReturnValue.ReturnTypes.Float: token.TokenValue = Math.Log(rv.DoubleValue, 10).ToString(); break; } } if (token.TokenName == TokenParser.Tokens.LogN) { string expression = token.TokenValue.Substring(4, token.TokenValue.Length - 4); SimplificationReturnValue rv = EvaluateExpression(new NumberClass { Expression = expression, NumberType = NumberClass.NumberTypes.Expression }); token.TokenName = TokenParser.Tokens.Float; switch (rv.ReturnType) { case SimplificationReturnValue.ReturnTypes.Integer: token.TokenValue = Math.Log(rv.IntValue).ToString(); break; case SimplificationReturnValue.ReturnTypes.Float: token.TokenValue = Math.Log(rv.DoubleValue).ToString(); break; } } if (token.TokenName == TokenParser.Tokens.Tan) { string expression = token.TokenValue.Substring(3, token.TokenValue.Length - 3); var rv = EvaluateExpression(new NumberClass { Expression = expression, NumberType = NumberClass.NumberTypes.Expression }); token.TokenName = TokenParser.Tokens.Float; switch (rv.ReturnType) { case SimplificationReturnValue.ReturnTypes.Integer: token.TokenValue = Math.Tan(rv.IntValue).ToString(); break; case SimplificationReturnValue.ReturnTypes.Float: token.TokenValue = Math.Tan(rv.DoubleValue).ToString(); break; } } if (token.TokenName == TokenParser.Tokens.Abs) { string expression = token.TokenValue.Substring(3, token.TokenValue.Length - 3); var rv = EvaluateExpression(new NumberClass { Expression = expression, NumberType = NumberClass.NumberTypes.Expression }); token.TokenName = TokenParser.Tokens.Float; switch (rv.ReturnType) { case SimplificationReturnValue.ReturnTypes.Integer: token.TokenValue = Math.Abs(rv.IntValue).ToString(); break; case SimplificationReturnValue.ReturnTypes.Float: token.TokenValue = Math.Abs(rv.DoubleValue).ToString(); break; } } if (token.TokenName == TokenParser.Tokens.Cos) { string expression = token.TokenValue.Substring(3, token.TokenValue.Length - 3); var rv = EvaluateExpression(new NumberClass { Expression = expression, NumberType = NumberClass.NumberTypes.Expression }); token.TokenName = TokenParser.Tokens.Float; switch (rv.ReturnType) { case SimplificationReturnValue.ReturnTypes.Integer: token.TokenValue = Math.Cos(rv.IntValue).ToString(); break; case SimplificationReturnValue.ReturnTypes.Float: token.TokenValue = Math.Cos(rv.DoubleValue).ToString(); break; } } if ((int)token.TokenName >= 100) { int ndx1 = token.TokenValue.IndexOf("("); string fn = token.TokenValue.Substring(0, ndx1); string origExpression = token.TokenValue.Substring(ndx1); string[] expressions = origExpression.Replace(",", "),(").Split(','); bool found = false; foreach(var _f in _customFunctions) { if(_f.Key.Equals(fn)) { found = true; break; } } if (found) { foreach (var ff in _customFunctions) { if (ff.Key.Equals(fn)) { var p = new Parser(); foreach (var cfr in _customFunctions) p.AddCustomFunction(cfr.Key, cfr.Value); foreach (var vr in _variables) p.AddVariable(vr.Key, vr.Value); foreach (var vf in _functions) p.AddFunction(vf.Name, vf.Arguments, vf.Expression); var ex = new SimplificationReturnValue[expressions.Length]; for(var i = 0; i < expressions.Length; i++) { ex[i] = p.Simplify(expressions[i]); } object funcRetval = null; if (ff.Value.Method.ReturnType == typeof(int)) { var intParams = new object[ex.Length]; int ndx = 0; foreach (var pp in ex) { if (pp.ReturnType == SimplificationReturnValue.ReturnTypes.Float) intParams[ndx] = (int)pp.DoubleValue; if (pp.ReturnType == SimplificationReturnValue.ReturnTypes.Integer) intParams[ndx] = pp.IntValue; ndx++; } funcRetval = ff.Value.DynamicInvoke(intParams); } if (ff.Value.Method.ReturnType == typeof(double)) { var floatParams = new object[ex.Length]; int ndx = 0; foreach (var pp in ex) { if (pp.ReturnType == SimplificationReturnValue.ReturnTypes.Float) floatParams[ndx] = pp.DoubleValue; if (pp.ReturnType == SimplificationReturnValue.ReturnTypes.Integer) floatParams[ndx] = pp.IntValue; ndx++; } funcRetval = ff.Value.DynamicInvoke(floatParams); } if (ff.Value.Method.ReturnType==typeof(object)) { var ex2 = new SimplificationReturnValue[expressions.Length]; for(var i = 0; i < ex2.Length; i++) ex2[i] = p.Simplify(expressions[i]); funcRetval = ff.Value.DynamicInvoke(ex2); } //object funcRetval = ff.Value.DynamicInvoke(expressions.Select(p.Simplify).ToArray()); if (funcRetval is double) { token.TokenValue = ((double)funcRetval).ToString(); token.TokenName = TokenParser.Tokens.Float; } if (funcRetval is int) { token.TokenValue = ((int)funcRetval).ToString(); token.TokenName = TokenParser.Tokens.Integer; } if (funcRetval is SimplificationReturnValue) { var srv = (SimplificationReturnValue)funcRetval; if (srv.ReturnType == SimplificationReturnValue.ReturnTypes.Integer) { token.TokenValue = srv.IntValue.ToString(); token.TokenName = TokenParser.Tokens.Integer; } if (srv.ReturnType == SimplificationReturnValue.ReturnTypes.Float) { token.TokenValue = srv.DoubleValue.ToString(); token.TokenName = TokenParser.Tokens.Float; } } break; } } } if (!found) { throw new NoSuchFunctionException(StringResources.No_such_function_defined + ": " + fn); } } if (token.TokenName == TokenParser.Tokens.Function) { int ndx1 = token.TokenValue.IndexOf("("); string fn = token.TokenValue.Substring(0, ndx1).Remove(0, 4); string origExpression = token.TokenValue.Substring(ndx1); string[] expressions = origExpression.Replace(",", "),(").Split(','); bool found = false; FunctionClass fun = null; foreach(var _f in _functions) { if(_f.Name.Equals(fn)) { found = true; break; } } if (found) { foreach (var ff in _functions) if (ff.Name.Equals(fn)) fun = ff; } if (!found) { throw new NoSuchFunctionException(StringResources.No_such_function_defined + ": " + fn); } var parser = new Parser(); foreach (var cfh in _customFunctions) parser.AddCustomFunction(cfh.Key, cfh.Value); foreach (var v in _variables) { if (v.Value.NumberType == NumberClass.NumberTypes.Float) { parser.AddVariable(v.Key, v.Value.FloatNumber); } if (v.Value.NumberType == NumberClass.NumberTypes.Integer) { parser.AddVariable(v.Key, v.Value.IntNumber); } if (v.Value.NumberType == NumberClass.NumberTypes.Expression) { parser.AddVariable(v.Key, v.Value.Expression); } } foreach (var f in _functions) { parser.AddFunction(f.Name, f.Arguments, f.Expression); } var expressionList = new List<NumberClass>(); foreach (var expression in expressions) { SimplificationReturnValue simRetval = parser.Simplify(expression); var numClass = new NumberClass(); if (simRetval.ReturnType == SimplificationReturnValue.ReturnTypes.Float) { numClass.FloatNumber = simRetval.DoubleValue; numClass.NumberType = NumberClass.NumberTypes.Float; } if (simRetval.ReturnType == SimplificationReturnValue.ReturnTypes.Integer) { numClass.IntNumber = simRetval.IntValue; numClass.NumberType = NumberClass.NumberTypes.Integer; } expressionList.Add(numClass); } if (fun != null) { var numClass = new NumberClass { NumberType = NumberClass.NumberTypes.Expression, Expression = fun.Expression }; SimplificationReturnValue sretval = parser.EvaluateFunction(numClass, fun, expressionList); if (sretval != null && sretval.ReturnType == SimplificationReturnValue.ReturnTypes.Integer) { token.TokenName = TokenParser.Tokens.Integer; token.TokenValue = sretval.IntValue.ToString(); } if (sretval != null && sretval.ReturnType == SimplificationReturnValue.ReturnTypes.Float) { token.TokenName = TokenParser.Tokens.Float; token.TokenValue = sretval.DoubleValue.ToString(); } } } if (token.TokenName == TokenParser.Tokens.Variable) { if (_variables.ContainsKey(token.TokenValue)) { var z = _variables[token.TokenValue]; if (z.NumberType == NumberClass.NumberTypes.Float) { token.TokenName = TokenParser.Tokens.Float; token.TokenValue = z.FloatNumber.ToString(); } else if (z.NumberType == NumberClass.NumberTypes.Integer) { token.TokenName = TokenParser.Tokens.Integer; token.TokenValue = z.IntNumber.ToString(); } } else { throw new NoSuchVariableException(StringResources.Undefined_Variable + ": " + token.TokenValue); } } if (token.TokenName == TokenParser.Tokens.Whitespace || token.TokenName == TokenParser.Tokens.Newline) { token = tp.GetToken(); continue; } if (token.TokenName == TokenParser.Tokens.Integer || token.TokenName == TokenParser.Tokens.Float) { var nc = new NumberClass(); switch (token.TokenName) { case TokenParser.Tokens.Float: nc.NumberType = NumberClass.NumberTypes.Float; nc.FloatNumber = double.Parse(token.TokenValue); break; case TokenParser.Tokens.Integer: nc.NumberType = NumberClass.NumberTypes.Integer; nc.IntNumber = int.Parse(token.TokenValue); break; } _outputQueue.Enqueue(nc); } if (IsOperator(token.TokenName)) { if (_operatorStack.Count > 0) { while (_operatorStack.Count > 0) { var op = _operatorStack.Peek(); //o2 if (op == "(" || op == ")") break; if ((GetPrecedence(token.TokenName) <= GetPrecedence(op) && IsLeftAssociative(token.TokenValue)) || !IsLeftAssociative(token.TokenValue) && GetPrecedence(token.TokenName) < GetPrecedence(op)) { op = _operatorStack.Pop(); var nc = new NumberClass { NumberType = NumberClass.NumberTypes.Operator, Operator = op }; _outputQueue.Enqueue(nc); } else break; } } _operatorStack.Push(token.TokenValue); } if (token.TokenName == TokenParser.Tokens.Lparen) _operatorStack.Push(token.TokenValue); if (token.TokenName == TokenParser.Tokens.Rparen) { if (_operatorStack.Count > 0) { var op = _operatorStack.Pop(); while (op != "(") { var nc = new NumberClass { Operator = op, NumberType = NumberClass.NumberTypes.Operator }; _outputQueue.Enqueue(nc); if (_operatorStack.Count > 0) op = _operatorStack.Pop(); else { throw new MismatchedParenthesisException(); } } } else { throw new MismatchedParenthesisException(); } } token = tp.GetToken(); } while (_operatorStack.Count > 0) { var op = _operatorStack.Pop(); if (op == "(" || op == ")") { throw new MismatchedParenthesisException(); } var nc = new NumberClass { NumberType = NumberClass.NumberTypes.Operator, Operator = op }; _outputQueue.Enqueue(nc); } bool floatAnswer = false; bool slashAnswer = false; foreach(var v in _outputQueue) { if(v.NumberType == NumberClass.NumberTypes.Float) { floatAnswer = true; } if(v.Operator == "/") { slashAnswer = true; } } if (floatAnswer || slashAnswer) { var dblStack = new Stack<double>(); foreach (var nc in _outputQueue) { if (nc.NumberType == NumberClass.NumberTypes.Integer) dblStack.Push(nc.IntNumber); if (nc.NumberType == NumberClass.NumberTypes.Float) dblStack.Push(nc.FloatNumber); if (nc.NumberType == NumberClass.NumberTypes.Operator) { double val = DoMath(nc.Operator, dblStack.Pop(), dblStack.Pop()); dblStack.Push(val); } } if (dblStack.Count == 0) throw new CouldNotParseExpressionException(); retval.DoubleValue = dblStack.Pop(); retval.ReturnType = SimplificationReturnValue.ReturnTypes.Float; } else { var intStack = new Stack<int>(); foreach (var nc in _outputQueue) { if (nc.NumberType == NumberClass.NumberTypes.Integer) intStack.Push(nc.IntNumber); if (nc.NumberType == NumberClass.NumberTypes.Float) intStack.Push((int)nc.FloatNumber); if (nc.NumberType == NumberClass.NumberTypes.Operator) { int val = DoMath(nc.Operator, intStack.Pop(), intStack.Pop()); intStack.Push(val); } } if (intStack.Count == 0) throw new CouldNotParseExpressionException(); retval.IntValue = intStack.Pop(); retval.ReturnType = SimplificationReturnValue.ReturnTypes.Integer; } return retval; } private static double DoMath(string op, double val1, double val2) { if (op == "*") return val1 * val2; if (op == "/") return val2 / val1; if (op == "+") return val1 + val2; if (op == "-") return val2 - val1; if (op == "%") return val2 % val1; if (op == "^") return Math.Pow(val2, val1); return 0f; } private static int DoMath(string op, int val1, int val2) { if (op == "*") return val1 * val2; if (op == "/") return val2 / val1; if (op == "+") return val1 + val2; if (op == "-") return val2 - val1; if (op == "%") return val2 % val1; if (op == "^") return (int)Math.Pow(val2, val1); return 0; } private static bool IsLeftAssociative(string op) { return op == "*" || op == "+" || op == "-" || op == "/" || op == "%"; } private static int GetPrecedence(TokenParser.Tokens token) { if (token == TokenParser.Tokens.Add || token == TokenParser.Tokens.Subtract) return 1; if (token == TokenParser.Tokens.Multiply || token == TokenParser.Tokens.Divide || token == TokenParser.Tokens.Modulus) return 2; if (token == TokenParser.Tokens.Exponent) return 3; if (token == TokenParser.Tokens.Lparen || token == TokenParser.Tokens.Rparen) return 4; return 0; } private static int GetPrecedence(string op) { if (op.Equals("+") || op.Equals("-")) return 1; if (op.Equals("*") || op.Equals("/") || op.Equals("%")) return 2; if (op.Equals("^")) return 3; if (op.Equals("(") || op.Equals(")")) return 4; return 0; } private static bool IsOperator(TokenParser.Tokens token) { return token == TokenParser.Tokens.Add || token == TokenParser.Tokens.Divide || token == TokenParser.Tokens.Exponent || token == TokenParser.Tokens.Modulus || token == TokenParser.Tokens.Multiply || token == TokenParser.Tokens.Subtract; } private class FunctionClass { public string Expression { get; set; } public string Name { get; set; } public FunctionArgumentList Arguments { get; set; } } private class NumberClass { public enum NumberTypes { Float, Integer, Operator, Expression } public NumberTypes NumberType { get; set; } public int IntNumber { get; set; } public double FloatNumber { get; set; } public string Operator { get; set; } public string Expression { get; set; } } } }
37.22973
136
0.453721
[ "BSD-3-Clause" ]
FlorianRappl/YAMP
YAMP.Core.Comparison/MathParserNet/Parser.cs
41,327
C#
// using System.Collections; // using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; public class MenuController : MonoBehaviour { [Header("Settings")] public string newgame = "NewGame"; public void StartGame(){ SceneManager.LoadScene(newgame); } public void OpenOptions(){ } public void CloseOption(){ } public void OpenCredits(){ } public void CloseCredits(){ } public void LoadScene(int sceneIndex){ SceneManager.LoadScene(sceneIndex); } public void QuitGame(){ Application.Quit(); } }
15.081081
45
0.724014
[ "MIT" ]
concat1911/UnityDefaultStyle
Assets/Scripts/_MENU/MenuController.cs
560
C#
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Data.SqlClient; using System.Configuration; using System.Data; namespace MyWebsite { public partial class YourCart : System.Web.UI.Page { SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["conString"].ToString()); protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { imguser1.Src = Session["pic"].ToString(); imguser2.Src = imguser1.Src; imguser3.Src = imguser1.Src; imguser4.Src = imguser1.Src; imguser5.Src = imguser1.Src; } SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["conString"].ToString()); con.Open(); string notessold = "0"; string notesuploaded = "0"; string notesbought = "0"; string cart = "0"; SqlCommand cmd1 = new SqlCommand(@"select count(*) from tbl_seller where username='" + Session["username"].ToString() + "'", con); int x = (int)cmd1.ExecuteScalar(); notesuploaded = x.ToString(); if (x != 0) { SqlCommand cmd2 = new SqlCommand(@"select count(*) from tbl_seller where username='" + Session["username"].ToString() + "' and sold is not null", con); int y = (int)cmd2.ExecuteScalar(); notessold = y.ToString(); } SqlCommand cmd3 = new SqlCommand(@"select count(*) from tbl_buyer where buyer_username='" + Session["username"].ToString() + "'", con); int z = (int)cmd3.ExecuteScalar(); notesbought = z.ToString(); SqlCommand cmd4 = new SqlCommand(@"select count(*) from tbl_cart where cart_username='" + Session["username"].ToString() + "'", con); int z1 = (int)cmd4.ExecuteScalar(); cart = z1.ToString(); Session["cart"] = cart.ToString(); lblnotesup.Text = notesuploaded; lblnotessold.Text = notessold; lblnotesbought.Text = notesbought; lblnotescart.Text = cart; con.Close(); BindData(); } protected void BindData() { con.Open(); SqlCommand cmd = new SqlCommand(@"select ppath,cart_id,ipath,note_id,title,author,price from tbl_cart where cart_username='" + Session["username"].ToString() + "'", con); SqlDataAdapter sda = new SqlDataAdapter(cmd); DataTable dt = new DataTable(); sda.Fill(dt); GridView1.DataSource = dt; GridView1.DataBind(); for (int i = 0; i < GridView1.Rows.Count; i++) { string ppath = dt.Rows[i][0].ToString(); HyperLink lnk = ((HyperLink)GridView1.Rows[i].FindControl("hyplnk")); lnk.NavigateUrl = ppath; System.Web.UI.WebControls.Image img = ((System.Web.UI.WebControls.Image)GridView1.Rows[i].FindControl("imgnote")); img.ImageUrl = dt.Rows[i][2].ToString(); } con.Close(); } protected void RemoveItem(object sender, EventArgs e) { con.Open(); LinkButton lnkRemove = (LinkButton)sender; string CART_ID = lnkRemove.CommandArgument.ToString(); SqlCommand cmd = new SqlCommand(@"delete from tbl_cart where cart_username='" + Session["username"].ToString() + "' and cart_id='"+CART_ID+"'", con); cmd.ExecuteNonQuery(); con.Close(); Page.ClientScript.RegisterClientScriptBlock(typeof(Page), "Alert", "alert('RECORD DELETED SUCCESSFULLY!')", true); BindData(); } protected void GridView1_SelectedIndexChanged(object sender, EventArgs e) { } protected void btnNote_Click(object sender, EventArgs e) { Response.Redirect("NewDAshBoard.aspx", false); } protected void btnNote1_Click(object sender, EventArgs e) { Response.Redirect("NewDAshBoard.aspx", false); } } }
40.698113
182
0.571164
[ "Apache-2.0", "MIT" ]
sabika19/AdhereCode
MyWebsite/MyWebsite/YourCart.aspx.cs
4,316
C#
namespace XQ.SDK.Enum { /// <summary> /// 图片消息的来源 /// </summary> public enum ImageMessageType { /// <summary> /// 来自文件 /// </summary> FromFile = 0, /// <summary> /// 来自Url /// </summary> FromWebUrl = 1, /// <summary> /// 来自收到的消息 /// </summary> FromMessage = 2 } }
17.478261
32
0.385572
[ "Apache-2.0" ]
Awbugl/XQCSharpSDK
XQ.SDK/Enum/ImageMessageType.cs
444
C#