content
stringlengths
5
1.04M
avg_line_length
float64
1.75
12.9k
max_line_length
int64
2
244k
alphanum_fraction
float64
0
0.98
licenses
list
repository_name
stringlengths
7
92
path
stringlengths
3
249
size
int64
5
1.04M
lang
stringclasses
2 values
using System; using System.Collections.Generic; using System.Configuration; using System.Data; using System.Linq; using System.Windows; namespace WpfToolkitChart { /// <summary> /// Interaction logic for App.xaml /// </summary> public partial class App : Application { } }
16.882353
40
0.724739
[ "Apache-2.0" ]
anh123minh/DES
WpfToolkitChart/WpfToolkitChart/App.xaml.cs
289
C#
using Microsoft.EntityFrameworkCore.Migrations; namespace ShoppingApprovalSystem.Migrations { public partial class Upgrade_ABP_381 : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.AlterColumn<string>( name: "LoginProvider", table: "AbpUserTokens", maxLength: 128, nullable: true, oldClrType: typeof(string), oldMaxLength: 64, oldNullable: true); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.AlterColumn<string>( name: "LoginProvider", table: "AbpUserTokens", maxLength: 64, nullable: true, oldClrType: typeof(string), oldMaxLength: 128, oldNullable: true); } } }
30
71
0.545833
[ "MIT" ]
AlanLang/ShoppingApprovalSystem
aspnet-core/src/ShoppingApprovalSystem.EntityFrameworkCore/Migrations/20180731132139_Upgrade_ABP_3.8.1.cs
962
C#
using System; using System.Collections.Generic; using Smooth.Collections; namespace Smooth.Comparisons { /// <summary> /// Allocation free sort order comparer for type T where T implements IComparable<T>. /// /// Only useful to circumvent potential JIT exceptions on platforms without JIT compilation. /// </summary> public class IComparableComparer<T> : Smooth.Collections.Comparer<T> where T : IComparable<T> { public override int Compare(T l, T r) { return l.CompareTo(r); } } }
29.352941
96
0.731463
[ "Apache-2.0" ]
AndroFARsh/BoidsExperiment
Assets/Plugins/Smooth/Foundations/Comparisons/IComparableComparer.cs
501
C#
using IntcodeInterpreter.Enums; using System.Collections.Generic; namespace IntcodeInterpreter.Instructions { internal class Add : InstructionBase { public Add(long parameters) : base(Instruction.Add, 4) { NounMode = (Mode)(parameters % 10); VerbMode = (Mode)((parameters / 10) % 10); ResultMode = (Mode)((parameters / 100) % 10); } internal Mode NounMode { get; private set; } internal Mode VerbMode { get; private set; } internal Mode ResultMode { get; private set; } internal override long? Execute(Dictionary<long, long> program, long instructionIndex, long relativeBase, long? input) { SetValue( program, ResultMode, instructionIndex + 3, relativeBase, GetValue(program, NounMode, instructionIndex + 1, relativeBase) + GetValue(program, VerbMode, instructionIndex + 2, relativeBase) ); return null; } } }
32.181818
145
0.578154
[ "MIT" ]
sowiszcze/AdventOfCode2019
IntcodeInterpreter/Instructions/Add.cs
1,064
C#
using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Windows; // アセンブリに関する一般情報は以下の属性セットをとおして制御されます。 // アセンブリに関連付けられている情報を変更するには、 // これらの属性値を変更してください。 [assembly: AssemblyTitle("GUIComponent")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("GUIComponent")] [assembly: AssemblyCopyright("Copyright © 2011")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // ComVisible を false に設定すると、その型はこのアセンブリ内で COM コンポーネントから // 参照不可能になります。COM からこのアセンブリ内の型にアクセスする場合は、 // その型の ComVisible 属性を true に設定してください。 [assembly: ComVisible(false)] //ローカライズ可能なアプリケーションのビルドを開始するには、 //.csproj ファイルの <UICulture>CultureYouAreCodingWith</UICulture> を //<PropertyGroup> 内部で設定します。たとえば、 //ソース ファイルで英語を使用している場合、<UICulture> を en-US に設定します。次に、 //下の NeutralResourceLanguage 属性のコメントを解除します。下の行の "en-US" を //プロジェクト ファイルの UICulture 設定と一致するよう更新します。 //[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)] [assembly: ThemeInfo( ResourceDictionaryLocation.None, //テーマ固有のリソース ディクショナリが置かれている場所 //(リソースがページ、 //またはアプリケーション リソース ディクショナリに見つからない場合に使用されます) ResourceDictionaryLocation.SourceAssembly //汎用リソース ディクショナリが置かれている場所 //(リソースがページ、 //アプリケーション、またはいずれのテーマ固有のリソース ディクショナリにも見つからない場合に使用されます) )] // アセンブリのバージョン情報は、以下の 4 つの値で構成されています: // // Major Version // Minor Version // Build Number // Revision // // すべての値を指定するか、下のように '*' を使ってビルドおよびリビジョン番号を // 既定値にすることができます: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
31.589286
92
0.742227
[ "BSD-2-Clause" ]
zoetrope/ReactiveRTM
Sample/GUIComponent/Properties/AssemblyInfo.cs
2,804
C#
using System.Collections.Generic; using System.Globalization; using System.Xml.Serialization; #region dynamo using Autodesk.DesignScript.Runtime; #endregion namespace FemDesign.Loads { [IsVisibleInDynamoLibrary(false)] public partial class LoadCase: EntityBase { /// <summary> /// Creates a load case. /// </summary> /// <remarks>Create</remarks> /// <param name="name">Name of LoadCase.</param> /// <param name="type">LoadCase type. "static"/"dead_load"/"soil_dead_load"/"shrinkage"/"prestressing"/"fire"/"seis_sxp"/"seis_sxm"/"seis_syp"/"seis_sym"</param> /// <param name="durationClass">LoadCase duration class. "permanent"/"long-term"/"medium-term"/"short-term"/"instantaneous"</param> /// <returns></returns> [IsVisibleInDynamoLibrary(true)] public static LoadCase CreateLoadCase(string name, string type = "static", string durationClass = "permanent") { LoadCaseType _type = FemDesign.GenericClasses.EnumParser.Parse<LoadCaseType>(type); LoadCaseDuration _durationClass = FemDesign.GenericClasses.EnumParser.Parse<LoadCaseDuration>(durationClass); LoadCase loadCase = new LoadCase(name, _type, _durationClass); return loadCase; } /// <summary> /// Returns a LoadCase from a list of LoadCases by name. The first LoadCase with a matching name will be returned. /// </summary> /// <remarks>Create</remarks> /// <param name="loadCases">List of LoadCase.</param> /// <param name="name">Name of LoadCase.</param> /// <returns></returns> [IsVisibleInDynamoLibrary(true)] public static LoadCase GetLoadCaseFromListByName(List<LoadCase> loadCases, string name) { foreach (LoadCase _loadCase in loadCases) { if (_loadCase.Name == name) { return _loadCase; } } return null; } } }
38.54717
169
0.620166
[ "MIT" ]
AmalieRask131/femdesign-api
FemDesign.Dynamo/Dynamo/Loads/LoadCase.cs
2,043
C#
/* Write a C# program in to show as many asterisks on the screen as told by the user, in the same row. For example, if the user enters 7, the answer would be: ******* (V2: starting with 0) */ using System; class Asterisks2 { static void Main() { Console.Write("How many asterisks? "); int n = Convert.ToInt32( Console.ReadLine() ); int i = 0; while (i < n) { Console.Write("*"); i = i + 1; } Console.WriteLine(); } }
16.969697
68
0.492857
[ "MIT" ]
Jokerlocco/2019-2020_DAM1_EjerciciosClase
chapter02-controlStructures/044b-Asterisks2.cs
560
C#
using FluentValidation; namespace Gear.Manager.Core.EntityServices.Reports.Queries.GetSprintListReportFromSelected { public class GetSprintListReportFromSelectedQueryValidator : AbstractValidator<GetSprintListReportFromSelectedQuery> { public GetSprintListReportFromSelectedQueryValidator() { RuleFor(x => x.Id) .NotEmpty(); RuleFor(x => x.SprintIds) .NotEmpty(); } } }
27.352941
120
0.664516
[ "MIT" ]
indrivo/bizon360_pm
IndrivoPM/IndrivoPM.Application/EntityServices/Reports/Queries/GetSprintListReportFromSelected/GetSprintListReportFromSelectedQueryValidator.cs
467
C#
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; public enum Type { BIO, MECH } public class EnemyType: MonoBehaviour { public Type type; }
14.538462
39
0.772487
[ "MIT" ]
Voossu/Zombie-Shooter-Project
Assets/Scripts/Enemy/EnemyType.cs
191
C#
using Microsoft.EntityFrameworkCore.Migrations; namespace WellBot.Infrastructure.DataAccess.Migrations { public partial class DeleteMessage : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.AddColumn<bool>( name: "IsActive", table: "PidorResultMessages", type: "INTEGER", nullable: false, defaultValue: true); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropColumn( name: "IsActive", table: "PidorResultMessages"); } } }
28.24
71
0.583569
[ "MIT" ]
ko-vasilev/WellBot
src/WellBot.Infrastructure.DataAccess/Migrations/20211212105417_DeleteMessage.cs
708
C#
using ClientLogic.Dto; using System; using System.Collections.Generic; using System.Text; namespace ClientLogic { public static class CalcHelper { public static double GetBruttoPrice(double nettoPrice, double vat) { return nettoPrice + nettoPrice * vat; } public static double GetTotalBrutto(double bruttoPrice, int amount) { return bruttoPrice * amount; } public static double GetTotalBrutto(List<EntryDto> entries) { double sum = 0; foreach(EntryDto entry in entries) { sum += GetTotalBrutto(entry.BruttoPrice, entry.Amount); } return sum; } } }
23.333333
76
0.55974
[ "Apache-2.0" ]
mantis1262/ProgamowanieUrzadzen
ClientLogic/CalcHelper.cs
772
C#
using Polly; namespace AdelaideFuel.Services { public interface IRetryPolicyService { /// <summary> /// Get retry policy to handle native web request exceptions /// </summary> PolicyBuilder GetNativeNetRetryPolicy(); } }
22.166667
68
0.642857
[ "MIT" ]
dmariogatto/adelaidefuel
src/App/AdelaideFuel/Services/Interfaces/IRetryPolicyService.cs
268
C#
// *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.Aws.WafV2.Inputs { public sealed class WebAclRuleStatementRateBasedStatementScopeDownStatementOrStatementStatementOrStatementStatementXssMatchStatementFieldToMatchSingleHeaderArgs : Pulumi.ResourceArgs { /// <summary> /// The name of the query header to inspect. This setting must be provided as lower case characters. /// </summary> [Input("name", required: true)] public Input<string> Name { get; set; } = null!; public WebAclRuleStatementRateBasedStatementScopeDownStatementOrStatementStatementOrStatementStatementXssMatchStatementFieldToMatchSingleHeaderArgs() { } } }
37.807692
186
0.743642
[ "ECL-2.0", "Apache-2.0" ]
Otanikotani/pulumi-aws
sdk/dotnet/WafV2/Inputs/WebAclRuleStatementRateBasedStatementScopeDownStatementOrStatementStatementOrStatementStatementXssMatchStatementFieldToMatchSingleHeaderArgs.cs
983
C#
#region Copyright notice and license // Copyright 2015 gRPC authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #endregion namespace Grpc.Core { /// <summary> /// Provides info about current version of gRPC. /// See https://codingforsmarties.wordpress.com/2016/01/21/how-to-version-assemblies-destined-for-nuget/ /// for rationale about assembly versioning. /// </summary> public static class VersionInfo { /// <summary> /// Current <c>AssemblyVersion</c> attribute of gRPC C# assemblies /// </summary> public const string CurrentAssemblyVersion = "2.0.0.0"; /// <summary> /// Current <c>AssemblyFileVersion</c> of gRPC C# assemblies /// </summary> public const string CurrentAssemblyFileVersion = "2.36.0.0"; /// <summary> /// Current version of gRPC C# /// </summary> public const string CurrentVersion = "2.36.0-dev"; } }
33.477273
108
0.665988
[ "Apache-2.0" ]
AaronDewes/grpc
src/csharp/Grpc.Core.Api/VersionInfo.cs
1,473
C#
namespace _3.BoomingCannon { using System; using System.Text.RegularExpressions; public class BoomingCannon { static int[] parameters; static int startIndex; static int count; static bool isFirst = true; static string targetsShotedDown = string.Empty; public static void Main() { parameters = ConvertToIntegerArray(Console.ReadLine()); startIndex = parameters[0]; count = parameters[1]; string target = Console.ReadLine(); MatchAndShootOf(target); Console.WriteLine(targetsShotedDown); } static int[] ConvertToIntegerArray(string input) { string[] splited = input.Split(new[] { " " }, StringSplitOptions.RemoveEmptyEntries); int[] integerArray = new int[splited.Length]; for (int index = 0; index < splited.Length; index++) { integerArray[index] = Convert.ToInt32(splited[index]); } return integerArray; } static void MatchAndShootOf(string target) { string pattern = @"((?<=\\<<<)(?<target>.+?))(?=\\<<<|$)"; if (Regex.IsMatch(target, pattern)) { MatchCollection currentTargets = Regex.Matches(target, pattern); foreach (Match match in currentTargets) { ShootOf(match.Groups["target"].Value); } } else return; } static void ShootOf(string currentTarget) { string down = string.Empty; if (startIndex >= 0 && startIndex < currentTarget.Length) { down = SubstringFrom(currentTarget.Replace("\\<<<", string.Empty)); AddToResult(down); } else return; } static string SubstringFrom(string currentTarget) { if (count >= 0 && startIndex + count < currentTarget.Length) { return currentTarget.Substring(startIndex, count); } else if (count >= 0 && startIndex + count >= currentTarget.Length) { return currentTarget.Substring(startIndex); } return string.Empty; } static void AddToResult(string down) { if (isFirst) { targetsShotedDown += down; isFirst = false; return; } targetsShotedDown += $"/\\{down}"; } } }
29.852273
97
0.507423
[ "MIT" ]
TsvetanNikolov123/CSharp---Programming-Fundamentals-Extended
35 RegEx - Exercises/3.BoomingCannon/BoomingCannon.cs
2,629
C#
namespace Coronado.ConsoleApp { public static class StringExtensions { public static string PadLeftWithDots(this string text, int totalWidth, bool includeTrailingDots = true) { if (text.Length > totalWidth) { return text.Substring(0, totalWidth) + (includeTrailingDots ? ".." : ""); } return text.PadLeft(totalWidth, '.') + (includeTrailingDots ? ".." : ""); } public static string PadRightWithDots(this string text, int totalWidth, bool includeTrailingDots = true) { if (text.Length > totalWidth) { return text.Substring(0, totalWidth) + (includeTrailingDots ? ".." : ""); } return text.PadRight(totalWidth, '.') + (includeTrailingDots ? ".." : ""); } } public static class DecimalExtensions { public static string PadLeftWithDots(this decimal number, int totalWidth, bool includeTrailingDots = true) { return number.ToString("#,##0.00").PadLeftWithDots(totalWidth, includeTrailingDots); } public static string PadRightWithDots(this decimal number, int totalWidth, bool includeTrailingDots = true) { return number.ToString("#,##0.00").PadRightWithDots(totalWidth, includeTrailingDots); } } }
37.194444
115
0.612397
[ "MIT" ]
kbaley/Coronado
Coronado.ConsoleApp/StringExtensions.cs
1,339
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Charlotte.Tools; using System.IO; namespace Charlotte { public class Gnd { private static Gnd _i = null; public static Gnd i { get { if (_i == null) _i = new Gnd(); return _i; } } private Gnd() { } // ---- conf data ---- public string ffmpegOptAudio = "-codec:a libvorbis -qscale:a 5 -ac 2"; public string ffmpegOptVideo = "-codec:v libtheora -qscale:v 7"; public int playListCountMax = 10000; public void loadConf() { try { List<string> lines = new List<string>(); foreach (string line in FileTools.readAllLines(getConfFile(), StringTools.ENCODING_SJIS)) if (line != "" && line[0] != ';') lines.Add(line); int c = 0; // items > ffmpegOptAudio = lines[c++]; ffmpegOptVideo = lines[c++]; playListCountMax = IntTools.toInt(lines[c++], 1); // < items } catch { } } private string getConfFile() { return Path.Combine(Program.selfDir, Path.GetFileNameWithoutExtension(Program.selfFile) + ".conf"); } // ---- saved data ---- public string ffmpegDir = ""; // "" == 未設定 public bool convWavMastering = false; public void loadData() { try { string[] lines = File.ReadAllLines(getDataFile(), Encoding.UTF8); int c = 0; // items > ffmpegDir = lines[c++]; convWavMastering = StringTools.toFlag(lines[c++]); // < items } catch { } } public void saveData() { try { List<string> lines = new List<string>(); // items > lines.Add(ffmpegDir); lines.Add(StringTools.toString(convWavMastering)); // < items File.WriteAllLines(getDataFile(), lines, Encoding.UTF8); } catch { } } private string getDataFile() { return Path.Combine(Program.selfDir, Path.GetFileNameWithoutExtension(Program.selfFile) + ".dat"); } // ---- public Logger logger = new Logger(); public AudioVideoExtensions audioVideoExtensions = new AudioVideoExtensions(); public string getMediaDir() { string tmp = Environment.GetEnvironmentVariable("TMP"); if (tmp == null || tmp == "") throw new Exception("env 'TMP' is empty"); return Path.Combine(tmp, Consts.MEDIA_DIR_ID); } } }
18.222222
102
0.619338
[ "MIT" ]
stackprobe/Kirara2
KiraraOld1/Kirara/Ground.cs
2,304
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // <auto-generated/> #nullable disable namespace Azure.AI.MetricsAdvisor.Models { /// <summary> The SqlSourceParameter. </summary> internal partial class SqlSourceParameter { /// <summary> Initializes a new instance of SqlSourceParameter. </summary> /// <param name="connectionString"> Database connection string. </param> /// <param name="query"> Query script. </param> public SqlSourceParameter(string connectionString, string query) { ConnectionString = connectionString; Query = query; } /// <summary> Database connection string. </summary> public string ConnectionString { get; set; } /// <summary> Query script. </summary> public string Query { get; set; } } }
31.678571
82
0.642616
[ "MIT" ]
0rland0Wats0n/azure-sdk-for-net
sdk/metricsadvisor/Azure.AI.MetricsAdvisor/src/Generated/Models/SqlSourceParameter.cs
887
C#
// ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ // **NOTE** This file was generated by a tool and any changes will be overwritten. // <auto-generated/> // Template Source: MethodRequestBody.cs.tt namespace Microsoft.Graph { using Newtonsoft.Json; using System; using System.Collections.Generic; using System.IO; using System.Runtime.Serialization; /// <summary> /// The type WorkbookFunctionsRoundRequestBody. /// </summary> [JsonObject(MemberSerialization = MemberSerialization.OptIn)] public partial class WorkbookFunctionsRoundRequestBody { /// <summary> /// Gets or sets Number. /// </summary> [JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "number", Required = Newtonsoft.Json.Required.Default)] public Newtonsoft.Json.Linq.JToken Number { get; set; } /// <summary> /// Gets or sets NumDigits. /// </summary> [JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "numDigits", Required = Newtonsoft.Json.Required.Default)] public Newtonsoft.Json.Linq.JToken NumDigits { get; set; } } }
37.333333
153
0.604396
[ "MIT" ]
DamienTehDemon/msgraph-sdk-dotnet
src/Microsoft.Graph/Generated/model/WorkbookFunctionsRoundRequestBody.cs
1,456
C#
// Copyright 2004-2012 Castle Project - http://www.castleproject.org/ // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. namespace Castle.MicroKernel.SubSystems.Naming { using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using Castle.Core.Internal; using Castle.MicroKernel.Util; [Serializable] public class DefaultNamingSubSystem : AbstractSubSystem, INamingSubSystem { protected readonly Lock @lock = Lock.Create(); /// <summary> /// Map(String, IHandler) to map component names to <see cref="IHandler" /> Items in this dictionary are sorted in insertion order. /// </summary> protected readonly Dictionary<string, IHandler> name2Handler = new Dictionary<string, IHandler>(StringComparer.OrdinalIgnoreCase); /// <summary> /// Map(Type, IHandler) to map a service to <see cref="IHandler" /> . If there is more than a single service of the type, only the first registered services is stored in this dictionary. It serve as a fast lookup for the common case of having a single handler for a type. /// </summary> protected readonly Dictionary<Type, HandlerWithPriority> service2Handler = new Dictionary<Type, HandlerWithPriority>(SimpleTypeEqualityComparer.Instance); protected IList<IHandlersFilter> filters; protected IList<IHandlerSelector> selectors; private readonly IDictionary<Type, IHandler[]> assignableHandlerListsByTypeCache = new Dictionary<Type, IHandler[]>(SimpleTypeEqualityComparer.Instance); private readonly IDictionary<Type, IHandler[]> handlerListsByTypeCache = new Dictionary<Type, IHandler[]>(SimpleTypeEqualityComparer.Instance); private Dictionary<string, IHandler> handlerByNameCache; private Dictionary<Type, IHandler> handlerByServiceCache; public virtual int ComponentCount { get { return HandlerByNameCache.Count; } } protected IDictionary<string, IHandler> HandlerByNameCache { get { var cache = handlerByNameCache; if (cache != null) { return cache; } using (@lock.ForWriting()) { cache = new Dictionary<string, IHandler>(name2Handler, name2Handler.Comparer); handlerByNameCache = cache; return cache; } } } protected IDictionary<Type, IHandler> HandlerByServiceCache { get { var cache = handlerByServiceCache; if (cache != null) { return cache; } using (@lock.ForWriting()) { cache = new Dictionary<Type, IHandler>(service2Handler.Count, service2Handler.Comparer); foreach (var item in service2Handler) { cache.Add(item.Key, item.Value.Handler); } handlerByServiceCache = cache; return cache; } } } public void AddHandlerSelector(IHandlerSelector selector) { if (selectors == null) { selectors = new List<IHandlerSelector>(); } selectors.Add(selector); } public void AddHandlersFilter(IHandlersFilter filter) { if (filters == null) { filters = new List<IHandlersFilter>(); } filters.Add(filter); } public virtual bool Contains(String name) { return HandlerByNameCache.ContainsKey(name); } public virtual bool Contains(Type service) { return GetHandler(service) != null; } public virtual IHandler[] GetAllHandlers() { var cache = HandlerByNameCache; var list = new IHandler[cache.Values.Count]; cache.Values.CopyTo(list, 0); return list; } public virtual IHandler[] GetAssignableHandlers(Type service) { if (service == null) { throw new ArgumentNullException("service"); } if (service == typeof(object)) { return GetAllHandlers(); } return GetAssignableHandlersNoFiltering(service); } public virtual IHandler GetHandler(String name) { if (name == null) { throw new ArgumentNullException("name"); } if (selectors != null) { var selectorsOpinion = GetSelectorsOpinion(name, null); if (selectorsOpinion != null) { return selectorsOpinion; } } IHandler value; HandlerByNameCache.TryGetValue(name, out value); return value; } public virtual IHandler GetHandler(Type service) { if (service == null) { throw new ArgumentNullException("service"); } if (selectors != null) { var selectorsOpinion = GetSelectorsOpinion(null, service); if (selectorsOpinion != null) { return selectorsOpinion; } } IHandler handler; if (HandlerByServiceCache.TryGetValue(service, out handler)) { return handler; } if (service.GetTypeInfo().IsGenericType && service.GetTypeInfo().IsGenericTypeDefinition == false) { var openService = service.GetGenericTypeDefinition(); if (HandlerByServiceCache.TryGetValue(openService, out handler) && handler.Supports(service)) { return handler; } var handlerCandidates = GetHandlers(openService); foreach (var handlerCandidate in handlerCandidates) { if (handlerCandidate.Supports(service)) { return handlerCandidate; } } } return null; } public virtual IHandler[] GetHandlers(Type service) { if (service == null) { throw new ArgumentNullException("service"); } if (filters != null) { var filtersOpinion = GetFiltersOpinion(service); if (filtersOpinion != null) { return filtersOpinion; } } IHandler[] result; using (var locker = @lock.ForReadingUpgradeable()) { if (handlerListsByTypeCache.TryGetValue(service, out result)) { return result; } result = GetHandlersNoLock(service); locker.Upgrade(); handlerListsByTypeCache[service] = result; } return result; } public virtual void Register(IHandler handler) { var name = handler.ComponentModel.Name; using (@lock.ForWriting()) { try { name2Handler.Add(name, handler); } catch (ArgumentException) { throw new ComponentRegistrationException( String.Format( "Component {0} could not be registered. There is already a component with that name. Did you want to modify the existing component instead? If not, make sure you specify a unique name.", name)); } var serviceSelector = GetServiceSelector(handler); foreach (var service in handler.ComponentModel.Services) { var handlerForService = serviceSelector(service); HandlerWithPriority previous; if (service2Handler.TryGetValue(service, out previous) == false || handlerForService.Triumphs(previous)) { service2Handler[service] = handlerForService; } } InvalidateCache(); } } protected IHandler[] GetAssignableHandlersNoFiltering(Type service) { IHandler[] result; using (var locker = @lock.ForReadingUpgradeable()) { if (assignableHandlerListsByTypeCache.TryGetValue(service, out result)) { return result; } locker.Upgrade(); if (assignableHandlerListsByTypeCache.TryGetValue(service, out result)) { return result; } result = name2Handler.Values.Where(h => h.SupportsAssignable(service)).ToArray(); assignableHandlerListsByTypeCache[service] = result; } return result; } protected virtual IHandler[] GetFiltersOpinion(Type service) { if (filters == null) { return null; } IHandler[] handlers = null; foreach (var filter in filters) { if (filter.HasOpinionAbout(service) == false) { continue; } if (handlers == null) { handlers = GetAssignableHandlersNoFiltering(service); } handlers = filter.SelectHandlers(service, handlers); if (handlers != null) { return handlers; } } return null; } protected virtual IHandler GetSelectorsOpinion(string name, Type type) { if (selectors == null) { return null; } type = type ?? typeof(object); // if type is null, we want everything, so object does well for that IHandler[] handlers = null; //only init if we have a selector with an opinion about this type foreach (var selector in selectors) { if (selector.HasOpinionAbout(name, type) == false) { continue; } if (handlers == null) { handlers = GetAssignableHandlersNoFiltering(type); } var handler = selector.SelectHandler(name, type, handlers); if (handler != null) { return handler; } } return null; } protected void InvalidateCache() { handlerListsByTypeCache.Clear(); assignableHandlerListsByTypeCache.Clear(); handlerByNameCache = null; handlerByServiceCache = null; } private IHandler[] GetHandlersNoLock(Type service) { //we have 3 segments const int defaults = 0; const int regulars = 1; const int fallbacks = 2; var handlers = new SegmentedList<IHandler>(3); foreach (var handler in name2Handler.Values) { if (handler.Supports(service) == false) { continue; } if (IsDefault(handler, service)) { handlers.AddFirst(defaults, handler); continue; } if (IsFallback(handler, service)) { handlers.AddLast(fallbacks, handler); continue; } handlers.AddLast(regulars, handler); } return handlers.ToArray(); } private Func<Type, HandlerWithPriority> GetServiceSelector(IHandler handler) { var defaultsFilter = handler.ComponentModel.GetDefaultComponentForServiceFilter(); var fallbackFilter = handler.ComponentModel.GetFallbackComponentForServiceFilter(); if (defaultsFilter == null) { if (fallbackFilter == null) { return service => new HandlerWithPriority(0, handler); } return service => new HandlerWithPriority(fallbackFilter(service) ? -1 : 0, handler); } if (fallbackFilter == null) { return service => new HandlerWithPriority(defaultsFilter(service) ? 1 : 0, handler); } return service => new HandlerWithPriority(defaultsFilter(service) ? 1 : (fallbackFilter(service) ? -1 : 0), handler); } private bool IsDefault(IHandler handler, Type service) { var filter = handler.ComponentModel.GetDefaultComponentForServiceFilter(); if (filter == null) { return false; } return filter(service); } private bool IsFallback(IHandler handler, Type service) { var filter = handler.ComponentModel.GetFallbackComponentForServiceFilter(); if (filter == null) { return false; } return filter(service); } protected struct HandlerWithPriority { private readonly IHandler handler; private readonly int priority; public HandlerWithPriority(int priority, IHandler handler) { this.priority = priority; this.handler = handler; } public IHandler Handler { get { return handler; } } public bool Triumphs(HandlerWithPriority other) { if (priority > other.priority) { return true; } if (priority == other.priority && priority > 0) { return true; } return false; } } } }
25.295806
275
0.68156
[ "Apache-2.0" ]
111cctv19/Windsor
src/Castle.Windsor/MicroKernel/SubSystems/Naming/DefaultNamingSubSystem.cs
11,459
C#
using System; using System.Collections.Generic; using System.Collections.Immutable; using Akka; using Akka.Actor; using Akka.Persistence.Query; using Akka.Streams.Dsl; using wyvern.api.@internal.surfaces; using wyvern.entity.@event; using wyvern.entity.@event.aggregate; namespace wyvern.api.abstractions { public interface ITaggedOffsetTopicProducer<TEvent> : InternalTopic where TEvent : AbstractEvent { ImmutableArray<AggregateEventTag> Tags { get; } Func<AggregateEventTag, Offset, Source<KeyValuePair<TEvent, Offset>, NotUsed>> ReadSideStream { get; } void Init(ActorSystem sys, string topicId, ISerializer serializer, IMessagePropertyExtractor extractor); } }
33.619048
112
0.770538
[ "Apache-2.0" ]
nagytech/lagom-dotnet
src/wyvern.api/abstractions/ITaggedOffsetTopicProducer.cs
706
C#
using System; namespace Bridge { public class TextSender : IMessageSender { public void SendMessage(string subject, string body) { string messageType = "Text"; Console.WriteLine($"{messageType}"); Console.WriteLine("--------------"); Console.WriteLine($"Subject: {subject} from {messageType}"); Console.WriteLine($"Body: {body}"); Console.WriteLine(); } } }
26.611111
73
0.530271
[ "MIT" ]
PetarTolev/High-Quality-Code
02. Structural Patterns/06Bridge/TextSender.cs
481
C#
using BL.Tecnologia; namespace Proyecto_WorldTec { partial class FormFactura { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); System.Windows.Forms.Label activoLabel; System.Windows.Forms.Label clienteIdLabel; System.Windows.Forms.Label fechaLabel; System.Windows.Forms.Label idLabel; System.Windows.Forms.Label impuestoLabel; System.Windows.Forms.Label subtotalLabel; System.Windows.Forms.Label totalLabel; System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(FormFactura)); this.listaFacturasBindingSource = new System.Windows.Forms.BindingSource(this.components); this.listaFacturasBindingNavigator = new System.Windows.Forms.BindingNavigator(this.components); this.bindingNavigatorCountItem = new System.Windows.Forms.ToolStripLabel(); this.bindingNavigatorMoveFirstItem = new System.Windows.Forms.ToolStripButton(); this.bindingNavigatorMovePreviousItem = new System.Windows.Forms.ToolStripButton(); this.bindingNavigatorSeparator = new System.Windows.Forms.ToolStripSeparator(); this.bindingNavigatorPositionItem = new System.Windows.Forms.ToolStripTextBox(); this.bindingNavigatorSeparator1 = new System.Windows.Forms.ToolStripSeparator(); this.bindingNavigatorMoveNextItem = new System.Windows.Forms.ToolStripButton(); this.bindingNavigatorMoveLastItem = new System.Windows.Forms.ToolStripButton(); this.bindingNavigatorSeparator2 = new System.Windows.Forms.ToolStripSeparator(); this.bindingNavigatorAddNewItem = new System.Windows.Forms.ToolStripButton(); this.bindingNavigatorDeleteItem = new System.Windows.Forms.ToolStripButton(); this.listaFacturasBindingNavigatorSaveItem = new System.Windows.Forms.ToolStripButton(); this.toolStripButtonCancelar = new System.Windows.Forms.ToolStripButton(); this.activoCheckBox = new System.Windows.Forms.CheckBox(); this.fechaDateTimePicker = new System.Windows.Forms.DateTimePicker(); this.idTextBox = new System.Windows.Forms.TextBox(); this.impuestoTextBox = new System.Windows.Forms.TextBox(); this.subtotalTextBox = new System.Windows.Forms.TextBox(); this.totalTextBox = new System.Windows.Forms.TextBox(); this.listaClientesBindingSource = new System.Windows.Forms.BindingSource(this.components); this.listaProductosBindingSource = new System.Windows.Forms.BindingSource(this.components); this.clienteIdComboBox = new System.Windows.Forms.ComboBox(); this.facturaDetalleBindingSource = new System.Windows.Forms.BindingSource(this.components); this.facturaDetalleDataGridView = new System.Windows.Forms.DataGridView(); this.dataGridViewTextBoxColumn3 = new System.Windows.Forms.DataGridViewComboBoxColumn(); this.dataGridViewTextBoxColumn4 = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.dataGridViewTextBoxColumn5 = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.dataGridViewTextBoxColumn6 = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.button1 = new System.Windows.Forms.Button(); this.button2 = new System.Windows.Forms.Button(); this.label1 = new System.Windows.Forms.Label(); this.listaDescuentosBindingSource = new System.Windows.Forms.BindingSource(this.components); activoLabel = new System.Windows.Forms.Label(); clienteIdLabel = new System.Windows.Forms.Label(); fechaLabel = new System.Windows.Forms.Label(); idLabel = new System.Windows.Forms.Label(); impuestoLabel = new System.Windows.Forms.Label(); subtotalLabel = new System.Windows.Forms.Label(); totalLabel = new System.Windows.Forms.Label(); ((System.ComponentModel.ISupportInitialize)(this.listaFacturasBindingSource)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.listaFacturasBindingNavigator)).BeginInit(); this.listaFacturasBindingNavigator.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.listaClientesBindingSource)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.listaProductosBindingSource)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.facturaDetalleBindingSource)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.facturaDetalleDataGridView)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.listaDescuentosBindingSource)).BeginInit(); this.SuspendLayout(); // // activoLabel // activoLabel.AutoSize = true; activoLabel.Location = new System.Drawing.Point(231, 47); activoLabel.Name = "activoLabel"; activoLabel.Size = new System.Drawing.Size(40, 13); activoLabel.TabIndex = 1; activoLabel.Text = "Activo:"; // // clienteIdLabel // clienteIdLabel.AutoSize = true; clienteIdLabel.Location = new System.Drawing.Point(44, 103); clienteIdLabel.Name = "clienteIdLabel"; clienteIdLabel.Size = new System.Drawing.Size(42, 13); clienteIdLabel.TabIndex = 3; clienteIdLabel.Text = "Cliente:"; // // fechaLabel // fechaLabel.AutoSize = true; fechaLabel.Location = new System.Drawing.Point(44, 75); fechaLabel.Name = "fechaLabel"; fechaLabel.Size = new System.Drawing.Size(40, 13); fechaLabel.TabIndex = 5; fechaLabel.Text = "Fecha:"; // // idLabel // idLabel.AutoSize = true; idLabel.Location = new System.Drawing.Point(44, 47); idLabel.Name = "idLabel"; idLabel.Size = new System.Drawing.Size(19, 13); idLabel.TabIndex = 7; idLabel.Text = "Id:"; // // impuestoLabel // impuestoLabel.AutoSize = true; impuestoLabel.Location = new System.Drawing.Point(315, 358); impuestoLabel.Name = "impuestoLabel"; impuestoLabel.Size = new System.Drawing.Size(53, 13); impuestoLabel.TabIndex = 9; impuestoLabel.Text = "Impuesto:"; // // subtotalLabel // subtotalLabel.AutoSize = true; subtotalLabel.Location = new System.Drawing.Point(320, 334); subtotalLabel.Name = "subtotalLabel"; subtotalLabel.Size = new System.Drawing.Size(49, 13); subtotalLabel.TabIndex = 11; subtotalLabel.Text = "Subtotal:"; // // totalLabel // totalLabel.AutoSize = true; totalLabel.Location = new System.Drawing.Point(334, 384); totalLabel.Name = "totalLabel"; totalLabel.Size = new System.Drawing.Size(34, 13); totalLabel.TabIndex = 13; totalLabel.Text = "Total:"; // // listaFacturasBindingSource // this.listaFacturasBindingSource.DataSource = typeof(BL.Tecnologia.Factura); this.listaFacturasBindingSource.CurrentChanged += new System.EventHandler(this.listaFacturasBindingSource_CurrentChanged); // // listaFacturasBindingNavigator // this.listaFacturasBindingNavigator.AddNewItem = null; this.listaFacturasBindingNavigator.BindingSource = this.listaFacturasBindingSource; this.listaFacturasBindingNavigator.CountItem = this.bindingNavigatorCountItem; this.listaFacturasBindingNavigator.DeleteItem = null; this.listaFacturasBindingNavigator.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.bindingNavigatorMoveFirstItem, this.bindingNavigatorMovePreviousItem, this.bindingNavigatorSeparator, this.bindingNavigatorPositionItem, this.bindingNavigatorCountItem, this.bindingNavigatorSeparator1, this.bindingNavigatorMoveNextItem, this.bindingNavigatorMoveLastItem, this.bindingNavigatorSeparator2, this.bindingNavigatorAddNewItem, this.bindingNavigatorDeleteItem, this.listaFacturasBindingNavigatorSaveItem, this.toolStripButtonCancelar}); this.listaFacturasBindingNavigator.Location = new System.Drawing.Point(0, 0); this.listaFacturasBindingNavigator.MoveFirstItem = this.bindingNavigatorMoveFirstItem; this.listaFacturasBindingNavigator.MoveLastItem = this.bindingNavigatorMoveLastItem; this.listaFacturasBindingNavigator.MoveNextItem = this.bindingNavigatorMoveNextItem; this.listaFacturasBindingNavigator.MovePreviousItem = this.bindingNavigatorMovePreviousItem; this.listaFacturasBindingNavigator.Name = "listaFacturasBindingNavigator"; this.listaFacturasBindingNavigator.PositionItem = this.bindingNavigatorPositionItem; this.listaFacturasBindingNavigator.Size = new System.Drawing.Size(600, 25); this.listaFacturasBindingNavigator.TabIndex = 0; this.listaFacturasBindingNavigator.Text = "bindingNavigator1"; // // bindingNavigatorCountItem // this.bindingNavigatorCountItem.Name = "bindingNavigatorCountItem"; this.bindingNavigatorCountItem.Size = new System.Drawing.Size(37, 22); this.bindingNavigatorCountItem.Text = "de {0}"; this.bindingNavigatorCountItem.ToolTipText = "Número total de elementos"; // // bindingNavigatorMoveFirstItem // this.bindingNavigatorMoveFirstItem.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.bindingNavigatorMoveFirstItem.Image = ((System.Drawing.Image)(resources.GetObject("bindingNavigatorMoveFirstItem.Image"))); this.bindingNavigatorMoveFirstItem.Name = "bindingNavigatorMoveFirstItem"; this.bindingNavigatorMoveFirstItem.RightToLeftAutoMirrorImage = true; this.bindingNavigatorMoveFirstItem.Size = new System.Drawing.Size(23, 22); this.bindingNavigatorMoveFirstItem.Text = "Mover primero"; // // bindingNavigatorMovePreviousItem // this.bindingNavigatorMovePreviousItem.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.bindingNavigatorMovePreviousItem.Image = ((System.Drawing.Image)(resources.GetObject("bindingNavigatorMovePreviousItem.Image"))); this.bindingNavigatorMovePreviousItem.Name = "bindingNavigatorMovePreviousItem"; this.bindingNavigatorMovePreviousItem.RightToLeftAutoMirrorImage = true; this.bindingNavigatorMovePreviousItem.Size = new System.Drawing.Size(23, 22); this.bindingNavigatorMovePreviousItem.Text = "Mover anterior"; // // bindingNavigatorSeparator // this.bindingNavigatorSeparator.Name = "bindingNavigatorSeparator"; this.bindingNavigatorSeparator.Size = new System.Drawing.Size(6, 25); // // bindingNavigatorPositionItem // this.bindingNavigatorPositionItem.AccessibleName = "Posición"; this.bindingNavigatorPositionItem.AutoSize = false; this.bindingNavigatorPositionItem.Font = new System.Drawing.Font("Segoe UI", 9F); this.bindingNavigatorPositionItem.Name = "bindingNavigatorPositionItem"; this.bindingNavigatorPositionItem.Size = new System.Drawing.Size(50, 23); this.bindingNavigatorPositionItem.Text = "0"; this.bindingNavigatorPositionItem.ToolTipText = "Posición actual"; // // bindingNavigatorSeparator1 // this.bindingNavigatorSeparator1.Name = "bindingNavigatorSeparator1"; this.bindingNavigatorSeparator1.Size = new System.Drawing.Size(6, 25); // // bindingNavigatorMoveNextItem // this.bindingNavigatorMoveNextItem.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.bindingNavigatorMoveNextItem.Image = ((System.Drawing.Image)(resources.GetObject("bindingNavigatorMoveNextItem.Image"))); this.bindingNavigatorMoveNextItem.Name = "bindingNavigatorMoveNextItem"; this.bindingNavigatorMoveNextItem.RightToLeftAutoMirrorImage = true; this.bindingNavigatorMoveNextItem.Size = new System.Drawing.Size(23, 22); this.bindingNavigatorMoveNextItem.Text = "Mover siguiente"; // // bindingNavigatorMoveLastItem // this.bindingNavigatorMoveLastItem.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.bindingNavigatorMoveLastItem.Image = ((System.Drawing.Image)(resources.GetObject("bindingNavigatorMoveLastItem.Image"))); this.bindingNavigatorMoveLastItem.Name = "bindingNavigatorMoveLastItem"; this.bindingNavigatorMoveLastItem.RightToLeftAutoMirrorImage = true; this.bindingNavigatorMoveLastItem.Size = new System.Drawing.Size(23, 22); this.bindingNavigatorMoveLastItem.Text = "Mover último"; // // bindingNavigatorSeparator2 // this.bindingNavigatorSeparator2.Name = "bindingNavigatorSeparator2"; this.bindingNavigatorSeparator2.Size = new System.Drawing.Size(6, 25); // // bindingNavigatorAddNewItem // this.bindingNavigatorAddNewItem.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.bindingNavigatorAddNewItem.Image = ((System.Drawing.Image)(resources.GetObject("bindingNavigatorAddNewItem.Image"))); this.bindingNavigatorAddNewItem.Name = "bindingNavigatorAddNewItem"; this.bindingNavigatorAddNewItem.RightToLeftAutoMirrorImage = true; this.bindingNavigatorAddNewItem.Size = new System.Drawing.Size(23, 22); this.bindingNavigatorAddNewItem.Text = "Agregar nuevo"; this.bindingNavigatorAddNewItem.Click += new System.EventHandler(this.bindingNavigatorAddNewItem_Click); // // bindingNavigatorDeleteItem // this.bindingNavigatorDeleteItem.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.bindingNavigatorDeleteItem.Image = ((System.Drawing.Image)(resources.GetObject("bindingNavigatorDeleteItem.Image"))); this.bindingNavigatorDeleteItem.Name = "bindingNavigatorDeleteItem"; this.bindingNavigatorDeleteItem.RightToLeftAutoMirrorImage = true; this.bindingNavigatorDeleteItem.Size = new System.Drawing.Size(23, 22); this.bindingNavigatorDeleteItem.Text = "Anular"; this.bindingNavigatorDeleteItem.Click += new System.EventHandler(this.bindingNavigatorDeleteItem_Click); // // listaFacturasBindingNavigatorSaveItem // this.listaFacturasBindingNavigatorSaveItem.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.listaFacturasBindingNavigatorSaveItem.Image = ((System.Drawing.Image)(resources.GetObject("listaFacturasBindingNavigatorSaveItem.Image"))); this.listaFacturasBindingNavigatorSaveItem.Name = "listaFacturasBindingNavigatorSaveItem"; this.listaFacturasBindingNavigatorSaveItem.Size = new System.Drawing.Size(23, 22); this.listaFacturasBindingNavigatorSaveItem.Text = "Guardar datos"; this.listaFacturasBindingNavigatorSaveItem.Click += new System.EventHandler(this.listaFacturasBindingNavigatorSaveItem_Click); // // toolStripButtonCancelar // this.toolStripButtonCancelar.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text; this.toolStripButtonCancelar.Image = ((System.Drawing.Image)(resources.GetObject("toolStripButtonCancelar.Image"))); this.toolStripButtonCancelar.ImageTransparentColor = System.Drawing.Color.Magenta; this.toolStripButtonCancelar.Name = "toolStripButtonCancelar"; this.toolStripButtonCancelar.Size = new System.Drawing.Size(57, 22); this.toolStripButtonCancelar.Text = "Cancelar"; this.toolStripButtonCancelar.Visible = false; this.toolStripButtonCancelar.Click += new System.EventHandler(this.toolStripButtonCancelar_Click); // // activoCheckBox // this.activoCheckBox.DataBindings.Add(new System.Windows.Forms.Binding("CheckState", this.listaFacturasBindingSource, "Activo", true)); this.activoCheckBox.Enabled = false; this.activoCheckBox.Location = new System.Drawing.Point(291, 42); this.activoCheckBox.Name = "activoCheckBox"; this.activoCheckBox.Size = new System.Drawing.Size(23, 24); this.activoCheckBox.TabIndex = 2; this.activoCheckBox.UseVisualStyleBackColor = true; // // fechaDateTimePicker // this.fechaDateTimePicker.DataBindings.Add(new System.Windows.Forms.Binding("Value", this.listaFacturasBindingSource, "Fecha", true)); this.fechaDateTimePicker.Location = new System.Drawing.Point(104, 71); this.fechaDateTimePicker.Name = "fechaDateTimePicker"; this.fechaDateTimePicker.Size = new System.Drawing.Size(200, 20); this.fechaDateTimePicker.TabIndex = 6; // // idTextBox // this.idTextBox.DataBindings.Add(new System.Windows.Forms.Binding("Text", this.listaFacturasBindingSource, "Id", true, System.Windows.Forms.DataSourceUpdateMode.OnValidation, null, "00000")); this.idTextBox.Location = new System.Drawing.Point(104, 44); this.idTextBox.Name = "idTextBox"; this.idTextBox.ReadOnly = true; this.idTextBox.Size = new System.Drawing.Size(75, 20); this.idTextBox.TabIndex = 8; // // impuestoTextBox // this.impuestoTextBox.DataBindings.Add(new System.Windows.Forms.Binding("Text", this.listaFacturasBindingSource, "Impuesto", true, System.Windows.Forms.DataSourceUpdateMode.OnValidation, null, "N2")); this.impuestoTextBox.Location = new System.Drawing.Point(380, 355); this.impuestoTextBox.Name = "impuestoTextBox"; this.impuestoTextBox.ReadOnly = true; this.impuestoTextBox.Size = new System.Drawing.Size(200, 20); this.impuestoTextBox.TabIndex = 10; this.impuestoTextBox.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; // // subtotalTextBox // this.subtotalTextBox.DataBindings.Add(new System.Windows.Forms.Binding("Text", this.listaFacturasBindingSource, "Subtotal", true, System.Windows.Forms.DataSourceUpdateMode.OnValidation, null, "N2")); this.subtotalTextBox.Location = new System.Drawing.Point(380, 331); this.subtotalTextBox.Name = "subtotalTextBox"; this.subtotalTextBox.ReadOnly = true; this.subtotalTextBox.Size = new System.Drawing.Size(200, 20); this.subtotalTextBox.TabIndex = 12; this.subtotalTextBox.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; // // totalTextBox // this.totalTextBox.DataBindings.Add(new System.Windows.Forms.Binding("Text", this.listaFacturasBindingSource, "Total", true, System.Windows.Forms.DataSourceUpdateMode.OnValidation, null, "N2")); this.totalTextBox.Location = new System.Drawing.Point(380, 381); this.totalTextBox.Name = "totalTextBox"; this.totalTextBox.ReadOnly = true; this.totalTextBox.Size = new System.Drawing.Size(200, 20); this.totalTextBox.TabIndex = 14; this.totalTextBox.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; // // listaClientesBindingSource // this.listaClientesBindingSource.DataSource = typeof(BL.Tecnologia.Cliente); // // listaProductosBindingSource // this.listaProductosBindingSource.DataSource = typeof(BL.Tecnologia.ProductosBL.Producto); // // clienteIdComboBox // this.clienteIdComboBox.DataBindings.Add(new System.Windows.Forms.Binding("SelectedValue", this.listaFacturasBindingSource, "ClienteId", true)); this.clienteIdComboBox.DataSource = this.listaClientesBindingSource; this.clienteIdComboBox.DisplayMember = "Nombre"; this.clienteIdComboBox.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.clienteIdComboBox.FormattingEnabled = true; this.clienteIdComboBox.Location = new System.Drawing.Point(104, 100); this.clienteIdComboBox.Name = "clienteIdComboBox"; this.clienteIdComboBox.Size = new System.Drawing.Size(200, 21); this.clienteIdComboBox.TabIndex = 15; this.clienteIdComboBox.ValueMember = "Id"; // // facturaDetalleBindingSource // this.facturaDetalleBindingSource.AllowNew = false; this.facturaDetalleBindingSource.DataMember = "FacturaDetalle"; this.facturaDetalleBindingSource.DataSource = this.listaFacturasBindingSource; // // facturaDetalleDataGridView // this.facturaDetalleDataGridView.AutoGenerateColumns = false; this.facturaDetalleDataGridView.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize; this.facturaDetalleDataGridView.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] { this.dataGridViewTextBoxColumn3, this.dataGridViewTextBoxColumn4, this.dataGridViewTextBoxColumn5, this.dataGridViewTextBoxColumn6}); this.facturaDetalleDataGridView.DataSource = this.facturaDetalleBindingSource; this.facturaDetalleDataGridView.Location = new System.Drawing.Point(47, 143); this.facturaDetalleDataGridView.Name = "facturaDetalleDataGridView"; this.facturaDetalleDataGridView.Size = new System.Drawing.Size(533, 181); this.facturaDetalleDataGridView.TabIndex = 15; this.facturaDetalleDataGridView.CellEndEdit += new System.Windows.Forms.DataGridViewCellEventHandler(this.facturaDetalleDataGridView_CellEndEdit); this.facturaDetalleDataGridView.DataError += new System.Windows.Forms.DataGridViewDataErrorEventHandler(this.facturaDetalleDataGridView_DataError); // // dataGridViewTextBoxColumn3 // this.dataGridViewTextBoxColumn3.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill; this.dataGridViewTextBoxColumn3.DataPropertyName = "ProductoId"; this.dataGridViewTextBoxColumn3.DataSource = this.listaProductosBindingSource; this.dataGridViewTextBoxColumn3.DisplayMember = "Descripcion"; this.dataGridViewTextBoxColumn3.HeaderText = "Producto"; this.dataGridViewTextBoxColumn3.Name = "dataGridViewTextBoxColumn3"; this.dataGridViewTextBoxColumn3.Resizable = System.Windows.Forms.DataGridViewTriState.True; this.dataGridViewTextBoxColumn3.SortMode = System.Windows.Forms.DataGridViewColumnSortMode.Automatic; this.dataGridViewTextBoxColumn3.ValueMember = "Id"; // // dataGridViewTextBoxColumn4 // this.dataGridViewTextBoxColumn4.DataPropertyName = "Cantidad"; this.dataGridViewTextBoxColumn4.HeaderText = "Cantidad"; this.dataGridViewTextBoxColumn4.Name = "dataGridViewTextBoxColumn4"; // // dataGridViewTextBoxColumn5 // this.dataGridViewTextBoxColumn5.DataPropertyName = "Precio"; this.dataGridViewTextBoxColumn5.HeaderText = "Precio"; this.dataGridViewTextBoxColumn5.Name = "dataGridViewTextBoxColumn5"; // // dataGridViewTextBoxColumn6 // this.dataGridViewTextBoxColumn6.DataPropertyName = "Total"; this.dataGridViewTextBoxColumn6.HeaderText = "Total"; this.dataGridViewTextBoxColumn6.Name = "dataGridViewTextBoxColumn6"; // // button1 // this.button1.Font = new System.Drawing.Font("Microsoft Sans Serif", 14.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.button1.Location = new System.Drawing.Point(462, 108); this.button1.Name = "button1"; this.button1.Size = new System.Drawing.Size(56, 29); this.button1.TabIndex = 16; this.button1.Text = "+"; this.button1.UseVisualStyleBackColor = true; this.button1.Click += new System.EventHandler(this.button1_Click); // // button2 // this.button2.Font = new System.Drawing.Font("Microsoft Sans Serif", 14.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.button2.Location = new System.Drawing.Point(524, 108); this.button2.Name = "button2"; this.button2.Size = new System.Drawing.Size(56, 29); this.button2.TabIndex = 17; this.button2.Text = "-"; this.button2.UseVisualStyleBackColor = true; this.button2.Click += new System.EventHandler(this.button2_Click); // // label1 // this.label1.AutoSize = true; this.label1.Font = new System.Drawing.Font("Microsoft Sans Serif", 14.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label1.ForeColor = System.Drawing.Color.Red; this.label1.Location = new System.Drawing.Point(472, 29); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(108, 24); this.label1.TabIndex = 18; this.label1.Text = "ANULADO"; this.label1.Visible = false; // // FormFactura // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(600, 449); this.Controls.Add(this.label1); this.Controls.Add(this.button2); this.Controls.Add(this.button1); this.Controls.Add(this.facturaDetalleDataGridView); this.Controls.Add(this.clienteIdComboBox); this.Controls.Add(activoLabel); this.Controls.Add(this.activoCheckBox); this.Controls.Add(clienteIdLabel); this.Controls.Add(fechaLabel); this.Controls.Add(this.fechaDateTimePicker); this.Controls.Add(idLabel); this.Controls.Add(this.idTextBox); this.Controls.Add(impuestoLabel); this.Controls.Add(this.impuestoTextBox); this.Controls.Add(subtotalLabel); this.Controls.Add(this.subtotalTextBox); this.Controls.Add(totalLabel); this.Controls.Add(this.totalTextBox); this.Controls.Add(this.listaFacturasBindingNavigator); this.Name = "FormFactura"; this.Text = "Factura"; ((System.ComponentModel.ISupportInitialize)(this.listaFacturasBindingSource)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.listaFacturasBindingNavigator)).EndInit(); this.listaFacturasBindingNavigator.ResumeLayout(false); this.listaFacturasBindingNavigator.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.listaClientesBindingSource)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.listaProductosBindingSource)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.facturaDetalleBindingSource)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.facturaDetalleDataGridView)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.listaDescuentosBindingSource)).EndInit(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.BindingSource listaFacturasBindingSource; private System.Windows.Forms.BindingNavigator listaFacturasBindingNavigator; private System.Windows.Forms.ToolStripButton bindingNavigatorAddNewItem; private System.Windows.Forms.ToolStripLabel bindingNavigatorCountItem; private System.Windows.Forms.ToolStripButton bindingNavigatorDeleteItem; private System.Windows.Forms.ToolStripButton bindingNavigatorMoveFirstItem; private System.Windows.Forms.ToolStripButton bindingNavigatorMovePreviousItem; private System.Windows.Forms.ToolStripSeparator bindingNavigatorSeparator; private System.Windows.Forms.ToolStripTextBox bindingNavigatorPositionItem; private System.Windows.Forms.ToolStripSeparator bindingNavigatorSeparator1; private System.Windows.Forms.ToolStripButton bindingNavigatorMoveNextItem; private System.Windows.Forms.ToolStripButton bindingNavigatorMoveLastItem; private System.Windows.Forms.ToolStripSeparator bindingNavigatorSeparator2; private System.Windows.Forms.ToolStripButton listaFacturasBindingNavigatorSaveItem; private System.Windows.Forms.CheckBox activoCheckBox; private System.Windows.Forms.DateTimePicker fechaDateTimePicker; private System.Windows.Forms.TextBox idTextBox; private System.Windows.Forms.TextBox impuestoTextBox; private System.Windows.Forms.TextBox subtotalTextBox; private System.Windows.Forms.TextBox totalTextBox; private System.Windows.Forms.BindingSource listaClientesBindingSource; private System.Windows.Forms.BindingSource listaProductosBindingSource; private System.Windows.Forms.ComboBox clienteIdComboBox; private System.Windows.Forms.ToolStripButton toolStripButtonCancelar; private System.Windows.Forms.BindingSource facturaDetalleBindingSource; private System.Windows.Forms.DataGridView facturaDetalleDataGridView; private System.Windows.Forms.Button button1; private System.Windows.Forms.Button button2; private System.Windows.Forms.DataGridViewComboBoxColumn dataGridViewTextBoxColumn3; private System.Windows.Forms.DataGridViewTextBoxColumn dataGridViewTextBoxColumn4; private System.Windows.Forms.DataGridViewTextBoxColumn dataGridViewTextBoxColumn5; private System.Windows.Forms.DataGridViewTextBoxColumn dataGridViewTextBoxColumn6; private System.Windows.Forms.Label label1; private System.Windows.Forms.BindingSource listaDescuentosBindingSource; } }
60.725092
211
0.672926
[ "MIT" ]
Jflores1703/Worldtec
Proyecto_WorldTec/Proyecto_WorldTec/FormFactura.Designer.cs
32,919
C#
namespace Company.BankApp.DataAccess { // Lecture: Sometimes you want to group up configurations that are constants // or values that you repeatedly need. Consolidating them into a "Constants" object // or a "Defaults" object is an option, but retrieving values from a configuration file // or some other external source would be more extensible and maintainable. public static class FormatDefaults { public static string UserFormat => "yyyyMMdd_hh_mm_ss_ms"; public static string BankAccountFormat => "yyyyMMdd_hh_mm_ss_ms"; } }
41.142857
91
0.736111
[ "MIT" ]
v-vong3/csulb
cecs_491/demo/full-stack-demo/backend/Company.BankApp.DataAccess/FormatDefaults.cs
578
C#
using System; using System.Collections.Generic; using System.IO; namespace NHM.Common { public static class Paths { public static string Root { get; private set; } = ""; public static string AppRoot { get; private set; } = ""; public static void SetRoot(string rootPath) { Root = rootPath; } public static void SetAppRoot(string appRootPath) { AppRoot = appRootPath; } [Obsolete("Use MinerPluginsPath(params string[] paths)", true)] public static string MinerPluginsPath() { return RootPath("miner_plugins"); } public static string MinerPluginsPath(params string[] paths) { return RootPath("miner_plugins", paths); } public static string ConfigsPath(params string[] paths) { return RootPath("configs", paths); } public static string InternalsPath(params string[] paths) { return RootPath("internals", paths); } public static string RootPath(string subPath, params string[] paths) { var combine = new List<string> { Root, subPath }; if (paths.Length > 0) combine.AddRange(paths); var path = Path.Combine(combine.ToArray()); return path; } public static string AppRootPath(string subPath, params string[] paths) { var combine = new List<string> { AppRoot, subPath }; if (paths.Length > 0) combine.AddRange(paths); var path = Path.Combine(combine.ToArray()); return path; } public static bool EnsureDirectoryPath(string directoryPath) { try { if (Directory.Exists(directoryPath)) return true; Directory.CreateDirectory(directoryPath); return true; } catch (Exception e) { Logger.Error("NHM.Common.Paths", $"EnsureDirectoryPath Error occured for directoryPath '{directoryPath}': {e.Message}"); return false; } } } }
29.266667
136
0.554442
[ "MIT" ]
Hungkoi99/NiceHashMiner
src/NHM.Common/Paths.cs
2,197
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace PhysisWeather.Core.Base.Extensions { public static class StringExtensions { public static string GetFirst(this string source, int numberOfChars) { if (source.Length > numberOfChars) { return source.Substring(0, numberOfChars); } return source; } public static string GetLast(this string source, int numberOfChars) { if (numberOfChars >= source.Length) { return source; } return source.Substring(source.Length - numberOfChars); } public static string GetAfterLastOrEmpty(this string text, string stopAt) { if (!string.IsNullOrEmpty(text) && !string.IsNullOrEmpty(stopAt)) { int charLocation = text.LastIndexOf(stopAt) + 1; if (charLocation > 0) { return text.Substring(charLocation, text.Length - charLocation); } } return string.Empty; } public static string GetUntilOrEmpty(this string text, string stopAt) { if (!string.IsNullOrEmpty(text) && !string.IsNullOrEmpty(stopAt)) { int charLocation = text.IndexOf(stopAt, StringComparison.Ordinal); if (charLocation > 0) { return text.Substring(0, charLocation); } } return string.Empty; } /// <summary> /// Takes PascalCase and transforms to Pascal Case. Also does AMACharter to AMA Charter. /// If the preposition is the first or last word, then it should still be capitalized. /// </summary> public static string ToDisplayName(this string s, string spacer = " ", bool ignorePrepositions = false) { string eval = s ?? ""; int words = 0; StringBuilder displayName = new StringBuilder(eval.Length); int wordStart = 0; int wordEnd = 0; for (int i = 0; i < eval.Length; i++) { wordEnd += 1; if (i + 1 < eval.Length && eval[i + 1].IsUpper()) { bool endsWithUpper = eval[i].IsUpper(); bool nextCharacterIsLower = i + 2 < eval.Length && eval[i + 2].IsLower(); if (!endsWithUpper || nextCharacterIsLower) { string wordString = eval.Substring(wordStart, wordEnd - wordStart); if (words > 0 && (!ignorePrepositions && prepositions.TryGetValue(wordString, out string preposition))) //If the preposition is not the first or last word, then it should be lower case { wordString = preposition; } displayName.Append(wordString); words++; if (eval[i] != '-')// No space after - { displayName.Append(spacer); } wordStart = wordEnd; } } } displayName.Append(eval, wordStart, wordEnd - wordStart); return displayName.ToString(); } /// <summary> /// A list of prepositions. /// </summary> private static readonly Dictionary<string, string> prepositions = new string[] { "a", "an", "and", "aboard", "about", "above", "across", "after", "against", "along", "amid", "among", "anti", "around", "as", "at", "before", "behind", "below", "beneath", "but", "beside", "besides", "between", "beyond", "by", "concerning", "underneath", "considering", "despite", "down", "during", "except", "excepting", "excluding", "following", "for", "from", "in", "inside", "into", "like", "minus", "near", "of", "or", "on", "onto", "opposite", "outside", "over", "past", "per", "plus", "regarding", "round", "save", "since", "the", "than", "through", "to", "toward", "towards", "under", "unlike", "until", "up", "upon", "versus", "via", "with", "within", "without", "now", "that", "if", "when", "because", "while", "where", "unless", "so", "though", "whether", "although", "nor", "once" } .ToDictionary(prep => prep, prep => prep, StringComparer.OrdinalIgnoreCase); } }
28.059701
208
0.416312
[ "MIT" ]
aaron-salisbury/PhysisWeather
PhysisWeather/PhysisWeather.Core/Base/Extensions/StringExtensions.cs
5,642
C#
namespace IAGrim.UI.Filters { partial class DamageOverTimeFilter { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Component Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.dotPanel = new IAGrim.Theme.CollapseablePanelBox(); this.dmgPoison = new FirefoxCheckBox(); this.dmgLifeLeech = new FirefoxCheckBox(); this.dmgVitalityDecay = new FirefoxCheckBox(); this.dmgFrost = new FirefoxCheckBox(); this.dmgTrauma = new FirefoxCheckBox(); this.dmgBurn = new FirefoxCheckBox(); this.dmgElectrocute = new FirefoxCheckBox(); this.dmgBleeding = new FirefoxCheckBox(); this.dotPanel.SuspendLayout(); this.SuspendLayout(); // // dotPanel // this.dotPanel.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(240)))), ((int)(((byte)(240)))), ((int)(((byte)(240))))); this.dotPanel.Controls.Add(this.dmgPoison); this.dotPanel.Controls.Add(this.dmgLifeLeech); this.dotPanel.Controls.Add(this.dmgVitalityDecay); this.dotPanel.Controls.Add(this.dmgFrost); this.dotPanel.Controls.Add(this.dmgTrauma); this.dotPanel.Controls.Add(this.dmgBurn); this.dotPanel.Controls.Add(this.dmgElectrocute); this.dotPanel.Controls.Add(this.dmgBleeding); this.dotPanel.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Bold); this.dotPanel.ForeColor = System.Drawing.Color.Black; this.dotPanel.HeaderColor = System.Drawing.Color.FromArgb(((int)(((byte)(231)))), ((int)(((byte)(231)))), ((int)(((byte)(231))))); this.dotPanel.HeaderHeight = 29; this.dotPanel.Location = new System.Drawing.Point(0, 0); this.dotPanel.Name = "dotPanel"; this.dotPanel.NoRounding = false; this.dotPanel.Size = new System.Drawing.Size(285, 296); this.dotPanel.TabIndex = 42; this.dotPanel.Tag = "iatag_ui_dot"; this.dotPanel.Text = "Damage over Time"; this.dotPanel.TextLocation = "8; 5"; // // dmgPoison // this.dmgPoison.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.dmgPoison.Bold = false; this.dmgPoison.EnabledCalc = true; this.dmgPoison.Font = new System.Drawing.Font("Segoe UI", 10F); this.dmgPoison.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(66)))), ((int)(((byte)(78)))), ((int)(((byte)(90))))); this.dmgPoison.IsDarkMode = false; this.dmgPoison.Location = new System.Drawing.Point(3, 264); this.dmgPoison.Name = "dmgPoison"; this.dmgPoison.Size = new System.Drawing.Size(267, 27); this.dmgPoison.TabIndex = 7; this.dmgPoison.Tag = "iatag_ui_poison"; this.dmgPoison.Text = "Poison"; // // dmgLifeLeech // this.dmgLifeLeech.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.dmgLifeLeech.Bold = false; this.dmgLifeLeech.EnabledCalc = true; this.dmgLifeLeech.Font = new System.Drawing.Font("Segoe UI", 10F); this.dmgLifeLeech.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(66)))), ((int)(((byte)(78)))), ((int)(((byte)(90))))); this.dmgLifeLeech.IsDarkMode = false; this.dmgLifeLeech.Location = new System.Drawing.Point(3, 231); this.dmgLifeLeech.Name = "dmgLifeLeech"; this.dmgLifeLeech.Size = new System.Drawing.Size(267, 27); this.dmgLifeLeech.TabIndex = 6; this.dmgLifeLeech.Tag = "iatag_ui_lifeleech"; this.dmgLifeLeech.Text = "Life Leech"; // // dmgVitalityDecay // this.dmgVitalityDecay.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.dmgVitalityDecay.Bold = false; this.dmgVitalityDecay.EnabledCalc = true; this.dmgVitalityDecay.Font = new System.Drawing.Font("Segoe UI", 10F); this.dmgVitalityDecay.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(66)))), ((int)(((byte)(78)))), ((int)(((byte)(90))))); this.dmgVitalityDecay.IsDarkMode = false; this.dmgVitalityDecay.Location = new System.Drawing.Point(3, 198); this.dmgVitalityDecay.Name = "dmgVitalityDecay"; this.dmgVitalityDecay.Size = new System.Drawing.Size(267, 27); this.dmgVitalityDecay.TabIndex = 5; this.dmgVitalityDecay.Tag = "iatag_ui_decay"; this.dmgVitalityDecay.Text = "Decay"; // // dmgFrost // this.dmgFrost.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.dmgFrost.Bold = false; this.dmgFrost.EnabledCalc = true; this.dmgFrost.Font = new System.Drawing.Font("Segoe UI", 10F); this.dmgFrost.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(66)))), ((int)(((byte)(78)))), ((int)(((byte)(90))))); this.dmgFrost.IsDarkMode = false; this.dmgFrost.Location = new System.Drawing.Point(3, 132); this.dmgFrost.Name = "dmgFrost"; this.dmgFrost.Size = new System.Drawing.Size(267, 27); this.dmgFrost.TabIndex = 3; this.dmgFrost.Tag = "iatag_ui_frost"; this.dmgFrost.Text = "Frost/freeze"; // // dmgTrauma // this.dmgTrauma.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.dmgTrauma.Bold = false; this.dmgTrauma.EnabledCalc = true; this.dmgTrauma.Font = new System.Drawing.Font("Segoe UI", 10F); this.dmgTrauma.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(66)))), ((int)(((byte)(78)))), ((int)(((byte)(90))))); this.dmgTrauma.IsDarkMode = false; this.dmgTrauma.Location = new System.Drawing.Point(3, 66); this.dmgTrauma.Name = "dmgTrauma"; this.dmgTrauma.Size = new System.Drawing.Size(267, 27); this.dmgTrauma.TabIndex = 1; this.dmgTrauma.Tag = "iatag_ui_trauma"; this.dmgTrauma.Text = "Trauma"; // // dmgBurn // this.dmgBurn.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.dmgBurn.Bold = false; this.dmgBurn.EnabledCalc = true; this.dmgBurn.Font = new System.Drawing.Font("Segoe UI", 10F); this.dmgBurn.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(66)))), ((int)(((byte)(78)))), ((int)(((byte)(90))))); this.dmgBurn.IsDarkMode = false; this.dmgBurn.Location = new System.Drawing.Point(3, 99); this.dmgBurn.Name = "dmgBurn"; this.dmgBurn.Size = new System.Drawing.Size(267, 27); this.dmgBurn.TabIndex = 2; this.dmgBurn.Tag = "iatag_ui_burn"; this.dmgBurn.Text = "Burn"; // // dmgElectrocute // this.dmgElectrocute.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.dmgElectrocute.Bold = false; this.dmgElectrocute.EnabledCalc = true; this.dmgElectrocute.Font = new System.Drawing.Font("Segoe UI", 10F); this.dmgElectrocute.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(66)))), ((int)(((byte)(78)))), ((int)(((byte)(90))))); this.dmgElectrocute.IsDarkMode = false; this.dmgElectrocute.Location = new System.Drawing.Point(3, 165); this.dmgElectrocute.Name = "dmgElectrocute"; this.dmgElectrocute.Size = new System.Drawing.Size(267, 27); this.dmgElectrocute.TabIndex = 4; this.dmgElectrocute.Tag = "iatag_ui_electrocute"; this.dmgElectrocute.Text = "Electrocute"; // // dmgBleeding // this.dmgBleeding.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.dmgBleeding.Bold = false; this.dmgBleeding.EnabledCalc = true; this.dmgBleeding.Font = new System.Drawing.Font("Segoe UI", 10F); this.dmgBleeding.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(66)))), ((int)(((byte)(78)))), ((int)(((byte)(90))))); this.dmgBleeding.IsDarkMode = false; this.dmgBleeding.Location = new System.Drawing.Point(3, 33); this.dmgBleeding.Name = "dmgBleeding"; this.dmgBleeding.Size = new System.Drawing.Size(267, 27); this.dmgBleeding.TabIndex = 0; this.dmgBleeding.Tag = "iatag_ui_bleeding"; this.dmgBleeding.Text = "Bleeding"; // // DamageOverTimeFilter // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.Controls.Add(this.dotPanel); this.Name = "DamageOverTimeFilter"; this.Size = new System.Drawing.Size(285, 299); this.dotPanel.ResumeLayout(false); this.ResumeLayout(false); } #endregion private Theme.CollapseablePanelBox dotPanel; private FirefoxCheckBox dmgLifeLeech; private FirefoxCheckBox dmgVitalityDecay; private FirefoxCheckBox dmgFrost; private FirefoxCheckBox dmgTrauma; private FirefoxCheckBox dmgBurn; private FirefoxCheckBox dmgElectrocute; private FirefoxCheckBox dmgBleeding; private FirefoxCheckBox dmgPoison; } }
54.023256
162
0.595867
[ "MIT" ]
211847750/iagd
IAGrim/UI/Filters/DamageOverTime.Designer.cs
11,617
C#
using Microsoft.Maui; using Microsoft.Maui.Controls; using Microsoft.Maui.Controls.Xaml; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace MediMinder.Pages { [XamlCompilation(XamlCompilationOptions.Compile)] public partial class MedicineListPage : ContentPage { public MedicineListPage() { InitializeComponent(); } } }
21.380952
55
0.719376
[ "MIT" ]
sander1095/mediminder-maui
MediMinder/Pages/MedicineListPage.xaml.cs
451
C#
/* * * (c) Copyright Ascensio System Limited 2010-2021 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System; using System.Collections.Generic; using System.Threading; using ASC.Common.Logging; using ASC.Core; using ASC.Core.Common.Contracts; using ASC.Core.Tenants; using ASC.Notify.Cron; namespace ASC.Data.Backup.Storage { public class Schedule { public int TenantId { get; private set; } public string Cron { get; set; } public bool BackupMail { get; set; } public int NumberOfBackupsStored { get; set; } public BackupStorageType StorageType { get; set; } public string StorageBasePath { get; set; } public DateTime LastBackupTime { get; internal set; } public Dictionary<string, string> StorageParams { get; internal set; } public Schedule(int tenantId) { TenantId = tenantId; } public bool IsToBeProcessed() { try { var cron = new CronExpression(Cron); var tenant = CoreContext.TenantManager.GetTenant(TenantId); var tenantTimeZone = tenant.TimeZone; var culture = tenant.GetCulture(); Thread.CurrentThread.CurrentCulture = culture; var lastBackupTime = LastBackupTime.Equals(default(DateTime)) ? DateTime.UtcNow.Date.AddSeconds(-1) : TenantUtil.DateTimeFromUtc(tenantTimeZone, LastBackupTime); var nextBackupTime = cron.GetTimeAfter(lastBackupTime); if (!nextBackupTime.HasValue) return false; var now = TenantUtil.DateTimeFromUtc(tenantTimeZone, DateTime.UtcNow); return nextBackupTime <= now; } catch (Exception e) { LogManager.GetLogger("ASC").Error("Schedule " + TenantId, e); return false; } } } }
33.445946
86
0.628687
[ "ECL-2.0", "Apache-2.0", "MIT" ]
ONLYOFFICE/CommunityServer
common/ASC.Data.Backup/Storage/Schedule.cs
2,475
C#
using System; using System.Data; using System.Configuration; using System.Collections; using System.Web; using System.Collections.Generic; using System.Security; using System.Web.Security; namespace EatFit.Data { public class Grade { private int grade_level_id; public int GradeLevelId { get { return grade_level_id; } set { grade_level_id = value; } } private string grade_level; public string GradeLevel { get { return grade_level; } set { grade_level = value; } } } public class Grades { private static CAESDO.DataOps dops = new CAESDO.DataOps(); public static List<Grade> GetAllGrades() { List<Grade> gradeList = new List<Grade>(); dops.ResetDops(); dops.Sproc = "grade_level_GetAllGrades"; ArrayList fields = new ArrayList(); fields.Add("grade_level_id"); fields.Add("grade_level"); ArrayList results = dops.get_arrayList(fields); ArrayList result; int i = 0; while (i < results.Count) { result = (ArrayList)results[i]; Grade grade = new Grade(); grade.GradeLevelId = (int)result[0]; grade.GradeLevel = (string)result[1]; gradeList.Add(grade); i++; } return gradeList; } public static bool AddUserToGrade(string UserName, int GradeLevelId) { bool retval = true; dops.ResetDops(); dops.Sproc = "grade_level_AddUserToGrade"; dops.SetParameter("@UserName", UserName, CAESDO.DataOps.DopsDirection.Input); dops.SetParameter("@grade_level_id", GradeLevelId, CAESDO.DataOps.DopsDirection.Input); try { dops.Execute_Sql(); } catch (System.Data.SqlClient.SqlException ex) { retval = false; throw ex; } return retval; } } }
24.954023
99
0.532934
[ "MIT" ]
ucdavis/EatFit
EatFit.Data/GradeLevel.cs
2,171
C#
// Copyright 1998-2016 Epic Games, Inc. All Rights Reserved. using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace UnrealBuildTool { /// <summary> /// Base class for file system objects (files or directories). /// </summary> [Serializable] public abstract class FileSystemReference { /// <summary> /// The path to this object. Stored as an absolute path, with O/S preferred separator characters, and no trailing slash for directories. /// </summary> public readonly string FullName; /// <summary> /// The canonical full name for this object. /// </summary> public readonly string CanonicalName; /// <summary> /// Constructs a filesystem object for the given path. /// </summary> public FileSystemReference(string InPath) { FullName = Path.GetFullPath(InPath).TrimEnd(Path.DirectorySeparatorChar); CanonicalName = FullName.ToLowerInvariant(); } /// <summary> /// Constructs a reference from the given FileSystemInfo. /// </summary> public FileSystemReference(FileSystemInfo InInfo) { FullName = InInfo.FullName; CanonicalName = FullName.ToLowerInvariant(); } /// <summary> /// Direct constructor for a path /// </summary> protected FileSystemReference(string InFullName, string InCanonicalName) { FullName = InFullName; CanonicalName = InCanonicalName; } /// <summary> /// Create a full path by concatenating multiple strings /// </summary> /// <returns></returns> static protected string CombineStrings(DirectoryReference BaseDirectory, params string[] Fragments) { // Get the initial string to append to, and strip any root directory suffix from it StringBuilder NewFullName = new StringBuilder(BaseDirectory.FullName); if (NewFullName.Length > 0 && NewFullName[NewFullName.Length - 1] == Path.DirectorySeparatorChar) { NewFullName.Remove(NewFullName.Length - 1, 1); } // Scan through the fragments to append, appending them to a string and updating the base length as we go foreach (string Fragment in Fragments) { // Check if this fragment is an absolute path if ((Fragment.Length >= 2 && Fragment[1] == ':') || (Fragment.Length >= 1 && (Fragment[0] == Path.DirectorySeparatorChar || Fragment[0] == Path.AltDirectorySeparatorChar))) { // It is. Reset the new name to the full version of this path. NewFullName.Clear(); NewFullName.Append(Path.GetFullPath(Fragment)); } else { // Append all the parts of this fragment to the end of the existing path. int StartIdx = 0; while (StartIdx < Fragment.Length) { // Find the end of this fragment. We may have been passed multiple paths in the same string. int EndIdx = StartIdx; while (EndIdx < Fragment.Length && Fragment[EndIdx] != Path.DirectorySeparatorChar && Fragment[EndIdx] != Path.AltDirectorySeparatorChar) { EndIdx++; } // Ignore any empty sections, like leading or trailing slashes, and '.' directory references. int Length = EndIdx - StartIdx; if (Length == 0) { // Multiple directory separators in a row; illegal. throw new ArgumentException("Path fragment '{0}' contains invalid directory separators."); } else if (Length == 2 && Fragment[StartIdx] == '.' && Fragment[StartIdx + 1] == '.') { // Remove the last directory name for (int SeparatorIdx = NewFullName.Length - 1; SeparatorIdx >= 0; SeparatorIdx--) { if (NewFullName[SeparatorIdx] == Path.DirectorySeparatorChar) { NewFullName.Remove(SeparatorIdx, NewFullName.Length - SeparatorIdx); break; } } } else if (Length != 1 || Fragment[StartIdx] != '.') { // Append this fragment NewFullName.Append(Path.DirectorySeparatorChar); NewFullName.Append(Fragment, StartIdx, Length); } // Move to the next part StartIdx = EndIdx + 1; } } } // Append the directory separator if (NewFullName.Length == 0 || (NewFullName.Length == 2 && NewFullName[1] == ':')) { NewFullName.Append(Path.DirectorySeparatorChar); } // Set the new path variables return NewFullName.ToString(); } /// <summary> /// Checks whether this name has the given extension. /// </summary> /// <param name="Extension">The extension to check</param> /// <returns>True if this name has the given extension, false otherwise</returns> public bool HasExtension(string Extension) { if (Extension.Length > 0 && Extension[0] != '.') { return HasExtension("." + Extension); } else { return CanonicalName.EndsWith(Extension.ToLowerInvariant()); } } /// <summary> /// Determines if the given object is at or under the given directory /// </summary> /// <param name="Directory"></param> /// <returns></returns> public bool IsUnderDirectory(DirectoryReference Other) { return CanonicalName.StartsWith(Other.CanonicalName) && (CanonicalName.Length == Other.CanonicalName.Length || CanonicalName[Other.CanonicalName.Length] == Path.DirectorySeparatorChar); } /// <summary> /// Creates a relative path from the given base directory /// </summary> /// <param name="Directory">The directory to create a relative path from</param> /// <returns>A relative path from the given directory</returns> public string MakeRelativeTo(DirectoryReference Directory) { // Find how much of the path is common between the two paths. This length does not include a trailing directory separator character. int CommonDirectoryLength = -1; for (int Idx = 0; ; Idx++) { if (Idx == CanonicalName.Length) { // The two paths are identical. Just return the "." character. if (Idx == Directory.CanonicalName.Length) { return "."; } // Check if we're finishing on a complete directory name if (Directory.CanonicalName[Idx] == Path.DirectorySeparatorChar) { CommonDirectoryLength = Idx; } break; } else if (Idx == Directory.CanonicalName.Length) { // Check whether the end of the directory name coincides with a boundary for the current name. if (CanonicalName[Idx] == Path.DirectorySeparatorChar) { CommonDirectoryLength = Idx; } break; } else { // Check the two paths match, and bail if they don't. Increase the common directory length if we've reached a separator. if (CanonicalName[Idx] != Directory.CanonicalName[Idx]) { break; } if (CanonicalName[Idx] == Path.DirectorySeparatorChar) { CommonDirectoryLength = Idx; } } } // If there's no relative path, just return the absolute path if (CommonDirectoryLength == -1) { return FullName; } // Append all the '..' separators to get back to the common directory, then the rest of the string to reach the target item StringBuilder Result = new StringBuilder(); for (int Idx = CommonDirectoryLength + 1; Idx < Directory.CanonicalName.Length; Idx++) { // Move up a directory Result.Append(".."); Result.Append(Path.DirectorySeparatorChar); // Scan to the next directory separator while (Idx < Directory.CanonicalName.Length && Directory.CanonicalName[Idx] != Path.DirectorySeparatorChar) { Idx++; } } if (CommonDirectoryLength + 1 < FullName.Length) { Result.Append(FullName, CommonDirectoryLength + 1, FullName.Length - CommonDirectoryLength - 1); } return Result.ToString(); } /// <summary> /// Returns a string representation of this filesystem object /// </summary> /// <returns>Full path to the object</returns> public override string ToString() { return FullName; } } /// <summary> /// Representation of an absolute directory path. Allows fast hashing and comparisons. /// </summary> [Serializable] public class DirectoryReference : FileSystemReference { /// <summary> /// Default constructor. /// </summary> /// <param name="InPath">Path to this directory.</param> public DirectoryReference(string InPath) : base(InPath) { } /// <summary> /// Construct a DirectoryReference from a DirectoryInfo object. /// </summary> /// <param name="InInfo">Path to this file</param> public DirectoryReference(DirectoryInfo InInfo) : base(InInfo) { } /// <summary> /// Constructor for creating a directory object directly from two strings. /// </summary> /// <param name="InFullName"></param> /// <param name="InCanonicalName"></param> protected DirectoryReference(string InFullName, string InCanonicalName) : base(InFullName, InCanonicalName) { } /// <summary> /// Gets the top level directory name /// </summary> /// <returns>The name of the directory</returns> public string GetDirectoryName() { return Path.GetFileName(FullName); } /// <summary> /// Gets the directory containing this object /// </summary> /// <returns>A new directory object representing the directory containing this object</returns> public DirectoryReference ParentDirectory { get { if (IsRootDirectory()) { return null; } int ParentLength = CanonicalName.LastIndexOf(Path.DirectorySeparatorChar); if (ParentLength == 2 && CanonicalName[1] == ':') { ParentLength++; } return new DirectoryReference(FullName.Substring(0, ParentLength), CanonicalName.Substring(0, ParentLength)); } } /// <summary> /// Gets the parent directory for a file /// </summary> /// <param name="File">The file to get directory for</param> /// <returns>The full directory name containing the given file</returns> public static DirectoryReference GetParentDirectory(FileReference File) { int ParentLength = File.CanonicalName.LastIndexOf(Path.DirectorySeparatorChar); return new DirectoryReference(File.FullName.Substring(0, ParentLength), File.CanonicalName.Substring(0, ParentLength)); } /// <summary> /// Creates the directory /// </summary> public void CreateDirectory() { Directory.CreateDirectory(FullName); } /// <summary> /// Checks whether the directory exists /// </summary> /// <returns>True if this directory exists</returns> public bool Exists() { return Directory.Exists(FullName); } /// <summary> /// Enumerate files from a given directory /// </summary> /// <returns>Sequence of file references</returns> public IEnumerable<FileReference> EnumerateFileReferences() { foreach (string FileName in Directory.EnumerateFiles(FullName)) { yield return FileReference.MakeFromNormalizedFullPath(FileName); } } /// <summary> /// Enumerate files from a given directory /// </summary> /// <returns>Sequence of file references</returns> public IEnumerable<FileReference> EnumerateFileReferences(string Pattern) { foreach (string FileName in Directory.EnumerateFiles(FullName, Pattern)) { yield return FileReference.MakeFromNormalizedFullPath(FileName); } } /// <summary> /// Enumerate files from a given directory /// </summary> /// <returns>Sequence of file references</returns> public IEnumerable<FileReference> EnumerateFileReferences(string Pattern, SearchOption Option) { foreach (string FileName in Directory.EnumerateFiles(FullName, Pattern, Option)) { yield return FileReference.MakeFromNormalizedFullPath(FileName); } } /// <summary> /// Enumerate subdirectories in a given directory /// </summary> /// <returns>Sequence of directory references</returns> public IEnumerable<DirectoryReference> EnumerateDirectoryReferences() { foreach (string DirectoryName in Directory.EnumerateDirectories(FullName)) { yield return DirectoryReference.MakeFromNormalizedFullPath(DirectoryName); } } /// <summary> /// Enumerate subdirectories in a given directory /// </summary> /// <returns>Sequence of directory references</returns> public IEnumerable<DirectoryReference> EnumerateDirectoryReferences(string Pattern) { foreach (string DirectoryName in Directory.EnumerateDirectories(FullName, Pattern)) { yield return DirectoryReference.MakeFromNormalizedFullPath(DirectoryName); } } /// <summary> /// Enumerate subdirectories in a given directory /// </summary> /// <returns>Sequence of directory references</returns> public IEnumerable<DirectoryReference> EnumerateDirectoryReferences(string Pattern, SearchOption Option) { foreach (string DirectoryName in Directory.EnumerateDirectories(FullName, Pattern, Option)) { yield return DirectoryReference.MakeFromNormalizedFullPath(DirectoryName); } } /// <summary> /// Determines whether this path represents a root directory in the filesystem /// </summary> /// <returns>True if this path is a root directory, false otherwise</returns> public bool IsRootDirectory() { return CanonicalName[CanonicalName.Length - 1] == Path.DirectorySeparatorChar; } /// <summary> /// Combine several fragments with a base directory, to form a new directory name /// </summary> /// <param name="BaseDirectory">The base directory</param> /// <param name="Fragments">Fragments to combine with the base directory</param> /// <returns>The new directory name</returns> public static DirectoryReference Combine(DirectoryReference BaseDirectory, params string[] Fragments) { string FullName = FileSystemReference.CombineStrings(BaseDirectory, Fragments); return new DirectoryReference(FullName, FullName.ToLowerInvariant()); } /// <summary> /// Compares two filesystem object names for equality. Uses the canonical name representation, not the display name representation. /// </summary> /// <param name="A">First object to compare.</param> /// <param name="B">Second object to compare.</param> /// <returns>True if the names represent the same object, false otherwise</returns> public static bool operator ==(DirectoryReference A, DirectoryReference B) { if ((object)A == null) { return (object)B == null; } else { return (object)B != null && A.CanonicalName == B.CanonicalName; } } /// <summary> /// Compares two filesystem object names for inequality. Uses the canonical name representation, not the display name representation. /// </summary> /// <param name="A">First object to compare.</param> /// <param name="B">Second object to compare.</param> /// <returns>False if the names represent the same object, true otherwise</returns> public static bool operator !=(DirectoryReference A, DirectoryReference B) { return !(A == B); } /// <summary> /// Compares against another object for equality. /// </summary> /// <param name="A">First name to compare.</param> /// <param name="B">Second name to compare.</param> /// <returns>True if the names represent the same object, false otherwise</returns> public override bool Equals(object Obj) { return (Obj is DirectoryReference) && ((DirectoryReference)Obj) == this; } /// <summary> /// Returns a hash code for this object /// </summary> /// <returns></returns> public override int GetHashCode() { return CanonicalName.GetHashCode(); } /// <summary> /// Helper function to create a remote directory reference. Unlike normal DirectoryReference objects, these aren't converted to a full path in the local filesystem. /// </summary> /// <param name="AbsolutePath">The absolute path in the remote file system</param> /// <returns>New directory reference</returns> public static DirectoryReference MakeRemote(string AbsolutePath) { return new DirectoryReference(AbsolutePath, AbsolutePath.ToLowerInvariant()); } /// <summary> /// Helper function to create a directory reference from a raw platform path. The path provided *MUST* be exactly the same as that returned by Path.GetFullPath(). /// </summary> /// <param name="AbsolutePath">The absolute path in the file system</param> /// <returns>New file reference</returns> public static DirectoryReference MakeFromNormalizedFullPath(string AbsolutePath) { return new DirectoryReference(AbsolutePath, AbsolutePath.ToLowerInvariant()); } /// <summary> /// Gets the parent directory for a file, or returns null if it's null. /// </summary> /// <param name="File">The file to create a directory reference for</param> /// <returns>The directory containing the file </returns> public static DirectoryReference FromFile(FileReference File) { return (File == null)? null : File.Directory; } } /// <summary> /// Representation of an absolute file path. Allows fast hashing and comparisons. /// </summary> [Serializable] public class FileReference : FileSystemReference { /// <summary> /// Default constructor. /// </summary> /// <param name="InPath">Path to this file</param> public FileReference(string InPath) : base(InPath) { } /// <summary> /// Construct a FileReference from a FileInfo object. /// </summary> /// <param name="InInfo">Path to this file</param> public FileReference(FileInfo InInfo) : base(InInfo) { } /// <summary> /// Default constructor. /// </summary> /// <param name="InPath">Path to this file</param> protected FileReference(string InFullName, string InCanonicalName) : base(InFullName, InCanonicalName) { } /// <summary> /// Gets the file name without path information /// </summary> /// <returns>A string containing the file name</returns> public string GetFileName() { return Path.GetFileName(FullName); } /// <summary> /// Gets the file name without path information or an extension /// </summary> /// <returns>A string containing the file name without an extension</returns> public string GetFileNameWithoutExtension() { return Path.GetFileNameWithoutExtension(FullName); } /// <summary> /// Gets the file name without path or any extensions /// </summary> /// <returns>A string containing the file name without an extension</returns> public string GetFileNameWithoutAnyExtensions() { int StartIdx = FullName.LastIndexOf(Path.DirectorySeparatorChar) + 1; int EndIdx = FullName.IndexOf('.', StartIdx); if (EndIdx < StartIdx) { return FullName.Substring(StartIdx); } else { return FullName.Substring(StartIdx, EndIdx - StartIdx); } } /// <summary> /// Gets the extension for this filename /// </summary> /// <returns>A string containing the extension of this filename</returns> public string GetExtension() { return Path.GetExtension(FullName); } /// <summary> /// Change the file's extension to something else /// </summary> /// <param name="Extension">The new extension</param> /// <returns>A FileReference with the same path and name, but with the new extension</returns> public FileReference ChangeExtension(string Extension) { string NewFullName = Path.ChangeExtension(FullName, Extension); return new FileReference(NewFullName, NewFullName.ToLowerInvariant()); } /// <summary> /// Gets the directory containing this file /// </summary> /// <returns>A new directory object representing the directory containing this object</returns> public DirectoryReference Directory { get { return DirectoryReference.GetParentDirectory(this); } } /// <summary> /// Determines whether the given filename exists /// </summary> /// <returns>True if it exists, false otherwise</returns> public bool Exists() { return File.Exists(FullName); } /// <summary> /// Deletes this file /// </summary> public void Delete() { File.Delete(FullName); } /// <summary> /// Combine several fragments with a base directory, to form a new filename /// </summary> /// <param name="BaseDirectory">The base directory</param> /// <param name="Fragments">Fragments to combine with the base directory</param> /// <returns>The new file name</returns> public static FileReference Combine(DirectoryReference BaseDirectory, params string[] Fragments) { string FullName = FileSystemReference.CombineStrings(BaseDirectory, Fragments); return new FileReference(FullName, FullName.ToLowerInvariant()); } /// <summary> /// Append a string to the end of a filename /// </summary> /// <param name="A">The base file reference</param> /// <param name="B">Suffix to be appended</param> /// <returns>The new file reference</returns> public static FileReference operator +(FileReference A, string B) { return new FileReference(A.FullName + B, A.CanonicalName + B.ToLowerInvariant()); } /// <summary> /// Compares two filesystem object names for equality. Uses the canonical name representation, not the display name representation. /// </summary> /// <param name="A">First object to compare.</param> /// <param name="B">Second object to compare.</param> /// <returns>True if the names represent the same object, false otherwise</returns> public static bool operator ==(FileReference A, FileReference B) { if ((object)A == null) { return (object)B == null; } else { return (object)B != null && A.CanonicalName == B.CanonicalName; } } /// <summary> /// Compares two filesystem object names for inequality. Uses the canonical name representation, not the display name representation. /// </summary> /// <param name="A">First object to compare.</param> /// <param name="B">Second object to compare.</param> /// <returns>False if the names represent the same object, true otherwise</returns> public static bool operator !=(FileReference A, FileReference B) { return !(A == B); } /// <summary> /// Compares against another object for equality. /// </summary> /// <param name="A">First name to compare.</param> /// <param name="B">Second name to compare.</param> /// <returns>True if the names represent the same object, false otherwise</returns> public override bool Equals(object Obj) { return (Obj is FileReference) && ((FileReference)Obj) == this; } /// <summary> /// Returns a hash code for this object /// </summary> /// <returns></returns> public override int GetHashCode() { return CanonicalName.GetHashCode(); } /// <summary> /// Helper function to create a remote file reference. Unlike normal FileReference objects, these aren't converted to a full path in the local filesystem, but are /// left as they are passed in. /// </summary> /// <param name="AbsolutePath">The absolute path in the remote file system</param> /// <returns>New file reference</returns> public static FileReference MakeRemote(string AbsolutePath) { return new FileReference(AbsolutePath, AbsolutePath.ToLowerInvariant()); } /// <summary> /// Helper function to create a file reference from a raw platform path. The path provided *MUST* be exactly the same as that returned by Path.GetFullPath(). /// </summary> /// <param name="AbsolutePath">The absolute path in the file system</param> /// <returns>New file reference</returns> public static FileReference MakeFromNormalizedFullPath(string AbsolutePath) { return new FileReference(AbsolutePath, AbsolutePath.ToLowerInvariant()); } } static class FileReferenceExtensionMethods { /// <summary> /// Manually serialize a file reference to a binary stream. /// </summary> /// <param name="Writer">Binary writer to write to</param> public static void Write(this BinaryWriter Writer, FileReference File) { Writer.Write((File == null) ? String.Empty : File.FullName); } /// <summary> /// Serializes a file reference, using a lookup table to avoid serializing the same name more than once. /// </summary> /// <param name="Writer">The writer to save this reference to</param> /// <param name="File">A file reference to output; may be null</param> /// <param name="FileToUniqueId">A lookup table that caches previous files that have been output, and maps them to unique id's.</param> public static void Write(this BinaryWriter Writer, FileReference File, Dictionary<FileReference, int> FileToUniqueId) { int UniqueId; if (File == null) { Writer.Write(-1); } else if (FileToUniqueId.TryGetValue(File, out UniqueId)) { Writer.Write(UniqueId); } else { Writer.Write(FileToUniqueId.Count); Writer.Write(File); FileToUniqueId.Add(File, FileToUniqueId.Count); } } /// <summary> /// Manually deserialize a file reference from a binary stream. /// </summary> /// <param name="Reader">Binary reader to read from</param> /// <returns>New FileReference object</returns> public static FileReference ReadFileReference(this BinaryReader Reader) { string FullName = Reader.ReadString(); return (FullName.Length == 0) ? null : FileReference.MakeFromNormalizedFullPath(FullName); } /// <summary> /// Deserializes a file reference, using a lookup table to avoid writing the same name more than once. /// </summary> /// <param name="Reader">The source to read from</param> /// <param name="UniqueFiles">List of previously read file references. The index into this array is used in place of subsequent ocurrences of the file.</param> /// <returns>The file reference that was read</returns> public static FileReference ReadFileReference(this BinaryReader Reader, List<FileReference> UniqueFiles) { int UniqueId = Reader.ReadInt32(); if (UniqueId == -1) { return null; } else if (UniqueId < UniqueFiles.Count) { return UniqueFiles[UniqueId]; } else { FileReference Result = Reader.ReadFileReference(); UniqueFiles.Add(Result); return Result; } } } }
32.468593
188
0.688721
[ "MIT" ]
armroyce/Unreal
UnrealEngine-4.11.2-release/Engine/Source/Programs/UnrealBuildTool/System/FileSystemReference.cs
25,847
C#
using System.Linq; using System.Linq.Expressions; using Marten.Linq.Fields; using Weasel.Postgresql.SqlGeneration; namespace Marten.Linq.Parsing.Methods { public class NgramSearch: IMethodCallParser { public bool Matches(MethodCallExpression expression) { return expression.Method.Name == nameof(LinqExtensions.NgramSearch) && expression.Method.DeclaringType == typeof(LinqExtensions); } public ISqlFragment Parse(IFieldMapping mapping, ISerializer serializer, MethodCallExpression expression) { var members = FindMembers.Determine(expression); var locator = mapping.FieldFor(members).RawLocator; var values = expression.Arguments.Last().Value(); return new WhereFragment($"mt_grams_vector({locator}) @@ mt_grams_query(?)", values); } } }
32.666667
113
0.678005
[ "MIT" ]
Rob89/marten
src/Marten/Linq/Parsing/Methods/NgramSearch.cs
882
C#
using System; using System.Collections.Generic; using System.Reactive.Linq; using System.Reactive.Threading.Tasks; using MS.Core; namespace System { public static class __TimeZoneInfo { public static IObservable<System.TimeZoneInfo.AdjustmentRule[]> GetAdjustmentRules( this IObservable<System.TimeZoneInfo> TimeZoneInfoValue) { return Observable.Select(TimeZoneInfoValue, (TimeZoneInfoValueLambda) => TimeZoneInfoValueLambda.GetAdjustmentRules()); } public static IObservable<System.TimeSpan[]> GetAmbiguousTimeOffsets( this IObservable<System.TimeZoneInfo> TimeZoneInfoValue, IObservable<System.DateTimeOffset> dateTimeOffset) { return Observable.Zip(TimeZoneInfoValue, dateTimeOffset, (TimeZoneInfoValueLambda, dateTimeOffsetLambda) => TimeZoneInfoValueLambda.GetAmbiguousTimeOffsets(dateTimeOffsetLambda)); } public static IObservable<System.TimeSpan[]> GetAmbiguousTimeOffsets( this IObservable<System.TimeZoneInfo> TimeZoneInfoValue, IObservable<System.DateTime> dateTime) { return Observable.Zip(TimeZoneInfoValue, dateTime, (TimeZoneInfoValueLambda, dateTimeLambda) => TimeZoneInfoValueLambda.GetAmbiguousTimeOffsets(dateTimeLambda)); } public static IObservable<System.TimeSpan> GetUtcOffset(this IObservable<System.TimeZoneInfo> TimeZoneInfoValue, IObservable<System.DateTimeOffset> dateTimeOffset) { return Observable.Zip(TimeZoneInfoValue, dateTimeOffset, (TimeZoneInfoValueLambda, dateTimeOffsetLambda) => TimeZoneInfoValueLambda.GetUtcOffset(dateTimeOffsetLambda)); } public static IObservable<System.TimeSpan> GetUtcOffset(this IObservable<System.TimeZoneInfo> TimeZoneInfoValue, IObservable<System.DateTime> dateTime) { return Observable.Zip(TimeZoneInfoValue, dateTime, (TimeZoneInfoValueLambda, dateTimeLambda) => TimeZoneInfoValueLambda.GetUtcOffset(dateTimeLambda)); } public static IObservable<System.Boolean> IsAmbiguousTime( this IObservable<System.TimeZoneInfo> TimeZoneInfoValue, IObservable<System.DateTimeOffset> dateTimeOffset) { return Observable.Zip(TimeZoneInfoValue, dateTimeOffset, (TimeZoneInfoValueLambda, dateTimeOffsetLambda) => TimeZoneInfoValueLambda.IsAmbiguousTime(dateTimeOffsetLambda)); } public static IObservable<System.Boolean> IsAmbiguousTime( this IObservable<System.TimeZoneInfo> TimeZoneInfoValue, IObservable<System.DateTime> dateTime) { return Observable.Zip(TimeZoneInfoValue, dateTime, (TimeZoneInfoValueLambda, dateTimeLambda) => TimeZoneInfoValueLambda.IsAmbiguousTime(dateTimeLambda)); } public static IObservable<System.Boolean> IsDaylightSavingTime( this IObservable<System.TimeZoneInfo> TimeZoneInfoValue, IObservable<System.DateTimeOffset> dateTimeOffset) { return Observable.Zip(TimeZoneInfoValue, dateTimeOffset, (TimeZoneInfoValueLambda, dateTimeOffsetLambda) => TimeZoneInfoValueLambda.IsDaylightSavingTime(dateTimeOffsetLambda)); } public static IObservable<System.Boolean> IsDaylightSavingTime( this IObservable<System.TimeZoneInfo> TimeZoneInfoValue, IObservable<System.DateTime> dateTime) { return Observable.Zip(TimeZoneInfoValue, dateTime, (TimeZoneInfoValueLambda, dateTimeLambda) => TimeZoneInfoValueLambda.IsDaylightSavingTime(dateTimeLambda)); } public static IObservable<System.Boolean> IsInvalidTime(this IObservable<System.TimeZoneInfo> TimeZoneInfoValue, IObservable<System.DateTime> dateTime) { return Observable.Zip(TimeZoneInfoValue, dateTime, (TimeZoneInfoValueLambda, dateTimeLambda) => TimeZoneInfoValueLambda.IsInvalidTime(dateTimeLambda)); } public static IObservable<System.Reactive.Unit> ClearCachedData() { return ObservableExt.Factory(() => System.TimeZoneInfo.ClearCachedData()); } public static IObservable<System.DateTimeOffset> ConvertTimeBySystemTimeZoneId( IObservable<System.DateTimeOffset> dateTimeOffset, IObservable<System.String> destinationTimeZoneId) { return Observable.Zip(dateTimeOffset, destinationTimeZoneId, (dateTimeOffsetLambda, destinationTimeZoneIdLambda) => System.TimeZoneInfo.ConvertTimeBySystemTimeZoneId(dateTimeOffsetLambda, destinationTimeZoneIdLambda)); } public static IObservable<System.DateTime> ConvertTimeBySystemTimeZoneId(IObservable<System.DateTime> dateTime, IObservable<System.String> destinationTimeZoneId) { return Observable.Zip(dateTime, destinationTimeZoneId, (dateTimeLambda, destinationTimeZoneIdLambda) => System.TimeZoneInfo.ConvertTimeBySystemTimeZoneId(dateTimeLambda, destinationTimeZoneIdLambda)); } public static IObservable<System.DateTime> ConvertTimeBySystemTimeZoneId(IObservable<System.DateTime> dateTime, IObservable<System.String> sourceTimeZoneId, IObservable<System.String> destinationTimeZoneId) { return Observable.Zip(dateTime, sourceTimeZoneId, destinationTimeZoneId, (dateTimeLambda, sourceTimeZoneIdLambda, destinationTimeZoneIdLambda) => System.TimeZoneInfo.ConvertTimeBySystemTimeZoneId(dateTimeLambda, sourceTimeZoneIdLambda, destinationTimeZoneIdLambda)); } public static IObservable<System.DateTimeOffset> ConvertTime(IObservable<System.DateTimeOffset> dateTimeOffset, IObservable<System.TimeZoneInfo> destinationTimeZone) { return Observable.Zip(dateTimeOffset, destinationTimeZone, (dateTimeOffsetLambda, destinationTimeZoneLambda) => System.TimeZoneInfo.ConvertTime(dateTimeOffsetLambda, destinationTimeZoneLambda)); } public static IObservable<System.DateTime> ConvertTime(IObservable<System.DateTime> dateTime, IObservable<System.TimeZoneInfo> destinationTimeZone) { return Observable.Zip(dateTime, destinationTimeZone, (dateTimeLambda, destinationTimeZoneLambda) => System.TimeZoneInfo.ConvertTime(dateTimeLambda, destinationTimeZoneLambda)); } public static IObservable<System.DateTime> ConvertTime(IObservable<System.DateTime> dateTime, IObservable<System.TimeZoneInfo> sourceTimeZone, IObservable<System.TimeZoneInfo> destinationTimeZone) { return Observable.Zip(dateTime, sourceTimeZone, destinationTimeZone, (dateTimeLambda, sourceTimeZoneLambda, destinationTimeZoneLambda) => System.TimeZoneInfo.ConvertTime(dateTimeLambda, sourceTimeZoneLambda, destinationTimeZoneLambda)); } public static IObservable<System.DateTime> ConvertTimeFromUtc(IObservable<System.DateTime> dateTime, IObservable<System.TimeZoneInfo> destinationTimeZone) { return Observable.Zip(dateTime, destinationTimeZone, (dateTimeLambda, destinationTimeZoneLambda) => System.TimeZoneInfo.ConvertTimeFromUtc(dateTimeLambda, destinationTimeZoneLambda)); } public static IObservable<System.DateTime> ConvertTimeToUtc(IObservable<System.DateTime> dateTime) { return Observable.Select(dateTime, (dateTimeLambda) => System.TimeZoneInfo.ConvertTimeToUtc(dateTimeLambda)); } public static IObservable<System.DateTime> ConvertTimeToUtc(IObservable<System.DateTime> dateTime, IObservable<System.TimeZoneInfo> sourceTimeZone) { return Observable.Zip(dateTime, sourceTimeZone, (dateTimeLambda, sourceTimeZoneLambda) => System.TimeZoneInfo.ConvertTimeToUtc(dateTimeLambda, sourceTimeZoneLambda)); } public static IObservable<System.Boolean> Equals(this IObservable<System.TimeZoneInfo> TimeZoneInfoValue, IObservable<System.TimeZoneInfo> other) { return Observable.Zip(TimeZoneInfoValue, other, (TimeZoneInfoValueLambda, otherLambda) => TimeZoneInfoValueLambda.Equals(otherLambda)); } public static IObservable<System.Boolean> Equals(this IObservable<System.TimeZoneInfo> TimeZoneInfoValue, IObservable<System.Object> obj) { return Observable.Zip(TimeZoneInfoValue, obj, (TimeZoneInfoValueLambda, objLambda) => TimeZoneInfoValueLambda.Equals(objLambda)); } public static IObservable<System.TimeZoneInfo> FromSerializedString(IObservable<System.String> source) { return Observable.Select(source, (sourceLambda) => System.TimeZoneInfo.FromSerializedString(sourceLambda)); } public static IObservable<System.Int32> GetHashCode(this IObservable<System.TimeZoneInfo> TimeZoneInfoValue) { return Observable.Select(TimeZoneInfoValue, (TimeZoneInfoValueLambda) => TimeZoneInfoValueLambda.GetHashCode()); } public static IObservable<System.Collections.ObjectModel.ReadOnlyCollection<System.TimeZoneInfo>> GetSystemTimeZones() { return ObservableExt.Factory(() => System.TimeZoneInfo.GetSystemTimeZones()); } public static IObservable<System.Boolean> HasSameRules(this IObservable<System.TimeZoneInfo> TimeZoneInfoValue, IObservable<System.TimeZoneInfo> other) { return Observable.Zip(TimeZoneInfoValue, other, (TimeZoneInfoValueLambda, otherLambda) => TimeZoneInfoValueLambda.HasSameRules(otherLambda)); } public static IObservable<System.String> ToSerializedString( this IObservable<System.TimeZoneInfo> TimeZoneInfoValue) { return Observable.Select(TimeZoneInfoValue, (TimeZoneInfoValueLambda) => TimeZoneInfoValueLambda.ToSerializedString()); } public static IObservable<System.String> ToString(this IObservable<System.TimeZoneInfo> TimeZoneInfoValue) { return Observable.Select(TimeZoneInfoValue, (TimeZoneInfoValueLambda) => TimeZoneInfoValueLambda.ToString()); } public static IObservable<System.TimeZoneInfo> CreateCustomTimeZone(IObservable<System.String> id, IObservable<System.TimeSpan> baseUtcOffset, IObservable<System.String> displayName, IObservable<System.String> standardDisplayName) { return Observable.Zip(id, baseUtcOffset, displayName, standardDisplayName, (idLambda, baseUtcOffsetLambda, displayNameLambda, standardDisplayNameLambda) => System.TimeZoneInfo.CreateCustomTimeZone(idLambda, baseUtcOffsetLambda, displayNameLambda, standardDisplayNameLambda)); } public static IObservable<System.TimeZoneInfo> CreateCustomTimeZone(IObservable<System.String> id, IObservable<System.TimeSpan> baseUtcOffset, IObservable<System.String> displayName, IObservable<System.String> standardDisplayName, IObservable<System.String> daylightDisplayName, IObservable<System.TimeZoneInfo.AdjustmentRule[]> adjustmentRules) { return Observable.Zip(id, baseUtcOffset, displayName, standardDisplayName, daylightDisplayName, adjustmentRules, (idLambda, baseUtcOffsetLambda, displayNameLambda, standardDisplayNameLambda, daylightDisplayNameLambda, adjustmentRulesLambda) => System.TimeZoneInfo.CreateCustomTimeZone(idLambda, baseUtcOffsetLambda, displayNameLambda, standardDisplayNameLambda, daylightDisplayNameLambda, adjustmentRulesLambda)); } public static IObservable<System.TimeZoneInfo> CreateCustomTimeZone(IObservable<System.String> id, IObservable<System.TimeSpan> baseUtcOffset, IObservable<System.String> displayName, IObservable<System.String> standardDisplayName, IObservable<System.String> daylightDisplayName, IObservable<System.TimeZoneInfo.AdjustmentRule[]> adjustmentRules, IObservable<System.Boolean> disableDaylightSavingTime) { return Observable.Zip(id, baseUtcOffset, displayName, standardDisplayName, daylightDisplayName, adjustmentRules, disableDaylightSavingTime, (idLambda, baseUtcOffsetLambda, displayNameLambda, standardDisplayNameLambda, daylightDisplayNameLambda, adjustmentRulesLambda, disableDaylightSavingTimeLambda) => System.TimeZoneInfo.CreateCustomTimeZone(idLambda, baseUtcOffsetLambda, displayNameLambda, standardDisplayNameLambda, daylightDisplayNameLambda, adjustmentRulesLambda, disableDaylightSavingTimeLambda)); } public static IObservable<System.TimeZoneInfo> FindSystemTimeZoneById(IObservable<System.String> id) { return Observable.Select(id, (idLambda) => System.TimeZoneInfo.FindSystemTimeZoneById(idLambda)); } public static IObservable<System.String> get_Id(this IObservable<System.TimeZoneInfo> TimeZoneInfoValue) { return Observable.Select(TimeZoneInfoValue, (TimeZoneInfoValueLambda) => TimeZoneInfoValueLambda.Id); } public static IObservable<System.String> get_DisplayName(this IObservable<System.TimeZoneInfo> TimeZoneInfoValue) { return Observable.Select(TimeZoneInfoValue, (TimeZoneInfoValueLambda) => TimeZoneInfoValueLambda.DisplayName); } public static IObservable<System.String> get_StandardName( this IObservable<System.TimeZoneInfo> TimeZoneInfoValue) { return Observable.Select(TimeZoneInfoValue, (TimeZoneInfoValueLambda) => TimeZoneInfoValueLambda.StandardName); } public static IObservable<System.String> get_DaylightName( this IObservable<System.TimeZoneInfo> TimeZoneInfoValue) { return Observable.Select(TimeZoneInfoValue, (TimeZoneInfoValueLambda) => TimeZoneInfoValueLambda.DaylightName); } public static IObservable<System.TimeSpan> get_BaseUtcOffset( this IObservable<System.TimeZoneInfo> TimeZoneInfoValue) { return Observable.Select(TimeZoneInfoValue, (TimeZoneInfoValueLambda) => TimeZoneInfoValueLambda.BaseUtcOffset); } public static IObservable<System.Boolean> get_SupportsDaylightSavingTime( this IObservable<System.TimeZoneInfo> TimeZoneInfoValue) { return Observable.Select(TimeZoneInfoValue, (TimeZoneInfoValueLambda) => TimeZoneInfoValueLambda.SupportsDaylightSavingTime); } public static IObservable<System.TimeZoneInfo> get_Local() { return ObservableExt.Factory(() => System.TimeZoneInfo.Local); } public static IObservable<System.TimeZoneInfo> get_Utc() { return ObservableExt.Factory(() => System.TimeZoneInfo.Utc); } } }
46.222222
122
0.69566
[ "MIT" ]
RixianOpenTech/RxWrappers
Source/Wrappers/mscorlib/System.TimeZoneInfo.cs
15,808
C#
using System.ComponentModel.DataAnnotations; namespace Papu.Models { public class CreateThursdayDto { //Śniadanie wchodzące w skład czwartku public int BreakfastThursdayId { get; set; } //Drugie śniadanie wchodzące w skład czwartku public int SecondBreakfastThursdayId { get; set; } //Obiad wchodzący w skład czwartku public int LunchThursdayId { get; set; } //Podwieczorek wchodzący w skład czwartku public int SnackThursdayId { get; set; } //Kolacja wchodząca w skład czwartku public int DinnerThursdayId { get; set; } } }
27.086957
58
0.666132
[ "Unlicense" ]
dawidkurant/applications
Projekt Web API/Papu/Papu/Models/Create/DayOfTheWeek/CreateThursdayDto.cs
637
C#
using MediatR; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using UserTesting.Application.Models.Results; using UserTesting.Domain.Entities.Offices; namespace UserTesting.Application.Features.UserManagements.Offices.Queries.GetAll { public class GetAllOfficesQuery : IRequest<DataResult<IEnumerable<Office>>> { } }
25
81
0.805
[ "MIT" ]
SargeMahoney/CustomUserAspCoreApp
UserTesting.Application/Features/UserManagements/Offices/Queries/GetAll/GetAllOfficesQuery.cs
402
C#
using System; using System.Collections.Generic; using System.Net; using System.Threading.Tasks; namespace ETModel { public enum LockStatus { /// <summary> /// 不是锁定状态 /// </summary> LockedNot, /// <summary> /// 待加锁状态 /// </summary> LockRequesting, /// <summary> /// 锁定状态 /// </summary> Locked, } /// <summary> /// 分布式锁组件,Unit对象可能在不同进程上有镜像,访问该对象的时候需要对他加锁 /// </summary> public class LockComponent: Component { /// <summary> /// 锁的状态 /// </summary> public LockStatus status = LockStatus.LockedNot; /// <summary> /// IP地址 /// </summary> public IPEndPoint address; /// <summary> /// 锁定次数 /// </summary> public int lockCount; /// <summary> /// 带加锁完成回调字典 /// </summary> public readonly Queue<TaskCompletionSource<bool>> queue = new Queue<TaskCompletionSource<bool>>(); } }
21.695652
106
0.52505
[ "MIT" ]
Greatdust/ET4.0
Server/Model/Module/BigWorld/LockComponent.cs
1,134
C#
// Copyright © 2020 Sovren Group, Inc. All rights reserved. // This file is provided for use by, or on behalf of, Sovren licensees // within the terms of their license of Sovren products or Sovren customers // within the Terms of Service pertaining to the Sovren SaaS products. using Sovren.Models.Resume.ContactInfo; using System.Collections.Generic; namespace Sovren.Models.Resume { /// <summary> /// A reference found on a resume /// </summary> public class CandidateReference { /// <summary> /// The name of the reference /// </summary> public PersonName ReferenceName { get; set; } /// <summary> /// The job title of the reference /// </summary> public string Title { get; set; } /// <summary> /// The employer of the reference /// </summary> public string Company { get; set; } /// <summary> /// The type of reference /// </summary> public string Type { get; set; } /// <summary> /// The physical location of the reference /// </summary> public Location Location { get; set; } /// <summary> /// Phone numbers listed for the reference /// </summary> public List<NormalizedString> Telephones { get; set; } /// <summary> /// Email addresses listed for the reference /// </summary> public List<string> EmailAddresses { get; set; } /// <summary> /// Other web addresses listed for the reference /// </summary> public List<WebAddress> WebAddresses { get; set; } } }
29.035088
75
0.58006
[ "Apache-2.0" ]
sovren/sovren-dotnet
src/Sovren.SDK/Models/Resume/CandidateReference.cs
1,656
C#
// <auto-generated> // Code generated by LUISGen // Tool github: https://github.com/microsoft/botbuilder-tools // Changes may cause incorrect behavior and will be lost if the code is // regenerated. // </auto-generated> using Newtonsoft.Json; using System.Collections.Generic; using Microsoft.Bot.Builder; using Microsoft.Bot.Builder.AI.Luis; namespace Luis { public class General : IRecognizerConvert { public string Text; public string AlteredText; public enum Intent { Cancel, Confirm, Escalate, FinishTask, GoBack, Help, None, Reject, Repeat, SelectAny, SelectItem, SelectNone, ShowNext, ShowPrevious, StartOver, Stop }; public Dictionary<Intent, IntentScore> Intents; public class _Entities { // Simple entities public string[] DirectionalReference; // Built-in entities public double[] number; public double[] ordinal; // Instance public class _Instance { public InstanceData[] DirectionalReference; public InstanceData[] number; public InstanceData[] ordinal; } [JsonProperty("$instance")] public _Instance _instance; } public _Entities Entities; [JsonExtensionData(ReadData = true, WriteData = true)] public IDictionary<string, object> Properties { get; set; } public void Convert(dynamic result) { var app = JsonConvert.DeserializeObject<General>(JsonConvert.SerializeObject(result)); Text = app.Text; AlteredText = app.AlteredText; Intents = app.Intents; Entities = app.Entities; Properties = app.Properties; } public (Intent intent, double score) TopIntent() { Intent maxIntent = Intent.None; var max = 0.0; foreach (var entry in Intents) { if (entry.Value.Score > max) { maxIntent = entry.Key; max = entry.Value.Score.Value; } } return (maxIntent, max); } } }
27.404494
98
0.527265
[ "MIT" ]
3ve4me/botframework-solutions
templates/Enterprise-Template/src/csharp/EnterpriseBotSample/EnterpriseBotSample/Dialogs/Shared/Resources/General.cs
2,439
C#
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. * * Contains some contributions under the Thrift Software License. * Please see doc/old-thrift-license.txt in the Thrift distribution for * details. */ using System; using System.IO.Pipes; using System.Threading; namespace Thrift.Transport { public class TNamedPipeClientTransport : TTransport { private NamedPipeClientStream client; private string ServerName; private string PipeName; private int ConnectTimeout; public TNamedPipeClientTransport(string pipe, int timeout = Timeout.Infinite) { ServerName = "."; PipeName = pipe; ConnectTimeout = timeout; } public TNamedPipeClientTransport(string server, string pipe, int timeout = Timeout.Infinite) { ServerName = (server != "") ? server : "."; PipeName = pipe; ConnectTimeout = timeout; } public override bool IsOpen { get { return client != null && client.IsConnected; } } public override void Open() { if (IsOpen) { throw new TTransportException(TTransportException.ExceptionType.AlreadyOpen); } client = new NamedPipeClientStream(ServerName, PipeName, PipeDirection.InOut, PipeOptions.None); client.Connect(ConnectTimeout); } public override void Close() { if (client != null) { client.Close(); client = null; } } public override int Read(byte[] buf, int off, int len) { if (client == null) { throw new TTransportException(TTransportException.ExceptionType.NotOpen); } return client.Read(buf, off, len); } public override void Write(byte[] buf, int off, int len) { if (client == null) { throw new TTransportException(TTransportException.ExceptionType.NotOpen); } // if necessary, send the data in chunks // there's a system limit around 0x10000 bytes that we hit otherwise // MSDN: "Pipe write operations across a network are limited to 65,535 bytes per write. For more information regarding pipes, see the Remarks section." var nBytes = Math.Min(len, 15 * 4096); // 16 would exceed the limit while (nBytes > 0) { client.Write(buf, off, nBytes); off += nBytes; len -= nBytes; nBytes = Math.Min(len, nBytes); } } protected override void Dispose(bool disposing) { client.Dispose(); } } }
32.160714
163
0.597723
[ "MIT" ]
2191116913-qq-com/bk-ci
src/agent/src/vendor/github.com/influxdata/telegraf/vendor/github.com/apache/thrift/lib/csharp/src/Transport/TNamedPipeClientTransport.cs
3,604
C#
using System; using System.Linq; using Microsoft.Xrm.Sdk; using Microsoft.Crm.Sdk.Messages; namespace FakeXrmEasy.FakeMessageExecutors { public class QualifyLeadRequestExecutor : IFakeMessageExecutor { public bool CanExecute(OrganizationRequest request) { return request is QualifyLeadRequest; } public OrganizationResponse Execute(OrganizationRequest request, XrmFakedContext ctx) { var req = request as QualifyLeadRequest; var orgService = ctx.GetOrganizationService(); if (req.LeadId == null) throw new Exception("Lead Id must be set in request."); var leads = (from l in ctx.CreateQuery("lead") where l.Id == req.LeadId.Id select l); var leadsCount = leads.Count(); if (leadsCount != 1) throw new Exception(string.Format("Number of Leads by given LeadId should be 1. Instead it is {0}.", leadsCount)); // Made here to get access to CreatedEntities collection var response = new QualifyLeadResponse(); response["CreatedEntities"] = new EntityReferenceCollection(); // Create Account if (req.CreateAccount) // ParentAccount { var account = new Entity("account") { Id = Guid.NewGuid() }; account.Attributes["originatingleadid"] = req.LeadId; orgService.Create(account); response.CreatedEntities.Add(account.ToEntityReference()); } // Create Contact if (req.CreateContact) { var contact = new Entity("contact") { Id = Guid.NewGuid() }; contact.Attributes["originatingleadid"] = req.LeadId; orgService.Create(contact); response.CreatedEntities.Add(contact.ToEntityReference()); } // Create Opportunity if (req.CreateOpportunity) { var opportunity = new Entity("opportunity") { Id = Guid.NewGuid() }; // Set OpportunityCurrencyId if given // MSDN link: // https://msdn.microsoft.com/en-us/library/microsoft.crm.sdk.messages.qualifyleadrequest.opportunitycurrencyid.aspx if (req.OpportunityCurrencyId != null) { opportunity.Attributes["transactioncurrencyid"] = req.OpportunityCurrencyId; } // Associate Account or Contact with Opportunity // MSDN link: // https://msdn.microsoft.com/en-us/library/microsoft.crm.sdk.messages.qualifyleadrequest.opportunitycustomerid.aspx if (req.OpportunityCustomerId != null) { var logicalName = req.OpportunityCustomerId.LogicalName; // Associate Account or Contact if (logicalName.Equals("account") || logicalName.Equals("contact")) { opportunity.Attributes["customerid"] = req.OpportunityCustomerId; } // Wrong Entity was given as parameter else { throw new Exception(string.Format("Opportunity Customer Id should be connected with Account or Contact. Instead OpportunityCustomerId was given with Entity.LogicalName = {0}", logicalName)); } } opportunity.Attributes["originatingleadid"] = req.LeadId; orgService.Create(opportunity); response.CreatedEntities.Add(opportunity.ToEntityReference()); } // Actual Lead var lead = leads.First(); lead.Attributes["statuscode"] = req.Status.Value; orgService.Update(lead); return response; } public Type GetResponsibleRequestType() { return typeof(QualifyLeadRequest); } } }
37.732143
214
0.54567
[ "MIT" ]
mallikarjunTH/FakeXRM1
FakeXrmEasy.Shared/FakeMessageExecutors/QualifyLeadRequestExecutor.cs
4,228
C#
namespace Model { public static class Globals { public const string STORAGE = "STORAGE_CONNECTION"; public const string PUBLISH_ENDPOINT = "PUBLISH_ENDPOINT"; public const string PUBLISH_KEY = "PUBLISH_KEY"; public const string TABLE = "inventory"; public const string CONTAINER = "inventoryimages"; } }
30.666667
67
0.652174
[ "MIT" ]
mjalaf/IgniteTheTour
DEV - Building your Applications for the Cloud/DEV50/src/TailwindTraderServerless/Model/Globals.cs
370
C#
using SuperCOOL.Core; using System.Collections.Generic; namespace SuperCOOL.CodeGeneration.CIL.AST { public abstract class ASTCILNode { public static implicit operator List<ASTCILNode>(ASTCILNode node) => new List<ASTCILNode>{node}; public virtual Result Accept<Result>( ICILVisitor<Result> Visitor ) => Visitor.VisitNode( this ); } }
30.416667
105
0.728767
[ "MIT" ]
jromero132/cool-compiler-supercool
src/SuperCOOL/CodeGeneration/CIL/AST/ASTCILNode.cs
367
C#
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Optimization; using System.Web.Routing; using System.Web.Security; using System.Web.SessionState; namespace findmydocs { public class Global : HttpApplication { void Application_Start(object sender, EventArgs e) { // Code that runs on application startup RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); } } }
24.363636
62
0.701493
[ "MIT" ]
Azure-Samples/AIP-Custom-Tracking-Portal-Samples
asp-donet-web-portal/Global.asax.cs
538
C#
// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information. // Ported from um/WebServices.h in the Windows SDK for Windows 10.0.19041.0 // Original source is Copyright © Microsoft. All rights reserved. using NUnit.Framework; using System; using System.Runtime.InteropServices; namespace TerraFX.Interop.UnitTests { /// <summary>Provides validation of the <see cref="WS_CUSTOM_LISTENER_CALLBACKS" /> struct.</summary> public static unsafe class WS_CUSTOM_LISTENER_CALLBACKSTests { /// <summary>Validates that the <see cref="WS_CUSTOM_LISTENER_CALLBACKS" /> struct is blittable.</summary> [Test] public static void IsBlittableTest() { Assert.That(Marshal.SizeOf<WS_CUSTOM_LISTENER_CALLBACKS>(), Is.EqualTo(sizeof(WS_CUSTOM_LISTENER_CALLBACKS))); } /// <summary>Validates that the <see cref="WS_CUSTOM_LISTENER_CALLBACKS" /> struct has the right <see cref="LayoutKind" />.</summary> [Test] public static void IsLayoutSequentialTest() { Assert.That(typeof(WS_CUSTOM_LISTENER_CALLBACKS).IsLayoutSequential, Is.True); } /// <summary>Validates that the <see cref="WS_CUSTOM_LISTENER_CALLBACKS" /> struct has the correct size.</summary> [Test] public static void SizeOfTest() { if (Environment.Is64BitProcess) { Assert.That(sizeof(WS_CUSTOM_LISTENER_CALLBACKS), Is.EqualTo(80)); } else { Assert.That(sizeof(WS_CUSTOM_LISTENER_CALLBACKS), Is.EqualTo(40)); } } } }
38.863636
145
0.661988
[ "MIT" ]
Perksey/terrafx.interop.windows
tests/Interop/Windows/um/WebServices/WS_CUSTOM_LISTENER_CALLBACKSTests.cs
1,712
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator 1.0.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.Insights { using Azure; using Management; using Rest; using Rest.Azure; using Models; using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; /// <summary> /// ServiceDiagnosticSettingsOperations operations. /// </summary> internal partial class ServiceDiagnosticSettingsOperations : IServiceOperations<MonitorManagementClient>, IServiceDiagnosticSettingsOperations { /// <summary> /// Initializes a new instance of the ServiceDiagnosticSettingsOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> internal ServiceDiagnosticSettingsOperations(MonitorManagementClient client) { if (client == null) { throw new System.ArgumentNullException("client"); } Client = client; } /// <summary> /// Gets a reference to the MonitorManagementClient /// </summary> public MonitorManagementClient Client { get; private set; } /// <summary> /// Gets the active diagnostic settings for the specified resource. /// </summary> /// <param name='resourceUri'> /// The identifier of the resource. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<ServiceDiagnosticSettingsResource>> GetWithHttpMessagesAsync(string resourceUri, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceUri == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceUri"); } string apiVersion = "2015-07-01"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceUri", resourceUri); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "{resourceUri}/providers/microsoft.insights/diagnosticSettings/service").ToString(); _url = _url.Replace("{resourceUri}", System.Uri.EscapeDataString(resourceUri)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<ServiceDiagnosticSettingsResource>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<ServiceDiagnosticSettingsResource>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Create or update new diagnostic settings for the specified resource. /// </summary> /// <param name='resourceUri'> /// The identifier of the resource. /// </param> /// <param name='parameters'> /// Parameters supplied to the operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<ServiceDiagnosticSettingsResource>> CreateOrUpdateWithHttpMessagesAsync(string resourceUri, ServiceDiagnosticSettingsResource parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceUri == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceUri"); } if (parameters == null) { throw new ValidationException(ValidationRules.CannotBeNull, "parameters"); } if (parameters != null) { parameters.Validate(); } string apiVersion = "2015-07-01"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceUri", resourceUri); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("parameters", parameters); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "CreateOrUpdate", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "{resourceUri}/providers/microsoft.insights/diagnosticSettings/service").ToString(); _url = _url.Replace("{resourceUri}", System.Uri.EscapeDataString(resourceUri)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("PUT"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if(parameters != null) { _requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(parameters, Client.SerializationSettings); _httpRequest.Content = new System.Net.Http.StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<ServiceDiagnosticSettingsResource>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<ServiceDiagnosticSettingsResource>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } } }
44.836406
307
0.567398
[ "MIT" ]
DiogenesPolanco/azure-sdk-for-net
src/ResourceManagement/Monitor/Microsoft.Azure.Monitor/Generated/Management/Monitor/ServiceDiagnosticSettingsOperations.cs
19,459
C#
using System.Collections.Generic; using Windows.ApplicationModel.Resources; namespace SpaceTraders { public static class Weapons { // A standard laser. public static readonly Weapon PULSE_LASER = new Weapon { Name = ResourceLoader.GetForViewIndependentUse().GetString("Weapon/Pulse/Name"), Price = 5000, MinTechLevel = TechLevel.INDUSTRIAL, SkillModifier = 1 }; // A better laser. public static readonly Weapon BEAM_LASER = new Weapon { Name = ResourceLoader.GetForViewIndependentUse().GetString("Weapon/Beam/Name"), Price = 10000, MinTechLevel = TechLevel.POST_INDUSTRIAL, SkillModifier = 2 }; // The best laser. public static readonly Weapon MILITARY_LASER = new Weapon { Name = ResourceLoader.GetForViewIndependentUse().GetString("Weapon/Military/Name"), Price = 20000, MinTechLevel = TechLevel.HI_TECH, SkillModifier = 4 }; public static readonly List<Weapon> Values = new List<Weapon> { PULSE_LASER, BEAM_LASER, MILITARY_LASER }; } }
31.684211
114
0.613787
[ "MIT" ]
AlteredCarrot71/SpaceTraders
SpaceTraders/Common/Objects/Weapons.cs
1,206
C#
#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; using System.Diagnostics; using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto; using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Digests; using BestHTTP.SecureProtocol.Org.BouncyCastle.Math.EC.Rfc7748; using BestHTTP.SecureProtocol.Org.BouncyCastle.Math.Raw; using BestHTTP.SecureProtocol.Org.BouncyCastle.Security; using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities; namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Math.EC.Rfc8032 { public abstract class Ed448 { // x^2 + y^2 == 1 - 39081 * x^2 * y^2 public enum Algorithm { Ed448 = 0, Ed448ph = 1, } private const ulong M26UL = 0x03FFFFFFUL; private const ulong M28UL = 0x0FFFFFFFUL; private const int PointBytes = 57; private const int ScalarUints = 14; private const int ScalarBytes = ScalarUints * 4 + 1; public static readonly int PrehashSize = 64; public static readonly int PublicKeySize = PointBytes; public static readonly int SecretKeySize = 57; public static readonly int SignatureSize = PointBytes + ScalarBytes; private static readonly byte[] Dom4Prefix = Strings.ToByteArray("SigEd448"); private static readonly uint[] P = { 0xFFFFFFFFU, 0xFFFFFFFFU, 0xFFFFFFFFU, 0xFFFFFFFFU, 0xFFFFFFFFU, 0xFFFFFFFFU, 0xFFFFFFFFU, 0xFFFFFFFEU, 0xFFFFFFFFU, 0xFFFFFFFFU, 0xFFFFFFFFU, 0xFFFFFFFFU, 0xFFFFFFFFU, 0xFFFFFFFFU }; private static readonly uint[] L = { 0xAB5844F3U, 0x2378C292U, 0x8DC58F55U, 0x216CC272U, 0xAED63690U, 0xC44EDB49U, 0x7CCA23E9U, 0xFFFFFFFFU, 0xFFFFFFFFU, 0xFFFFFFFFU, 0xFFFFFFFFU, 0xFFFFFFFFU, 0xFFFFFFFFU, 0x3FFFFFFFU }; private static readonly BigInteger N = Nat.ToBigInteger(L.Length, L); private const int L_0 = 0x04A7BB0D; // L_0:26/24 private const int L_1 = 0x0873D6D5; // L_1:27/23 private const int L_2 = 0x0A70AADC; // L_2:27/26 private const int L_3 = 0x03D8D723; // L_3:26/-- private const int L_4 = 0x096FDE93; // L_4:27/25 private const int L_5 = 0x0B65129C; // L_5:27/26 private const int L_6 = 0x063BB124; // L_6:27/-- private const int L_7 = 0x08335DC1; // L_7:27/22 private const int L4_0 = 0x029EEC34; // L4_0:25/24 private const int L4_1 = 0x01CF5B55; // L4_1:25/-- private const int L4_2 = 0x09C2AB72; // L4_2:27/25 private const int L4_3 = 0x0F635C8E; // L4_3:28/-- private const int L4_4 = 0x05BF7A4C; // L4_4:26/25 private const int L4_5 = 0x0D944A72; // L4_5:28/-- private const int L4_6 = 0x08EEC492; // L4_6:27/24 private const int L4_7 = 0x20CD7705; // L4_7:29/24 private static readonly uint[] B_x = { 0x070CC05EU, 0x026A82BCU, 0x00938E26U, 0x080E18B0U, 0x0511433BU, 0x0F72AB66U, 0x0412AE1AU, 0x0A3D3A46U, 0x0A6DE324U, 0x00F1767EU, 0x04657047U, 0x036DA9E1U, 0x05A622BFU, 0x0ED221D1U, 0x066BED0DU, 0x04F1970CU }; private static readonly uint[] B_y = { 0x0230FA14U, 0x008795BFU, 0x07C8AD98U, 0x0132C4EDU, 0x09C4FDBDU, 0x01CE67C3U, 0x073AD3FFU, 0x005A0C2DU, 0x07789C1EU, 0x0A398408U, 0x0A73736CU, 0x0C7624BEU, 0x003756C9U, 0x02488762U, 0x016EB6BCU, 0x0693F467U }; private const int C_d = -39081; private const int WnafWidthBase = 7; private const int PrecompBlocks = 5; private const int PrecompTeeth = 5; private const int PrecompSpacing = 18; private const int PrecompPoints = 1 << (PrecompTeeth - 1); private const int PrecompMask = PrecompPoints - 1; private static readonly object precompLock = new object(); // TODO[ed448] Convert to PointPrecomp private static PointExt[] precompBaseTable = null; private static uint[] precompBase = null; private class PointExt { internal uint[] x = X448Field.Create(); internal uint[] y = X448Field.Create(); internal uint[] z = X448Field.Create(); } private class PointPrecomp { internal uint[] x = X448Field.Create(); internal uint[] y = X448Field.Create(); } private static byte[] CalculateS(byte[] r, byte[] k, byte[] s) { uint[] t = new uint[ScalarUints * 2]; DecodeScalar(r, 0, t); uint[] u = new uint[ScalarUints]; DecodeScalar(k, 0, u); uint[] v = new uint[ScalarUints]; DecodeScalar(s, 0, v); Nat.MulAddTo(14, u, v, t); byte[] result = new byte[ScalarBytes * 2]; for (int i = 0; i < t.Length; ++i) { Encode32(t[i], result, i * 4); } return ReduceScalar(result); } private static bool CheckContextVar(byte[] ctx) { return ctx != null && ctx.Length < 256; } private static int CheckPoint(uint[] x, uint[] y) { uint[] t = X448Field.Create(); uint[] u = X448Field.Create(); uint[] v = X448Field.Create(); X448Field.Sqr(x, u); X448Field.Sqr(y, v); X448Field.Mul(u, v, t); X448Field.Add(u, v, u); X448Field.Mul(t, -C_d, t); X448Field.SubOne(t); X448Field.Add(t, u, t); X448Field.Normalize(t); return X448Field.IsZero(t); } private static int CheckPoint(uint[] x, uint[] y, uint[] z) { uint[] t = X448Field.Create(); uint[] u = X448Field.Create(); uint[] v = X448Field.Create(); uint[] w = X448Field.Create(); X448Field.Sqr(x, u); X448Field.Sqr(y, v); X448Field.Sqr(z, w); X448Field.Mul(u, v, t); X448Field.Add(u, v, u); X448Field.Mul(u, w, u); X448Field.Sqr(w, w); X448Field.Mul(t, -C_d, t); X448Field.Sub(t, w, t); X448Field.Add(t, u, t); X448Field.Normalize(t); return X448Field.IsZero(t); } private static bool CheckPointVar(byte[] p) { if ((p[PointBytes - 1] & 0x7F) != 0x00) return false; uint[] t = new uint[14]; Decode32(p, 0, t, 0, 14); return !Nat.Gte(14, t, P); } private static bool CheckScalarVar(byte[] s) { if (s[ScalarBytes - 1] != 0x00) return false; uint[] n = new uint[ScalarUints]; DecodeScalar(s, 0, n); return !Nat.Gte(ScalarUints, n, L); } public static IXof CreatePrehash() { return CreateXof(); } private static IXof CreateXof() { return new ShakeDigest(256); } private static uint Decode16(byte[] bs, int off) { uint n = bs[off]; n |= (uint)bs[++off] << 8; return n; } private static uint Decode24(byte[] bs, int off) { uint n = bs[off]; n |= (uint)bs[++off] << 8; n |= (uint)bs[++off] << 16; return n; } private static uint Decode32(byte[] bs, int off) { uint n = bs[off]; n |= (uint)bs[++off] << 8; n |= (uint)bs[++off] << 16; n |= (uint)bs[++off] << 24; return n; } private static void Decode32(byte[] bs, int bsOff, uint[] n, int nOff, int nLen) { for (int i = 0; i < nLen; ++i) { n[nOff + i] = Decode32(bs, bsOff + i * 4); } } private static bool DecodePointVar(byte[] p, int pOff, bool negate, PointExt r) { byte[] py = Arrays.CopyOfRange(p, pOff, pOff + PointBytes); if (!CheckPointVar(py)) return false; int x_0 = (py[PointBytes - 1] & 0x80) >> 7; py[PointBytes - 1] &= 0x7F; X448Field.Decode(py, 0, r.y); uint[] u = X448Field.Create(); uint[] v = X448Field.Create(); X448Field.Sqr(r.y, u); X448Field.Mul(u, (uint)-C_d, v); X448Field.Negate(u, u); X448Field.AddOne(u); X448Field.AddOne(v); if (!X448Field.SqrtRatioVar(u, v, r.x)) return false; X448Field.Normalize(r.x); if (x_0 == 1 && X448Field.IsZeroVar(r.x)) return false; if (negate ^ (x_0 != (r.x[0] & 1))) { X448Field.Negate(r.x, r.x); } PointExtendXY(r); return true; } private static void DecodeScalar(byte[] k, int kOff, uint[] n) { Debug.Assert(k[kOff + ScalarBytes - 1] == 0x00); Decode32(k, kOff, n, 0, ScalarUints); } private static void Dom4(IXof d, byte x, byte[] y) { d.BlockUpdate(Dom4Prefix, 0, Dom4Prefix.Length); d.Update(x); d.Update((byte)y.Length); d.BlockUpdate(y, 0, y.Length); } private static void Encode24(uint n, byte[] bs, int off) { bs[off] = (byte)(n); bs[++off] = (byte)(n >> 8); bs[++off] = (byte)(n >> 16); } private static void Encode32(uint n, byte[] bs, int off) { bs[off] = (byte)(n); bs[++off] = (byte)(n >> 8); bs[++off] = (byte)(n >> 16); bs[++off] = (byte)(n >> 24); } private static void Encode56(ulong n, byte[] bs, int off) { Encode32((uint)n, bs, off); Encode24((uint)(n >> 32), bs, off + 4); } private static int EncodePoint(PointExt p, byte[] r, int rOff) { uint[] x = X448Field.Create(); uint[] y = X448Field.Create(); X448Field.Inv(p.z, y); X448Field.Mul(p.x, y, x); X448Field.Mul(p.y, y, y); X448Field.Normalize(x); X448Field.Normalize(y); int result = CheckPoint(x, y); X448Field.Encode(y, r, rOff); r[rOff + PointBytes - 1] = (byte)((x[0] & 1) << 7); return result; } public static void GeneratePrivateKey(SecureRandom random, byte[] k) { random.NextBytes(k); } public static void GeneratePublicKey(byte[] sk, int skOff, byte[] pk, int pkOff) { IXof d = CreateXof(); byte[] h = new byte[ScalarBytes * 2]; d.BlockUpdate(sk, skOff, SecretKeySize); d.DoFinal(h, 0, h.Length); byte[] s = new byte[ScalarBytes]; PruneScalar(h, 0, s); ScalarMultBaseEncoded(s, pk, pkOff); } private static sbyte[] GetWnaf(uint[] n, int width) { Debug.Assert(n[ScalarUints - 1] >> 30 == 0U); uint[] t = new uint[ScalarUints * 2]; { uint c = 0; int tPos = t.Length, i = ScalarUints; while (--i >= 0) { uint next = n[i]; t[--tPos] = (next >> 16) | (c << 16); t[--tPos] = c = next; } } sbyte[] ws = new sbyte[447]; uint pow2 = 1U << width; uint mask = pow2 - 1U; uint sign = pow2 >> 1; uint carry = 0U; int j = 0; for (int i = 0; i < t.Length; ++i, j -= 16) { uint word = t[i]; while (j < 16) { uint word16 = word >> j; uint bit = word16 & 1U; if (bit == carry) { ++j; continue; } uint digit = (word16 & mask) + carry; carry = digit & sign; digit -= (carry << 1); carry >>= (width - 1); ws[(i << 4) + j] = (sbyte)digit; j += width; } } Debug.Assert(carry == 0); return ws; } private static void ImplSign(IXof d, byte[] h, byte[] s, byte[] pk, int pkOff, byte[] ctx, byte phflag, byte[] m, int mOff, int mLen, byte[] sig, int sigOff) { Dom4(d, phflag, ctx); d.BlockUpdate(h, ScalarBytes, ScalarBytes); d.BlockUpdate(m, mOff, mLen); d.DoFinal(h, 0, h.Length); byte[] r = ReduceScalar(h); byte[] R = new byte[PointBytes]; ScalarMultBaseEncoded(r, R, 0); Dom4(d, phflag, ctx); d.BlockUpdate(R, 0, PointBytes); d.BlockUpdate(pk, pkOff, PointBytes); d.BlockUpdate(m, mOff, mLen); d.DoFinal(h, 0, h.Length); byte[] k = ReduceScalar(h); byte[] S = CalculateS(r, k, s); Array.Copy(R, 0, sig, sigOff, PointBytes); Array.Copy(S, 0, sig, sigOff + PointBytes, ScalarBytes); } private static void ImplSign(byte[] sk, int skOff, byte[] ctx, byte phflag, byte[] m, int mOff, int mLen, byte[] sig, int sigOff) { if (!CheckContextVar(ctx)) throw new ArgumentException("ctx"); IXof d = CreateXof(); byte[] h = new byte[ScalarBytes * 2]; d.BlockUpdate(sk, skOff, SecretKeySize); d.DoFinal(h, 0, h.Length); byte[] s = new byte[ScalarBytes]; PruneScalar(h, 0, s); byte[] pk = new byte[PointBytes]; ScalarMultBaseEncoded(s, pk, 0); ImplSign(d, h, s, pk, 0, ctx, phflag, m, mOff, mLen, sig, sigOff); } private static void ImplSign(byte[] sk, int skOff, byte[] pk, int pkOff, byte[] ctx, byte phflag, byte[] m, int mOff, int mLen, byte[] sig, int sigOff) { if (!CheckContextVar(ctx)) throw new ArgumentException("ctx"); IXof d = CreateXof(); byte[] h = new byte[ScalarBytes * 2]; d.BlockUpdate(sk, skOff, SecretKeySize); d.DoFinal(h, 0, h.Length); byte[] s = new byte[ScalarBytes]; PruneScalar(h, 0, s); ImplSign(d, h, s, pk, pkOff, ctx, phflag, m, mOff, mLen, sig, sigOff); } private static bool ImplVerify(byte[] sig, int sigOff, byte[] pk, int pkOff, byte[] ctx, byte phflag, byte[] m, int mOff, int mLen) { if (!CheckContextVar(ctx)) throw new ArgumentException("ctx"); byte[] R = Arrays.CopyOfRange(sig, sigOff, sigOff + PointBytes); byte[] S = Arrays.CopyOfRange(sig, sigOff + PointBytes, sigOff + SignatureSize); if (!CheckPointVar(R)) return false; if (!CheckScalarVar(S)) return false; PointExt pA = new PointExt(); if (!DecodePointVar(pk, pkOff, true, pA)) return false; IXof d = CreateXof(); byte[] h = new byte[ScalarBytes * 2]; Dom4(d, phflag, ctx); d.BlockUpdate(R, 0, PointBytes); d.BlockUpdate(pk, pkOff, PointBytes); d.BlockUpdate(m, mOff, mLen); d.DoFinal(h, 0, h.Length); byte[] k = ReduceScalar(h); uint[] nS = new uint[ScalarUints]; DecodeScalar(S, 0, nS); uint[] nA = new uint[ScalarUints]; DecodeScalar(k, 0, nA); PointExt pR = new PointExt(); ScalarMultStrausVar(nS, nA, pA, pR); byte[] check = new byte[PointBytes]; return 0 != EncodePoint(pR, check, 0) && Arrays.AreEqual(check, R); } private static void PointAddVar(bool negate, PointExt p, PointExt r) { uint[] A = X448Field.Create(); uint[] B = X448Field.Create(); uint[] C = X448Field.Create(); uint[] D = X448Field.Create(); uint[] E = X448Field.Create(); uint[] F = X448Field.Create(); uint[] G = X448Field.Create(); uint[] H = X448Field.Create(); uint[] b, e, f, g; if (negate) { b = E; e = B; f = G; g = F; X448Field.Sub(p.y, p.x, H); } else { b = B; e = E; f = F; g = G; X448Field.Add(p.y, p.x, H); } X448Field.Mul(p.z, r.z, A); X448Field.Sqr(A, B); X448Field.Mul(p.x, r.x, C); X448Field.Mul(p.y, r.y, D); X448Field.Mul(C, D, E); X448Field.Mul(E, -C_d, E); //X448Field.Apm(B, E, F, G); X448Field.Add(B, E, f); X448Field.Sub(B, E, g); X448Field.Add(r.x, r.y, E); X448Field.Mul(H, E, H); //X448Field.Apm(D, C, B, E); X448Field.Add(D, C, b); X448Field.Sub(D, C, e); X448Field.Carry(b); X448Field.Sub(H, B, H); X448Field.Mul(H, A, H); X448Field.Mul(E, A, E); X448Field.Mul(F, H, r.x); X448Field.Mul(E, G, r.y); X448Field.Mul(F, G, r.z); } private static void PointAddPrecomp(PointPrecomp p, PointExt r) { uint[] B = X448Field.Create(); uint[] C = X448Field.Create(); uint[] D = X448Field.Create(); uint[] E = X448Field.Create(); uint[] F = X448Field.Create(); uint[] G = X448Field.Create(); uint[] H = X448Field.Create(); X448Field.Sqr(r.z, B); X448Field.Mul(p.x, r.x, C); X448Field.Mul(p.y, r.y, D); X448Field.Mul(C, D, E); X448Field.Mul(E, -C_d, E); //X448Field.Apm(B, E, F, G); X448Field.Add(B, E, F); X448Field.Sub(B, E, G); X448Field.Add(p.x, p.y, B); X448Field.Add(r.x, r.y, E); X448Field.Mul(B, E, H); //X448Field.Apm(D, C, B, E); X448Field.Add(D, C, B); X448Field.Sub(D, C, E); X448Field.Carry(B); X448Field.Sub(H, B, H); X448Field.Mul(H, r.z, H); X448Field.Mul(E, r.z, E); X448Field.Mul(F, H, r.x); X448Field.Mul(E, G, r.y); X448Field.Mul(F, G, r.z); } private static PointExt PointCopy(PointExt p) { PointExt r = new PointExt(); X448Field.Copy(p.x, 0, r.x, 0); X448Field.Copy(p.y, 0, r.y, 0); X448Field.Copy(p.z, 0, r.z, 0); return r; } private static void PointDouble(PointExt r) { uint[] B = X448Field.Create(); uint[] C = X448Field.Create(); uint[] D = X448Field.Create(); uint[] E = X448Field.Create(); uint[] H = X448Field.Create(); uint[] J = X448Field.Create(); X448Field.Add(r.x, r.y, B); X448Field.Sqr(B, B); X448Field.Sqr(r.x, C); X448Field.Sqr(r.y, D); X448Field.Add(C, D, E); X448Field.Carry(E); X448Field.Sqr(r.z, H); X448Field.Add(H, H, H); X448Field.Carry(H); X448Field.Sub(E, H, J); X448Field.Sub(B, E, B); X448Field.Sub(C, D, C); X448Field.Mul(B, J, r.x); X448Field.Mul(E, C, r.y); X448Field.Mul(E, J, r.z); } private static void PointExtendXY(PointExt p) { X448Field.One(p.z); } private static void PointLookup(int block, int index, PointPrecomp p) { Debug.Assert(0 <= block && block < PrecompBlocks); Debug.Assert(0 <= index && index < PrecompPoints); int off = block * PrecompPoints * 2 * X448Field.Size; for (int i = 0; i < PrecompPoints; ++i) { int cond = ((i ^ index) - 1) >> 31; X448Field.CMov(cond, precompBase, off, p.x, 0); off += X448Field.Size; X448Field.CMov(cond, precompBase, off, p.y, 0); off += X448Field.Size; } } private static PointExt[] PointPrecompVar(PointExt p, int count) { Debug.Assert(count > 0); PointExt d = PointCopy(p); PointDouble(d); PointExt[] table = new PointExt[count]; table[0] = PointCopy(p); for (int i = 1; i < count; ++i) { table[i] = PointCopy(table[i - 1]); PointAddVar(false, d, table[i]); } return table; } private static void PointSetNeutral(PointExt p) { X448Field.Zero(p.x); X448Field.One(p.y); X448Field.One(p.z); } public static void Precompute() { lock (precompLock) { if (precompBase != null) return; PointExt p = new PointExt(); X448Field.Copy(B_x, 0, p.x, 0); X448Field.Copy(B_y, 0, p.y, 0); PointExtendXY(p); precompBaseTable = PointPrecompVar(p, 1 << (WnafWidthBase - 2)); precompBase = new uint[PrecompBlocks * PrecompPoints * 2 * X448Field.Size]; int off = 0; for (int b = 0; b < PrecompBlocks; ++b) { PointExt[] ds = new PointExt[PrecompTeeth]; PointExt sum = new PointExt(); PointSetNeutral(sum); for (int t = 0; t < PrecompTeeth; ++t) { PointAddVar(true, p, sum); PointDouble(p); ds[t] = PointCopy(p); if (b + t != PrecompBlocks + PrecompTeeth - 2) { for (int s = 1; s < PrecompSpacing; ++s) { PointDouble(p); } } } PointExt[] points = new PointExt[PrecompPoints]; int k = 0; points[k++] = sum; for (int t = 0; t < (PrecompTeeth - 1); ++t) { int size = 1 << t; for (int j = 0; j < size; ++j, ++k) { points[k] = PointCopy(points[k - size]); PointAddVar(false, ds[t], points[k]); } } Debug.Assert(k == PrecompPoints); for (int i = 0; i < PrecompPoints; ++i) { PointExt q = points[i]; // TODO[ed448] Batch inversion X448Field.Inv(q.z, q.z); X448Field.Mul(q.x, q.z, q.x); X448Field.Mul(q.y, q.z, q.y); //X448Field.Normalize(q.x); //X448Field.Normalize(q.y); X448Field.Copy(q.x, 0, precompBase, off); off += X448Field.Size; X448Field.Copy(q.y, 0, precompBase, off); off += X448Field.Size; } } Debug.Assert(off == precompBase.Length); } } private static void PruneScalar(byte[] n, int nOff, byte[] r) { Array.Copy(n, nOff, r, 0, ScalarBytes - 1); r[0] &= 0xFC; r[ScalarBytes - 2] |= 0x80; r[ScalarBytes - 1] = 0x00; } private static byte[] ReduceScalar(byte[] n) { ulong x00 = Decode32(n, 0); // x00:32/-- ulong x01 = (Decode24(n, 4) << 4); // x01:28/-- ulong x02 = Decode32(n, 7); // x02:32/-- ulong x03 = (Decode24(n, 11) << 4); // x03:28/-- ulong x04 = Decode32(n, 14); // x04:32/-- ulong x05 = (Decode24(n, 18) << 4); // x05:28/-- ulong x06 = Decode32(n, 21); // x06:32/-- ulong x07 = (Decode24(n, 25) << 4); // x07:28/-- ulong x08 = Decode32(n, 28); // x08:32/-- ulong x09 = (Decode24(n, 32) << 4); // x09:28/-- ulong x10 = Decode32(n, 35); // x10:32/-- ulong x11 = (Decode24(n, 39) << 4); // x11:28/-- ulong x12 = Decode32(n, 42); // x12:32/-- ulong x13 = (Decode24(n, 46) << 4); // x13:28/-- ulong x14 = Decode32(n, 49); // x14:32/-- ulong x15 = (Decode24(n, 53) << 4); // x15:28/-- ulong x16 = Decode32(n, 56); // x16:32/-- ulong x17 = (Decode24(n, 60) << 4); // x17:28/-- ulong x18 = Decode32(n, 63); // x18:32/-- ulong x19 = (Decode24(n, 67) << 4); // x19:28/-- ulong x20 = Decode32(n, 70); // x20:32/-- ulong x21 = (Decode24(n, 74) << 4); // x21:28/-- ulong x22 = Decode32(n, 77); // x22:32/-- ulong x23 = (Decode24(n, 81) << 4); // x23:28/-- ulong x24 = Decode32(n, 84); // x24:32/-- ulong x25 = (Decode24(n, 88) << 4); // x25:28/-- ulong x26 = Decode32(n, 91); // x26:32/-- ulong x27 = (Decode24(n, 95) << 4); // x27:28/-- ulong x28 = Decode32(n, 98); // x28:32/-- ulong x29 = (Decode24(n, 102) << 4); // x29:28/-- ulong x30 = Decode32(n, 105); // x30:32/-- ulong x31 = (Decode24(n, 109) << 4); // x31:28/-- ulong x32 = Decode16(n, 112); // x32:16/-- // x32 += (x31 >> 28); x31 &= M28UL; x16 += x32 * L4_0; // x16:42/-- x17 += x32 * L4_1; // x17:41/28 x18 += x32 * L4_2; // x18:43/42 x19 += x32 * L4_3; // x19:44/28 x20 += x32 * L4_4; // x20:43/-- x21 += x32 * L4_5; // x21:44/28 x22 += x32 * L4_6; // x22:43/41 x23 += x32 * L4_7; // x23:45/41 x31 += (x30 >> 28); x30 &= M28UL; // x31:28/--, x30:28/-- x15 += x31 * L4_0; // x15:54/-- x16 += x31 * L4_1; // x16:53/42 x17 += x31 * L4_2; // x17:55/54 x18 += x31 * L4_3; // x18:56/44 x19 += x31 * L4_4; // x19:55/-- x20 += x31 * L4_5; // x20:56/43 x21 += x31 * L4_6; // x21:55/53 x22 += x31 * L4_7; // x22:57/53 //x30 += (x29 >> 28); x29 &= M28UL; x14 += x30 * L4_0; // x14:54/-- x15 += x30 * L4_1; // x15:54/53 x16 += x30 * L4_2; // x16:56/-- x17 += x30 * L4_3; // x17:57/-- x18 += x30 * L4_4; // x18:56/55 x19 += x30 * L4_5; // x19:56/55 x20 += x30 * L4_6; // x20:57/-- x21 += x30 * L4_7; // x21:57/56 x29 += (x28 >> 28); x28 &= M28UL; // x29:28/--, x28:28/-- x13 += x29 * L4_0; // x13:54/-- x14 += x29 * L4_1; // x14:54/53 x15 += x29 * L4_2; // x15:56/-- x16 += x29 * L4_3; // x16:57/-- x17 += x29 * L4_4; // x17:57/55 x18 += x29 * L4_5; // x18:57/55 x19 += x29 * L4_6; // x19:57/52 x20 += x29 * L4_7; // x20:58/52 //x28 += (x27 >> 28); x27 &= M28UL; x12 += x28 * L4_0; // x12:54/-- x13 += x28 * L4_1; // x13:54/53 x14 += x28 * L4_2; // x14:56/-- x15 += x28 * L4_3; // x15:57/-- x16 += x28 * L4_4; // x16:57/55 x17 += x28 * L4_5; // x17:58/-- x18 += x28 * L4_6; // x18:58/-- x19 += x28 * L4_7; // x19:58/53 x27 += (x26 >> 28); x26 &= M28UL; // x27:28/--, x26:28/-- x11 += x27 * L4_0; // x11:54/-- x12 += x27 * L4_1; // x12:54/53 x13 += x27 * L4_2; // x13:56/-- x14 += x27 * L4_3; // x14:57/-- x15 += x27 * L4_4; // x15:57/55 x16 += x27 * L4_5; // x16:58/-- x17 += x27 * L4_6; // x17:58/56 x18 += x27 * L4_7; // x18:59/-- //x26 += (x25 >> 28); x25 &= M28UL; x10 += x26 * L4_0; // x10:54/-- x11 += x26 * L4_1; // x11:54/53 x12 += x26 * L4_2; // x12:56/-- x13 += x26 * L4_3; // x13:57/-- x14 += x26 * L4_4; // x14:57/55 x15 += x26 * L4_5; // x15:58/-- x16 += x26 * L4_6; // x16:58/56 x17 += x26 * L4_7; // x17:59/-- x25 += (x24 >> 28); x24 &= M28UL; // x25:28/--, x24:28/-- x09 += x25 * L4_0; // x09:54/-- x10 += x25 * L4_1; // x10:54/53 x11 += x25 * L4_2; // x11:56/-- x12 += x25 * L4_3; // x12:57/-- x13 += x25 * L4_4; // x13:57/55 x14 += x25 * L4_5; // x14:58/-- x15 += x25 * L4_6; // x15:58/56 x16 += x25 * L4_7; // x16:59/-- x21 += (x20 >> 28); x20 &= M28UL; // x21:58/--, x20:28/-- x22 += (x21 >> 28); x21 &= M28UL; // x22:57/54, x21:28/-- x23 += (x22 >> 28); x22 &= M28UL; // x23:45/42, x22:28/-- x24 += (x23 >> 28); x23 &= M28UL; // x24:28/18, x23:28/-- x08 += x24 * L4_0; // x08:54/-- x09 += x24 * L4_1; // x09:55/-- x10 += x24 * L4_2; // x10:56/46 x11 += x24 * L4_3; // x11:57/46 x12 += x24 * L4_4; // x12:57/55 x13 += x24 * L4_5; // x13:58/-- x14 += x24 * L4_6; // x14:58/56 x15 += x24 * L4_7; // x15:59/-- x07 += x23 * L4_0; // x07:54/-- x08 += x23 * L4_1; // x08:54/53 x09 += x23 * L4_2; // x09:56/53 x10 += x23 * L4_3; // x10:57/46 x11 += x23 * L4_4; // x11:57/55 x12 += x23 * L4_5; // x12:58/-- x13 += x23 * L4_6; // x13:58/56 x14 += x23 * L4_7; // x14:59/-- x06 += x22 * L4_0; // x06:54/-- x07 += x22 * L4_1; // x07:54/53 x08 += x22 * L4_2; // x08:56/-- x09 += x22 * L4_3; // x09:57/53 x10 += x22 * L4_4; // x10:57/55 x11 += x22 * L4_5; // x11:58/-- x12 += x22 * L4_6; // x12:58/56 x13 += x22 * L4_7; // x13:59/-- x18 += (x17 >> 28); x17 &= M28UL; // x18:59/31, x17:28/-- x19 += (x18 >> 28); x18 &= M28UL; // x19:58/54, x18:28/-- x20 += (x19 >> 28); x19 &= M28UL; // x20:30/29, x19:28/-- x21 += (x20 >> 28); x20 &= M28UL; // x21:28/03, x20:28/-- x05 += x21 * L4_0; // x05:54/-- x06 += x21 * L4_1; // x06:55/-- x07 += x21 * L4_2; // x07:56/31 x08 += x21 * L4_3; // x08:57/31 x09 += x21 * L4_4; // x09:57/56 x10 += x21 * L4_5; // x10:58/-- x11 += x21 * L4_6; // x11:58/56 x12 += x21 * L4_7; // x12:59/-- x04 += x20 * L4_0; // x04:54/-- x05 += x20 * L4_1; // x05:54/53 x06 += x20 * L4_2; // x06:56/53 x07 += x20 * L4_3; // x07:57/31 x08 += x20 * L4_4; // x08:57/55 x09 += x20 * L4_5; // x09:58/-- x10 += x20 * L4_6; // x10:58/56 x11 += x20 * L4_7; // x11:59/-- x03 += x19 * L4_0; // x03:54/-- x04 += x19 * L4_1; // x04:54/53 x05 += x19 * L4_2; // x05:56/-- x06 += x19 * L4_3; // x06:57/53 x07 += x19 * L4_4; // x07:57/55 x08 += x19 * L4_5; // x08:58/-- x09 += x19 * L4_6; // x09:58/56 x10 += x19 * L4_7; // x10:59/-- x15 += (x14 >> 28); x14 &= M28UL; // x15:59/31, x14:28/-- x16 += (x15 >> 28); x15 &= M28UL; // x16:59/32, x15:28/-- x17 += (x16 >> 28); x16 &= M28UL; // x17:31/29, x16:28/-- x18 += (x17 >> 28); x17 &= M28UL; // x18:28/04, x17:28/-- x02 += x18 * L4_0; // x02:54/-- x03 += x18 * L4_1; // x03:55/-- x04 += x18 * L4_2; // x04:56/32 x05 += x18 * L4_3; // x05:57/32 x06 += x18 * L4_4; // x06:57/56 x07 += x18 * L4_5; // x07:58/-- x08 += x18 * L4_6; // x08:58/56 x09 += x18 * L4_7; // x09:59/-- x01 += x17 * L4_0; // x01:54/-- x02 += x17 * L4_1; // x02:54/53 x03 += x17 * L4_2; // x03:56/53 x04 += x17 * L4_3; // x04:57/32 x05 += x17 * L4_4; // x05:57/55 x06 += x17 * L4_5; // x06:58/-- x07 += x17 * L4_6; // x07:58/56 x08 += x17 * L4_7; // x08:59/-- x16 *= 4; x16 += (x15 >> 26); x15 &= M26UL; x16 += 1; // x16:30/01 x00 += x16 * L_0; x01 += x16 * L_1; x02 += x16 * L_2; x03 += x16 * L_3; x04 += x16 * L_4; x05 += x16 * L_5; x06 += x16 * L_6; x07 += x16 * L_7; x01 += (x00 >> 28); x00 &= M28UL; x02 += (x01 >> 28); x01 &= M28UL; x03 += (x02 >> 28); x02 &= M28UL; x04 += (x03 >> 28); x03 &= M28UL; x05 += (x04 >> 28); x04 &= M28UL; x06 += (x05 >> 28); x05 &= M28UL; x07 += (x06 >> 28); x06 &= M28UL; x08 += (x07 >> 28); x07 &= M28UL; x09 += (x08 >> 28); x08 &= M28UL; x10 += (x09 >> 28); x09 &= M28UL; x11 += (x10 >> 28); x10 &= M28UL; x12 += (x11 >> 28); x11 &= M28UL; x13 += (x12 >> 28); x12 &= M28UL; x14 += (x13 >> 28); x13 &= M28UL; x15 += (x14 >> 28); x14 &= M28UL; x16 = (x15 >> 26); x15 &= M26UL; x16 -= 1; Debug.Assert(x16 == 0UL || x16 == ulong.MaxValue); x00 -= x16 & L_0; x01 -= x16 & L_1; x02 -= x16 & L_2; x03 -= x16 & L_3; x04 -= x16 & L_4; x05 -= x16 & L_5; x06 -= x16 & L_6; x07 -= x16 & L_7; x01 += (ulong)((long)x00 >> 28); x00 &= M28UL; x02 += (ulong)((long)x01 >> 28); x01 &= M28UL; x03 += (ulong)((long)x02 >> 28); x02 &= M28UL; x04 += (ulong)((long)x03 >> 28); x03 &= M28UL; x05 += (ulong)((long)x04 >> 28); x04 &= M28UL; x06 += (ulong)((long)x05 >> 28); x05 &= M28UL; x07 += (ulong)((long)x06 >> 28); x06 &= M28UL; x08 += (ulong)((long)x07 >> 28); x07 &= M28UL; x09 += (ulong)((long)x08 >> 28); x08 &= M28UL; x10 += (ulong)((long)x09 >> 28); x09 &= M28UL; x11 += (ulong)((long)x10 >> 28); x10 &= M28UL; x12 += (ulong)((long)x11 >> 28); x11 &= M28UL; x13 += (ulong)((long)x12 >> 28); x12 &= M28UL; x14 += (ulong)((long)x13 >> 28); x13 &= M28UL; x15 += (ulong)((long)x14 >> 28); x14 &= M28UL; Debug.Assert(x15 >> 26 == 0UL); byte[] r = new byte[ScalarBytes]; Encode56(x00 | (x01 << 28), r, 0); Encode56(x02 | (x03 << 28), r, 7); Encode56(x04 | (x05 << 28), r, 14); Encode56(x06 | (x07 << 28), r, 21); Encode56(x08 | (x09 << 28), r, 28); Encode56(x10 | (x11 << 28), r, 35); Encode56(x12 | (x13 << 28), r, 42); Encode56(x14 | (x15 << 28), r, 49); //r[ScalarBytes - 1] = 0; return r; } private static void ScalarMultBase(byte[] k, PointExt r) { Precompute(); PointSetNeutral(r); uint[] n = new uint[ScalarUints + 1]; DecodeScalar(k, 0, n); // Recode the scalar into signed-digit form { n[ScalarUints] = 4U + Nat.CAdd(ScalarUints, ~(int)n[0] & 1, n, L, n); uint c = Nat.ShiftDownBit(n.Length, n, 0); Debug.Assert(c == (1U << 31)); } PointPrecomp p = new PointPrecomp(); int cOff = PrecompSpacing - 1; for (;;) { int tPos = cOff; for (int b = 0; b < PrecompBlocks; ++b) { uint w = 0; for (int t = 0; t < PrecompTeeth; ++t) { uint tBit = n[tPos >> 5] >> (tPos & 0x1F); w &= ~(1U << t); w ^= (tBit << t); tPos += PrecompSpacing; } int sign = (int)(w >> (PrecompTeeth - 1)) & 1; int abs = ((int)w ^ -sign) & PrecompMask; Debug.Assert(sign == 0 || sign == 1); Debug.Assert(0 <= abs && abs < PrecompPoints); PointLookup(b, abs, p); X448Field.CNegate(sign, p.x); PointAddPrecomp(p, r); } if (--cOff < 0) break; PointDouble(r); } } private static void ScalarMultBaseEncoded(byte[] k, byte[] r, int rOff) { PointExt p = new PointExt(); ScalarMultBase(k, p); if (0 == EncodePoint(p, r, rOff)) throw new InvalidOperationException(); } internal static void ScalarMultBaseXY(byte[] k, int kOff, uint[] x, uint[] y) { byte[] n = new byte[ScalarBytes]; PruneScalar(k, kOff, n); PointExt p = new PointExt(); ScalarMultBase(n, p); if (0 == CheckPoint(p.x, p.y, p.z)) throw new InvalidOperationException(); X448Field.Copy(p.x, 0, x, 0); X448Field.Copy(p.y, 0, y, 0); } private static void ScalarMultStrausVar(uint[] nb, uint[] np, PointExt p, PointExt r) { Precompute(); int width = 5; sbyte[] ws_b = GetWnaf(nb, WnafWidthBase); sbyte[] ws_p = GetWnaf(np, width); PointExt[] tp = PointPrecompVar(p, 1 << (width - 2)); PointSetNeutral(r); for (int bit = 446;;) { int wb = ws_b[bit]; if (wb != 0) { int sign = wb >> 31; int index = (wb ^ sign) >> 1; PointAddVar((sign != 0), precompBaseTable[index], r); } int wp = ws_p[bit]; if (wp != 0) { int sign = wp >> 31; int index = (wp ^ sign) >> 1; PointAddVar((sign != 0), tp[index], r); } if (--bit < 0) break; PointDouble(r); } } public static void Sign(byte[] sk, int skOff, byte[] ctx, byte[] m, int mOff, int mLen, byte[] sig, int sigOff) { byte phflag = 0x00; ImplSign(sk, skOff, ctx, phflag, m, mOff, mLen, sig, sigOff); } public static void Sign(byte[] sk, int skOff, byte[] pk, int pkOff, byte[] ctx, byte[] m, int mOff, int mLen, byte[] sig, int sigOff) { byte phflag = 0x00; ImplSign(sk, skOff, pk, pkOff, ctx, phflag, m, mOff, mLen, sig, sigOff); } public static void SignPrehash(byte[] sk, int skOff, byte[] ctx, byte[] ph, int phOff, byte[] sig, int sigOff) { byte phflag = 0x01; ImplSign(sk, skOff, ctx, phflag, ph, phOff, PrehashSize, sig, sigOff); } public static void SignPrehash(byte[] sk, int skOff, byte[] pk, int pkOff, byte[] ctx, byte[] ph, int phOff, byte[] sig, int sigOff) { byte phflag = 0x01; ImplSign(sk, skOff, pk, pkOff, ctx, phflag, ph, phOff, PrehashSize, sig, sigOff); } public static void SignPrehash(byte[] sk, int skOff, byte[] ctx, IXof ph, byte[] sig, int sigOff) { byte[] m = new byte[PrehashSize]; if (PrehashSize != ph.DoFinal(m, 0, PrehashSize)) throw new ArgumentException("ph"); byte phflag = 0x01; ImplSign(sk, skOff, ctx, phflag, m, 0, m.Length, sig, sigOff); } public static void SignPrehash(byte[] sk, int skOff, byte[] pk, int pkOff, byte[] ctx, IXof ph, byte[] sig, int sigOff) { byte[] m = new byte[PrehashSize]; if (PrehashSize != ph.DoFinal(m, 0, PrehashSize)) throw new ArgumentException("ph"); byte phflag = 0x01; ImplSign(sk, skOff, pk, pkOff, ctx, phflag, m, 0, m.Length, sig, sigOff); } public static bool Verify(byte[] sig, int sigOff, byte[] pk, int pkOff, byte[] ctx, byte[] m, int mOff, int mLen) { byte phflag = 0x00; return ImplVerify(sig, sigOff, pk, pkOff, ctx, phflag, m, mOff, mLen); } public static bool VerifyPrehash(byte[] sig, int sigOff, byte[] pk, int pkOff, byte[] ctx, byte[] ph, int phOff) { byte phflag = 0x01; return ImplVerify(sig, sigOff, pk, pkOff, ctx, phflag, ph, phOff, PrehashSize); } public static bool VerifyPrehash(byte[] sig, int sigOff, byte[] pk, int pkOff, byte[] ctx, IXof ph) { byte[] m = new byte[PrehashSize]; if (PrehashSize != ph.DoFinal(m, 0, PrehashSize)) throw new ArgumentException("ph"); byte phflag = 0x01; return ImplVerify(sig, sigOff, pk, pkOff, ctx, phflag, m, 0, m.Length); } } } #pragma warning restore #endif
38.230897
141
0.410732
[ "MPL-2.0", "MPL-2.0-no-copyleft-exception" ]
jneless/wireless_AR_skeleton_realtime_sync
Unity_ARFoundation_IOS_clients/Assets/Best HTTP/Source/SecureProtocol/math/ec/rfc8032/Ed448.cs
46,030
C#
using System; using System.ComponentModel; using System.IO; using System.Reflection; using System.Runtime; using System.Runtime.InteropServices; using System.Text; using System.Threading; namespace NewLife.Log { /// <summary>日志基类。提供日志的基本实现</summary> [EditorBrowsable(EditorBrowsableState.Advanced)] public abstract class Logger : ILog { #region 主方法 /// <summary>调试日志</summary> /// <param name="format">格式化字符串</param> /// <param name="args">格式化参数</param> public virtual void Debug(String format, params Object[] args) => Write(LogLevel.Debug, format, args); /// <summary>信息日志</summary> /// <param name="format">格式化字符串</param> /// <param name="args">格式化参数</param> public virtual void Info(String format, params Object[] args) => Write(LogLevel.Info, format, args); /// <summary>警告日志</summary> /// <param name="format">格式化字符串</param> /// <param name="args">格式化参数</param> public virtual void Warn(String format, params Object[] args) => Write(LogLevel.Warn, format, args); /// <summary>错误日志</summary> /// <param name="format">格式化字符串</param> /// <param name="args">格式化参数</param> public virtual void Error(String format, params Object[] args) => Write(LogLevel.Error, format, args); /// <summary>严重错误日志</summary> /// <param name="format">格式化字符串</param> /// <param name="args">格式化参数</param> public virtual void Fatal(String format, params Object[] args) => Write(LogLevel.Fatal, format, args); #endregion #region 核心方法 /// <summary>写日志</summary> /// <param name="level"></param> /// <param name="format"></param> /// <param name="args"></param> public virtual void Write(LogLevel level, String format, params Object[] args) { if (Enable && level >= Level) OnWrite(level, format, args); } /// <summary>写日志</summary> /// <param name="level"></param> /// <param name="format"></param> /// <param name="args"></param> protected abstract void OnWrite(LogLevel level, String format, params Object[] args); #endregion #region 辅助方法 /// <summary>格式化参数,特殊处理异常和时间</summary> /// <param name="format"></param> /// <param name="args"></param> /// <returns></returns> protected virtual String Format(String format, Object[] args) { //处理时间的格式化 if (args != null && args.Length > 0) { // 特殊处理异常 if (args.Length == 1 && args[0] is Exception ex && (format.IsNullOrEmpty() || format == "{0}")) return ex.GetMessage(); for (var i = 0; i < args.Length; i++) { if (args[i] != null && args[i].GetType() == typeof(DateTime)) { // 根据时间值的精确度选择不同的格式化输出 var dt = (DateTime)args[i]; if (dt.Millisecond > 0) args[i] = dt.ToString("yyyy-MM-dd HH:mm:ss.fff"); else if (dt.Hour > 0 || dt.Minute > 0 || dt.Second > 0) args[i] = dt.ToString("yyyy-MM-dd HH:mm:ss"); else args[i] = dt.ToString("yyyy-MM-dd"); } } } if (args == null || args.Length < 1) return format; //format = format.Replace("{", "{{").Replace("}", "}}"); return String.Format(format, args); } #endregion #region 属性 /// <summary>是否启用日志。默认true</summary> public virtual Boolean Enable { get; set; } = true; private LogLevel? _Level; /// <summary>日志等级,只输出大于等于该级别的日志,默认Info</summary> public virtual LogLevel Level { get { if (_Level != null) return _Level.Value; return Setting.Current.LogLevel; } set { _Level = value; } } #endregion #region 静态空实现 /// <summary>空日志实现</summary> public static ILog Null { get; } = new NullLogger(); class NullLogger : Logger { public override Boolean Enable { get => false; set { } } protected override void OnWrite(LogLevel level, String format, params Object[] args) { } } #endregion #region 日志头 /// <summary>输出日志头,包含所有环境信息</summary> protected static String GetHead() { var process = System.Diagnostics.Process.GetCurrentProcess(); var name = String.Empty; var ver = Environment.Version + ""; var target = ""; var asm = Assembly.GetEntryAssembly(); if (asm != null) { if (String.IsNullOrEmpty(name)) { var att = asm.GetCustomAttribute<AssemblyTitleAttribute>(); if (att != null) name = att.Title; } if (String.IsNullOrEmpty(name)) { var att = asm.GetCustomAttribute<AssemblyProductAttribute>(); if (att != null) name = att.Product; } if (String.IsNullOrEmpty(name)) { var att = asm.GetCustomAttribute<AssemblyDescriptionAttribute>(); if (att != null) name = att.Description; } var tar = asm.GetCustomAttribute<System.Runtime.Versioning.TargetFrameworkAttribute>(); if (tar != null) target = !tar.FrameworkDisplayName.IsNullOrEmpty() ? tar.FrameworkDisplayName : tar.FrameworkName; } target = RuntimeInformation.FrameworkDescription; if (String.IsNullOrEmpty(name)) { try { name = process.ProcessName; } catch { } } var sb = new StringBuilder(); sb.AppendFormat("#Software: {0}\r\n", name); sb.AppendFormat("#ProcessID: {0}{1}\r\n", process.Id, Environment.Is64BitProcess ? " x64" : ""); sb.AppendFormat("#AppDomain: {0}\r\n", AppDomain.CurrentDomain.FriendlyName); var fileName = String.Empty; // MonoAndroid无法识别MainModule,致命异常 try { fileName = process.MainModule.FileName; } catch { } if (fileName.IsNullOrEmpty() || fileName.EndsWithIgnoreCase("dotnet", "dotnet.exe")) { try { fileName = process.StartInfo.FileName; } catch { } } if (!fileName.IsNullOrEmpty()) sb.AppendFormat("#FileName: {0}\r\n", fileName); // 应用域目录 var baseDir = AppDomain.CurrentDomain.BaseDirectory; sb.AppendFormat("#BaseDirectory: {0}\r\n", baseDir); // 当前目录。如果由别的进程启动,默认的当前目录就是父级进程的当前目录 var curDir = Environment.CurrentDirectory; //if (!curDir.EqualIC(baseDir) && !(curDir + "\\").EqualIC(baseDir)) if (!baseDir.EqualIgnoreCase(curDir, curDir + "\\", curDir + "/")) sb.AppendFormat("#CurrentDirectory: {0}\r\n", curDir); var basePath = PathHelper.BasePath; if (basePath != baseDir) sb.AppendFormat("#BasePath: {0}\r\n", basePath); // 临时目录 sb.AppendFormat("#TempPath: {0}\r\n", Path.GetTempPath()); // 命令行不为空,也不是文件名时,才输出 // 当使用cmd启动程序时,这里就是用户输入的整个命令行,所以可能包含空格和各种符号 var line = Environment.CommandLine; if (!line.IsNullOrEmpty()) sb.AppendFormat("#CommandLine: {0}\r\n", line); var apptype = ""; if (Runtime.IsWeb) apptype = "Web"; else if (!Environment.UserInteractive) apptype = "Service"; else if (Runtime.IsConsole) apptype = "Console"; else apptype = "WinForm"; sb.AppendFormat("#ApplicationType: {0}\r\n", apptype); sb.AppendFormat("#CLR: {0}, {1}\r\n", ver, target); var os = ""; // 获取丰富的机器信息,需要提注册 MachineInfo.RegisterAsync var mi = MachineInfo.Current; if (mi != null) { os = mi.OSName + " " + mi.OSVersion; } else { // 特别识别Linux发行版 os = Environment.OSVersion + ""; if (Runtime.Linux) os = MachineInfo.GetLinuxName(); } sb.AppendFormat("#OS: {0}, {1}/{2}\r\n", os, Environment.MachineName, Environment.UserName); sb.AppendFormat("#CPU: {0}\r\n", Environment.ProcessorCount); if (mi != null) { sb.AppendFormat("#Memory: {0:n0}M/{1:n0}M\r\n", mi.AvailableMemory / 1024 / 1024, mi.Memory / 1024 / 1024); sb.AppendFormat("#Processor: {0}\r\n", mi.Processor); if (!mi.Product.IsNullOrEmpty()) sb.AppendFormat("#Product: {0}\r\n", mi.Product); if (mi.Temperature > 0) sb.AppendFormat("#Temperature: {0}\r\n", mi.Temperature); } sb.AppendFormat("#GC: IsServerGC={0}, LatencyMode={1}\r\n", GCSettings.IsServerGC, GCSettings.LatencyMode); ThreadPool.GetMinThreads(out var minWorker, out var minIO); ThreadPool.GetMaxThreads(out var maxWorker, out var maxIO); ThreadPool.GetAvailableThreads(out var avaWorker, out var avaIO); sb.AppendFormat("#ThreadPool: Min={0}/{1}, Max={2}/{3}, Available={4}/{5}\r\n", minWorker, minIO, maxWorker, maxIO, avaWorker, avaIO); sb.AppendFormat("#Date: {0:yyyy-MM-dd}\r\n", DateTime.Now); sb.AppendFormat("#字段: 时间 线程ID 线程池Y/网页W/普通N/定时T 线程名/任务ID 消息内容\r\n"); sb.AppendFormat("#Fields: Time ThreadID Kind Name Message\r\n"); return sb.ToString(); } #endregion } }
39.65283
147
0.504187
[ "MIT" ]
doujia/X
NewLife.Core/Log/Logger.cs
11,244
C#
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="EchoServer.cs"> // Copyright (c) 2021 Johannes Deml. All rights reserved. // </copyright> // <author> // Johannes Deml // public@deml.io // </author> // -------------------------------------------------------------------------------------------------------------------- using System; using System.Net; using System.Net.Sockets; using System.Threading; using LiteNetLib; namespace NetworkBenchmark.LiteNetLib { internal class EchoServer : AServer { public override bool IsStarted => netManager != null && netManager.IsRunning; private readonly Configuration config; private readonly BenchmarkStatistics benchmarkStatistics; private readonly EventBasedNetListener listener; private readonly NetManager netManager; private readonly DeliveryMethod deliveryMethod; public EchoServer(Configuration config, BenchmarkStatistics benchmarkStatistics) : base(config) { this.config = config; this.benchmarkStatistics = benchmarkStatistics; deliveryMethod = LiteNetLibBenchmark.GetDeliveryMethod(config.Transmission); listener = new EventBasedNetListener(); netManager = new NetManager(listener); netManager.UpdateTime = Utilities.CalculateTimeout(config.ServerTickRate); if (!config.Address.Contains(':')) { // For LiteNetLib 1.0 and above //netManager.IPv6Mode = IPv6Mode.Disabled; // LiteNetLib up to 0.9.4 netManager.IPv6Enabled = IPv6Mode.Disabled; } netManager.UnsyncedEvents = true; listener.ConnectionRequestEvent += OnConnectionRequest; listener.NetworkReceiveEvent += OnNetworkReceive; listener.NetworkErrorEvent += OnNetworkError; listener.PeerDisconnectedEvent += OnPeerDisconnected; } public override void StartServer() { base.StartServer(); netManager.Start(config.Port); } public override void StopServer() { base.StopServer(); netManager.Stop(); } public override void Dispose() { listener.ConnectionRequestEvent -= OnConnectionRequest; listener.NetworkReceiveEvent -= OnNetworkReceive; listener.NetworkErrorEvent -= OnNetworkError; listener.PeerDisconnectedEvent -= OnPeerDisconnected; } #region ManualMode public override void SendMessages(int messageCount, TransmissionType transmissionType) { var delivery = LiteNetLibBenchmark.GetDeliveryMethod(transmissionType); for (int i = 0; i < messageCount; i++) { Broadcast(MessageBuffer, delivery); } netManager.TriggerUpdate(); } #endregion private void OnConnectionRequest(ConnectionRequest request) { if (netManager.ConnectedPeerList.Count > config.Clients) { Console.WriteLine("Too many clients try to connect to the server"); request.Reject(); return; } request.Accept(); } private void OnNetworkReceive(NetPeer peer, NetPacketReader reader, DeliveryMethod clientDeliveryMethod) { if (benchmarkRunning) { Interlocked.Increment(ref benchmarkStatistics.MessagesServerReceived); if (!ManualMode) { Buffer.BlockCopy(reader.RawData, reader.UserDataOffset, MessageBuffer, 0, reader.UserDataSize); peer.Send(MessageBuffer, deliveryMethod); Interlocked.Increment(ref benchmarkStatistics.MessagesServerSent); netManager.TriggerUpdate(); } } reader.Recycle(); } private void Broadcast(byte[] data, DeliveryMethod delivery) { netManager.SendToAll(data, delivery); var messagesSent = netManager.ConnectedPeersCount; Interlocked.Add(ref benchmarkStatistics.MessagesServerSent, messagesSent); } private void OnNetworkError(IPEndPoint endpoint, SocketError socketerror) { Interlocked.Increment(ref benchmarkStatistics.Errors); } private void OnPeerDisconnected(NetPeer peer, DisconnectInfo disconnectinfo) { if (benchmarkPreparing || benchmarkRunning) { Utilities.WriteVerboseLine($"Client {peer.Id} disconnected while benchmark is running - {disconnectinfo.Reason}."); } } } }
29.028571
120
0.703002
[ "MIT" ]
JohannesDeml/NetCoreNetworkBenchmark
NetworkBenchmarkDotNet/Libraries/LiteNetLib/EchoServer.cs
4,066
C#
// Copyright (c) 2021 Alachisoft // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License using Alachisoft.NCache.Automation.ToolsOutput; using Alachisoft.NCache.Client; using Alachisoft.NCache.Common.Enum; using Alachisoft.NCache.Common.Monitoring; using Alachisoft.NCache.Common.Net; using Alachisoft.NCache.Common.Util; using Alachisoft.NCache.Config.NewDom; using Alachisoft.NCache.Management; using Alachisoft.NCache.Management.ServiceControl; using Alachisoft.NCache.Runtime.Exceptions; using Alachisoft.NCache.ServiceControl; using Alachisoft.NCache.Tools.Common; using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Net; using System.Text; using System.Threading.Tasks; namespace Alachisoft.NCache.Automation.Util { public class ToolsUtil { public static bool VerifyClusterConfigurations(Alachisoft.NCache.Config.NewDom.CacheServerConfig serverConfig , string cacheName) { if(serverConfig==null) { throw new Exception("Specified cache is not registered on the given server"); } double configVersion = -1; double deploymentVersion =-1; string configId = "dummyconfig"; NCacheRPCService NCache =new NCacheRPCService(""); if (serverConfig.CacheSettings.CacheType == "clustered-cache") { foreach (Address node in serverConfig.CacheDeployment.Servers.GetAllConfiguredNodes()) { NCache.ServerName = node.IpAddress.ToString(); ICacheServer cacheServer = NCache.GetCacheServer(new TimeSpan(0, 0, 0, 30)); ConfigurationVersion config = cacheServer.GetConfigurationVersion(cacheName); if (configId.Equals(configId)) { configId = config.ConfigID; } else if (!configId.Equals(config.ConfigID, StringComparison.InvariantCultureIgnoreCase)) { throw new VersionException("same name cache is already registered on node : " + node.IpAddress, 0); } if (configVersion == -1) { configVersion = config.ConfigVersion; } else if (configVersion != config.ConfigVersion) { throw new VersionException("There is a configuration mismatch for caches : " + cacheName, 0); } if (deploymentVersion == -1) { deploymentVersion = config.DeploymentVersion; } else if (deploymentVersion != config.DeploymentVersion) { throw new Exception("Deployement version is not same on all nodes"); } cacheServer.Dispose(); } } return true; } public static void ConveyCommandToAllRunningCacheHost(ConfiguredCacheInfo[] cacheHostprocesses, string Action, string server, IOutputConsole OutputProvider) { foreach (ConfiguredCacheInfo cacheHost in cacheHostprocesses) { NCacheRPCService nCache = new NCacheRPCService(""); nCache.Port = cacheHost.ManagementPort; nCache.ServerName = server; if (nCache.Port > 0) { ICacheServer hostService = nCache.GetCacheServer(new TimeSpan(0, 0, 0, 30)); if (Action.ToLower().Equals("start")) { OutputProvider.WriteLine("Starting monitoring on server {0}:{1}.", nCache.ServerName, nCache.Port); hostService.StartMonitoringActivity(); } else if (Action.ToLower().Equals("stop")) { OutputProvider.WriteLine("Stop monitoring on server {0}:{1}.", nCache.ServerName, nCache.Port); hostService.StopMonitoringActivity(); } hostService.PublishActivity(); } } } public static CacheConnectionOptions AddServersInCacheConnectionOptions(string server, CacheConnectionOptions options) { if (!String.IsNullOrEmpty(server)) { ServerInfo[] cacheServers; string[] servers = server.Split(new char[] { ',' }); if (servers.Length > 0) { cacheServers = new ServerInfo[servers.Length]; for (int i = 0; i < cacheServers.Length; i++) { ServerInfo serverinfo = new ServerInfo(servers[i], 9800); cacheServers[i] = serverinfo; } options.ServerList = cacheServers; } } return options; } public static void PrintLogo(IOutputConsole outputProvider, bool printLogo, string TOOLNAME) { if (printLogo) { string logo = @"Alachisoft (R) NCache Utility " + TOOLNAME + ". Version NCache Open Source 5.0 SP5" + @" Copyright (C) Alachisoft 2021. All rights reserved."; outputProvider.WriteLine(logo); outputProvider.WriteLine(Environment.NewLine); } } public static bool IsValidIP(string ip) { IPAddress adress; return IPAddress.TryParse(ip, out adress); } public static void PrintMessage(IOutputConsole outputProvider,string msg) { outputProvider.WriteErrorLine(msg); } public static string GetTopologyName(CacheTopologyParam? Topology) { string topologyName = ""; switch (Topology) { case CacheTopologyParam.Local: topologyName = "local"; break; case CacheTopologyParam.Replicated: topologyName = "replicated"; break; case CacheTopologyParam.Partitioned: topologyName = "partitioned"; break; default: topologyName =null; break; } return topologyName; } public static Common.Enum.CacheTopology GetTopologyType(string topologyName) { Common.Enum.CacheTopology topology = new Common.Enum.CacheTopology(); switch (topologyName.ToLower()) { case "local": topology = Common.Enum.CacheTopology.Local; return topology; case "mirrored": topology = Common.Enum.CacheTopology.Mirror; return topology; default: throw new Exception("Invalid Topology name"); } } } }
35.772727
164
0.545235
[ "Apache-2.0" ]
Alachisoft/NCache
Tools/NCAutomation/Util/ToolsUtil.cs
7,872
C#
using System.Collections.Generic; using System.Collections.ObjectModel; using System.Windows; using Microsoft.VisualBasic.ApplicationServices; using StartupEventArgs = System.Windows.StartupEventArgs; namespace Frame { public class SingleInstanceApp : Application { public readonly List<string> Args = new List<string>(); protected override void OnStartup(StartupEventArgs e) { base.OnStartup(e); MainWindow = new MainWindow(); foreach (var arg in Args) { ((MainWindow)MainWindow).AddNewTab(arg); } MainWindow.Show(); Shutdown(); } public void Poke() { MainWindow?.Activate(); } } public class SingleAppMangager : WindowsFormsApplicationBase { public SingleInstanceApp app; public SingleAppMangager() { IsSingleInstance = true; } protected override bool OnStartup(Microsoft.VisualBasic.ApplicationServices.StartupEventArgs eventArgs) { app = new SingleInstanceApp(); foreach (var arg in eventArgs.CommandLine) { app.Args.Add(arg); } app.Run(); return false; } protected override void OnStartupNextInstance(StartupNextInstanceEventArgs eventArgs) { base.OnStartupNextInstance(eventArgs); var mainWindow = (MainWindow) app.MainWindow; foreach (var arg in eventArgs.CommandLine) { mainWindow?.AddNewTab(arg); } if (app.MainWindow != null && app.MainWindow.WindowState == WindowState.Minimized) { app.MainWindow.WindowState = WindowState.Normal; } app.Poke(); } } }
23.328571
107
0.661359
[ "MIT" ]
Stromberg90/Frame
ImageViewer/SingleInstanceApp.cs
1,635
C#
#region license //MIT License //Copyright(c) 2016 Andreas Huebner //Permission is hereby granted, free of charge, to any person obtaining a copy //of this software and associated documentation files (the "Software"), to deal //in the Software without restriction, including without limitation the rights //to use, copy, modify, merge, publish, distribute, sublicense, and/or sell //copies of the Software, and to permit persons to whom the Software is //furnished to do so, subject to the following conditions: //The above copyright notice and this permission notice shall be included in all //copies or substantial portions of the Software. //THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR //IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, //FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE //AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER //LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, //OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE //SOFTWARE. #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Text.RegularExpressions; namespace AdtGekid { /// <summary> /// Definiert Erweiterungsmethode für <see cref="string"/>-Objekte. /// </summary> public static class StringHelper { /// <summary> /// Erzwingt die Kleinschreibung von Strings. /// </summary> /// <param name="str">Der zu bereinigende String.</param> /// <returns>Ein <see cref="string"/>, der nur Kleinschreibung enthält und dem führende und angehängte /// Leerzeichen entfernt wurden (Trim) bzw. <c>null</c>, falls der übergebene String leer oder ebenfalls <c>null</c> war.</returns> public static string EnforceTrimmedLowerCase(this string str) { if (IsNothing(str)) { return null; } else { return str.Trim().ToLower(); } } /// <summary> /// Erzwingt die Großschreibung von Strings. /// </summary> /// <param name="str">Der zu bereinigende String.</param> /// <returns>Ein <see cref="string"/>, der nur Großschreibung enthält und dem führende und angehängte /// Leerzeichen entfernt wurden (Trim) bzw. <c>null</c>, falls der übergebene String leer oder ebenfalls <c>null</c> war.</returns> public static string EnforceTrimmedUpperCase(this string str) { if (IsNothing(str)) { return null; } else { return str.Trim().ToUpper(); } } /// <summary> /// Bestimmt, ob der String <c>null</c> oder leer ist oder aber /// ausschließlich aus Leerzeichen besteht. /// </summary> /// <param name="str">Zu prüfender <see cref="string"/>.</param> /// <returns><c>true</c> falls der String <c>null</c> oder ein leerer String war /// oder wenn er lediglich Leerzeichen enthielt. Andernfalls <c>false</c>.</returns> public static bool IsNothing(this string str) { if(str == null) { return true; } str = str.Trim(); return string.IsNullOrEmpty(str); } /// <summary> /// Versucht einen String in einen Integer umzuwandeln. /// </summary> /// <param name="str">Der zu parsende String.</param> /// <returns>Einen <see cref="int?"/>, der den geparsten Integer /// enthält, sofern dieser korrekt erkannt werden konnte, andernfalls <c>null</c>.</returns> public static int? ParseNullableInt(this string str) { if(str.IsNothing()) { return null; } else { int i; if(int.TryParse(str, out i)) { return i; } return null; } } /// <summary> /// Prüft ob die angegebene Zeichenfolge mit dem Typ <see cref="int"/> /// kompatibel ist. /// </summary> /// <param name="str"></param> /// <returns></returns> public static bool IsIntegerCompatible(this string str) { return int.TryParse(str, out _); } } }
35.271318
139
0.588132
[ "MIT" ]
tetrodoxin/AdtGekid
src/AdtGekid/StringHelper.cs
4,565
C#
using System; using System.Collections.Generic; using System.Diagnostics; namespace IntersectSortedArrays { /// <summary> /// Linear search on both arrays /// </summary> public class StandardIntersecter:IntersecterBase { public StandardIntersecter(ICounter counter):base(counter) { } protected override IList<int> DoIntersect(IList<int> arr1, IList<int> arr2) { var p1 = 0; var p2 = 0; var result = new List<int>(); while (p1 < arr1.Count && p2 < arr2.Count) { var v1 = arr1[p1]; var v2 = arr2[p2]; _counter.Add(1); switch (v1.CompareTo(v2)) { case -1: p1++; break; case 0: result.Add(v1); p1++; p2++; break; case 1: p2++; break; } } return result; } } }
26.386364
83
0.394488
[ "MIT" ]
Siderite/SortedArrayIntersect
src/IntersectSortedArrays/Intersecters/StandardIntersecter.cs
1,163
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Senai.Opflix.WebApi.Domains; using Senai.Opflix.WebApi.Interface; using Senai.Opflix.WebApi.Repositories; namespace Senai.Opflix.WebApi.Controller { [Route("api/[controller]")] [Produces("application/json")] [ApiController] public class ConteudoController : ControllerBase { private ILancamentosRepository conteudoRepository { get; set; } public ConteudoController() { conteudoRepository = new ConteudoRepository(); } [HttpGet] public IActionResult Listar() { return Ok(conteudoRepository.Listar()); } [HttpGet("{Id}")] public IActionResult BuscarPorId(int Id) { return Ok(conteudoRepository.BuscarPorId(Id)); } [HttpPost] public void Cadastrar(Conteudo conteudo) { using (opflixContext ctx = new opflixContext()) { ctx.Conteudo.Add(conteudo); ctx.SaveChanges(); } } [HttpPut] public IActionResult Atualizar(Conteudo conteudo) { try { Conteudo conteudobuscado = conteudoRepository.BuscarPorId(conteudo.IdConteudo); if (conteudo == null) return NotFound(); conteudoRepository.Atualizar(conteudo); return Ok(); } catch (Exception ex) { return BadRequest(new { mensagem = "Errooouuu, ~Silva, Fausto" + ex.Message }); } } } }
28.322581
95
0.574032
[ "MIT" ]
GuigaxD/2s2019-sprint-1-bd-opflix-
Senai.Opflix.WebApi/Controller/ConteudoController.cs
1,758
C#
using System.Collections; using System.Collections.Generic; using UnityEditor; using UnityEngine; using UnityEngine.XR; using System.IO; using System.Xml.Linq; public class BuildApp { public static void Test() { Debug.Log("old:" + EditorUserBuildSettings.GetPlatformSettings("", "metroPackageVersion")); Debug.Log("Test:" + EditorPrefs.GetString("metroPackageVersion")); Debug.Log(";;:" + EditorUserSettings.GetConfigValue("metroPackageVersion")); } public static void BuildAll() { string appId = GetArg("-AppID"); string buildScene = GetArg("-BuildScene"); string targetProjetPath = GetArg("-TargetProjectPath"); string targetPlatform = GetArg("-TargetPlatform"); string compilerParam = GetArg("-CompilerParam"); string version = GetArg("-version"); Debug.Log("AppID=[" + appId + "]"); Debug.Log("Build Scene [" + buildScene + "]"); Debug.Log("Path=[" + targetProjetPath + "]"); Debug.Log("Platform=[" + targetPlatform + "]"); Debug.Log("version=" + version); if (appId == null) { Debug.Log("appId can not be null!"); EditorApplication.Exit(1); return; } PlayerSettings.productName = appId; EditorUserBuildSettings.development = false; EditorUserBuildSettings.allowDebugging = false; BuildPlayerOptions option = new BuildPlayerOptions(); option.options = BuildOptions.None; // 设置需要编译的场景 if (buildScene != null) { option.scenes = new[] { buildScene }; } else { List<string> sceneList = new List<string>(); for (int i = 0;i < EditorBuildSettings.scenes.Length;i ++) { EditorBuildSettingsScene scene = EditorBuildSettings.scenes[i]; if (scene.enabled) { sceneList.Add(scene.path); Debug.Log("Need Scene -> " + scene.path); } } option.scenes = sceneList.ToArray(); } // 设置平台信息 BuildTargetGroup group = BuildTargetGroup.WSA; if (targetPlatform == "HoloLens" || targetPlatform == "Surface") { group = BuildTargetGroup.WSA; EditorUserBuildSettings.SwitchActiveBuildTarget(group, BuildTarget.WSAPlayer); //EditorUserBuildSettings.wsaSDK = WSASDK.UWP; if (targetPlatform == "HoloLens") { EditorUserBuildSettings.wsaSubtarget = WSASubtarget.HoloLens; PlayerSettings.virtualRealitySupported = true; //VRSettings.LoadDeviceByName("HoloLens"); //VRSettings.enabled = true; } else if (targetPlatform == "Surface") { EditorUserBuildSettings.wsaSubtarget = WSASubtarget.PC; PlayerSettings.virtualRealitySupported = false; } EditorUserBuildSettings.wsaUWPBuildType = WSAUWPBuildType.D3D; EditorUserBuildSettings.wsaBuildAndRunDeployTarget = WSABuildAndRunDeployTarget.LocalMachine; EditorUserBuildSettings.wsaGenerateReferenceProjects = true; option.target = BuildTarget.WSAPlayer; // 设置产出路径 option.locationPathName = targetProjetPath; PlayerSettings.runInBackground = false; } else if (targetPlatform == "PC") { group = BuildTargetGroup.Standalone; EditorUserBuildSettings.SwitchActiveBuildTarget(group, BuildTarget.StandaloneWindows64); PlayerSettings.SetApiCompatibilityLevel(group, ApiCompatibilityLevel.NET_4_6); option.target = BuildTarget.StandaloneWindows64; // 设置产出路径 string ending = ""; if (!targetProjetPath.EndsWith("/")) ending = "/"; option.locationPathName = targetProjetPath + ending + appId + ".exe"; // PC端设置为可背景运行 PlayerSettings.runInBackground = true; } else { Debug.LogError("[Build]No Such Platform!!"); return; } // 设置编译参数 string define = PlayerSettings.GetScriptingDefineSymbolsForGroup(group); // 先排除可能需要排除的编译参数 define = RemoveParam(define, "ME_LIVE_ACTIVE"); // 再添加编译参数 if (compilerParam != null) { define += ";" + compilerParam; PlayerSettings.SetScriptingDefineSymbolsForGroup(group, define); } // 设置路径 Debug.Log(targetProjetPath); if (!System.IO.Directory.Exists(targetProjetPath)) { System.IO.Directory.CreateDirectory(targetProjetPath); } // 开始编译 string buildError = BuildPipeline.BuildPlayer(option); if (buildError.StartsWith("Error")) { Debug.Log("Build Error! " + buildError); EditorApplication.Exit(1); return; } else { Debug.Log("Try to change version!"); } // 修改版本号 if (targetPlatform == "HoloLens" || targetPlatform == "Surface") { SetPackageNameAndVersion(targetProjetPath, appId, version); } } private static string RemoveParam(string all, string paramToRemove) { int index = all.IndexOf(paramToRemove); string rs = all; if (index >= 0) { int end = index + paramToRemove.Length; rs = all.Substring(0, index); rs += all.Substring(end); } return rs; } private static string GetArg(string name) { var args = System.Environment.GetCommandLineArgs(); for (int i = 0; i < args.Length; i++) { if (args[i] == name && args.Length > i + 1) { return args[i + 1]; } } return null; } private static void SetPackageNameAndVersion(string projectPath, string name, string version) { // Find the manifest, assume the one we want is the first one string[] manifests = Directory.GetFiles(projectPath, "Package.appxmanifest", SearchOption.AllDirectories); if (manifests.Length == 0) { Debug.LogError("Unable to find Package.appxmanifest file for build (in path - " + projectPath + ")"); return; } string manifest = manifests[0]; XElement rootNode = XElement.Load(manifest); XNamespace ns = rootNode.GetDefaultNamespace(); var identityNode = rootNode.Element(ns + "Identity"); if (identityNode == null) { Debug.LogError("Package.appxmanifest for build (in path - " + projectPath + ") is missing an <Identity /> node"); return; } var nameAttr = identityNode.Attribute(XName.Get("Name")); if (nameAttr == null) { Debug.LogError("Package.appxmanifest for build (in path - " + projectPath + ") is missing a version attribute in the <Identity /> node."); } else { nameAttr.Value = name; } // We use XName.Get instead of string -> XName implicit conversion because // when we pass in the string "Version", the program doesn't find the attribute. // Best guess as to why this happens is that implicit string conversion doesn't set the namespace to empty var versionAttr = identityNode.Attribute(XName.Get("Version")); if (versionAttr == null) { Debug.LogError("Package.appxmanifest for build (in path - " + projectPath + ") is missing a version attribute in the <Identity /> node."); } else { versionAttr.Value = version; } // Assume package version always has a '.'. // According to https://msdn.microsoft.com/en-us/library/windows/apps/br211441.aspx // Package versions are always of the form Major.Minor.Build.Revision rootNode.Save(manifest); } static void BuildPCStandalone() { EditorUserBuildSettings.SwitchActiveBuildTarget(BuildTarget.StandaloneWindows64); string projectPath = Application.dataPath; projectPath = projectPath.Substring(0, projectPath.IndexOf("Assets")) + "VSProject_SpectatorView/"; Debug.Log(projectPath); if (!System.IO.Directory.Exists(projectPath)) { System.IO.Directory.CreateDirectory(projectPath); } BuildPlayerOptions option = new BuildPlayerOptions(); option.locationPathName = projectPath; option.scenes = new[] { "Assets/Scenes/DemoShare.unity" }; option.target = BuildTarget.WSAPlayer; option.options = BuildOptions.None; PlayerSettings.runInBackground = true; BuildPipeline.BuildPlayer(option); } static void BuildHoloLens() { EditorUserBuildSettings.SwitchActiveBuildTarget(BuildTarget.WSAPlayer); EditorUserBuildSettings.wsaSDK = WSASDK.UWP; EditorUserBuildSettings.wsaSubtarget = WSASubtarget.HoloLens; EditorUserBuildSettings.wsaUWPBuildType = WSAUWPBuildType.D3D; EditorUserBuildSettings.wsaBuildAndRunDeployTarget = WSABuildAndRunDeployTarget.LocalMachine; PlayerSettings.virtualRealitySupported = true; //VRSettings.LoadDeviceByName("HoloLens"); //VRSettings.enabled = true; string projectPath = Application.dataPath; projectPath = projectPath.Substring(0, projectPath.IndexOf("Assets")) + "VSProject_Normal/"; Debug.Log(projectPath); if (!System.IO.Directory.Exists(projectPath)) { System.IO.Directory.CreateDirectory(projectPath); } BuildPlayerOptions option = new BuildPlayerOptions(); option.locationPathName = projectPath; option.scenes = new[] { "Assets/Scenes/DemoShare.unity" }; option.target = BuildTarget.WSAPlayer; option.options = BuildOptions.None; PlayerSettings.runInBackground = false; BuildPipeline.BuildPlayer(option); } static void BuildSurface() { EditorUserBuildSettings.SwitchActiveBuildTarget(BuildTarget.WSAPlayer); EditorUserBuildSettings.wsaSDK = WSASDK.UWP; EditorUserBuildSettings.wsaSubtarget = WSASubtarget.PC; EditorUserBuildSettings.wsaUWPBuildType = WSAUWPBuildType.D3D; EditorUserBuildSettings.wsaBuildAndRunDeployTarget = WSABuildAndRunDeployTarget.LocalMachine; PlayerSettings.virtualRealitySupported = false; string projectPath = Application.dataPath; projectPath = projectPath.Substring(0, projectPath.IndexOf("Assets")) + "VSProject_Normal/"; Debug.Log(projectPath); if (!System.IO.Directory.Exists(projectPath)) { System.IO.Directory.CreateDirectory(projectPath); } BuildPlayerOptions option = new BuildPlayerOptions(); option.locationPathName = projectPath; option.scenes = new[] { "Assets/Scenes/DemoShare.unity" }; option.target = BuildTarget.WSAPlayer; option.options = BuildOptions.None; PlayerSettings.runInBackground = false; BuildPipeline.BuildPlayer(option); } }
32.33711
150
0.609724
[ "MIT" ]
DataMesh-OpenSource/METoolkit
Assets/DataMesh/ARModule/Build/Editor/BuildApp.cs
11,569
C#
// Auto-Generated by FAKE; do not edit // <auto-generated/> using System.Reflection; [assembly: AssemblyVersion("4.1.1")] [assembly: AssemblyFileVersion("4.1.1")] [assembly: AssemblyInformationalVersion("4.1.1 7c6024")] namespace System { internal static class AssemblyVersionInformation { internal const System.String AssemblyVersion = "4.1.1"; internal const System.String AssemblyFileVersion = "4.1.1"; internal const System.String AssemblyInformationalVersion = "4.1.1 7c6024"; } }
34.666667
83
0.721154
[ "MIT" ]
drcolombo/CsvReader
code/SolutionInfo.cs
522
C#
#region Copyright /////////////////////////////////////////////////////////////////////////////// // // Copyright (c) Phoenix Contact GmbH & Co KG // This software is licensed under Apache-2.0 // /////////////////////////////////////////////////////////////////////////////// #endregion using System; using System.Collections.Generic; using System.Globalization; using System.Runtime.Serialization; using System.Text; using PlcNext.Common.Tools; namespace PlcNext.Common.Project { internal class FileExistsException : FormattableException { public FileExistsException(string fileName, string templateName) : base(string.Format(CultureInfo.InvariantCulture, ExceptionTexts.FileExists, fileName, Environment.NewLine, templateName)) { } public FileExistsException(string destinationDirectory) : base(string.Format(CultureInfo.InvariantCulture, ExceptionTexts.FilesExistingInsideDirectory, destinationDirectory, Environment.NewLine)) { } } }
33.774194
204
0.612225
[ "Apache-2.0" ]
PLCnext/PLCnext_CLI
src/PlcNext.Common/Project/FileExistsException.cs
1,049
C#
using UnityEngine; using System.Collections; public class DecisionTree : DecisionTreeNode { public DecisionTreeNode root; private Action actionNew; private Action actionOld; void Update() { actionNew.activated = false; actionOld = actionNew; actionNew = root.MakeDecision() as Action; if (actionNew == null) actionNew = actionOld; actionNew.activated = true; } public override DecisionTreeNode MakeDecision() { return root.MakeDecision(); } }
22.04
51
0.635209
[ "MIT" ]
maricak/Santorini
book/UAIPC/Assets/Scripts/Ch03DecisionMaking/DecisionTree.cs
553
C#
#region License /* * All content copyright Terracotta, Inc., unless otherwise indicated. 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. You may obtain a copy * of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. * */ #endregion using System; using System.Collections.Specialized; using System.Threading; using Common.Logging; using Quartz.Impl; namespace Quartz.Examples.Example12 { /// <author>Bill Kratzer</author> /// <author>Marko Lahma (.NET)</author> public class RemoteServerExample : IExample { public string Name { get { return GetType().Name; } } /// <summary> This example will spawn a large number of jobs to run /// /// </summary> /// <author> James House, Bill Kratzer /// </author> public virtual void Run() { ILog log = LogManager.GetLogger(typeof(RemoteServerExample)); NameValueCollection properties = new NameValueCollection(); properties["quartz.scheduler.instanceName"] = "RemoteServer"; // set thread pool info properties["quartz.threadPool.type"] = "Quartz.Simpl.SimpleThreadPool, Quartz"; properties["quartz.threadPool.threadCount"] = "5"; properties["quartz.threadPool.threadPriority"] = "Normal"; // set remoting expoter properties["quartz.scheduler.exporter.type"] = "Quartz.Simpl.RemotingSchedulerExporter, Quartz"; properties["quartz.scheduler.exporter.port"] = "555"; properties["quartz.scheduler.exporter.bindName"] = "QuartzScheduler"; properties["quartz.scheduler.exporter.channelType"] = "tcp"; ISchedulerFactory sf = new StdSchedulerFactory(properties); IScheduler sched = sf.GetScheduler(); log.Info("------- Initialization Complete -----------"); log.Info("------- (Not Scheduling any Jobs - relying on a remote client to schedule jobs --"); log.Info("------- Starting Scheduler ----------------"); // start the schedule sched.Start(); log.Info("------- Started Scheduler -----------------"); log.Info("------- Waiting ten minutes... ------------"); // wait five minutes to give our jobs a chance to run try { Thread.Sleep(TimeSpan.FromMinutes(5)); } catch (ThreadInterruptedException) { } // shut down the scheduler log.Info("------- Shutting Down ---------------------"); sched.Shutdown(true); log.Info("------- Shutdown Complete -----------------"); SchedulerMetaData metaData = sched.GetMetaData(); log.Info("Executed " + metaData.NumberOfJobsExecuted + " jobs."); } } }
32.123711
108
0.631579
[ "Apache-2.0" ]
Leftyx/quartznet
src/Quartz.Examples/example12/RemoteServerExample.cs
3,116
C#
// // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. // // Microsoft Cognitive Services: http://www.microsoft.com/cognitive // // Microsoft Cognitive Services Github: // https://github.com/Microsoft/Cognitive // // Copyright (c) Microsoft Corporation // All rights reserved. // // MIT License: // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED ""AS IS"", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using ServiceHelpers; using Microsoft.ProjectOxford.Face; using Microsoft.ProjectOxford.Face.Contract; using System; using System.Collections.Generic; using System.ComponentModel; using System.IO; using System.Linq; using System.Runtime.InteropServices.WindowsRuntime; using System.Threading.Tasks; using Windows.Foundation; using Windows.Foundation.Collections; using Windows.Storage; using Windows.Storage.Pickers; using Windows.UI.Popups; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Controls.Primitives; using Windows.UI.Xaml.Data; using Windows.UI.Xaml.Input; using Windows.UI.Xaml.Media; using Windows.UI.Xaml.Navigation; using Microsoft.ProjectOxford.Common; // The User Control item template is documented at http://go.microsoft.com/fwlink/?LinkId=234236 namespace IntelligentKioskSample.Controls { public sealed partial class ImageSearchUserControl : UserControl { private Task processingLoopTask; private bool isProcessingLoopInProgress; private bool isProcessingPhoto; public static readonly DependencyProperty ClearStateWhenClosedProperty = DependencyProperty.Register( "ClearStateWhenClosed", typeof(bool), typeof(ImageSearchUserControl), new PropertyMetadata(true) ); public static readonly DependencyProperty DetectFacesOnLoadProperty = DependencyProperty.Register( "DetectFacesOnLoad", typeof(bool), typeof(ImageSearchUserControl), new PropertyMetadata(false) ); public static readonly DependencyProperty ImageContentTypeProperty = DependencyProperty.Register( "ImageContentType", typeof(string), typeof(ImageSearchUserControl), new PropertyMetadata("Face") ); public static readonly DependencyProperty EnableCameraCaptureProperty = DependencyProperty.Register( "EnableCameraCapture", typeof(bool), typeof(ImageSearchUserControl), new PropertyMetadata(false) ); public static readonly DependencyProperty RequireFaceInCameraCaptureProperty = DependencyProperty.Register( "RequireFaceInCameraCapture", typeof(bool), typeof(ImageSearchUserControl), new PropertyMetadata(true) ); public event EventHandler<IEnumerable<ImageAnalyzer>> OnImageSearchCompleted; public event EventHandler OnImageSearchCanceled; public bool DetectFacesOnLoad { get { return (bool)GetValue(DetectFacesOnLoadProperty); } set { SetValue(DetectFacesOnLoadProperty, (bool)value); } } public bool ClearStateWhenClosed { get { return (bool)GetValue(ClearStateWhenClosedProperty); } set { SetValue(ClearStateWhenClosedProperty, (bool)value); } } public string ImageContentType { get { return (string)GetValue(ImageContentTypeProperty); } set { SetValue(ImageContentTypeProperty, (string)value); } } public bool EnableCameraCapture { get { return (bool)GetValue(EnableCameraCaptureProperty); } set { SetValue(EnableCameraCaptureProperty, (bool)value); } } public bool RequireFaceInCameraCapture { get { return (bool)GetValue(RequireFaceInCameraCaptureProperty); } set { SetValue(RequireFaceInCameraCaptureProperty, (bool)value); } } public ImageSearchUserControl() { this.InitializeComponent(); } public void TriggerSearch(string query) { this.imageResultsGrid.ItemsSource = Enumerable.Empty<string>(); this.autoSuggestBox.Text = query; } private async void onQuerySubmitted(AutoSuggestBox sender, AutoSuggestBoxQuerySubmittedEventArgs args) { await QueryBingImages(args.QueryText); } private async Task QueryBingImages(string query) { this.progressRing.IsActive = true; if (BingSearchHelper.AutoSuggestionApiKey != null && BingSearchHelper.AutoSuggestionApiKey.Length > 0) { try { IEnumerable<string> imageUrls = await BingSearchHelper.GetImageSearchResults(query, imageContent: this.ImageContentType, count: 30); this.imageResultsGrid.ItemsSource = imageUrls.Select(url => new ImageAnalyzer(url)); } catch (Exception ex) { this.imageResultsGrid.ItemsSource = null; await Util.GenericApiCallExceptionHandler(ex, "Failure querying Bing Images"); } } this.progressRing.IsActive = false; } private void ClearFlyoutState() { if (this.ClearStateWhenClosed) { this.autoSuggestBox.Text = ""; this.imageResultsGrid.ItemsSource = Enumerable.Empty<string>(); } else { this.imageResultsGrid.DeselectRange(new ItemIndexRange(0, (uint)this.imageResultsGrid.Items.Count)); } } private async void onTextChanged(AutoSuggestBox sender, AutoSuggestBoxTextChangedEventArgs args) { if (args.Reason == AutoSuggestionBoxTextChangeReason.UserInput) { try { this.autoSuggestBox.ItemsSource = await BingSearchHelper.GetAutoSuggestResults(this.autoSuggestBox.Text); } catch (Exception) { // Default to no suggestions this.autoSuggestBox.ItemsSource = null; } } else if (args.Reason == AutoSuggestionBoxTextChangeReason.ProgrammaticChange && !string.IsNullOrEmpty(this.autoSuggestBox.Text)) { await QueryBingImages(this.autoSuggestBox.Text); } } private void OnAcceptButtonClicked(object sender, RoutedEventArgs e) { if (this.OnImageSearchCompleted != null) { this.OnImageSearchCompleted(this, this.imageResultsGrid.SelectedItems.Cast<ImageAnalyzer>().ToArray()); } this.ClearFlyoutState(); } private void OnCancelButtonClicked(object sender, RoutedEventArgs e) { if (this.OnImageSearchCanceled != null) { this.OnImageSearchCanceled(this, EventArgs.Empty); } this.ClearFlyoutState(); } private void OnImageResultSelectionChanged(object sender, SelectionChangedEventArgs e) { this.addSelectedPhotosButton.IsEnabled = this.imageResultsGrid.SelectedItems.Any(); } private async void LoadImagesFromFileClicked(object sender, RoutedEventArgs e) { this.progressRing.IsActive = true; try { FileOpenPicker fileOpenPicker = new FileOpenPicker { SuggestedStartLocation = PickerLocationId.PicturesLibrary, ViewMode = PickerViewMode.Thumbnail }; fileOpenPicker.FileTypeFilter.Add(".jpg"); fileOpenPicker.FileTypeFilter.Add(".jpeg"); fileOpenPicker.FileTypeFilter.Add(".png"); fileOpenPicker.FileTypeFilter.Add(".bmp"); IReadOnlyList<StorageFile> selectedFiles = await fileOpenPicker.PickMultipleFilesAsync(); if (selectedFiles != null) { this.OnImageSearchCompleted?.Invoke(this, selectedFiles.Select(file => new ImageAnalyzer(file.OpenStreamForReadAsync, file.Path))); } } catch (Exception ex) { this.imageResultsGrid.ItemsSource = null; await Util.GenericApiCallExceptionHandler(ex, "Failure processing local images"); } this.progressRing.IsActive = false; } private async void OnCameraImageCaptured(object sender, ImageAnalyzer e) { this.cameraCaptureFlyout.Hide(); await this.HandleTrainingImageCapture(e); } private async Task HandleTrainingImageCapture(ImageAnalyzer img) { var croppedImage = img; if (this.RequireFaceInCameraCapture) { croppedImage = await GetPrimaryFaceFromCameraCaptureAsync(img); } if (croppedImage != null) { this.OnImageSearchCompleted?.Invoke(this, new ImageAnalyzer[] { croppedImage }); } } private async Task<ImageAnalyzer> GetPrimaryFaceFromCameraCaptureAsync(ImageAnalyzer img) { if (img == null) { return null; } await img.DetectFacesAsync(); if (img.DetectedFaces == null || !img.DetectedFaces.Any()) { return null; } // Crop the primary face and return it as the result FaceRectangle rect = img.DetectedFaces.First().FaceRectangle; double heightScaleFactor = 1.8; double widthScaleFactor = 1.8; Rectangle biggerRectangle = new Rectangle { Height = Math.Min((int)(rect.Height * heightScaleFactor), img.DecodedImageHeight), Width = Math.Min((int)(rect.Width * widthScaleFactor), img.DecodedImageWidth) }; biggerRectangle.Left = Math.Max(0, rect.Left - (int)(rect.Width * ((widthScaleFactor - 1) / 2))); biggerRectangle.Top = Math.Max(0, rect.Top - (int)(rect.Height * ((heightScaleFactor - 1) / 1.4))); StorageFile tempFile = await ApplicationData.Current.TemporaryFolder.CreateFileAsync( "FaceRecoCameraCapture.jpg", CreationCollisionOption.GenerateUniqueName); await Util.CropBitmapAsync(img.GetImageStreamCallback, biggerRectangle, tempFile); return new ImageAnalyzer(tempFile.OpenStreamForReadAsync, tempFile.Path); } private async void OnCameraFlyoutOpened(object sender, object e) { await this.cameraControl.StartStreamAsync(); } private async void OnCameraFlyoutClosed(object sender, object e) { await this.cameraControl.StopStreamAsync(); this.isProcessingLoopInProgress = false; this.autoCaptureToggle.IsOn = false; } private void StartAutoCaptureProcessingLoop() { this.isProcessingLoopInProgress = true; if (this.processingLoopTask == null || this.processingLoopTask.Status != TaskStatus.Running) { this.processingLoopTask = Task.Run(() => this.AutoCaptureProcessingLoop()); } } private async void AutoCaptureProcessingLoop() { while (this.isProcessingLoopInProgress) { await this.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, async () => { if (!this.isProcessingPhoto) { this.isProcessingPhoto = true; await this.HandleTrainingImageCapture(await this.cameraControl.TakeAutoCapturePhoto()); this.isProcessingPhoto = false; } }); await Task.Delay(1000); } } private void OnCameraAutoCaptureToggleChanged(object sender, RoutedEventArgs e) { if (this.autoCaptureToggle.IsOn) { this.StartAutoCaptureProcessingLoop(); } else { this.isProcessingLoopInProgress = false; } } } }
36.964865
166
0.613804
[ "MIT" ]
kaiyee0/AIKiosk
Kiosk/Controls/ImageSearchUserControl.xaml.cs
13,679
C#
// *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.Aws.WafV2.Outputs { [OutputType] public sealed class RuleGroupRuleStatementNotStatementStatementSqliMatchStatementTextTransformation { /// <summary> /// The relative processing order for multiple transformations that are defined for a rule statement. AWS WAF processes all transformations, from lowest priority to highest, before inspecting the transformed content. /// </summary> public readonly int Priority; /// <summary> /// The transformation to apply, you can specify the following types: `NONE`, `COMPRESS_WHITE_SPACE`, `HTML_ENTITY_DECODE`, `LOWERCASE`, `CMD_LINE`, `URL_DECODE`. See the [documentation](https://docs.aws.amazon.com/waf/latest/APIReference/API_TextTransformation.html) for more details. /// </summary> public readonly string Type; [OutputConstructor] private RuleGroupRuleStatementNotStatementStatementSqliMatchStatementTextTransformation( int priority, string type) { Priority = priority; Type = type; } } }
39.666667
293
0.701681
[ "ECL-2.0", "Apache-2.0" ]
Otanikotani/pulumi-aws
sdk/dotnet/WafV2/Outputs/RuleGroupRuleStatementNotStatementStatementSqliMatchStatementTextTransformation.cs
1,428
C#
using Litium.Accelerator.ViewModels.Framework; using Litium.Accelerator.ViewModels.Product; using System.Collections.Generic; namespace Litium.Accelerator.ViewModels.Search { public class FacetSearchResult { public IEnumerable<FacetGroupFilter> FacetFilters { get; set; } public CategoryFilteringViewModel SortCriteria { get; set; } public SubNavigationLinkModel SubNavigation { get; set; } public string ProductsView { get; set; } public string NavigationTheme { get; set; } } }
33.375
71
0.730337
[ "MIT" ]
tonnguyen/Litium.GraphQL
Src/Litium.Accelerator/ViewModels/Search/FacetSearchResult.cs
536
C#
using System.Collections.Generic; using System.Text; namespace SwishSvg.Tests.IO { public class ElementBuilder { private readonly Dictionary<string, string> attributes = new Dictionary<string, string>(); public static ElementBuilder Create(string elementName, bool selfClosing = true) { return new ElementBuilder { ElementName = elementName, SelfClosing = selfClosing }; } public string ElementName { get; private set; } public bool SelfClosing { get; private set; } public ElementBuilder AddAttribute(string name, string value) { attributes.Add(name, value); return this; } public override string ToString() { var builder = new StringBuilder(); builder.Append($"<{ElementName}"); foreach (var att in attributes) { builder.Append($" {att.Key}=\"{att.Value}\""); } if (SelfClosing) { builder.Append(" />"); } else { builder.Append($"></{ElementName}>"); } return builder.ToString(); } } }
22.327586
98
0.509653
[ "MIT" ]
dswisher/swish-svg
test/SwishSvg.Tests/IO/ElementBuilder.cs
1,295
C#
namespace GMap.NET.MapProviders { using System; /// <summary> /// GoogleTerrainMap provider /// </summary> public class GoogleTerrainMapProvider : GoogleMapProviderBase { public static readonly GoogleTerrainMapProvider Instance; GoogleTerrainMapProvider() { } static GoogleTerrainMapProvider() { Instance = new GoogleTerrainMapProvider(); } public string Version = "t@132,r@333000000"; #region GMapProvider Members readonly Guid id = new Guid("A42EDF2E-63C5-4967-9DBF-4EFB3AF7BC11"); public override Guid Id { get { return id; } } readonly string name = "GoogleTerrainMap"; public override string Name { get { return name; } } public override PureImage GetTileImage(GPoint pos, int zoom) { string url = MakeTileImageUrl(pos, zoom, LanguageStr); return GetTileImageUsingHttp(url); } #endregion string MakeTileImageUrl(GPoint pos, int zoom, string language) { string sec1 = string.Empty; // after &x=... string sec2 = string.Empty; // after &zoom=... GetSecureWords(pos, out sec1, out sec2); return string.Format(UrlFormat, UrlFormatServer, GetServerNum(pos, 4), UrlFormatRequest, Version, language, pos.X, sec1, pos.Y, zoom, sec2, Server); } static readonly string UrlFormatServer = "mt"; static readonly string UrlFormatRequest = "vt"; static readonly string UrlFormat = "http://{0}{1}.{10}/maps/{2}/lyrs={3}&hl={4}&x={5}{6}&y={7}&z={8}&s={9}"; } }
27.6
160
0.56243
[ "Apache-2.0" ]
forgy/ntripshare-pro
GMap.NET.Core/GMap.NET.MapProviders/Google/GoogleTerrainMapProvider.cs
1,796
C#
using System.IO; using System.Windows.Forms; using AxMapWinGIS; using MapWinGIS; namespace Examples { public partial class MapExamples { // <summary> // Adds the layers and register event handler. // </summary> public void SelectBox(AxMap axMap1, string dataPath) { axMap1.Projection = tkMapProjection.PROJECTION_GOOGLE_MERCATOR; string filename = dataPath + "landuse.shp"; if (!File.Exists(filename)) { MessageBox.Show("Couldn't file the file: " + filename); return; } Shapefile sf = new Shapefile(); sf.Open(filename, null); if (!sf.StartEditingShapes(true, null)) { MessageBox.Show("Failed to start edit mode: " + sf.Table.ErrorMsg[sf.LastErrorCode]); } else { sf.UseQTree = true; sf.Labels.Generate("[Name]", tkLabelPositioning.lpCentroid, false); axMap1.AddLayer(sf, true); axMap1.SendSelectBoxFinal = true; MapEvents.SelectBoxFinal += AxMap1SelectBoxFinal; // change MapEvents to axMap1 axMap1.MapUnits = tkUnitsOfMeasure.umMeters; axMap1.CurrentScale = 50000; axMap1.CursorMode = tkCursorMode.cmSelection; } } // <summary> // Performs selection, updates charts // </summary> void AxMap1SelectBoxFinal(object sender, _DMapEvents_SelectBoxFinalEvent e) { // it's assumed here that the layer we want to edit is the first 1 (with 0 index) int layerHandle = axMap1.get_LayerHandle(0); Shapefile sf = axMap1.get_Shapefile(layerHandle); if (sf != null) { double left = 0.0; double top = 0.0; double bottom = 0.0; double right = 0.0; axMap1.PixelToProj(e.left, e.top, ref left, ref top); axMap1.PixelToProj(e.right, e.bottom, ref right, ref bottom); object result = null; var ext = new Extents(); ext.SetBounds(left, bottom, 0.0, right, top, 0.0); sf.SelectNone(); if (sf.SelectShapes(ext, 0.0, SelectMode.INTERSECTION, ref result)) { int[] shapes = result as int[]; if (shapes == null) return; for (int i = 0; i < shapes.Length; i++) { sf.set_ShapeSelected(shapes[i], true); } } axMap1.Redraw(); } } } }
35.8125
102
0.49075
[ "MPL-2.0" ]
AiScientists/MapWinGIS
docs/Examples/src/SelectBox.cs
2,867
C#
//****************************************************************************************************** // DataSubscriber.cs - Gbtc // // Copyright © 2010, Grid Protection Alliance. All Rights Reserved. // // Licensed to the Grid Protection Alliance (GPA) under one or more contributor license agreements. See // the NOTICE file distributed with this work for additional information regarding copyright ownership. // The GPA licenses this file to you under the Eclipse Public License -v 1.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.opensource.org/licenses/eclipse-1.0.php // // Unless agreed to in writing, the subject software distributed under the License is distributed on an // "AS-IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. Refer to the // License for the specific language governing permissions and limitations. // // Code Modification History: // ---------------------------------------------------------------------------------------------------- // 08/20/2010 - J. Ritchie Carroll // Generated original version of source code. // 02/07/2012 - Mehulbhai Thakkar // Modified SynchronizeMetadata to filter devices by original source and modified insert query // to populate OriginalSource value. Added to flag to optionally avoid metadata synchronization. // //****************************************************************************************************** using GSF.Collections; using GSF.Communication; //using GSF.Data; using GSF.IO; using GSF.Reflection; //using GSF.Security.Cryptography; using GSF.TimeSeries.Adapters; //using GSF.TimeSeries.Statistics; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.IO; using System.IO.Compression; using System.Linq; using System.Text; using System.Threading; using System.Xml; namespace GSF.TimeSeries.Transport { /// <summary> /// Represents a data subscribing client that will connect to a data publisher for a data subscription. /// </summary> [Description("DataSubscriber: client that subscribes to a publishing server for a streaming data.")] [EditorBrowsable(EditorBrowsableState.Advanced)] // Normally defined as an input device protocol public class DataSubscriber : InputAdapterBase { #region [ Members ] // Nested Types // Local measurement concentrator private class LocalConcentrator : ConcentratorBase { #region [ Members ] // Fields private DataSubscriber m_parent; private bool m_disposed; #endregion #region [ Constructors ] /// <summary> /// Creates a new local concentrator. /// </summary> public LocalConcentrator(DataSubscriber parent) { m_parent = parent; } #endregion #region [ Methods ] /// <summary> /// Releases the unmanaged resources used by the <see cref="LocalConcentrator"/> object and optionally releases the managed resources. /// </summary> /// <param name="disposing">true to release both managed and unmanaged resources; false to release only unmanaged resources.</param> protected override void Dispose(bool disposing) { if (!m_disposed) { try { if (disposing) m_parent = null; } finally { m_disposed = true; // Prevent duplicate dispose. base.Dispose(disposing); // Call base class Dispose(). } } } /// <summary> /// Publish <see cref="IFrame"/> of time-aligned collection of <see cref="IMeasurement"/> values that arrived within the /// concentrator's defined <see cref="ConcentratorBase.LagTime"/>. /// </summary> /// <param name="frame"><see cref="IFrame"/> of measurements with the same timestamp that arrived within <see cref="ConcentratorBase.LagTime"/> that are ready for processing.</param> /// <param name="index">Index of <see cref="IFrame"/> within a second ranging from zero to <c><see cref="ConcentratorBase.FramesPerSecond"/> - 1</c>.</param> protected override void PublishFrame(IFrame frame, int index) { // Publish locally sorted measurements if ((object)m_parent != null) m_parent.OnNewMeasurements(frame.Measurements.Values); } #endregion } // Constants private const int EvenKey = 0; // Even key/IV index private const int OddKey = 1; // Odd key/IV index private const int KeyIndex = 0; // Index of cipher key component in keyIV array private const int IVIndex = 1; // Index of initialization vector component in keyIV array private const long MissingCacheWarningInterval = 20000000; // Events /// <summary> /// Occurs when client connection to the data publication server is established. /// </summary> public event EventHandler ConnectionEstablished; /// <summary> /// Occurs when client connection to the data publication server is terminated. /// </summary> public event EventHandler ConnectionTerminated; /// <summary> /// Occurs when client connection to the data publication server has successfully authenticated. /// </summary> public event EventHandler ConnectionAuthenticated; /// <summary> /// Occurs when client receives requested meta-data transmitted by data publication server. /// </summary> public event EventHandler<EventArgs<DataSet>> MetaDataReceived; /// <summary> /// Occurs when first measurement is transmitted by data publication server. /// </summary> public event EventHandler<EventArgs<Ticks>> DataStartTime; /// <summary> /// Indicates that processing for an input adapter (via temporal session) has completed. /// </summary> /// <remarks> /// This event is expected to only be raised when an input adapter has been designed to process /// a finite amount of data, e.g., reading a historical range of data during temporal procesing. /// </remarks> public new event EventHandler<EventArgs<string>> ProcessingComplete; // Fields private TcpClient m_commandChannel; private UdpClient m_dataChannel; private LocalConcentrator m_localConcentrator; private System.Timers.Timer m_dataStreamMonitor; private long m_commandChannelConnectionAttempts; private long m_dataChannelConnectionAttempts; private volatile SignalIndexCache m_remoteSignalIndexCache; private volatile SignalIndexCache m_signalIndexCache; private volatile long[] m_baseTimeOffsets; private volatile int m_timeIndex; private volatile byte[][][] m_keyIVs; private volatile int m_cipherIndex; private volatile bool m_authenticated; private volatile bool m_subscribed; private volatile int m_lastBytesReceived; private long m_monitoredBytesReceived; private long m_totalBytesReceived; private long m_lastMissingCacheWarning; private Guid m_nodeID; private int m_gatewayProtocolID; private List<ServerCommand> m_requests; private bool m_synchronizedSubscription; private bool m_requireAuthentication; private bool m_useMillisecondResolution; private bool m_autoConnect; private string m_sharedSecret; private string m_authenticationID; private bool m_includeTime; private bool m_synchronizeMetadata; private bool m_internal; private OperationalModes m_operationalModes; private Encoding m_encoding; private bool m_disposed; #endregion #region [ Constructors ] /// <summary> /// Creates a new <see cref="DataSubscriber"/>. /// </summary> public DataSubscriber() { m_requests = new List<ServerCommand>(); m_encoding = Encoding.Unicode; DataLossInterval = 10.0D; } #endregion #region [ Properties ] /// <summary> /// Gets or sets flag that determines if <see cref="DataPublisher"/> requires subscribers to authenticate before making data requests. /// </summary> public bool RequireAuthentication { get { return m_requireAuthentication; } set { m_requireAuthentication = value; } } /// <summary> /// Gets or sets flag that determines if <see cref="DataSubscriber"/> should attempt to autoconnection to <see cref="DataPublisher"/> using defined connection settings. /// </summary> public bool AutoConnect { get { return m_autoConnect; } set { m_autoConnect = value; } } /// <summary> /// Gets or sets flag that informs publisher if base time-offsets can use millisecond resolution to conserve bandwidth. /// </summary> [Obsolete("SubscriptionInfo object defines this parameter.", false)] public bool UseMillisecondResolution { get { return m_useMillisecondResolution; } set { m_useMillisecondResolution = value; } } /// <summary> /// Gets flag that determines if this <see cref="DataSubscriber"/> has successfully authenticated with the <see cref="DataPublisher"/>. /// </summary> public bool Authenticated { get { return m_authenticated; } } /// <summary> /// Gets total data packet bytes received during this session. /// </summary> public long TotalBytesReceived { get { return m_totalBytesReceived; } } /// <summary> /// Gets or sets data loss monitoring interval, in seconds. Set to zero to disable monitoring. /// </summary> public double DataLossInterval { get { if ((object)m_dataStreamMonitor != null) return m_dataStreamMonitor.Interval / 1000.0D; return 0.0D; } set { if (value > 0.0D) { if ((object)m_dataStreamMonitor == null) { // Create data stream monitoring timer m_dataStreamMonitor = new System.Timers.Timer(); m_dataStreamMonitor.Elapsed += m_dataStreamMonitor_Elapsed; m_dataStreamMonitor.AutoReset = true; m_dataStreamMonitor.Enabled = false; } // Set user specified interval m_dataStreamMonitor.Interval = value * 1000.0D; } else { // Disable data monitor if ((object)m_dataStreamMonitor != null) { m_dataStreamMonitor.Elapsed -= m_dataStreamMonitor_Elapsed; m_dataStreamMonitor.Dispose(); } m_dataStreamMonitor = null; } } } /// <summary> /// Gets or sets a set of flags that define ways in /// which the subscriber and publisher communicate. /// </summary> public OperationalModes OperationalModes { get { return m_operationalModes; } set { OperationalEncoding operationalEncoding; m_operationalModes = value; operationalEncoding = (OperationalEncoding)(value & OperationalModes.EncodingMask); m_encoding = GetCharacterEncoding(operationalEncoding); } } /// <summary> /// Gets or sets the <see cref="OperationalEncoding"/> used by the subscriber and publisher. /// </summary> public OperationalEncoding OperationalEncoding { get { return (OperationalEncoding)(m_operationalModes & OperationalModes.EncodingMask); } set { m_operationalModes &= ~OperationalModes.EncodingMask; m_operationalModes |= (OperationalModes)value; m_encoding = GetCharacterEncoding(value); } } /// <summary> /// Gets the flag indicating if this adapter supports temporal processing. /// </summary> /// <remarks> /// Although the data subscriber provisions support for temporal processing by receiving historical data from a remote source, /// the adapter opens sockets and does not need to be engaged within an actual temporal <see cref="IaonSession"/>, therefore /// this method returns <c>false</c> to make sure the adapter doesn't get instantiated within a temporal session. /// </remarks> public override bool SupportsTemporalProcessing { get { return false; } } /// <summary> /// Gets or sets the desired processing interval, in milliseconds, for the adapter. /// </summary> /// <remarks> /// With the exception of the values of -1 and 0, this value specifies the desired processing interval for data, i.e., /// basically a delay, or timer interval, overwhich to process data. A value of -1 means to use the default processing /// interval while a value of 0 means to process data as fast as possible. /// </remarks> public override int ProcessingInterval { get { return base.ProcessingInterval; } set { base.ProcessingInterval = value; // Request server update the processing interval SendServerCommand(ServerCommand.UpdateProcessingInterval, EndianOrder.BigEndian.GetBytes(value)); } } /// <summary> /// Gets the status of this <see cref="DataSubscriber"/>. /// </summary> /// <remarks> /// Derived classes should provide current status information about the adapter for display purposes. /// </remarks> public override string Status { get { StringBuilder status = new StringBuilder(); status.AppendFormat(" Subscription mode: {0}", m_synchronizedSubscription ? "Remotely Synchronized" : (object)m_localConcentrator == null ? "Unsynchronized" : "Locally Synchronized"); status.AppendLine(); status.AppendFormat(" Pending command requests: {0}", m_requests.Count); status.AppendLine(); status.AppendFormat(" Authenticated: {0}", m_authenticated); status.AppendLine(); status.AppendFormat(" Subscribed: {0}", m_subscribed); status.AppendLine(); status.AppendFormat(" Data packet security: {0}", m_keyIVs == null ? "unencrypted" : "encrypted"); status.AppendLine(); if (DataLossInterval > 0.0D) status.AppendFormat("No data reconnect interval: {0} seconds", DataLossInterval.ToString("0.000")); else status.Append("No data reconnect interval: disabled"); status.AppendLine(); if ((object)m_dataChannel != null) { status.AppendLine(); status.AppendLine("Data Channel Status".CenterText(50)); status.AppendLine("-------------------".CenterText(50)); status.Append(m_dataChannel.Status); } if ((object)m_commandChannel != null) { status.AppendLine(); status.AppendLine("Command Channel Status".CenterText(50)); status.AppendLine("----------------------".CenterText(50)); status.Append(m_commandChannel.Status); } if ((object)m_localConcentrator != null) { status.AppendLine(); status.AppendLine("Local Concentrator Status".CenterText(50)); status.AppendLine("-------------------------".CenterText(50)); status.Append(m_localConcentrator.Status); } status.Append(base.Status); return status.ToString(); } } /// <summary> /// Gets a flag that determines if this <see cref="DataSubscriber"/> uses an asynchronous connection. /// </summary> protected override bool UseAsyncConnect { get { return true; } } /// <summary> /// Gets or sets reference to <see cref="UdpClient"/> data channel, attaching and/or detaching to events as needed. /// </summary> protected UdpClient DataChannel { get { return m_dataChannel; } set { if (m_dataChannel != null) { // Detach from events on existing data channel reference m_dataChannel.ConnectionException -= m_dataChannel_ConnectionException; m_dataChannel.ConnectionAttempt -= m_dataChannel_ConnectionAttempt; m_dataChannel.ReceiveData -= m_dataChannel_ReceiveData; m_dataChannel.ReceiveDataException -= m_dataChannel_ReceiveDataException; if (m_dataChannel != value) m_dataChannel.Dispose(); } // Assign new data channel reference m_dataChannel = value; if (m_dataChannel != null) { // Attach to desired events on new data channel reference m_dataChannel.ConnectionException += m_dataChannel_ConnectionException; m_dataChannel.ConnectionAttempt += m_dataChannel_ConnectionAttempt; m_dataChannel.ReceiveData += m_dataChannel_ReceiveData; m_dataChannel.ReceiveDataException += m_dataChannel_ReceiveDataException; } } } /// <summary> /// Gets or sets reference to <see cref="TcpClient"/> command channel, attaching and/or detaching to events as needed. /// </summary> protected TcpClient CommandChannel { get { return m_commandChannel; } set { if (m_commandChannel != null) { // Detach from events on existing command channel reference m_commandChannel.ConnectionAttempt -= m_commandChannel_ConnectionAttempt; m_commandChannel.ConnectionEstablished -= m_commandChannel_ConnectionEstablished; m_commandChannel.ConnectionException -= m_commandChannel_ConnectionException; m_commandChannel.ConnectionTerminated -= m_commandChannel_ConnectionTerminated; m_commandChannel.ReceiveData -= m_commandChannel_ReceiveData; m_commandChannel.ReceiveDataException -= m_commandChannel_ReceiveDataException; m_commandChannel.SendDataException -= m_commandChannel_SendDataException; if (m_commandChannel != value) m_commandChannel.Dispose(); } // Assign new command channel reference m_commandChannel = value; if (m_commandChannel != null) { // Attach to desired events on new command channel reference m_commandChannel.ConnectionAttempt += m_commandChannel_ConnectionAttempt; m_commandChannel.ConnectionEstablished += m_commandChannel_ConnectionEstablished; m_commandChannel.ConnectionException += m_commandChannel_ConnectionException; m_commandChannel.ConnectionTerminated += m_commandChannel_ConnectionTerminated; m_commandChannel.ReceiveData += m_commandChannel_ReceiveData; m_commandChannel.ReceiveDataException += m_commandChannel_ReceiveDataException; m_commandChannel.SendDataException += m_commandChannel_SendDataException; } } } #endregion #region [ Methods ] /// <summary> /// Releases the unmanaged resources used by the <see cref="DataSubscriber"/> object and optionally releases the managed resources. /// </summary> /// <param name="disposing">true to release both managed and unmanaged resources; false to release only unmanaged resources.</param> protected override void Dispose(bool disposing) { if (!m_disposed) { try { if (disposing) { DataLossInterval = 0.0D; CommandChannel = null; DataChannel = null; DisposeLocalConcentrator(); } } finally { m_disposed = true; // Prevent duplicate dispose. base.Dispose(disposing); // Call base class Dispose(). } } } /// <summary> /// Initializes <see cref="DataSubscriber"/>. /// </summary> public override void Initialize() { base.Initialize(); Dictionary<string, string> settings = Settings; string setting; double interval; // Setup connection to data publishing server with or without authentication required if (settings.TryGetValue("requireAuthentication", out setting)) m_requireAuthentication = setting.ParseBoolean(); else m_requireAuthentication = false; if (m_requireAuthentication) { if (!settings.TryGetValue("sharedSecret", out m_sharedSecret) && !m_sharedSecret.IsNullOrWhiteSpace()) throw new ArgumentException("The \"sharedSecret\" setting must defined when authentication is required."); if (!settings.TryGetValue("authenticationID", out m_authenticationID) && !m_authenticationID.IsNullOrWhiteSpace()) throw new ArgumentException("The \"authenticationID\" setting must defined when authentication is required."); } // Check if synchronize metadata is disabled. if (settings.TryGetValue("synchronizeMetadata", out setting)) m_synchronizeMetadata = setting.ParseBoolean(); else m_synchronizeMetadata = true; // by default, we will always perform this. // Check if measurements for this connection should be marked as "internal" - i.e., owned and allowed for proxy if (settings.TryGetValue("internal", out setting)) m_internal = setting.ParseBoolean(); // Check if we should be using the alternate binary format for communications with the publisher if (settings.TryGetValue("operationalModes", out setting)) m_operationalModes = (OperationalModes)uint.Parse(setting); // Check if user wants to request that publisher use millisecond resolution to conserve bandwidth if (settings.TryGetValue("useMillisecondResolution", out setting)) m_useMillisecondResolution = setting.ParseBoolean(); // Define auto connect setting if (settings.TryGetValue("autoConnect", out setting)) m_autoConnect = setting.ParseBoolean(); // Define data loss interval if (settings.TryGetValue("dataLossInterval", out setting) && double.TryParse(setting, out interval)) DataLossInterval = interval; if (m_autoConnect) { // Connect to local events when automatically engaging connection cycle ConnectionAuthenticated += DataSubscriber_ConnectionAuthenticated; MetaDataReceived += DataSubscriber_MetaDataReceived; // If active measurements are defined, attempt to defined desired subscription points from there if (DataSource != null && (object)DataSource.Tables != null && DataSource.Tables.Contains("ActiveMeasurements")) { try { // Filter to points associated with this subscriber that have been requested for subscription, are enabled and not owned locally DataRow[] filteredRows = DataSource.Tables["ActiveMeasurements"].Select("Subscribed <> 0"); List<IMeasurement> subscribedMeasurements = new List<IMeasurement>(); MeasurementKey key; Guid signalID; foreach (DataRow row in filteredRows) { // Create a new measurement for the provided field level information Measurement measurement = new Measurement(); // Parse primary measurement identifier signalID = row["SignalID"].ToNonNullString(Guid.Empty.ToString()).ConvertToType<Guid>(); // Set measurement key if defined if (MeasurementKey.TryParse(row["ID"].ToString(), signalID, out key)) measurement.Key = key; // Assign other attributes measurement.ID = signalID; measurement.TagName = row["PointTag"].ToNonNullString(); measurement.Multiplier = double.Parse(row["Multiplier"].ToString()); measurement.Adder = double.Parse(row["Adder"].ToString()); subscribedMeasurements.Add(measurement); } if (subscribedMeasurements.Count > 0) { // Combine subscribed output measurement with any existing output measurement and return unique set if (OutputMeasurements == null) OutputMeasurements = subscribedMeasurements.ToArray(); else OutputMeasurements = subscribedMeasurements.Concat(OutputMeasurements).Distinct().ToArray(); } } catch (Exception ex) { // Errors here may not be catastrophic, this simply limits the auto-assignment of input measurement keys desired for subscription OnProcessException(new InvalidOperationException(string.Format("Failed to define subscribed measurements: {0}", ex.Message), ex)); } } } // Create a new TCP client TcpClient commandChannel = new TcpClient(); // Initialize default settings commandChannel.ConnectionString = "server=localhost:6165"; commandChannel.PayloadAware = true; commandChannel.PersistSettings = false; commandChannel.MaxConnectionAttempts = 1; // Assign command channel client reference and attach to needed events this.CommandChannel = commandChannel; // Get proper connection string - either from specified command channel // or from base connection string if (settings.TryGetValue("commandChannel", out setting)) commandChannel.ConnectionString = setting; else commandChannel.ConnectionString = ConnectionString; // Register subscriber with the statistics engine //StatisticsEngine.Register(this, "Subscriber", "SUB"); Initialized = true; } /// <summary> /// Authenticates subcriber to a data publisher. /// </summary> /// <param name="sharedSecret">Shared secret used to look up private crypto key and initialization vector.</param> /// <param name="authenticationID">Authentication ID that publisher will use to validate subscriber identity.</param> /// <returns><c>true</c> if authentication transmission was successful; otherwise <c>false</c>.</returns> public virtual bool Authenticate(string sharedSecret, string authenticationID) { return false; // if (!authenticationID.IsNullOrWhiteSpace()) // { // try // { // MemoryStream buffer = new MemoryStream(); // byte[] salt = new byte[DataPublisher.CipherSaltLength]; // byte[] bytes; // // // Generate some random prefix data to make sure auth key transmission is always unique // GSF.Security.Cryptography.Random.GetBytes(salt); // // // Get encoded bytes of authentication key // bytes = salt.Combine(m_encoding.GetBytes(authenticationID)); // // // Encrypt authentication key // bytes = bytes.Encrypt(sharedSecret, CipherStrength.Aes256); // // // Write encoded authentication key length into buffer // buffer.Write(EndianOrder.BigEndian.GetBytes(bytes.Length), 0, 4); // // // Encode encrypted authentication key into buffer // buffer.Write(bytes, 0, bytes.Length); // // // Send authentication command to server with associated command buffer // return SendServerCommand(ServerCommand.Authenticate, buffer.ToArray()); // } // catch (Exception ex) // { // OnProcessException(new InvalidOperationException("Exception occurred while trying to authenticate publisher subscription: " + ex.Message, ex)); // } // } // else // OnProcessException(new InvalidOperationException("Cannot authenticate subscription without a connection string.")); // // return false; } /// <summary> /// Subscribes (or re-subscribes) to a data publisher for a set of data points. /// </summary> /// <param name="info">Configuration object that defines the subscription.</param> /// <returns><c>true</c> if subscribe transmission was successful; otherwise <c>false</c>.</returns> public bool Subscribe(SubscriptionInfo info) { if (info is SynchronizedSubscriptionInfo) return SynchronizedSubscribe((SynchronizedSubscriptionInfo)info); if (info is UnsynchronizedSubscriptionInfo) return UnsynchronizedSubscribe((UnsynchronizedSubscriptionInfo)info); throw new NotSupportedException("Type of subscription used is not supported"); } /// <summary> /// Subscribes (or re-subscribes) to a data publisher for a synchronized set of data points. /// </summary> /// <param name="info">Configuration object that defines the subscription.</param> /// <returns><c>true</c> if subscribe transmission was successful; otherwise <c>false</c>.</returns> public bool SynchronizedSubscribe(SynchronizedSubscriptionInfo info) { StringBuilder connectionString = new StringBuilder(); AssemblyInfo assemblyInfo = AssemblyInfo.ExecutingAssembly; // Dispose of any previously established local concentrator DisposeLocalConcentrator(); if (info.RemotelySynchronized) { connectionString.AppendFormat("framesPerSecond={0};", info.FramesPerSecond); connectionString.AppendFormat("lagTime={0};", info.LagTime); connectionString.AppendFormat("leadTime={0};", info.LeadTime); connectionString.AppendFormat("includeTime=false;"); connectionString.AppendFormat("useLocalClockAsRealTime={0};", info.UseLocalClockAsRealTime); connectionString.AppendFormat("ignoreBadTimestamps={0};", info.IgnoreBadTimestamps); connectionString.AppendFormat("allowSortsByArrival={0};", info.AllowSortsByArrival); connectionString.AppendFormat("timeResolution={0};", info.TimeResolution); connectionString.AppendFormat("allowPreemptivePublishing={0};", info.AllowPreemptivePublishing); connectionString.AppendFormat("downsamplingMethod={0};", info.DownsamplingMethod.ToString()); connectionString.AppendFormat("processingInterval={0};", info.ProcessingInterval); connectionString.AppendFormat("assemblyInfo={{source={0};version={1}.{2}.{3};buildDate={4}}};", assemblyInfo.Name, assemblyInfo.Version.Major, assemblyInfo.Version.Minor, assemblyInfo.Version.Build, assemblyInfo.BuildDate.ToString("yyyy-MM-dd HH:mm:ss")); if (!info.FilterExpression.IsNullOrWhiteSpace()) connectionString.AppendFormat("inputMeasurementKeys={{{0}}};", info.FilterExpression); if (info.UdpDataChannel) connectionString.AppendFormat("dataChannel={{localport={0}}};", info.DataChannelLocalPort); if (!info.StartTime.IsNullOrWhiteSpace()) connectionString.AppendFormat("startTimeConstraint={0};", info.StartTime); if (!info.StopTime.IsNullOrWhiteSpace()) connectionString.AppendFormat("stopTimeConstraint={0};", info.StopTime); if (!info.ConstraintParameters.IsNullOrWhiteSpace()) connectionString.AppendFormat("timeConstraintParameters={0};", info.ConstraintParameters); if (!info.WaitHandleNames.IsNullOrWhiteSpace()) { connectionString.AppendFormat("waitHandleNames={0};", info.WaitHandleNames); connectionString.AppendFormat("waitHandleTimeout={0};", info.WaitHandleTimeout); } if (!info.ExtraConnectionStringParameters.IsNullOrWhiteSpace()) connectionString.AppendFormat("{0};", info.ExtraConnectionStringParameters); return Subscribe(true, info.UseCompactMeasurementFormat, connectionString.ToString()); } else { // Locally concentrated subscription simply uses an unsynchronized subscription and concentrates the // measurements on the subscriber side if (Subscribe(FromLocallySynchronizedInfo(info))) { // Establish a local concentrator to synchronize received measurements LocalConcentrator localConcentrator = new LocalConcentrator(this); localConcentrator.ProcessException += m_localConcentrator_ProcessException; localConcentrator.FramesPerSecond = info.FramesPerSecond; localConcentrator.LagTime = info.LagTime; localConcentrator.LeadTime = info.LeadTime; localConcentrator.UseLocalClockAsRealTime = info.UseLocalClockAsRealTime; localConcentrator.IgnoreBadTimestamps = info.IgnoreBadTimestamps; localConcentrator.AllowSortsByArrival = info.AllowSortsByArrival; localConcentrator.TimeResolution = info.TimeResolution; localConcentrator.AllowPreemptivePublishing = info.AllowPreemptivePublishing; localConcentrator.DownsamplingMethod = info.DownsamplingMethod; localConcentrator.UsePrecisionTimer = false; // Parse time constraints, if defined DateTime startTimeConstraint = !info.StartTime.IsNullOrWhiteSpace() ? AdapterBase.ParseTimeTag(info.StartTime) : DateTime.MinValue; DateTime stopTimeConstraint = !info.StopTime.IsNullOrWhiteSpace() ? AdapterBase.ParseTimeTag(info.StopTime) : DateTime.MaxValue; // When processing historical data, timestamps should not be evaluated for reasonability if (startTimeConstraint != DateTime.MinValue || stopTimeConstraint != DateTime.MaxValue) { localConcentrator.PerformTimestampReasonabilityCheck = false; localConcentrator.LeadTime = double.MaxValue; } // Assign alternate processing interval, if defined if (info.ProcessingInterval != -1) localConcentrator.ProcessingInterval = info.ProcessingInterval; // Start local concentrator localConcentrator.Start(); // Move concentrator to member variable Interlocked.Exchange(ref m_localConcentrator, localConcentrator); return true; } return false; } } /// <summary> /// Subscribes (or re-subscribes) to a data publisher for an unsynchronized set of data points. /// </summary> /// <param name="info">Configuration object that defines the subscription.</param> /// <returns><c>true</c> if subscribe transmission was successful; otherwise <c>false</c>.</returns> public bool UnsynchronizedSubscribe(UnsynchronizedSubscriptionInfo info) { // Dispose of any previously established local concentrator DisposeLocalConcentrator(); StringBuilder connectionString = new StringBuilder(); AssemblyInfo assemblyInfo = AssemblyInfo.ExecutingAssembly; connectionString.AppendFormat("trackLatestMeasurements={0};", info.Throttled); connectionString.AppendFormat("publishInterval={0};", info.PublishInterval); connectionString.AppendFormat("includeTime={0};", info.IncludeTime); connectionString.AppendFormat("lagTime={0};", info.LagTime); connectionString.AppendFormat("leadTime={0};", info.LeadTime); connectionString.AppendFormat("useLocalClockAsRealTime={0};", info.UseLocalClockAsRealTime); connectionString.AppendFormat("processingInterval={0};", info.ProcessingInterval); connectionString.AppendFormat("useMillisecondResolution={0};", info.UseMillisecondResolution); connectionString.AppendFormat("assemblyInfo={{source={0};version={1}.{2}.{3};buildDate={4}}};", assemblyInfo.Name, assemblyInfo.Version.Major, assemblyInfo.Version.Minor, assemblyInfo.Version.Build, assemblyInfo.BuildDate.ToString("yyyy-MM-dd HH:mm:ss")); if (!info.FilterExpression.IsNullOrWhiteSpace()) connectionString.AppendFormat("inputMeasurementKeys={{{0}}};", info.FilterExpression); if (info.UdpDataChannel) connectionString.AppendFormat("dataChannel={{localport={0}}};", info.DataChannelLocalPort); if (!info.StartTime.IsNullOrWhiteSpace()) connectionString.AppendFormat("startTimeConstraint={0};", info.StartTime); if (!info.StopTime.IsNullOrWhiteSpace()) connectionString.AppendFormat("stopTimeConstraint={0};", info.StopTime); if (!info.ConstraintParameters.IsNullOrWhiteSpace()) connectionString.AppendFormat("timeConstraintParameters={0};", info.ConstraintParameters); if (!info.WaitHandleNames.IsNullOrWhiteSpace()) { connectionString.AppendFormat("waitHandleNames={0};", info.WaitHandleNames); connectionString.AppendFormat("waitHandleTimeout={0};", info.WaitHandleTimeout); } if (!info.ExtraConnectionStringParameters.IsNullOrWhiteSpace()) connectionString.AppendFormat("{0};", info.ExtraConnectionStringParameters); // Make sure not to monitor for data loss any faster than downsample time on throttled connections - additionally // you will want to make sure data stream monitor is twice lagtime to allow time for initial points to arrive. if (info.Throttled && (object)m_dataStreamMonitor != null && m_dataStreamMonitor.Interval / 1000.0D < info.LagTime) m_dataStreamMonitor.Interval = 2.0D * info.LagTime * 1000.0D; // Set millisecond resolution member variable for compact measurement parsing m_useMillisecondResolution = info.UseMillisecondResolution; return Subscribe(false, info.UseCompactMeasurementFormat, connectionString.ToString()); } public bool RemotelySynchronizedSubscribe(bool compactFormat, int framesPerSecond, double lagTime, double leadTime, string filterExpression) { return RemotelySynchronizedSubscribe(compactFormat, framesPerSecond, lagTime, leadTime, filterExpression, null, false, false, true, Ticks.PerMillisecond, true, DownsamplingMethod.LastReceived, null, null, null, -1, null, 0); } /// <summary> /// Subscribes (or re-subscribes) to a data publisher for a remotely synchronized set of data points. /// </summary> /// <param name="compactFormat">Boolean value that determines if the compact measurement format should be used. Set to <c>false</c> for full fidelity measurement serialization; otherwise set to <c>true</c> for bandwidth conservation.</param> /// <param name="framesPerSecond">The desired number of data frames per second.</param> /// <param name="lagTime">Allowed past time deviation tolerance, in seconds (can be subsecond).</param> /// <param name="leadTime">Allowed future time deviation tolerance, in seconds (can be subsecond).</param> /// <param name="filterExpression">Filtering expression that defines the measurements that are being subscribed.</param> /// <param name="dataChannel">Desired UDP return data channel connection string to use for data packet transmission. Set to <c>null</c> to use TCP channel for data transmission.</param> /// <param name="useLocalClockAsRealTime">Boolean value that determines whether or not to use the local clock time as real-time.</param> /// <param name="ignoreBadTimestamps">Boolean value that determines if bad timestamps (as determined by measurement's timestamp quality) should be ignored when sorting measurements.</param> /// <param name="allowSortsByArrival"> Gets or sets flag that determines whether or not to allow incoming measurements with bad timestamps to be sorted by arrival time.</param> /// <param name="timeResolution">Gets or sets the maximum time resolution, in ticks, to use when sorting measurements by timestamps into their proper destination frame.</param> /// <param name="allowPreemptivePublishing">Gets or sets flag that allows system to preemptively publish frames assuming all expected measurements have arrived.</param> /// <param name="downsamplingMethod">Gets the total number of downsampled measurements processed by the concentrator.</param> /// <param name="startTime">Defines a relative or exact start time for the temporal constraint to use for historical playback.</param> /// <param name="stopTime">Defines a relative or exact stop time for the temporal constraint to use for historical playback.</param> /// <param name="constraintParameters">Defines any temporal parameters related to the constraint to use for historical playback.</param> /// <param name="processingInterval">Defines the desired processing interval milliseconds, i.e., historical play back speed, to use when temporal constraints are defined.</param> /// <param name="waitHandleNames">Comma separated list of wait handle names used to establish external event wait handles needed for inter-adapter synchronization.</param> /// <param name="waitHandleTimeout">Maximum wait time for external events, in milliseconds, before proceeding.</param> /// <returns><c>true</c> if subscribe transmission was successful; otherwise <c>false</c>.</returns> /// <remarks> /// <para> /// When the <paramref name="startTime"/> or <paramref name="stopTime"/> temporal processing contraints are defined (i.e., not <c>null</c>), this /// specifies the start and stop time over which the subscriber session will process data. Passing in <c>null</c> for the <paramref name="startTime"/> /// and <paramref name="stopTime"/> specifies the the subscriber session will process data in standard, i.e., real-time, operation. /// </para> /// <para> /// With the exception of the values of -1 and 0, the <paramref name="processingInterval"/> value specifies the desired historical playback data /// processing interval in milliseconds. This is basically a delay, or timer interval, overwhich to process data. Setting this value to -1 means /// to use the default processing interval while setting the value to 0 means to process data as fast as possible. /// </para> /// <para> /// The <paramref name="startTime"/> and <paramref name="stopTime"/> parameters can be specified in one of the /// following formats: /// <list type="table"> /// <listheader> /// <term>Time Format</term> /// <description>Format Description</description> /// </listheader> /// <item> /// <term>12-30-2000 23:59:59.033</term> /// <description>Absolute date and time.</description> /// </item> /// <item> /// <term>*</term> /// <description>Evaluates to <see cref="DateTime.UtcNow"/>.</description> /// </item> /// <item> /// <term>*-20s</term> /// <description>Evaluates to 20 seconds before <see cref="DateTime.UtcNow"/>.</description> /// </item> /// <item> /// <term>*-10m</term> /// <description>Evaluates to 10 minutes before <see cref="DateTime.UtcNow"/>.</description> /// </item> /// <item> /// <term>*-1h</term> /// <description>Evaluates to 1 hour before <see cref="DateTime.UtcNow"/>.</description> /// </item> /// <item> /// <term>*-1d</term> /// <description>Evaluates to 1 day before <see cref="DateTime.UtcNow"/>.</description> /// </item> /// </list> /// </para> /// </remarks> [Obsolete("Preferred method uses SubscriptionInfo object to subscribe.", false)] public virtual bool RemotelySynchronizedSubscribe(bool compactFormat, int framesPerSecond, double lagTime, double leadTime, string filterExpression, string dataChannel, bool useLocalClockAsRealTime, bool ignoreBadTimestamps, bool allowSortsByArrival, long timeResolution, bool allowPreemptivePublishing, DownsamplingMethod downsamplingMethod, string startTime, string stopTime, string constraintParameters, int processingInterval, string waitHandleNames, int waitHandleTimeout) { // Dispose of any previously established local concentrator DisposeLocalConcentrator(); StringBuilder connectionString = new StringBuilder(); AssemblyInfo assemblyInfo = AssemblyInfo.ExecutingAssembly; connectionString.AppendFormat("framesPerSecond={0}; ", framesPerSecond); connectionString.AppendFormat("lagTime={0}; ", lagTime); connectionString.AppendFormat("leadTime={0}; ", leadTime); connectionString.AppendFormat("inputMeasurementKeys={{{0}}}; ", filterExpression.ToNonNullString()); connectionString.AppendFormat("dataChannel={{{0}}}; ", dataChannel.ToNonNullString()); connectionString.AppendFormat("includeTime=false; "); connectionString.AppendFormat("useLocalClockAsRealTime={0}; ", useLocalClockAsRealTime); connectionString.AppendFormat("ignoreBadTimestamps={0}; ", ignoreBadTimestamps); connectionString.AppendFormat("allowSortsByArrival={0}; ", allowSortsByArrival); connectionString.AppendFormat("timeResolution={0}; ", (long)timeResolution); connectionString.AppendFormat("allowPreemptivePublishing={0}; ", allowPreemptivePublishing); connectionString.AppendFormat("downsamplingMethod={0}; ", downsamplingMethod.ToString()); connectionString.AppendFormat("startTimeConstraint={0}; ", startTime.ToNonNullString()); connectionString.AppendFormat("stopTimeConstraint={0}; ", stopTime.ToNonNullString()); connectionString.AppendFormat("timeConstraintParameters={0}; ", constraintParameters.ToNonNullString()); connectionString.AppendFormat("processingInterval={0}; ", processingInterval); connectionString.AppendFormat("assemblyInfo={{source={0}; version={1}.{2}.{3}; buildDate={4}}}", assemblyInfo.Name, assemblyInfo.Version.Major, assemblyInfo.Version.Minor, assemblyInfo.Version.Build, assemblyInfo.BuildDate.ToString("yyyy-MM-dd HH:mm:ss")); if (!waitHandleNames.IsNullOrWhiteSpace()) { connectionString.AppendFormat("; waitHandleNames={0}", waitHandleNames); connectionString.AppendFormat("; waitHandleTimeout={0}", waitHandleTimeout); } return Subscribe(true, compactFormat, connectionString.ToString()); } public bool LocallySynchronizedSubscribe(bool compactFormat, int framesPerSecond, double lagTime, double leadTime, string filterExpression) { return LocallySynchronizedSubscribe(compactFormat, framesPerSecond, lagTime, leadTime, filterExpression, null, false, false, true, Ticks.PerMillisecond, true, DownsamplingMethod.LastReceived, null, null, null, -1, null, 0); } /// <summary> /// Subscribes (or re-subscribes) to a data publisher for a locally synchronized set of data points. /// </summary> /// <param name="compactFormat">Boolean value that determines if the compact measurement format should be used. Set to <c>false</c> for full fidelity measurement serialization; otherwise set to <c>true</c> for bandwidth conservation.</param> /// <param name="framesPerSecond">The desired number of data frames per second.</param> /// <param name="lagTime">Allowed past time deviation tolerance, in seconds (can be subsecond).</param> /// <param name="leadTime">Allowed future time deviation tolerance, in seconds (can be subsecond).</param> /// <param name="filterExpression">Filtering expression that defines the measurements that are being subscribed.</param> /// <param name="dataChannel">Desired UDP return data channel connection string to use for data packet transmission. Set to <c>null</c> to use TCP channel for data transmission.</param> /// <param name="useLocalClockAsRealTime">Boolean value that determines whether or not to use the local clock time as real-time.</param> /// <param name="ignoreBadTimestamps">Boolean value that determines if bad timestamps (as determined by measurement's timestamp quality) should be ignored when sorting measurements.</param> /// <param name="allowSortsByArrival"> Gets or sets flag that determines whether or not to allow incoming measurements with bad timestamps to be sorted by arrival time.</param> /// <param name="timeResolution">Gets or sets the maximum time resolution, in ticks, to use when sorting measurements by timestamps into their proper destination frame.</param> /// <param name="allowPreemptivePublishing">Gets or sets flag that allows system to preemptively publish frames assuming all expected measurements have arrived.</param> /// <param name="downsamplingMethod">Gets the total number of downsampled measurements processed by the concentrator.</param> /// <param name="startTime">Defines a relative or exact start time for the temporal constraint to use for historical playback.</param> /// <param name="stopTime">Defines a relative or exact stop time for the temporal constraint to use for historical playback.</param> /// <param name="constraintParameters">Defines any temporal parameters related to the constraint to use for historical playback.</param> /// <param name="processingInterval">Defines the desired processing interval milliseconds, i.e., historical play back speed, to use when temporal constraints are defined.</param> /// <param name="waitHandleNames">Comma separated list of wait handle names used to establish external event wait handles needed for inter-adapter synchronization.</param> /// <param name="waitHandleTimeout">Maximum wait time for external events, in milliseconds, before proceeding.</param> /// <returns><c>true</c> if subscribe transmission was successful; otherwise <c>false</c>.</returns> /// <remarks> /// <para> /// When the <paramref name="startTime"/> or <paramref name="stopTime"/> temporal processing contraints are defined (i.e., not <c>null</c>), this /// specifies the start and stop time over which the subscriber session will process data. Passing in <c>null</c> for the <paramref name="startTime"/> /// and <paramref name="stopTime"/> specifies the the subscriber session will process data in standard, i.e., real-time, operation. /// </para> /// <para> /// With the exception of the values of -1 and 0, the <paramref name="processingInterval"/> value specifies the desired historical playback data /// processing interval in milliseconds. This is basically a delay, or timer interval, overwhich to process data. Setting this value to -1 means /// to use the default processing interval while setting the value to 0 means to process data as fast as possible. /// </para> /// <para> /// The <paramref name="startTime"/> and <paramref name="stopTime"/> parameters can be specified in one of the /// following formats: /// <list type="table"> /// <listheader> /// <term>Time Format</term> /// <description>Format Description</description> /// </listheader> /// <item> /// <term>12-30-2000 23:59:59.033</term> /// <description>Absolute date and time.</description> /// </item> /// <item> /// <term>*</term> /// <description>Evaluates to <see cref="DateTime.UtcNow"/>.</description> /// </item> /// <item> /// <term>*-20s</term> /// <description>Evaluates to 20 seconds before <see cref="DateTime.UtcNow"/>.</description> /// </item> /// <item> /// <term>*-10m</term> /// <description>Evaluates to 10 minutes before <see cref="DateTime.UtcNow"/>.</description> /// </item> /// <item> /// <term>*-1h</term> /// <description>Evaluates to 1 hour before <see cref="DateTime.UtcNow"/>.</description> /// </item> /// <item> /// <term>*-1d</term> /// <description>Evaluates to 1 day before <see cref="DateTime.UtcNow"/>.</description> /// </item> /// </list> /// </para> /// </remarks> [Obsolete("Preferred method uses SubscriptionInfo object to subscribe.", false)] public virtual bool LocallySynchronizedSubscribe(bool compactFormat, int framesPerSecond, double lagTime, double leadTime, string filterExpression, string dataChannel, bool useLocalClockAsRealTime, bool ignoreBadTimestamps, bool allowSortsByArrival, long timeResolution, bool allowPreemptivePublishing, DownsamplingMethod downsamplingMethod, string startTime, string stopTime, string constraintParameters, int processingInterval, string waitHandleNames, int waitHandleTimeout) { // Dispose of any previously established local concentrator DisposeLocalConcentrator(); // Establish a local concentrator to synchronize received measurements m_localConcentrator = new LocalConcentrator(this); m_localConcentrator.ProcessException += m_localConcentrator_ProcessException; m_localConcentrator.FramesPerSecond = framesPerSecond; m_localConcentrator.LagTime = lagTime; m_localConcentrator.LeadTime = leadTime; m_localConcentrator.UseLocalClockAsRealTime = useLocalClockAsRealTime; m_localConcentrator.IgnoreBadTimestamps = ignoreBadTimestamps; m_localConcentrator.AllowSortsByArrival = allowSortsByArrival; m_localConcentrator.TimeResolution = timeResolution; m_localConcentrator.AllowPreemptivePublishing = allowPreemptivePublishing; m_localConcentrator.DownsamplingMethod = downsamplingMethod; m_localConcentrator.UsePrecisionTimer = false; // Parse time constraints, if defined DateTime startTimeConstraint = !startTime.IsNullOrWhiteSpace() ? AdapterBase.ParseTimeTag(startTime) : DateTime.MinValue; DateTime stopTimeConstraint = !stopTime.IsNullOrWhiteSpace() ? AdapterBase.ParseTimeTag(stopTime) : DateTime.MaxValue; // When processing historical data, timestamps should not be evaluated for reasonability if (startTimeConstraint != DateTime.MinValue || stopTimeConstraint != DateTime.MaxValue) { m_localConcentrator.PerformTimestampReasonabilityCheck = false; m_localConcentrator.LeadTime = double.MaxValue; } // Assign alternate processing interval, if defined if (processingInterval != -1) m_localConcentrator.ProcessingInterval = processingInterval; // Initiate unsynchronized subscribe StringBuilder connectionString = new StringBuilder(); AssemblyInfo assemblyInfo = AssemblyInfo.ExecutingAssembly; connectionString.AppendFormat("trackLatestMeasurements={0}; ", false); connectionString.AppendFormat("inputMeasurementKeys={{{0}}}; ", filterExpression.ToNonNullString()); connectionString.AppendFormat("dataChannel={{{0}}}; ", dataChannel.ToNonNullString()); connectionString.AppendFormat("includeTime={0}; ", true); connectionString.AppendFormat("lagTime={0}; ", 10.0D); connectionString.AppendFormat("leadTime={0}; ", 5.0D); connectionString.AppendFormat("useLocalClockAsRealTime={0}; ", false); connectionString.AppendFormat("startTimeConstraint={0}; ", startTime.ToNonNullString()); connectionString.AppendFormat("stopTimeConstraint={0}; ", stopTime.ToNonNullString()); connectionString.AppendFormat("timeConstraintParameters={0}; ", constraintParameters.ToNonNullString()); connectionString.AppendFormat("processingInterval={0}; ", processingInterval); connectionString.AppendFormat("useMillisecondResolution={0}; ", m_useMillisecondResolution); connectionString.AppendFormat("assemblyInfo={{source={0}; version={1}.{2}.{3}; buildDate={4}}}", assemblyInfo.Name, assemblyInfo.Version.Major, assemblyInfo.Version.Minor, assemblyInfo.Version.Build, assemblyInfo.BuildDate.ToString("yyyy-MM-dd HH:mm:ss")); if (!waitHandleNames.IsNullOrWhiteSpace()) { connectionString.AppendFormat("; waitHandleNames={0}", waitHandleNames); connectionString.AppendFormat("; waitHandleTimeout={0}", waitHandleTimeout); } // Start subscription process if (Subscribe(false, compactFormat, connectionString.ToString())) { // If subscription succeeds, start local concentrator m_localConcentrator.Start(); return true; } return false; } public bool UnsynchronizedSubscribe(bool compactFormat, bool throttled, string filterExpression) { return UnsynchronizedSubscribe(compactFormat, throttled, filterExpression, null, true, 10.0D, 5.0D, false, null, null, null, -1, null, 0); } /// <summary> /// Subscribes (or re-subscribes) to a data publisher for an unsynchronized set of data points. /// </summary> /// <param name="compactFormat">Boolean value that determines if the compact measurement format should be used. Set to <c>false</c> for full fidelity measurement serialization; otherwise set to <c>true</c> for bandwidth conservation.</param> /// <param name="throttled">Boolean value that determines if data should be throttled at a set transmission interval or sent on change.</param> /// <param name="filterExpression">Filtering expression that defines the measurements that are being subscribed.</param> /// <param name="dataChannel">Desired UDP return data channel connection string to use for data packet transmission. Set to <c>null</c> to use TCP channel for data transmission.</param> /// <param name="includeTime">Boolean value that determines if time is a necessary component in streaming data.</param> /// <param name="lagTime">When <paramref name="throttled"/> is <c>true</c>, defines the data transmission speed in seconds (can be subsecond).</param> /// <param name="leadTime">When <paramref name="throttled"/> is <c>true</c>, defines the allowed time deviation tolerance to real-time in seconds (can be subsecond).</param> /// <param name="useLocalClockAsRealTime">When <paramref name="throttled"/> is <c>true</c>, defines boolean value that determines whether or not to use the local clock time as real-time. Set to <c>false</c> to use latest received measurement timestamp as real-time.</param> /// <param name="startTime">Defines a relative or exact start time for the temporal constraint to use for historical playback.</param> /// <param name="stopTime">Defines a relative or exact stop time for the temporal constraint to use for historical playback.</param> /// <param name="constraintParameters">Defines any temporal parameters related to the constraint to use for historical playback.</param> /// <param name="processingInterval">Defines the desired processing interval milliseconds, i.e., historical play back speed, to use when temporal constraints are defined.</param> /// <param name="waitHandleNames">Comma separated list of wait handle names used to establish external event wait handles needed for inter-adapter synchronization.</param> /// <param name="waitHandleTimeout">Maximum wait time for external events, in milliseconds, before proceeding.</param> /// <returns><c>true</c> if subscribe transmission was successful; otherwise <c>false</c>.</returns> /// <remarks> /// <para> /// When the <paramref name="startTime"/> or <paramref name="stopTime"/> temporal processing contraints are defined (i.e., not <c>null</c>), this /// specifies the start and stop time over which the subscriber session will process data. Passing in <c>null</c> for the <paramref name="startTime"/> /// and <paramref name="stopTime"/> specifies the the subscriber session will process data in standard, i.e., real-time, operation. /// </para> /// <para> /// With the exception of the values of -1 and 0, the <paramref name="processingInterval"/> value specifies the desired historical playback data /// processing interval in milliseconds. This is basically a delay, or timer interval, overwhich to process data. Setting this value to -1 means /// to use the default processing interval while setting the value to 0 means to process data as fast as possible. /// </para> /// <para> /// The <paramref name="startTime"/> and <paramref name="stopTime"/> parameters can be specified in one of the /// following formats: /// <list type="table"> /// <listheader> /// <term>Time Format</term> /// <description>Format Description</description> /// </listheader> /// <item> /// <term>12-30-2000 23:59:59.033</term> /// <description>Absolute date and time.</description> /// </item> /// <item> /// <term>*</term> /// <description>Evaluates to <see cref="DateTime.UtcNow"/>.</description> /// </item> /// <item> /// <term>*-20s</term> /// <description>Evaluates to 20 seconds before <see cref="DateTime.UtcNow"/>.</description> /// </item> /// <item> /// <term>*-10m</term> /// <description>Evaluates to 10 minutes before <see cref="DateTime.UtcNow"/>.</description> /// </item> /// <item> /// <term>*-1h</term> /// <description>Evaluates to 1 hour before <see cref="DateTime.UtcNow"/>.</description> /// </item> /// <item> /// <term>*-1d</term> /// <description>Evaluates to 1 day before <see cref="DateTime.UtcNow"/>.</description> /// </item> /// </list> /// </para> /// </remarks> [Obsolete("Preferred method uses SubscriptionInfo object to subscribe.", false)] public virtual bool UnsynchronizedSubscribe(bool compactFormat, bool throttled, string filterExpression, string dataChannel, bool includeTime, double lagTime, double leadTime, bool useLocalClockAsRealTime, string startTime, string stopTime, string constraintParameters, int processingInterval, string waitHandleNames, int waitHandleTimeout) { // Dispose of any previously established local concentrator DisposeLocalConcentrator(); StringBuilder connectionString = new StringBuilder(); AssemblyInfo assemblyInfo = AssemblyInfo.ExecutingAssembly; connectionString.AppendFormat("trackLatestMeasurements={0}; ", throttled); connectionString.AppendFormat("inputMeasurementKeys={{{0}}}; ", filterExpression.ToNonNullString()); connectionString.AppendFormat("dataChannel={{{0}}}; ", dataChannel.ToNonNullString()); connectionString.AppendFormat("includeTime={0}; ", includeTime); connectionString.AppendFormat("lagTime={0}; ", lagTime); connectionString.AppendFormat("leadTime={0}; ", leadTime); connectionString.AppendFormat("useLocalClockAsRealTime={0}; ", useLocalClockAsRealTime); connectionString.AppendFormat("startTimeConstraint={0}; ", startTime.ToNonNullString()); connectionString.AppendFormat("stopTimeConstraint={0}; ", stopTime.ToNonNullString()); connectionString.AppendFormat("timeConstraintParameters={0}; ", constraintParameters.ToNonNullString()); connectionString.AppendFormat("processingInterval={0}; ", processingInterval); connectionString.AppendFormat("useMillisecondResolution={0}; ", m_useMillisecondResolution); connectionString.AppendFormat("assemblyInfo={{source={0}; version={1}.{2}.{3}; buildDate={4}}}", assemblyInfo.Name, assemblyInfo.Version.Major, assemblyInfo.Version.Minor, assemblyInfo.Version.Build, assemblyInfo.BuildDate.ToString("yyyy-MM-dd HH:mm:ss")); if (!waitHandleNames.IsNullOrWhiteSpace()) { connectionString.AppendFormat("; waitHandleNames={0}", waitHandleNames); connectionString.AppendFormat("; waitHandleTimeout={0}", waitHandleTimeout); } // Make sure not to monitor for data loss any faster than downsample time on throttled connections - additionally // you will want to make sure data stream monitor is twice lagtime to allow time for initial points to arrive. if (throttled && (object)m_dataStreamMonitor != null && m_dataStreamMonitor.Interval / 1000.0D < lagTime) m_dataStreamMonitor.Interval = 2.0D * lagTime * 1000.0D; return Subscribe(false, compactFormat, connectionString.ToString()); } /// <summary> /// Subscribes (or re-subscribes) to a data publisher for a set of data points. /// </summary> /// <param name="remotelySynchronized">Boolean value that determines if subscription should be remotely synchronized - note that data publisher may not allow remote synchronization.</param> /// <param name="compactFormat">Boolean value that determines if the compact measurement format should be used. Set to <c>false</c> for full fidelity measurement serialization; otherwise set to <c>true</c> for bandwidth conservation.</param> /// <param name="connectionString">Connection string that defines required and optional parameters for the subscription.</param> /// <returns><c>true</c> if subscribe transmission was successful; otherwise <c>false</c>.</returns> public virtual bool Subscribe(bool remotelySynchronized, bool compactFormat, string connectionString) { bool success = false; if (!connectionString.IsNullOrWhiteSpace()) { try { // Parse connection string to see if it contains a data channel definition Dictionary<string, string> settings = connectionString.ParseKeyValuePairs(); UdpClient dataChannel = null; string setting; // Track specified time inclusion for later deserialization if (settings.TryGetValue("includeTime", out setting)) m_includeTime = setting.ParseBoolean(); else m_includeTime = true; settings.TryGetValue("dataChannel", out setting); if (!setting.IsNullOrWhiteSpace()) { dataChannel = new UdpClient(setting); dataChannel.ReceiveBufferSize = ushort.MaxValue; dataChannel.MaxConnectionAttempts = -1; dataChannel.ConnectAsync(); } // Assign data channel client reference and attach to needed events this.DataChannel = dataChannel; // Setup subcription packet MemoryStream buffer = new MemoryStream(); DataPacketFlags flags = DataPacketFlags.NoFlags; byte[] bytes; if (remotelySynchronized) flags |= DataPacketFlags.Synchronized; if (compactFormat) flags |= DataPacketFlags.Compact; // Write data packet flags into buffer buffer.WriteByte((byte)flags); // Get encoded bytes of connection string bytes = m_encoding.GetBytes(connectionString); // Write encoded connection string length into buffer buffer.Write(EndianOrder.BigEndian.GetBytes(bytes.Length), 0, 4); // Encode connection string into buffer buffer.Write(bytes, 0, bytes.Length); // Cache subscribed synchronization state m_synchronizedSubscription = remotelySynchronized; // Send subscribe server command with associated command buffer success = SendServerCommand(ServerCommand.Subscribe, buffer.ToArray()); } catch (Exception ex) { OnProcessException(new InvalidOperationException("Exception occurred while trying to make publisher subscription: " + ex.Message, ex)); } } else OnProcessException(new InvalidOperationException("Cannot make publisher subscription without a connection string.")); return success; } /// <summary> /// Unsubscribes from a data publisher. /// </summary> /// <returns><c>true</c> if unsubscribe transmission was successful; otherwise <c>false</c>.</returns> public virtual bool Unsubscribe() { // Send unsubscribe server command return SendServerCommand(ServerCommand.Unsubscribe, null); } /// <summary> /// Returns the measurements signal IDs that were authorized after the last successful subscription request. /// </summary> [AdapterCommand("Gets authorized signal IDs from last subscription request.")] public virtual Guid[] GetAuthorizedSignalIDs() { if (m_signalIndexCache != null) return m_signalIndexCache.AuthorizedSignalIDs; return new Guid[0]; } /// <summary> /// Returns the measurements signal IDs that were unauthorized after the last successful subscription request. /// </summary> [AdapterCommand("Gets unauthorized signal IDs from last subscription request.")] public virtual Guid[] GetUnauthorizedSignalIDs() { if (m_signalIndexCache != null) return m_signalIndexCache.UnauthorizedSignalIDs; return new Guid[0]; } /// <summary> /// Initiate a metadata refresh. /// </summary> [AdapterCommand("Initiates a metadata refresh.")] public virtual void RefreshMetadata() { SendServerCommand(ServerCommand.MetaDataRefresh); } public bool SendServerCommand(ServerCommand commandCode) { return SendServerCommand(commandCode, null); } /// <summary> /// Sends a server command to the publisher connection. /// </summary> /// <param name="commandCode"><see cref="ServerCommand"/> to send.</param> /// <param name="data">Command data to send.</param> /// <returns><c>true</c> if <paramref name="commandCode"/> transmission was successful; otherwise <c>false</c>.</returns> public virtual bool SendServerCommand(ServerCommand commandCode, byte[] data) { if (m_commandChannel != null && m_commandChannel.CurrentState == ClientState.Connected) { try { MemoryStream commandPacket = new MemoryStream(); // Write command code into command packet commandPacket.WriteByte((byte)commandCode); // Write command buffer into command packet if (data != null && data.Length > 0) commandPacket.Write(data, 0, data.Length); // Send command packet to publisher m_commandChannel.SendAsync(commandPacket.ToArray()); // Track server command in pending request queue lock (m_requests) { // Make sure a pending request does not already exist int index = m_requests.BinarySearch(commandCode); if (index < 0) { // Add the new server command to the request list m_requests.Add(commandCode); // Make sure requests are sorted to allow for binary searching m_requests.Sort(); } } return true; } catch (Exception ex) { OnProcessException(new InvalidOperationException(string.Format("Exception occurred while trying to send server command \"{0}\" to publisher: {1}", commandCode, ex.Message), ex)); } } else OnProcessException(new InvalidOperationException(string.Format("Subscriber is currently unconnected. Cannot send server command \"{0}\" to publisher.", commandCode))); return false; } /// <summary> /// Attempts to connect to this <see cref="DataSubscriber"/>. /// </summary> protected override void AttemptConnection() { m_commandChannelConnectionAttempts = 0; m_dataChannelConnectionAttempts = 0; m_commandChannel.ConnectAsync(); m_authenticated = false; m_subscribed = false; m_keyIVs = null; m_totalBytesReceived = 0L; m_monitoredBytesReceived = 0L; m_lastBytesReceived = 0; } /// <summary> /// Attempts to disconnect from this <see cref="DataSubscriber"/>. /// </summary> protected override void AttemptDisconnection() { // Stop data stream monitor if ((object)m_dataStreamMonitor != null) m_dataStreamMonitor.Enabled = false; // Disconnect command channel if ((object)m_commandChannel != null) m_commandChannel.Disconnect(); } /// <summary> /// Gets a short one-line status of this <see cref="DataSubscriber"/>. /// </summary> /// <param name="maxLength">Maximum length of the status message.</param> /// <returns>Text of the status message.</returns> public override string GetShortStatus(int maxLength) { if (m_commandChannel != null && m_commandChannel.CurrentState == ClientState.Connected) return string.Format("Subscriber is connected and receiving {0} data points", m_synchronizedSubscription ? "synchronized" : "unsynchronized").CenterText(maxLength); return "Subscriber is not connected.".CenterText(maxLength); } /// <summary> /// Get message from string based response. /// </summary> /// <param name="buffer">Response buffer.</param> /// <param name="startIndex">Start index of response message.</param> /// <param name="length">Length of response message.</param> /// <returns>Decoded response string.</returns> protected string InterpretResponseMessage(byte[] buffer, int startIndex, int length) { return m_encoding.GetString(buffer, startIndex, length); } // Restarts the subscriber. private void Restart() { try { base.Start(); } catch (Exception ex) { OnProcessException(ex); } } private void ProcessServerResponse(byte[] buffer, int length) { // Currently this work is done on the async socket completion thread, make sure work to be done is timely and if the response processing // is coming in via the command channel and needs to send a command back to the server, it should be done on a separate thread... if (buffer != null && length > 0) { try { ServerResponse responseCode = (ServerResponse)buffer[0]; ServerCommand commandCode = (ServerCommand)buffer[1]; int responseLength = EndianOrder.BigEndian.ToInt32(buffer, 2); int responseIndex = 6; bool solicited = false; byte[][][] keyIVs; // See if this was a solicited response to a requested server command if (responseCode.IsSolicited()) { lock (m_requests) { int index = m_requests.BinarySearch(commandCode); if (index >= 0) { solicited = true; m_requests.RemoveAt(index); } } // Disconnect any established UDP data channel upon successful unsubscribe if (solicited && commandCode == ServerCommand.Unsubscribe && responseCode == ServerResponse.Succeeded) DataChannel = null; } switch (responseCode) { case ServerResponse.Succeeded: if (solicited) { switch (commandCode) { case ServerCommand.Authenticate: OnStatusMessage("Success code received in response to server command \"{0}\": {1}", commandCode, InterpretResponseMessage(buffer, responseIndex, responseLength)); m_authenticated = true; OnConnectionAuthenticated(); break; case ServerCommand.Subscribe: OnStatusMessage("Success code received in response to server command \"{0}\": {1}", commandCode, InterpretResponseMessage(buffer, responseIndex, responseLength)); m_subscribed = true; if ((object)m_dataStreamMonitor != null) m_dataStreamMonitor.Enabled = true; break; case ServerCommand.Unsubscribe: OnStatusMessage("Success code received in response to server command \"{0}\": {1}", commandCode, InterpretResponseMessage(buffer, responseIndex, responseLength)); m_subscribed = false; if ((object)m_dataStreamMonitor != null) m_dataStreamMonitor.Enabled = false; break; case ServerCommand.RotateCipherKeys: OnStatusMessage("Success code received in response to server command \"{0}\": {1}", commandCode, InterpretResponseMessage(buffer, responseIndex, responseLength)); break; case ServerCommand.MetaDataRefresh: OnStatusMessage("Success code received in response to server command \"{0}\": latest meta-data received.", commandCode); OnMetaDataReceived(DeserializeMetadata(buffer.BlockCopy(responseIndex, responseLength))); break; } } else { switch (commandCode) { case ServerCommand.MetaDataRefresh: // Meta-data refresh may be unsolicited OnStatusMessage("Received server confirmation for unsolicited request to \"{0}\" command: latest meta-data received.", commandCode); OnMetaDataReceived(DeserializeMetadata(buffer.BlockCopy(responseIndex, responseLength))); break; case ServerCommand.RotateCipherKeys: // Key rotation may be unsolicited OnStatusMessage("Received server confirmation for unsolicited request to \"{0}\" command: {1}", commandCode, InterpretResponseMessage(buffer, responseIndex, responseLength)); break; case ServerCommand.Subscribe: OnStatusMessage("Received unsolicited response to \"{0}\" command: {1}", commandCode, InterpretResponseMessage(buffer, responseIndex, responseLength)); break; default: OnProcessException(new InvalidOperationException("Publisher sent a success code for an unsolicited server command: " + commandCode)); break; } } break; case ServerResponse.Failed: if (solicited) OnStatusMessage("Failure code received in response to server command \"{0}\": {1}", commandCode, InterpretResponseMessage(buffer, responseIndex, responseLength)); else OnProcessException(new InvalidOperationException("Publisher sent a failed code for an unsolicited server command: " + commandCode)); break; case ServerResponse.DataPacket: long now = DateTime.UtcNow.Ticks; // Deserialize data packet List<IMeasurement> measurements = new List<IMeasurement>(); DataPacketFlags flags; Ticks timestamp = 0; int count; // Track total data packet bytes received from any channel m_totalBytesReceived += m_lastBytesReceived; m_monitoredBytesReceived += m_lastBytesReceived; // Get data packet flags flags = (DataPacketFlags)buffer[responseIndex]; responseIndex++; bool synchronizedMeasurements = ((byte)(flags & DataPacketFlags.Synchronized) > 0); bool compactMeasurementFormat = ((byte)(flags & DataPacketFlags.Compact) > 0); int cipherIndex = (flags & DataPacketFlags.CipherIndex) > 0 ? 1 : 0; // Decrypt data packet payload if keys are available // if (m_keyIVs != null) // { // // Get a local copy of volatile keyIVs reference since this can change at any time // keyIVs = m_keyIVs; // // // Decrypt payload portion of data packet // buffer = Common.SymmetricAlgorithm.Decrypt(buffer, responseIndex, responseLength - 1, keyIVs[cipherIndex][0], keyIVs[cipherIndex][1]); // responseIndex = 0; // responseLength = buffer.Length; // } // Synchronized packets contain a frame level timestamp if (synchronizedMeasurements) { timestamp = EndianOrder.BigEndian.ToInt64(buffer, responseIndex); responseIndex += 8; } // Deserialize number of measurements that follow count = EndianOrder.BigEndian.ToInt32(buffer, responseIndex); responseIndex += 4; // Deserialize measurements for (int i = 0; i < count; i++) { if (!compactMeasurementFormat) { // Deserialize full measurement format SerializableMeasurement measurement = new SerializableMeasurement(m_encoding); responseIndex += measurement.ParseBinaryImage(buffer, responseIndex, responseLength - responseIndex); measurements.Add(measurement); } else if ((object)m_signalIndexCache != null) { // Deserialize compact measurement format CompactMeasurement measurement = new CompactMeasurement(m_signalIndexCache, m_includeTime, m_baseTimeOffsets, m_timeIndex, m_useMillisecondResolution); responseIndex += measurement.ParseBinaryImage(buffer, responseIndex, responseLength - responseIndex); // Apply timestamp from frame if not included in transmission if (!measurement.IncludeTime) measurement.Timestamp = timestamp; measurements.Add(measurement); } else if (m_lastMissingCacheWarning + MissingCacheWarningInterval < now) { if (m_lastMissingCacheWarning != 0L) { // Warning message for missing signal index cache OnStatusMessage("WARNING: Signal index cache has not arrived. No compact measurements can be parsed."); } m_lastMissingCacheWarning = now; } } // Provide new measurements to local concentrator, if defined, otherwise directly expose them to the consumer if ((object)m_localConcentrator != null) m_localConcentrator.SortMeasurements(measurements); else OnNewMeasurements(measurements); break; case ServerResponse.DataStartTime: // Raise data start time event OnDataStartTime(EndianOrder.BigEndian.ToInt64(buffer, responseIndex)); break; case ServerResponse.ProcessingComplete: // Raise input processing completed event OnProcessingComplete(InterpretResponseMessage(buffer, responseIndex, responseLength)); break; case ServerResponse.UpdateSignalIndexCache: // Deserialize new signal index cache m_remoteSignalIndexCache = DeserializeSignalIndexCache(buffer.BlockCopy(responseIndex, responseLength)); m_signalIndexCache = new SignalIndexCache(DataSource, m_remoteSignalIndexCache); break; case ServerResponse.UpdateBaseTimes: // Get active time index m_timeIndex = EndianOrder.BigEndian.ToInt32(buffer, responseIndex); responseIndex += 4; // Deserialize new base time offsets m_baseTimeOffsets = new long[] { EndianOrder.BigEndian.ToInt64(buffer, responseIndex), EndianOrder.BigEndian.ToInt64(buffer, responseIndex + 8) }; break; case ServerResponse.UpdateCipherKeys: // Get active cipher index m_cipherIndex = buffer[responseIndex++]; // Extract remaining response byte[] bytes = buffer.BlockCopy(responseIndex, responseLength - 1); // // Decrypt response payload if subscription is authenticated // if (m_authenticated) // bytes = bytes.Decrypt(m_sharedSecret, CipherStrength.Aes256); // Deserialize new cipher keys keyIVs = new byte[2][][]; keyIVs[EvenKey] = new byte[2][]; keyIVs[OddKey] = new byte[2][]; int index = 0; int bufferLen; // Read even key size bufferLen = EndianOrder.BigEndian.ToInt32(bytes, index); index += 4; // Read even key keyIVs[EvenKey][KeyIndex] = new byte[bufferLen]; Buffer.BlockCopy(bytes, index, keyIVs[EvenKey][KeyIndex], 0, bufferLen); index += bufferLen; // Read even initialization vector size bufferLen = EndianOrder.BigEndian.ToInt32(bytes, index); index += 4; // Read even initialization vector keyIVs[EvenKey][IVIndex] = new byte[bufferLen]; Buffer.BlockCopy(bytes, index, keyIVs[EvenKey][IVIndex], 0, bufferLen); index += bufferLen; // Read odd key size bufferLen = EndianOrder.BigEndian.ToInt32(bytes, index); index += 4; // Read odd key keyIVs[OddKey][KeyIndex] = new byte[bufferLen]; Buffer.BlockCopy(bytes, index, keyIVs[OddKey][KeyIndex], 0, bufferLen); index += bufferLen; // Read odd initialization vector size bufferLen = EndianOrder.BigEndian.ToInt32(bytes, index); index += 4; // Read odd initialization vector keyIVs[OddKey][IVIndex] = new byte[bufferLen]; Buffer.BlockCopy(bytes, index, keyIVs[OddKey][IVIndex], 0, bufferLen); index += bufferLen; // Exchange keys m_keyIVs = keyIVs; OnStatusMessage("Successfully established new cipher keys for data packet transmissions."); break; } } catch (Exception ex) { OnProcessException(new InvalidOperationException("Failed to process publisher response packet due to exception: " + ex.Message, ex)); } } } // Handles auto-connection subscription initialization private void StartSubscription() { StringBuilder filterExpression = new StringBuilder(); string dataChannel = null; // If TCP command channel is defined separately, then base connection string defines data channel if (Settings.ContainsKey("commandChannel")) dataChannel = ConnectionString; if (OutputMeasurements != null) { foreach (IMeasurement measurement in OutputMeasurements) { if (filterExpression.Length > 0) filterExpression.Append(';'); // Subscribe by associated Guid... filterExpression.Append(measurement.ID.ToString()); } // Start unsynchronized subscription UnsynchronizedSubscribe(true, false, filterExpression.ToString(), dataChannel, true, 10.0D, 5.0D, false, null, null, null, -1, null, 0); } else { OnStatusMessage("WARNING: No measurements are currently defined for subscription."); } // Initiate meta-data refresh if (m_synchronizeMetadata) SendServerCommand(ServerCommand.MetaDataRefresh); } /// <summary> /// Handles auto-connection metadata synchronization to local system. /// </summary> /// <param name="state"><see cref="DataSet"/> metadata collection passed into state parameter.</param> /// <remarks> /// This function is normally called from thread pool since synchronization can take some time. /// </remarks> protected virtual void SynchronizeMetadata(object state) { // try // { // DataSet metadata = state as DataSet; // // if (metadata != null) // { // // Track total meta-data synchronization process time // Ticks startTime = DateTime.UtcNow.Ticks; // // // Open the configuration database using settings found in the config file // AdoDataConnection database = new AdoDataConnection("systemSettings"); // IDbConnection connection = database.Connection; // string guidPrefix = database.DatabaseType == DatabaseType.Access ? "{" : "'"; // string guidSuffix = database.DatabaseType == DatabaseType.Access ? "}" : "'"; // // // Query the actual record ID based on the known run-time ID for this subscriber device // int parentID = Convert.ToInt32(connection.ExecuteScalar(string.Format("SELECT SourceID FROM Runtime WHERE ID = {0} AND SourceTable='Device'", ID))); // // // Validate that the subscriber device is marked as a concentrator (we are about to associate children devices with it) // if (!connection.ExecuteScalar(string.Format("SELECT IsConcentrator FROM Device WHERE ID = {0}", parentID)).ToString().ParseBoolean()) // connection.ExecuteNonQuery(string.Format("UPDATE Device SET IsConcentrator = 1 WHERE ID = {0}", parentID)); // // // Determine the active node ID - we cache this since this value won't change for the lifetime of this class // if (m_nodeID == Guid.Empty) // m_nodeID = new Guid(connection.ExecuteScalar(string.Format("SELECT NodeID FROM IaonInputAdapter WHERE ID = {0}", ID)).ToString()); // // // Determine the protocol record auto-inc ID value for the gateway transport protocol (GEP) - this value is also cached since it shouldn't change for the lifetime of this class // if (m_gatewayProtocolID == 0) // m_gatewayProtocolID = int.Parse(connection.ExecuteScalar("SELECT ID FROM Protocol WHERE Acronym='GatewayTransport'").ToString()); // // // Prefix all children devices with the name of the parent since the same device names could appear in different connections (helps keep device names unique) // string sourcePrefix = Name + "!"; // Dictionary<string, int> deviceIDs = new Dictionary<string, int>(StringComparer.InvariantCultureIgnoreCase); // string selectSql, insertSql, updateSql, deleteSql, deviceAcronym, signalTypeAcronym; // int deviceID; // // // Check to see if data for the "DeviceDetail" table was included in the meta-data // if (metadata.Tables.Contains("DeviceDetail")) // { // List<Guid> uniqueIDs = new List<Guid>(); // // foreach (DataRow row in metadata.Tables["DeviceDetail"].Rows) // { // Guid uniqueID = new Guid(row.Field<object>("UniqueID").ToString()); // adoDatabase.Guid(row, "UniqueID"); // row.Field<Guid>("UniqueID"); // // // Track unique device guid's in this meta-data session, we'll need to remove any old associated devices that no longer exist // uniqueIDs.Add(uniqueID); // // // We will synchronize metadata only if the source owns this device and it's not defined as a concentrator (these should normally be filtered by publisher - but we check just in case). // if (row.Field<object>("OriginalSource") == null && !row["IsConcentrator"].ToNonNullString("0").ParseBoolean()) // { // // Define query to determine if this device is already defined (this should always be based on the unique device Guid) // selectSql = database.ParameterizedQueryString("SELECT COUNT(*) FROM Device WHERE UniqueID = {0}", "deviceGuid"); // // if (Convert.ToInt32(connection.ExecuteScalar(selectSql, database.Guid(uniqueID))) == 0) // { // // Insert new device record // insertSql = database.ParameterizedQueryString("INSERT INTO Device(NodeID, ParentID, Acronym, Name, ProtocolID, IsConcentrator, Enabled, OriginalSource) " + // "VALUES ({0}, {1}, {2}, {3}, {4}, 0, 1, {5})", "nodeID", "parentID", "acronym", "name", "protocolID", "originalSource"); // // connection.ExecuteNonQuery(insertSql, database.Guid(m_nodeID), parentID, sourcePrefix + row.Field<string>("Acronym"), row.Field<string>("Name"), m_gatewayProtocolID, // m_internal == true ? (object)DBNull.Value : string.IsNullOrEmpty(row.Field<string>("ParentAcronym")) ? sourcePrefix + row.Field<string>("Acronym") : sourcePrefix + row.Field<string>("ParentAcronym")); // // // Guids are normally auto-generated during insert - after insertion update the guid so that it matches the source data. Most of the database // // scripts have triggers that support properly assigning the Guid during an insert, but this code ensures the Guid will always get assigned. // updateSql = database.ParameterizedQueryString("UPDATE Device SET UniqueID = {0} WHERE Acronym = {1}", "uniqueID", "acronym"); // connection.ExecuteNonQuery(updateSql, database.Guid(uniqueID), sourcePrefix + row.Field<string>("Acronym")); // } // else // { // // Update existing device record // if (m_internal) // { // // Gateway is assuming ownership of the device records when the "interal" flag is true - this means the device's measurements can be forwarded to another party. // // From a device record perspective, ownership is inferred by setting 'OriginalSource' to null. // updateSql = database.ParameterizedQueryString("UPDATE Device SET Acronym = {0}, Name = {1}, OriginalSource = {2}, ProtocolID = {3} WHERE UniqueID = {4}", "acronym", "name", "originalSource", "protocolID", "uniqueID"); // connection.ExecuteNonQuery(updateSql, sourcePrefix + row.Field<string>("Acronym"), row.Field<string>("Name"), (object)DBNull.Value, m_gatewayProtocolID, database.Guid(uniqueID)); // } // else // { // // When gateway doesn't own device records (i.e., the "interal" flag is false), this means the device's measurements can only be consumed locally. From a device // // record perspective this means the 'OriginalSource' field is set to the acronym of the PDC or PMU that generated the source measurments. This field allows a // // mirrored source restriction to be implemented later to ensure all devices in an output protocol came from the same original source connection. // updateSql = database.ParameterizedQueryString("UPDATE Device SET Acronym = {0}, Name = {1}, ProtocolID = {2} WHERE UniqueID = {3}", "acronym", "name", "protocolID", "uniqueID"); // connection.ExecuteNonQuery(updateSql, sourcePrefix + row.Field<string>("Acronym"), row.Field<string>("Name"), m_gatewayProtocolID, database.Guid(uniqueID)); // } // } // } // // // Capture local device ID auto-inc value for measurement association // selectSql = database.ParameterizedQueryString("SELECT ID FROM Device WHERE UniqueID = {0}", "deviceGuid"); // deviceIDs[row.Field<string>("Acronym")] = Convert.ToInt32(connection.ExecuteScalar(selectSql, database.Guid(uniqueID))); // } // // // Remove any device records associated with this subscriber that no longer exist in the meta-data // if (uniqueIDs.Count > 0) // { // deleteSql = string.Format("DELETE FROM Device WHERE ParentID = {0} AND UniqueID NOT IN ({1})", parentID, uniqueIDs.Select(uniqueID => guidPrefix + uniqueID.ToString().ToLower() + guidSuffix).ToDelimitedString(", ")); // connection.ExecuteNonQuery(deleteSql); // } // } // // // Check to see if data for the "MeasurementDetail" table was included in the meta-data // if (metadata.Tables.Contains("MeasurementDetail")) // { // List<Guid> signalIDs = new List<Guid>(); // // // Load signal type ID's from local database associated with their acronym for proper signal type translation // Dictionary<string, int> signalTypeIDs = new Dictionary<string, int>(StringComparer.InvariantCultureIgnoreCase); // // foreach (DataRow row in connection.RetrieveData(database.AdapterType, "SELECT ID, Acronym FROM SignalType").Rows) // { // signalTypeAcronym = row.Field<string>("Acronym"); // // if (!signalTypeAcronym.IsNullOrWhiteSpace()) // signalTypeIDs[signalTypeAcronym] = row.ConvertField<int>("ID"); // } // // foreach (DataRow row in metadata.Tables["MeasurementDetail"].Rows) // { // // Verify that this measurement record is internal to the publisher (these should be filtered by the publisher, but we still check since we won't be able to subscribe to any measurements it doesn't own) // if (row["Internal"].ToNonNullString("1").ParseBoolean()) // { // // Get device and signal type acronyms // deviceAcronym = row.Field<string>("DeviceAcronym") ?? string.Empty; // signalTypeAcronym = row.Field<string>("SignalAcronym") ?? string.Empty; // // // Make sure we have an associated device and signal type already defined for the measurement // if (!deviceAcronym.IsNullOrWhiteSpace() && deviceIDs.ContainsKey(deviceAcronym) && !signalTypeAcronym.IsNullOrWhiteSpace() && signalTypeIDs.ContainsKey(signalTypeAcronym)) // { // // Prefix the tag name with the "updated" device name // deviceID = deviceIDs[deviceAcronym]; // string pointTag = sourcePrefix + row.Field<string>("PointTag") ?? string.Empty; // Guid signalID = new Guid(row.Field<object>("SignalID").ToString()); // adoDatabase.Guid(row, "SignalID"); // row.Field<Guid>("SignalID"); // // // Track unique measurement signal guid's in this meta-data session, we'll need to remove any old associated measurements that no longer exist // signalIDs.Add(signalID); // // // Define query to determine if this measurement is already defined (this should always be based on the unique signal ID Guid) // selectSql = database.ParameterizedQueryString("SELECT COUNT(*) FROM Measurement WHERE SignalID = {0}", "signalID"); // // if (Convert.ToInt32(connection.ExecuteScalar(selectSql, database.Guid(signalID))) == 0) // { // // Insert new measurement record // insertSql = database.ParameterizedQueryString("INSERT INTO Measurement (DeviceID, PointTag, SignalTypeID, SignalReference, Description, Internal, Subscribed, Enabled) VALUES ({0}, {1}, {2}, {3}, {4}, {5}, 0, 1)", "deviceID", "pointTag", "signalTypeID", "signalReference", "description", "internal"); // connection.ExecuteNonQuery(insertSql, 30, deviceID, pointTag, signalTypeIDs[signalTypeAcronym], sourcePrefix + row.Field<string>("SignalReference"), row.Field<string>("Description") ?? string.Empty, database.Bool(m_internal)); // // // Guids are normally auto-generated during insert - after insertion update the guid so that it matches the source data. Most of the database // // scripts have triggers that support properly assigning the Guid during an insert, but this code ensures the Guid will always get assigned. // updateSql = database.ParameterizedQueryString("UPDATE Measurement SET SignalID = {0} WHERE PointTag = {1}", "signalID", "pointTag"); // connection.ExecuteNonQuery(updateSql, database.Guid(signalID), pointTag); // } // else // { // // Update existing measurement record. Note that this update assumes that measurements will remain associated with a static source device. // updateSql = database.ParameterizedQueryString("UPDATE Measurement SET PointTag = {0}, SignalTypeID = {1}, SignalReference = {2}, Description = {3}, Internal = {4} WHERE SignalID = {5}", "pointTag", "signalTypeID", "signalReference", "description", "internal", "signalID"); // connection.ExecuteNonQuery(updateSql, pointTag, signalTypeIDs[signalTypeAcronym], sourcePrefix + row.Field<string>("SignalReference"), row.Field<string>("Description") ?? string.Empty, database.Bool(m_internal), database.Guid(signalID)); // } // } // } // } // // // Remove any measurement records associated with existing devices in this session but no longer exist in the meta-data // if (deviceIDs.Count > 0 && signalIDs.Count > 0) // { // deleteSql = string.Format("DELETE FROM Measurement WHERE DeviceID IN ({0}) AND SignalID NOT IN ({1})", deviceIDs.Values.ToDelimitedString(", "), signalIDs.Select(uniqueID => guidPrefix + uniqueID.ToString() + guidSuffix).ToDelimitedString(", ")); // connection.ExecuteNonQuery(deleteSql); // } // } // // // Check to see if data for the "PhasorDetail" table was included in the meta-data // if (metadata.Tables.Contains("PhasorDetail")) // { // Dictionary<int, int> maxSourceIndicies = new Dictionary<int, int>(); // int sourceIndex; // // // Phasor data is normally only needed so that the user can property generate a mirrored IEEE C37.118 output stream from the source data. // // This is necessary since, in this protocol, the phasors are described (i.e., labeled) as a unit (i.e., as a complex number) instead of // // as two distinct angle and magnitude measurements. // // foreach (DataRow row in metadata.Tables["PhasorDetail"].Rows) // { // // Get device acronym // deviceAcronym = row.Field<string>("DeviceAcronym") ?? string.Empty; // // // Make sure we have an associated device already defined for the phasor record // if (!deviceAcronym.IsNullOrWhiteSpace() && deviceIDs.ContainsKey(deviceAcronym)) // { // deviceID = deviceIDs[deviceAcronym]; // // // Define query to determine if this phasor record is already defined, this is no Guid for these simple label records // selectSql = database.ParameterizedQueryString("SELECT COUNT(*) FROM Phasor WHERE DeviceID = {0} AND SourceIndex = {1}", "deviceID", "sourceIndex"); // // if (Convert.ToInt32(connection.ExecuteScalar(selectSql, 30, deviceID, row.ConvertField<int>("SourceIndex"))) == 0) // { // // Insert new phasor record // insertSql = database.ParameterizedQueryString("INSERT INTO Phasor (DeviceID, Label, Type, Phase, SourceIndex) VALUES ({0}, {1}, {2}, {3}, {4})", "deviceID", "label", "type", "phase", "sourceIndex"); // connection.ExecuteNonQuery(insertSql, 30, deviceID, row.Field<string>("Label") ?? "undefined", (row.Field<string>("Type") ?? "V").TruncateLeft(1), (row.Field<string>("Phase") ?? "+").TruncateLeft(1), row.ConvertField<int>("SourceIndex")); // } // else // { // // Update existing phasor record // updateSql = database.ParameterizedQueryString("UPDATE Phasor SET Label = {0}, Type = {1}, Phase = {2} WHERE DeviceID = {3} AND SourceIndex = {4}", "label", "type", "phase", "deviceID", "sourceIndex"); // connection.ExecuteNonQuery(updateSql, row.Field<string>("Label") ?? "undefined", (row.Field<string>("Type") ?? "V").TruncateLeft(1), (row.Field<string>("Phase") ?? "+").TruncateLeft(1), deviceID, row.ConvertField<int>("SourceIndex")); // } // // // Track largest source index for each device // maxSourceIndicies.TryGetValue(deviceID, out sourceIndex); // // if (row.ConvertField<int>("SourceIndex") > sourceIndex) // maxSourceIndicies[deviceID] = row.ConvertField<int>("SourceIndex"); // } // } // // // Remove any phasor records associated with existing devices in this session but no longer exist in the meta-data // if (maxSourceIndicies.Count > 0) // { // foreach (KeyValuePair<int, int> deviceIndexPair in maxSourceIndicies) // { // deleteSql = string.Format("DELETE FROM Phasor WHERE DeviceID = {0} AND SourceIndex > {1}", deviceIndexPair.Key, deviceIndexPair.Value); // connection.ExecuteNonQuery(deleteSql); // } // } // } // // // New signals may have been defined, take original remote signal index cache and apply changes // if (m_remoteSignalIndexCache != null) // m_signalIndexCache = new SignalIndexCache(DataSource, m_remoteSignalIndexCache); // // OnStatusMessage("Meta-data synchronization completed successfully in {0}", (DateTime.UtcNow.Ticks - startTime).ToElapsedTimeString(3)); // } // else // { // OnStatusMessage("WARNING: Meta-data synchronization was not performed, deserialized dataset was empty."); // } // } // catch (Exception ex) // { // OnProcessException(new InvalidOperationException("Failed to synchronize meta-data to local cache: " + ex.Message, ex)); // } } private SignalIndexCache DeserializeSignalIndexCache(byte[] buffer) { GatewayCompressionMode gatewayCompressionMode = (GatewayCompressionMode)(m_operationalModes & OperationalModes.CompressionModeMask); bool useCommonSerializationFormat = (m_operationalModes & OperationalModes.UseCommonSerializationFormat) > 0; bool compressSignalIndexCache = (m_operationalModes & OperationalModes.CompressSignalIndexCache) > 0; SignalIndexCache deserializedCache; MemoryStream compressedData = null; GZipStream inflater = null; if (compressSignalIndexCache && gatewayCompressionMode == GatewayCompressionMode.GZip) { try { compressedData = new MemoryStream(buffer); inflater = new GZipStream(compressedData, CompressionMode.Decompress); buffer = inflater.ReadStream(); } finally { if ((object)inflater != null) inflater.Close(); if ((object)compressedData != null) compressedData.Close(); } } if (useCommonSerializationFormat) { deserializedCache = new SignalIndexCache(); deserializedCache.Encoding = m_encoding; deserializedCache.ParseBinaryImage(buffer, 0, buffer.Length); } else { deserializedCache = Serialization.Deserialize<SignalIndexCache>(buffer, GSF.SerializationFormat.Binary); } return deserializedCache; } private DataSet DeserializeMetadata(byte[] buffer) { GatewayCompressionMode gatewayCompressionMode = (GatewayCompressionMode)(m_operationalModes & OperationalModes.CompressionModeMask); bool useCommonSerializationFormat = (m_operationalModes & OperationalModes.UseCommonSerializationFormat) > 0; bool compressMetadata = (m_operationalModes & OperationalModes.CompressMetadata) > 0; DataSet deserializedMetadata; MemoryStream compressedData = null; GZipStream inflater = null; MemoryStream encodedData = null; XmlTextReader unicodeReader = null; if (compressMetadata && gatewayCompressionMode == GatewayCompressionMode.GZip) { try { // Insert compressed data into compressed buffer compressedData = new MemoryStream(buffer); inflater = new GZipStream(compressedData, CompressionMode.Decompress); buffer = inflater.ReadStream(); } finally { if ((object)inflater != null) inflater.Close(); if ((object)compressedData != null) compressedData.Close(); } } if (useCommonSerializationFormat) { try { // Copy decompressed data into encoded buffer encodedData = new MemoryStream(buffer); // Read encoded data into data set as XML unicodeReader = new XmlTextReader(encodedData); deserializedMetadata = new DataSet(); deserializedMetadata.ReadXml(unicodeReader, XmlReadMode.ReadSchema); } finally { if ((object)unicodeReader != null) unicodeReader.Close(); if ((object)encodedData != null) encodedData.Close(); } } else { deserializedMetadata = Serialization.Deserialize<DataSet>(buffer, GSF.SerializationFormat.Binary); } return deserializedMetadata; } private UnsynchronizedSubscriptionInfo FromLocallySynchronizedInfo(SynchronizedSubscriptionInfo info) { return new UnsynchronizedSubscriptionInfo(false) { FilterExpression = info.FilterExpression, UseCompactMeasurementFormat = info.UseCompactMeasurementFormat, UdpDataChannel = info.UdpDataChannel, DataChannelLocalPort = info.DataChannelLocalPort, LagTime = info.LagTime, LeadTime = info.LeadTime, UseLocalClockAsRealTime = false, UseMillisecondResolution = info.UseMillisecondResolution, StartTime = info.StartTime, StopTime = info.StopTime, ConstraintParameters = info.ConstraintParameters, ProcessingInterval = info.ProcessingInterval, WaitHandleNames = info.WaitHandleNames, WaitHandleTimeout = info.WaitHandleTimeout, ExtraConnectionStringParameters = info.ExtraConnectionStringParameters }; } private Encoding GetCharacterEncoding(OperationalEncoding operationalEncoding) { Encoding encoding; switch (operationalEncoding) { case OperationalEncoding.Unicode: encoding = Encoding.Unicode; break; case OperationalEncoding.BigEndianUnicode: encoding = Encoding.BigEndianUnicode; break; case OperationalEncoding.UTF8: encoding = Encoding.UTF8; break; case OperationalEncoding.ANSI: encoding = Encoding.Default; break; default: throw new InvalidOperationException(string.Format("Unsupported encoding detected: {0}", operationalEncoding)); } return encoding; } // Socket exception handler private bool HandleSocketException(System.Net.Sockets.SocketException ex) { if ((object)ex != null) { // WSAECONNABORTED and WSAECONNRESET are common errors after a client disconnect, // if they happen for other reasons, make sure disconnect procedure is handled if (ex.ErrorCode == 10053 || ex.ErrorCode == 10054) { DisconnectClient(); return true; } } return false; } // Disconnect client, restarting if disconnect was not intentional private void DisconnectClient() { DataChannel = null; // If user didn't initiate disconnect, restart the connection if (Enabled) Start(); } // This method is called when connection has been authenticated private void DataSubscriber_ConnectionAuthenticated(object sender, EventArgs e) { if (m_autoConnect) StartSubscription(); } // This method is called then new metadata has been received private void DataSubscriber_MetaDataReceived(object sender, EventArgs<DataSet> e) { try { // We handle synchronization on a seperate thread since this process may be lengthy if (m_synchronizeMetadata) ThreadPool.QueueUserWorkItem(SynchronizeMetadata, e.Argument); } catch (Exception ex) { // Process exception for logging OnProcessException(new InvalidOperationException("Failed to queue metadata synchronization due to exception: " + ex.Message, ex)); } } /// <summary> /// Raises the <see cref="ConnectionEstablished"/> event. /// </summary> protected void OnConnectionEstablished() { try { if (ConnectionEstablished != null) ConnectionEstablished(this, EventArgs.Empty); } catch (Exception ex) { // We protect our code from consumer thrown exceptions OnProcessException(new InvalidOperationException(string.Format("Exception in consumer handler for ConnectionEstablished event: {0}", ex.Message), ex)); } } /// <summary> /// Raises the <see cref="ConnectionTerminated"/> event. /// </summary> protected void OnConnectionTerminated() { try { if (ConnectionTerminated != null) ConnectionTerminated(this, EventArgs.Empty); } catch (Exception ex) { // We protect our code from consumer thrown exceptions OnProcessException(new InvalidOperationException(string.Format("Exception in consumer handler for ConnectionTerminated event: {0}", ex.Message), ex)); } } /// <summary> /// Raises the <see cref="ConnectionAuthenticated"/> event. /// </summary> protected void OnConnectionAuthenticated() { try { if (ConnectionAuthenticated != null) ConnectionAuthenticated(this, EventArgs.Empty); } catch (Exception ex) { // We protect our code from consumer thrown exceptions OnProcessException(new InvalidOperationException(string.Format("Exception in consumer handler for ConnectionAuthenticated event: {0}", ex.Message), ex)); } } /// <summary> /// Raises the <see cref="MetaDataReceived"/> event. /// </summary> /// <param name="metadata">Meta-data <see cref="DataSet"/> instance to send to client subscription.</param> protected void OnMetaDataReceived(DataSet metadata) { try { if (MetaDataReceived != null) MetaDataReceived(this, new EventArgs<DataSet>(metadata)); } catch (Exception ex) { // We protect our code from consumer thrown exceptions OnProcessException(new InvalidOperationException(string.Format("Exception in consumer handler for MetaDataReceived event: {0}", ex.Message), ex)); } } /// <summary> /// Raises the <see cref="DataStartTime"/> event. /// </summary> /// <param name="startTime">Start time, in <see cref="Ticks"/>, of first measurement transmitted.</param> protected void OnDataStartTime(Ticks startTime) { try { if (DataStartTime != null) DataStartTime(this, new EventArgs<Ticks>(startTime)); } catch (Exception ex) { // We protect our code from consumer thrown exceptions OnProcessException(new InvalidOperationException(string.Format("Exception in consumer handler for DataStartTime event: {0}", ex.Message), ex)); } } /// <summary> /// Raises the <see cref="ProcessingComplete"/> event. /// </summary> /// <param name="source">Type name of adapter that sent the processing completed notification.</param> protected void OnProcessingComplete(string source) { try { if (ProcessingComplete != null) ProcessingComplete(this, new EventArgs<string>(source)); // Also raise base class event in case this event has been subscribed OnProcessingComplete(); } catch (Exception ex) { // We protect our code from consumer thrown exceptions OnProcessException(new InvalidOperationException(string.Format("Exception in consumer handler for ProcessingComplete event: {0}", ex.Message), ex)); } } /// <summary> /// Disposes of any previously defined local concentrator. /// </summary> protected internal void DisposeLocalConcentrator() { if ((object)m_localConcentrator != null) { m_localConcentrator.ProcessException -= m_localConcentrator_ProcessException; m_localConcentrator.Dispose(); } m_localConcentrator = null; } private void m_localConcentrator_ProcessException(object sender, EventArgs<Exception> e) { // Make sure any exceptions reported by local concentrator get exposed as needed OnProcessException(e.Argument); } private void m_dataStreamMonitor_Elapsed(object sender, System.Timers.ElapsedEventArgs e) { if (m_monitoredBytesReceived == 0) { // If we've received no data in the last timespan, we restart connect cycle... m_dataStreamMonitor.Enabled = false; OnStatusMessage("\r\nNo data received in {0} seconds, restarting connect cycle...\r\n", (m_dataStreamMonitor.Interval / 1000.0D).ToString("0.0")); ThreadPool.QueueUserWorkItem(state => Restart()); } // Reset bytes received bytes being monitored m_monitoredBytesReceived = 0L; } #region [ Command Channel Event Handlers ] private void m_commandChannel_ConnectionEstablished(object sender, EventArgs e) { // Make sure no existing requests are queued for a new publisher connection lock (m_requests) { m_requests.Clear(); } // Define operational modes as soon as possible SendServerCommand(ServerCommand.DefineOperationalModes, EndianOrder.BigEndian.GetBytes((uint)m_operationalModes)); // Notify input adapter base that asynchronous connection succeeded OnConnected(); // Notify consumer that connection was sucessfully established OnConnectionEstablished(); OnStatusMessage("Data subscriber command channel connection to publisher was established."); if (m_autoConnect) { // Attempt authentication if required, remaining steps will happen on successful authentication if (m_requireAuthentication) Authenticate(m_sharedSecret, m_authenticationID); else StartSubscription(); } } private void m_commandChannel_ConnectionTerminated(object sender, EventArgs e) { OnConnectionTerminated(); OnStatusMessage("Data subscriber command channel connection to publisher was terminated."); DisconnectClient(); } private void m_commandChannel_ConnectionException(object sender, EventArgs<Exception> e) { Exception ex = e.Argument; OnProcessException(new InvalidOperationException("Data subscriber encountered an exception while attempting command channel publisher connection: " + ex.Message, ex)); } private void m_commandChannel_ConnectionAttempt(object sender, EventArgs e) { // Inject a short delay between multiple connection attempts if (m_commandChannelConnectionAttempts > 0) Thread.Sleep(2000); OnStatusMessage("Attempting command channel connection to publisher..."); m_commandChannelConnectionAttempts++; } private void m_commandChannel_SendDataException(object sender, EventArgs<Exception> e) { Exception ex = e.Argument; if (!HandleSocketException(ex as System.Net.Sockets.SocketException) && !(ex is ObjectDisposedException)) OnProcessException(new InvalidOperationException("Data subscriber encountered an exception while sending command channel data to publisher connection: " + ex.Message, ex)); } private void m_commandChannel_ReceiveData(object sender, EventArgs<int> e) { try { byte[] buffer; int length = e.Argument; m_lastBytesReceived = length; buffer = BufferPool.TakeBuffer(length); try { m_commandChannel.Read(buffer, 0, length); ProcessServerResponse(buffer, length); } finally { if (buffer != null) BufferPool.ReturnBuffer(buffer); } } catch (Exception ex) { OnProcessException(ex); } } private void m_commandChannel_ReceiveDataException(object sender, EventArgs<Exception> e) { Exception ex = e.Argument; if (!HandleSocketException(ex as System.Net.Sockets.SocketException) && !(ex is ObjectDisposedException)) OnProcessException(new InvalidOperationException("Data subscriber encountered an exception while receiving command channel data from publisher connection: " + ex.Message, ex)); } #endregion #region [ Data Channel Event Handlers ] private void m_dataChannel_ConnectionException(object sender, EventArgs<Exception> e) { Exception ex = e.Argument; OnProcessException(new InvalidOperationException("Data subscriber encountered an exception while attempting to establish UDP data channel connection: " + ex.Message, ex)); } private void m_dataChannel_ConnectionAttempt(object sender, EventArgs e) { // Inject a short delay between multiple connection attempts if (m_dataChannelConnectionAttempts > 0) Thread.Sleep(2000); OnStatusMessage("Attempting to establish data channel connection to publisher..."); m_dataChannelConnectionAttempts++; } private void m_dataChannel_ReceiveData(object sender, EventArgs<int> e) { try { byte[] buffer; int length = e.Argument; m_lastBytesReceived = length; buffer = BufferPool.TakeBuffer(length); try { m_dataChannel.Read(buffer, 0, length); ProcessServerResponse(buffer, length); } finally { if (buffer != null) BufferPool.ReturnBuffer(buffer); } } catch (Exception ex) { OnProcessException(ex); } } private void m_dataChannel_ReceiveDataException(object sender, EventArgs<Exception> e) { Exception ex = e.Argument; if (!HandleSocketException(ex as System.Net.Sockets.SocketException) && !(ex is ObjectDisposedException)) OnProcessException(new InvalidOperationException("Data subscriber encountered an exception while receiving UDP data from publisher connection: " + ex.Message, ex)); } #endregion #endregion } }
53.821223
485
0.575109
[ "MIT" ]
GridProtectionAlliance/gsf
Source/Libraries/GSF.Unity/GSF.TimeSeries/Transport/DataSubscriber.cs
139,992
C#
using System.Linq; using Microsoft.VisualStudio.TestTools.UnitTesting; using DpdtInject.Injector.Src.Excp; using DpdtInject.Injector.Src; namespace DpdtInject.Tests.NonGeneric.IncorrectRequest { public partial class NonGenericIncorrectRequest_Cluster : DefaultCluster { [DpdtBindingMethod] public void BindMethod() { Bind<IA>() .To<A>() .WithSingletonScope() ; } public class NonGenericIncorrectRequest_ClusterTester { public void PerformClusterTesting() { var cluster = new FakeCluster<NonGenericIncorrectRequest_Cluster>( null ); try { var r = cluster.Get(typeof(IB)); Assert.Fail("test fails, this line should never be executed"); } catch (DpdtException excp) when (excp.Type == DpdtExceptionTypeEnum.NoBindingAvailable && excp.AdditionalArgument == typeof(IB).FullName) { //it's ok } try { var rs = cluster.GetAll(typeof(IB)).ToList(); Assert.Fail("test fails, this line should never be executed"); } catch (DpdtException excp) when (excp.Type == DpdtExceptionTypeEnum.NoBindingAvailable && excp.AdditionalArgument == typeof(IB).FullName) { //it's ok } } } } public interface IA { } public class A : IA { } public interface IB { } }
26.208955
130
0.499431
[ "MIT" ]
lsoft/DpDtInject
DpdtInject.Tests/NonGeneric/IncorrectRequest/NonGenericIncorrectRequest_Cluster.cs
1,758
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Components; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.HttpsPolicy; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Blazor.SSBDemo.Data; namespace Blazor.SSBDemo { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940 public void ConfigureServices(IServiceCollection services) { services.AddRazorPages(); services.AddServerSideBlazor(); services.AddSingleton<WeatherForecastService>(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Error"); // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. app.UseHsts(); } app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseRouting(); app.UseEndpoints(endpoints => { endpoints.MapBlazorHub(); endpoints.MapFallbackToPage("/_Host"); }); } } }
32.147541
143
0.63539
[ "MIT" ]
biishan/Blazor.GridLoading
demo/Blazor.SSBDemo/Startup.cs
1,961
C#
using System; using System.Drawing; namespace Aigamo.Saruhashi { public abstract class ButtonBase : Control { [Flags] private enum States { MouseOver = 0x0001, MouseDown = 0x0002, MousePressed = 0x0004, InButtonUp = 0x0008, CurrentlyAnimating = 0x0010, AutoEllipsis = 0x0020, IsDefault = 0x0040, UseMnemonic = 0x0080, ShowToolTip = 0x0100, } private IButtonRenderer? _buttonRenderer; private States _state; // OPTIMIZE public IButtonRenderer ButtonRenderer { get => _buttonRenderer ??= new ButtonRenderer(); set => _buttonRenderer = value; } protected override Size DefaultSize => new Size(75, 23); internal bool MouseIsPressed => _state.HasFlag(States.MousePressed); internal bool MouseIsDown => _state.HasFlag(States.MouseDown); internal bool MouseIsOver => _state.HasFlag(States.MouseOver); protected override void OnLostFocus(EventArgs e) { base.OnLostFocus(e); _state &= ~States.MouseDown; } protected override void OnMouseDown(MouseEventArgs e) { base.OnMouseDown(e); if (e.Button == MouseButtons.Left) { _state |= States.MouseDown; _state |= States.MousePressed; } } protected override void OnMouseEnter(EventArgs e) { base.OnMouseEnter(e); _state |= States.MouseOver; } protected override void OnMouseLeave(EventArgs e) { base.OnMouseLeave(e); _state &= ~States.MouseOver; } protected override void OnMouseMove(MouseEventArgs e) { base.OnMouseMove(e); if (MouseIsPressed) { if (Capture && ClientRectangle.Contains(e.Location)) _state |= States.MouseDown; else _state &= ~States.MouseDown; } } protected override void OnMouseUp(MouseEventArgs e) { base.OnMouseUp(e); _state &= ~States.MousePressed; _state &= ~States.MouseDown; } } }
20.164835
70
0.691553
[ "MIT" ]
ycanardeau/Saruhashi
Aigamo.Saruhashi/ButtonBase.cs
1,837
C#
using System; using NetRuntimeSystem = System; using System.Runtime.InteropServices; using System.ComponentModel; using System.Runtime.CompilerServices; using System.Reflection; using System.Collections.Generic; using NetOffice; namespace NetOffice.VisioApi { ///<summary> /// Interface LPVISIOMENUITEM /// SupportByVersion Visio, 11,12,14,15,16 ///</summary> [SupportByVersionAttribute("Visio", 11,12,14,15,16)] [EntityTypeAttribute(EntityType.IsInterface)] public class LPVISIOMENUITEM : COMObject { #pragma warning disable #region Type Information private static Type _type; [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public static Type LateBindingApiWrapperType { get { if (null == _type) _type = typeof(LPVISIOMENUITEM); return _type; } } #endregion #region Construction ///<param name="factory">current used factory core</param> ///<param name="parentObject">object there has created the proxy</param> ///<param name="comProxy">inner wrapped COM proxy</param> public LPVISIOMENUITEM(Core factory, ICOMObject parentObject, object comProxy) : base(factory, parentObject, comProxy) { } ///<param name="parentObject">object there has created the proxy</param> ///<param name="comProxy">inner wrapped COM proxy</param> [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public LPVISIOMENUITEM(ICOMObject parentObject, object comProxy) : base(parentObject, comProxy) { } ///<param name="factory">current used factory core</param> ///<param name="parentObject">object there has created the proxy</param> ///<param name="comProxy">inner wrapped COM proxy</param> ///<param name="comProxyType">Type of inner wrapped COM proxy"</param> [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public LPVISIOMENUITEM(Core factory, ICOMObject parentObject, object comProxy, NetRuntimeSystem.Type comProxyType) : base(factory, parentObject, comProxy, comProxyType) { } ///<param name="parentObject">object there has created the proxy</param> ///<param name="comProxy">inner wrapped COM proxy</param> ///<param name="comProxyType">Type of inner wrapped COM proxy"</param> [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public LPVISIOMENUITEM(ICOMObject parentObject, object comProxy, NetRuntimeSystem.Type comProxyType) : base(parentObject, comProxy, comProxyType) { } ///<param name="replacedObject">object to replaced. replacedObject are not usable after this action</param> [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public LPVISIOMENUITEM(ICOMObject replacedObject) : base(replacedObject) { } [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public LPVISIOMENUITEM() : base() { } /// <param name="progId">registered ProgID</param> [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public LPVISIOMENUITEM(string progId) : base(progId) { } #endregion #region Properties /// <summary> /// SupportByVersion Visio 11, 12, 14, 15, 16 /// Get /// </summary> [SupportByVersionAttribute("Visio", 11,12,14,15,16)] [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public string Default { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "Default", paramsArray); return NetRuntimeSystem.Convert.ToString(returnItem); } } /// <summary> /// SupportByVersion Visio 11, 12, 14, 15, 16 /// Get /// </summary> [SupportByVersionAttribute("Visio", 11,12,14,15,16)] public Int32 Index { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "Index", paramsArray); return NetRuntimeSystem.Convert.ToInt32(returnItem); } } /// <summary> /// SupportByVersion Visio 11, 12, 14, 15, 16 /// Get /// </summary> [SupportByVersionAttribute("Visio", 11,12,14,15,16)] public NetOffice.VisioApi.IVMenuItems MenuItems { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "MenuItems", paramsArray); NetOffice.VisioApi.IVMenuItems newObject = Factory.CreateObjectFromComProxy(this,returnItem) as NetOffice.VisioApi.IVMenuItems; return newObject; } } /// <summary> /// SupportByVersion Visio 11, 12, 14, 15, 16 /// Get /// </summary> [SupportByVersionAttribute("Visio", 11,12,14,15,16)] public NetOffice.VisioApi.IVMenuItems Parent { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "Parent", paramsArray); NetOffice.VisioApi.IVMenuItems newObject = Factory.CreateObjectFromComProxy(this,returnItem) as NetOffice.VisioApi.IVMenuItems; return newObject; } } /// <summary> /// SupportByVersion Visio 11, 12, 14, 15, 16 /// Get/Set /// </summary> [SupportByVersionAttribute("Visio", 11,12,14,15,16)] public Int16 CmdNum { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "CmdNum", paramsArray); return NetRuntimeSystem.Convert.ToInt16(returnItem); } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "CmdNum", paramsArray); } } /// <summary> /// SupportByVersion Visio 11, 12, 14, 15, 16 /// Get/Set /// </summary> [SupportByVersionAttribute("Visio", 11,12,14,15,16)] [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public Int16 HelpContextID { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "HelpContextID", paramsArray); return NetRuntimeSystem.Convert.ToInt16(returnItem); } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "HelpContextID", paramsArray); } } /// <summary> /// SupportByVersion Visio 11, 12, 14, 15, 16 /// Get /// </summary> [SupportByVersionAttribute("Visio", 11,12,14,15,16)] [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public Int16 IsSeparator { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "IsSeparator", paramsArray); return NetRuntimeSystem.Convert.ToInt16(returnItem); } } /// <summary> /// SupportByVersion Visio 11, 12, 14, 15, 16 /// Get /// </summary> [SupportByVersionAttribute("Visio", 11,12,14,15,16)] public Int16 IsHierarchical { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "IsHierarchical", paramsArray); return NetRuntimeSystem.Convert.ToInt16(returnItem); } } /// <summary> /// SupportByVersion Visio 11, 12, 14, 15, 16 /// Get/Set /// </summary> [SupportByVersionAttribute("Visio", 11,12,14,15,16)] public string Caption { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "Caption", paramsArray); return NetRuntimeSystem.Convert.ToString(returnItem); } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "Caption", paramsArray); } } /// <summary> /// SupportByVersion Visio 11, 12, 14, 15, 16 /// Get/Set /// </summary> [SupportByVersionAttribute("Visio", 11,12,14,15,16)] public string ActionText { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "ActionText", paramsArray); return NetRuntimeSystem.Convert.ToString(returnItem); } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "ActionText", paramsArray); } } /// <summary> /// SupportByVersion Visio 11, 12, 14, 15, 16 /// Get/Set /// </summary> [SupportByVersionAttribute("Visio", 11,12,14,15,16)] [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public string MiniHelp { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "MiniHelp", paramsArray); return NetRuntimeSystem.Convert.ToString(returnItem); } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "MiniHelp", paramsArray); } } /// <summary> /// SupportByVersion Visio 11, 12, 14, 15, 16 /// Get/Set /// </summary> [SupportByVersionAttribute("Visio", 11,12,14,15,16)] public string AddOnName { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "AddOnName", paramsArray); return NetRuntimeSystem.Convert.ToString(returnItem); } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "AddOnName", paramsArray); } } /// <summary> /// SupportByVersion Visio 11, 12, 14, 15, 16 /// Get/Set /// </summary> [SupportByVersionAttribute("Visio", 11,12,14,15,16)] public string AddOnArgs { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "AddOnArgs", paramsArray); return NetRuntimeSystem.Convert.ToString(returnItem); } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "AddOnArgs", paramsArray); } } /// <summary> /// SupportByVersion Visio 11, 12, 14, 15, 16 /// Get/Set /// </summary> [SupportByVersionAttribute("Visio", 11,12,14,15,16)] [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public string HelpFile { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "HelpFile", paramsArray); return NetRuntimeSystem.Convert.ToString(returnItem); } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "HelpFile", paramsArray); } } /// <summary> /// SupportByVersion Visio 11, 12, 14, 15, 16 /// Get/Set /// </summary> [SupportByVersionAttribute("Visio", 11,12,14,15,16)] public Int16 CntrlType { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "CntrlType", paramsArray); return NetRuntimeSystem.Convert.ToInt16(returnItem); } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "CntrlType", paramsArray); } } /// <summary> /// SupportByVersion Visio 11, 12, 14, 15, 16 /// Get/Set /// </summary> [SupportByVersionAttribute("Visio", 11,12,14,15,16)] [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public Int16 CntrlID { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "CntrlID", paramsArray); return NetRuntimeSystem.Convert.ToInt16(returnItem); } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "CntrlID", paramsArray); } } /// <summary> /// SupportByVersion Visio 11, 12, 14, 15, 16 /// Get/Set /// </summary> [SupportByVersionAttribute("Visio", 11,12,14,15,16)] public Int16 TypeSpecific1 { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "TypeSpecific1", paramsArray); return NetRuntimeSystem.Convert.ToInt16(returnItem); } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "TypeSpecific1", paramsArray); } } /// <summary> /// SupportByVersion Visio 11, 12, 14, 15, 16 /// Get/Set /// </summary> [SupportByVersionAttribute("Visio", 11,12,14,15,16)] [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public Int16 Priority { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "Priority", paramsArray); return NetRuntimeSystem.Convert.ToInt16(returnItem); } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "Priority", paramsArray); } } /// <summary> /// SupportByVersion Visio 11, 12, 14, 15, 16 /// Get/Set /// </summary> [SupportByVersionAttribute("Visio", 11,12,14,15,16)] [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public Int16 Spacing { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "Spacing", paramsArray); return NetRuntimeSystem.Convert.ToInt16(returnItem); } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "Spacing", paramsArray); } } /// <summary> /// SupportByVersion Visio 11, 12, 14, 15, 16 /// Get/Set /// </summary> [SupportByVersionAttribute("Visio", 11,12,14,15,16)] public Int16 TypeSpecific2 { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "TypeSpecific2", paramsArray); return NetRuntimeSystem.Convert.ToInt16(returnItem); } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "TypeSpecific2", paramsArray); } } /// <summary> /// SupportByVersion Visio 11, 12, 14, 15, 16 /// Get /// </summary> [SupportByVersionAttribute("Visio", 11,12,14,15,16)] public bool BuiltIn { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "BuiltIn", paramsArray); return NetRuntimeSystem.Convert.ToBoolean(returnItem); } } /// <summary> /// SupportByVersion Visio 11, 12, 14, 15, 16 /// Get/Set /// </summary> [SupportByVersionAttribute("Visio", 11,12,14,15,16)] public bool Enabled { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "Enabled", paramsArray); return NetRuntimeSystem.Convert.ToBoolean(returnItem); } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "Enabled", paramsArray); } } /// <summary> /// SupportByVersion Visio 11, 12, 14, 15, 16 /// Get/Set /// </summary> [SupportByVersionAttribute("Visio", 11,12,14,15,16)] public Int16 FaceID { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "FaceID", paramsArray); return NetRuntimeSystem.Convert.ToInt16(returnItem); } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "FaceID", paramsArray); } } /// <summary> /// SupportByVersion Visio 11, 12, 14, 15, 16 /// Get/Set /// </summary> [SupportByVersionAttribute("Visio", 11,12,14,15,16)] public Int16 State { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "State", paramsArray); return NetRuntimeSystem.Convert.ToInt16(returnItem); } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "State", paramsArray); } } /// <summary> /// SupportByVersion Visio 11, 12, 14, 15, 16 /// Get/Set /// </summary> [SupportByVersionAttribute("Visio", 11,12,14,15,16)] public Int16 Style { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "Style", paramsArray); return NetRuntimeSystem.Convert.ToInt16(returnItem); } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "Style", paramsArray); } } /// <summary> /// SupportByVersion Visio 11, 12, 14, 15, 16 /// Get/Set /// </summary> [SupportByVersionAttribute("Visio", 11,12,14,15,16)] public bool Visible { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "Visible", paramsArray); return NetRuntimeSystem.Convert.ToBoolean(returnItem); } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "Visible", paramsArray); } } /// <summary> /// SupportByVersion Visio 11, 12, 14, 15, 16 /// Get/Set /// </summary> [SupportByVersionAttribute("Visio", 11,12,14,15,16)] public Int16 Width { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "Width", paramsArray); return NetRuntimeSystem.Convert.ToInt16(returnItem); } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "Width", paramsArray); } } /// <summary> /// SupportByVersion Visio 11, 12, 14, 15, 16 /// Get/Set /// </summary> [SupportByVersionAttribute("Visio", 11,12,14,15,16)] public Int16 PaletteWidth { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "PaletteWidth", paramsArray); return NetRuntimeSystem.Convert.ToInt16(returnItem); } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "PaletteWidth", paramsArray); } } /// <summary> /// SupportByVersion Visio 11, 12, 14, 15, 16 /// Get/Set /// </summary> [SupportByVersionAttribute("Visio", 11,12,14,15,16)] public bool BeginGroup { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "BeginGroup", paramsArray); return NetRuntimeSystem.Convert.ToBoolean(returnItem); } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "BeginGroup", paramsArray); } } #endregion #region Methods /// <summary> /// SupportByVersion Visio 11, 12, 14, 15, 16 /// /// </summary> [SupportByVersionAttribute("Visio", 11,12,14,15,16)] public void Delete() { object[] paramsArray = null; Invoker.Method(this, "Delete", paramsArray); } /// <summary> /// SupportByVersion Visio 11, 12, 14, 15, 16 /// /// </summary> /// <param name="iconFileName">string IconFileName</param> [SupportByVersionAttribute("Visio", 11,12,14,15,16)] public void IconFileName(string iconFileName) { object[] paramsArray = Invoker.ValidateParamsArray(iconFileName); Invoker.Method(this, "IconFileName", paramsArray); } #endregion #pragma warning restore } }
27.008837
170
0.670811
[ "MIT" ]
brunobola/NetOffice
Source/Visio/Interfaces/LPVISIOMENUITEM.cs
18,341
C#
using Android.Views; namespace Forms9Patch.Droid { internal static class MeasureSpecFactory { public static int GetSize(int measureSpec) { const int modeMask = 0x3 << 30; return measureSpec & ~modeMask; } // Literally does the same thing as the android code, 1000x faster because no bridge cross // benchmarked by calling 1,000,000 times in a loop on actual device public static int MakeMeasureSpec(int size, MeasureSpecMode mode) { return size + (int)mode; } } }
24.7
92
0.726721
[ "MIT" ]
Mourad57/Forms9Patch
Forms9Patch/Forms9Patch.Droid/Extensions/MeasureSpecFactory.cs
496
C#
using System; using Game.Services.EventProcessor.Core.Entities.Exceptions; using MicroBootstrap.Types; namespace Game.Services.EventProcessor.Core.Entities { public class GameEventSource : IIdentifiable<Guid> { public Guid Id { get; set; } public bool IsWin { get; set; } public int Score { get; set; } private GameEventSource() { } public GameEventSource(Guid id, bool isWin, int score) { if (id == Guid.Empty) { throw new InvalidGameEventSourceIdException(); } if (score < 0) { throw new InvalidGameEventSourceScoreException(); } Id = id; Score = score; IsWin = isWin; } // for new resource we use static factory method and once we fetch data from database and we want to restore that as a aggregate // we will use aggregate constructor and we don't have events in constructor public static GameEventSource Create(Guid id, bool isWin, int score) { var gameEventSource = new GameEventSource(id, isWin, score); //calling our internal constructor //we can add events to our domain model for event sourcing here //gameEventSource.AddEvent(new GameEventSourceCreated(gameEventSource)); return gameEventSource; } } }
31.173913
137
0.601813
[ "MIT" ]
GhalamborM/MicroBootstrap
samples/Game-Microservices-Sample/Game.Services.EventProcessor/src/Game.Services.EventProcessor.Core/Entities/GameEventSource.cs
1,434
C#
using CWTNet; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CWT_dev_server.CWTNet { public class PacketBase : IPacket { public virtual uint GetPacketOpcode() { return uint.MaxValue; } public byte[] Serialize() { using (var ms = new MemoryStream()) { var wtr = new BinaryWriter(ms); Serialize(ref wtr); wtr.Flush(); ms.Flush(); return ms.GetBuffer(); } } public void Deserialize(byte[] data) { using (var ms = new MemoryStream(data)) { var rdr = new BinaryReader(ms); Deserialize(ref rdr); rdr.Close(); } } public virtual void Serialize(ref BinaryWriter wtr) { throw new NotImplementedException(); } public virtual void Deserialize(ref BinaryReader rdr) { throw new NotImplementedException(); } } }
22.09434
61
0.510675
[ "MIT" ]
CWTesseract/CWT_dev_server
CWT_dev_server/CWTNet/PacketBase.cs
1,173
C#
using System.Collections.Generic; namespace dto.endpoint.marketdetails.v2 { public class DepositBanding{ ///<Summary> ///Boundaries ///</Summary> public List<string> boundaries { get; set; } ///<Summary> ///Margin factor ///</Summary> public List<string> factors { get; set; } ///<Summary> ///Currency ///</Summary> public string currency { get; set; } } }
17.666667
45
0.668464
[ "BSD-3-Clause" ]
teebeast/ig-webapi-dotnet-sample
IGWebApiClient/Model/dto/endpoint/marketdetails/v2/DepositBanding.cs
371
C#
using System; using Newtonsoft.Json; namespace Essensoft.AspNetCore.Payment.Alipay.Domain { /// <summary> /// MallCardUpdate Data Structure. /// </summary> [Serializable] public class MallCardUpdate : AlipayObject { /// <summary> /// 资金卡余额,单位:元,精确到小数点后两位。 /// </summary> [JsonProperty("balance")] public string Balance { get; set; } /// <summary> /// 会员业务卡号 说明: 1、开卡成功后返回该参数,需要保存留用; 2、开卡/更新/删卡/查询卡接口请求中都需要传该参数; /// </summary> [JsonProperty("biz_card_no")] public string BizCardNo { get; set; } /// <summary> /// 商户外部会员卡卡号 说明: 1、会员卡开卡接口,如果卡类型为外部会员卡,请求中则必须提供该参数; 2、更新、查询、删除等接口,请求中则不需要提供该参数值; /// </summary> [JsonProperty("external_card_no")] public string ExternalCardNo { get; set; } /// <summary> /// 会员卡等级(由商户自定义,并可以在卡模板创建时,定义等级信息) /// </summary> [JsonProperty("level")] public string Level { get; set; } /// <summary> /// 会员卡积分,积分必须为数字型 /// </summary> [JsonProperty("point")] public long Point { get; set; } } }
26.976744
95
0.549138
[ "MIT" ]
gebiWangshushu/payment
src/Essensoft.AspNetCore.Payment.Alipay/Domain/MallCardUpdate.cs
1,540
C#
// Copyright (c) Six Labors and contributors. // Licensed under the Apache License, Version 2.0. using System; using System.Buffers.Binary; namespace SixLabors.ImageSharp.Formats.Gif { internal readonly struct GifNetscapeLoopingApplicationExtension : IGifExtension { public GifNetscapeLoopingApplicationExtension(ushort repeatCount) => this.RepeatCount = repeatCount; public byte Label => GifConstants.ApplicationExtensionLabel; /// <summary> /// Gets the repeat count. /// 0 means loop indefinitely. Count is set as play n + 1 times. /// </summary> public ushort RepeatCount { get; } public static GifNetscapeLoopingApplicationExtension Parse(ReadOnlySpan<byte> buffer) { ushort repeatCount = BinaryPrimitives.ReadUInt16LittleEndian(buffer.Slice(0, 2)); return new GifNetscapeLoopingApplicationExtension(repeatCount); } public int WriteTo(Span<byte> buffer) { buffer[0] = GifConstants.ApplicationBlockSize; // Write NETSCAPE2.0 GifConstants.NetscapeApplicationIdentificationBytes.AsSpan().CopyTo(buffer.Slice(1, 11)); // Application Data ---- buffer[12] = 3; // Application block length (always 3) buffer[13] = 1; // Data sub-block indentity (always 1) // 0 means loop indefinitely. Count is set as play n + 1 times. BinaryPrimitives.WriteUInt16LittleEndian(buffer.Slice(14, 2), this.RepeatCount); return 16; // Length - Introducer + Label + Terminator. } } }
36
108
0.657407
[ "Apache-2.0" ]
Davidsv/ImageSharp
src/ImageSharp/Formats/Gif/Sections/GifNetscapeLoopingApplicationExtension.cs
1,622
C#
using Microsoft.VisualStudio.TestTools.UnitTesting; using System; using System.Collections.Generic; using Xyaneon.Bioinformatics.FASTA.ActualSequences; using Xyaneon.Bioinformatics.FASTA.Identifiers; using System.Linq; namespace Xyaneon.Bioinformatics.FASTA.Test { [TestClass] public class SequenceTest { [TestMethod] [ExpectedException(typeof(ArgumentNullException))] public void Constructor_ShouldRejectNullHeader() { _ = new Sequence(null, NucleicAcidSequence.Parse("ATCG")); } [TestMethod] [ExpectedException(typeof(ArgumentNullException))] public void Constructor_ShouldRejectNullData() { var identifier = new LocalIdentifier("value"); var header = new Header(identifier); _ = new Sequence(header, null); } [TestMethod] [ExpectedException(typeof(ArgumentNullException))] public void Parse_ShouldRejectNullString() { _ = Sequence.Parse((string)null); } [TestMethod] [ExpectedException(typeof(ArgumentNullException))] public void Parse_ShouldRejectNullLinesCollection() { _ = Sequence.Parse((IEnumerable<string>)null); } [TestMethod] public void Parse_ShouldProduceExpectedOutputForString() { string inputString = ">lcl|123" + Environment.NewLine + "ATCG" + Environment.NewLine + "AAAA"; Sequence sequence = Sequence.Parse(inputString); Assert.IsNotNull(sequence); Header header = sequence.Header; Assert.IsNotNull(header); Assert.AreEqual(1, header.Items.Count); LocalIdentifier identifier = header.Items[0] as LocalIdentifier; Assert.IsNotNull(identifier); Assert.AreEqual("lcl", identifier.Code); Assert.AreEqual("123", identifier.Value); NucleicAcidSequence data = (NucleicAcidSequence)sequence.Data; Assert.AreEqual("ATCGAAAA", data.Characters); } [TestMethod] [ExpectedException(typeof(FormatException))] public void Parse_ShouldRejectMissingHeaderForString() { string inputString = "ATCG" + Environment.NewLine + "AAAA"; _ = Sequence.Parse(inputString); } [TestMethod] [ExpectedException(typeof(FormatException))] public void Parse_ShouldRejectMissingSequenceForString() { string inputString = ">lcl|123"; _ = Sequence.Parse(inputString); } [TestMethod] public void Parse_ShouldProduceExpectedOutputForLines() { IEnumerable<string> inputLines = new string[] { ">lcl|123", "ATCG", "AAAA" }; Sequence sequence = Sequence.Parse(inputLines); Assert.IsNotNull(sequence); Header header = sequence.Header; Assert.IsNotNull(header); Assert.AreEqual(1, header.Items.Count); LocalIdentifier identifier = header.Items[0] as LocalIdentifier; Assert.IsNotNull(identifier); Assert.AreEqual("lcl", identifier.Code); Assert.AreEqual("123", identifier.Value); NucleicAcidSequence data = (NucleicAcidSequence)sequence.Data; Assert.AreEqual("ATCGAAAA", data.Characters); } [TestMethod] [ExpectedException(typeof(FormatException))] public void Parse_ShouldRejectMissingHeaderForLines() { IEnumerable<string> inputLines = new string[] { "ATCG", "AAAA" }; _ = Sequence.Parse(inputLines); } [TestMethod] [ExpectedException(typeof(FormatException))] public void Parse_ShouldRejectMissingSequenceForLines() { IEnumerable<string> inputLines = new string[] { ">lcl|123" }; _ = Sequence.Parse(inputLines); } [TestMethod] [ExpectedException(typeof(ArgumentNullException))] public void ParseMultiple_ShouldRejectNullLinesCollection() { _ = Sequence.ParseMultiple((IEnumerable<string>)null); } [TestMethod] [ExpectedException(typeof(ArgumentOutOfRangeException))] public void ToInterleavedLines_ShouldRejectNegativeLineLength() { string inputSequence = "MDSKGSSQKGSRLLLLLVVSNLLLCQGVVSTPVCPNGPGNCQVSLRDLFDRAVMVSHYIHDLSS" + "EMFNEFDKRYAQGKGFITMALNSCHTSSLPTPEDKEQAQQTHHEVLMSLILGLLRSWNDPLYHL"; Identifier identifier = new LocalIdentifier("123"); Header header = new Header(identifier); IActualSequence sequence = AminoAcidSequence.Parse(inputSequence); var singleFASTAFileData = new Sequence(header, sequence); _ = singleFASTAFileData.ToInterleavedLines(-1).ToList(); } [TestMethod] [ExpectedException(typeof(ArgumentOutOfRangeException))] public void ToInterleavedLines_ShouldRejectLineLengthOfZero() { string inputSequence = "MDSKGSSQKGSRLLLLLVVSNLLLCQGVVSTPVCPNGPGNCQVSLRDLFDRAVMVSHYIHDLSS" + "EMFNEFDKRYAQGKGFITMALNSCHTSSLPTPEDKEQAQQTHHEVLMSLILGLLRSWNDPLYHL"; Identifier identifier = new LocalIdentifier("123"); Header header = new Header(identifier); IActualSequence sequence = AminoAcidSequence.Parse(inputSequence); var singleFASTAFileData = new Sequence(header, sequence); _ = singleFASTAFileData.ToInterleavedLines(0).ToList(); } [TestMethod] public void ToInterleavedLines_ShouldProduceExpectedOutputForDefaultLineLength() { string inputSequence = "MDSKGSSQKGSRLLLLLVVSNLLLCQGVVSTPVCPNGPGNCQVSLRDLFDRAVMVSHYIHDLSS" + "EMFNEFDKRYAQGKGFITMALNSCHTSSLPTPEDKEQAQQTHHEVLMSLILGLLRSWNDPLYHL"; IEnumerable<string> expectedOutputLines = new string[] { ">lcl|123", "MDSKGSSQKGSRLLLLLVVSNLLLCQGVVSTPVCPNGPGNCQVSLRDLFDRAVMVSHYIHDLSSEMFNEFDKRYAQGKGF", "ITMALNSCHTSSLPTPEDKEQAQQTHHEVLMSLILGLLRSWNDPLYHL" }; Identifier identifier = new LocalIdentifier("123"); Header header = new Header(identifier); IActualSequence sequence = AminoAcidSequence.Parse(inputSequence); var singleFASTAFileData = new Sequence(header, sequence); IEnumerable<string> actualOutputLines = singleFASTAFileData.ToInterleavedLines(); CollectionAssert.AreEqual(expectedOutputLines.ToList(), actualOutputLines.ToList()); } [TestMethod] public void ToInterleavedLines_ShouldProduceExpectedOutputForNonDefaultLineLength() { string inputSequence = "MDSKGSSQKGSRLLLLLVVSNLLLCQGVVSTPVCPNGPGNCQVSLRDLFDRAVMVSHYIHDLSS" + "EMFNEFDKRYAQGKGFITMALNSCHTSSLPTPEDKEQAQQTHHEVLMSLILGLLRSWNDPLYHL"; IEnumerable<string> expectedOutputLines = new string[] { ">lcl|123", "MDSKGSSQ", "KGSRLLLL", "LVVSNLLL", "CQGVVSTP", "VCPNGPGN", "CQVSLRDL", "FDRAVMVS", "HYIHDLSS", "EMFNEFDK", "RYAQGKGF", "ITMALNSC", "HTSSLPTP", "EDKEQAQQ", "THHEVLMS", "LILGLLRS", "WNDPLYHL" }; Identifier identifier = new LocalIdentifier("123"); Header header = new Header(identifier); IActualSequence sequence = AminoAcidSequence.Parse(inputSequence); var singleFASTAFileData = new Sequence(header, sequence); IEnumerable<string> actualOutputLines = singleFASTAFileData.ToInterleavedLines(8); CollectionAssert.AreEqual(expectedOutputLines.ToList(), actualOutputLines.ToList()); } [TestMethod] public void ToSequentialLines_ShouldProduceExpectedOutput() { string inputSequence = "MDSKGSSQKGSRLLLLLVVSNLLLCQGVVSTPVCPNGPGNCQVSLRDLFDRAVMVSHYIHDLSS" + "EMFNEFDKRYAQGKGFITMALNSCHTSSLPTPEDKEQAQQTHHEVLMSLILGLLRSWNDPLYHL"; IEnumerable<string> expectedOutputLines = new string[] { ">lcl|123", "MDSKGSSQKGSRLLLLLVVSNLLLCQGVVSTPVCPNGPGNCQVSLRDLFDRAVMVSHYIHDLSSEMFNEFDKRYAQGKGFITMALNSCHTSSLPTPEDKEQAQQTHHEVLMSLILGLLRSWNDPLYHL" }; Identifier identifier = new LocalIdentifier("123"); Header header = new Header(identifier); IActualSequence sequence = AminoAcidSequence.Parse(inputSequence); var singleFASTAFileData = new Sequence(header, sequence); IEnumerable<string> actualOutputLines = singleFASTAFileData.ToSequentialLines(); CollectionAssert.AreEqual(expectedOutputLines.ToList(), actualOutputLines.ToList()); } } }
38.1375
146
0.630285
[ "MIT" ]
Xyaneon/Xyaneon.Bioinformatics.FASTA
Xyaneon.Bioinformatics.FASTA.Test/SequenceTest.cs
9,155
C#
namespace Inboxy.Ticket.DataAccess { using Inboxy.Ticket.Domain; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Metadata.Builders; internal class TicketStatusMap: IEntityTypeConfiguration<TicketStatus> { public void Configure(EntityTypeBuilder<TicketStatus> builder) { builder.ToTable("TicketStatus", TicketDbContext.Schema); builder.HasKey(t => t.Id); } } }
30.533333
74
0.696507
[ "MIT" ]
niaher/inboxy
Inboxy.Ticket/DataAccess/TicketStatusMap.cs
460
C#
/* * Copyright (c) 2018 THL A29 Limited, a Tencent company. 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. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ namespace TencentCloud.Gse.V20191112.Models { using Newtonsoft.Json; using System.Collections.Generic; using TencentCloud.Common; public class DeleteAliasResponse : AbstractModel { /// <summary> /// 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 /// </summary> [JsonProperty("RequestId")] public string RequestId{ get; set; } /// <summary> /// For internal usage only. DO NOT USE IT. /// </summary> public override void ToMap(Dictionary<string, string> map, string prefix) { this.SetParamSimple(map, prefix + "RequestId", this.RequestId); } } }
30.159091
81
0.66315
[ "Apache-2.0" ]
TencentCloud/tencentcloud-sdk-dotnet
TencentCloud/Gse/V20191112/Models/DeleteAliasResponse.cs
1,385
C#
/* * Tencent is pleased to support the open source community by making xLua available. * Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved. * Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at * http://opensource.org/licenses/MIT * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using System; using LuaAPI = XLua.LuaDLL.Lua; namespace XLua { public partial class DelegateBridge : DelegateBridgeBase { public void Action() { #if THREAD_SAFE || HOTFIX_ENABLE lock(luaEnv.luaEnvLock) { #endif var L = luaEnv.L; var translator = luaEnv.translator; int oldTop = LuaAPI.lua_gettop(L); int errFunc = LuaAPI.load_error_func(L, luaEnv.errorFuncRef); LuaAPI.lua_getref(L, luaReference); int error = LuaAPI.lua_pcall(L, 0, 0, errFunc); if (error != 0) luaEnv.ThrowExceptionFromError(oldTop); LuaAPI.lua_settop(L, oldTop); #if THREAD_SAFE || HOTFIX_ENABLE } #endif } public void Action<T1>(T1 p1) { #if THREAD_SAFE || HOTFIX_ENABLE lock(luaEnv.luaEnvLock) { #endif var L = luaEnv.L; var translator = luaEnv.translator; int oldTop = LuaAPI.lua_gettop(L); int errFunc = LuaAPI.load_error_func(L, luaEnv.errorFuncRef); LuaAPI.lua_getref(L, luaReference); translator.PushByType(L, p1); int error = LuaAPI.lua_pcall(L, 1, 0, errFunc); if (error != 0) luaEnv.ThrowExceptionFromError(oldTop); LuaAPI.lua_settop(L, oldTop); #if THREAD_SAFE || HOTFIX_ENABLE } #endif } public void Action<T1, T2>(T1 p1, T2 p2) { #if THREAD_SAFE || HOTFIX_ENABLE lock(luaEnv.luaEnvLock) { #endif var L = luaEnv.L; var translator = luaEnv.translator; int oldTop = LuaAPI.lua_gettop(L); int errFunc = LuaAPI.load_error_func(L, luaEnv.errorFuncRef); LuaAPI.lua_getref(L, luaReference); translator.PushByType(L, p1); translator.PushByType(L, p2); int error = LuaAPI.lua_pcall(L, 2, 0, errFunc); if (error != 0) luaEnv.ThrowExceptionFromError(oldTop); LuaAPI.lua_settop(L, oldTop); #if THREAD_SAFE || HOTFIX_ENABLE } #endif } public void Action<T1, T2, T3>(T1 p1, T2 p2, T3 p3) { #if THREAD_SAFE || HOTFIX_ENABLE lock(luaEnv.luaEnvLock) { #endif var L = luaEnv.L; var translator = luaEnv.translator; int oldTop = LuaAPI.lua_gettop(L); int errFunc = LuaAPI.load_error_func(L, luaEnv.errorFuncRef); LuaAPI.lua_getref(L, luaReference); translator.PushByType(L, p1); translator.PushByType(L, p2); translator.PushByType(L, p3); int error = LuaAPI.lua_pcall(L, 3, 0, errFunc); if (error != 0) luaEnv.ThrowExceptionFromError(oldTop); LuaAPI.lua_settop(L, oldTop); #if THREAD_SAFE || HOTFIX_ENABLE } #endif } public void Action<T1, T2, T3, T4>(T1 p1, T2 p2, T3 p3, T4 p4) { #if THREAD_SAFE || HOTFIX_ENABLE lock(luaEnv.luaEnvLock) { #endif var L = luaEnv.L; var translator = luaEnv.translator; int oldTop = LuaAPI.lua_gettop(L); int errFunc = LuaAPI.load_error_func(L, luaEnv.errorFuncRef); LuaAPI.lua_getref(L, luaReference); translator.PushByType(L, p1); translator.PushByType(L, p2); translator.PushByType(L, p3); translator.PushByType(L, p4); int error = LuaAPI.lua_pcall(L, 4, 0, errFunc); if (error != 0) luaEnv.ThrowExceptionFromError(oldTop); LuaAPI.lua_settop(L, oldTop); #if THREAD_SAFE || HOTFIX_ENABLE } #endif } public TResult Func<TResult>() { #if THREAD_SAFE || HOTFIX_ENABLE lock(luaEnv.luaEnvLock) { #endif var L = luaEnv.L; var translator = luaEnv.translator; int oldTop = LuaAPI.lua_gettop(L); int errFunc = LuaAPI.load_error_func(L, luaEnv.errorFuncRef); LuaAPI.lua_getref(L, luaReference); int error = LuaAPI.lua_pcall(L, 0, 1, errFunc); if (error != 0) luaEnv.ThrowExceptionFromError(oldTop); TResult ret; try { translator.Get(L, -1, out ret); } catch (Exception e) { throw e; } finally { LuaAPI.lua_settop(L, oldTop); } return ret; #if THREAD_SAFE || HOTFIX_ENABLE } #endif } public TResult Func<T1, TResult>(T1 p1) { #if THREAD_SAFE || HOTFIX_ENABLE lock(luaEnv.luaEnvLock) { #endif var L = luaEnv.L; var translator = luaEnv.translator; int oldTop = LuaAPI.lua_gettop(L); int errFunc = LuaAPI.load_error_func(L, luaEnv.errorFuncRef); LuaAPI.lua_getref(L, luaReference); translator.PushByType(L, p1); int error = LuaAPI.lua_pcall(L, 1, 1, errFunc); if (error != 0) luaEnv.ThrowExceptionFromError(oldTop); TResult ret; try { translator.Get(L, -1, out ret); } catch (Exception e) { throw e; } finally { LuaAPI.lua_settop(L, oldTop); } return ret; #if THREAD_SAFE || HOTFIX_ENABLE } #endif } public TResult Func<T1, T2, TResult>(T1 p1, T2 p2) { #if THREAD_SAFE || HOTFIX_ENABLE lock(luaEnv.luaEnvLock) { #endif var L = luaEnv.L; var translator = luaEnv.translator; int oldTop = LuaAPI.lua_gettop(L); int errFunc = LuaAPI.load_error_func(L, luaEnv.errorFuncRef); LuaAPI.lua_getref(L, luaReference); translator.PushByType(L, p1); translator.PushByType(L, p2); int error = LuaAPI.lua_pcall(L, 2, 1, errFunc); if (error != 0) luaEnv.ThrowExceptionFromError(oldTop); TResult ret; try { translator.Get(L, -1, out ret); } catch (Exception e) { throw e; } finally { LuaAPI.lua_settop(L, oldTop); } return ret; #if THREAD_SAFE || HOTFIX_ENABLE } #endif } public TResult Func<T1, T2, T3, TResult>(T1 p1, T2 p2, T3 p3) { #if THREAD_SAFE || HOTFIX_ENABLE lock(luaEnv.luaEnvLock) { #endif var L = luaEnv.L; var translator = luaEnv.translator; int oldTop = LuaAPI.lua_gettop(L); int errFunc = LuaAPI.load_error_func(L, luaEnv.errorFuncRef); LuaAPI.lua_getref(L, luaReference); translator.PushByType(L, p1); translator.PushByType(L, p2); translator.PushByType(L, p3); int error = LuaAPI.lua_pcall(L, 3, 1, errFunc); if (error != 0) luaEnv.ThrowExceptionFromError(oldTop); TResult ret; try { translator.Get(L, -1, out ret); } catch (Exception e) { throw e; } finally { LuaAPI.lua_settop(L, oldTop); } return ret; #if THREAD_SAFE || HOTFIX_ENABLE } #endif } public TResult Func<T1, T2, T3, T4, TResult>(T1 p1, T2 p2, T3 p3, T4 p4) { #if THREAD_SAFE || HOTFIX_ENABLE lock(luaEnv.luaEnvLock) { #endif var L = luaEnv.L; var translator = luaEnv.translator; int oldTop = LuaAPI.lua_gettop(L); int errFunc = LuaAPI.load_error_func(L, luaEnv.errorFuncRef); LuaAPI.lua_getref(L, luaReference); translator.PushByType(L, p1); translator.PushByType(L, p2); translator.PushByType(L, p3); translator.PushByType(L, p4); int error = LuaAPI.lua_pcall(L, 4, 1, errFunc); if (error != 0) luaEnv.ThrowExceptionFromError(oldTop); TResult ret; try { translator.Get(L, -1, out ret); } catch (Exception e) { throw e; } finally { LuaAPI.lua_settop(L, oldTop); } return ret; #if THREAD_SAFE || HOTFIX_ENABLE } #endif } } }
32.042802
309
0.609472
[ "BSD-3-Clause" ]
Blavtes/xLua
Assets/XLua/Src/GenericDelegateBridge.cs
8,237
C#
using FinRust.Application.Common.Interfaces; using FinRust.Common; using FinRust.Domain.Common; using FinRust.Domain.Entities; using Microsoft.EntityFrameworkCore; using System.Threading; using System.Threading.Tasks; namespace FinRust.Persistence { public class FinRustDbContext : DbContext, IFinRustDbContext { private readonly ICurrentUserService _currentUserService; private readonly IDateTime _dateTime; public FinRustDbContext(DbContextOptions<FinRustDbContext> options) : base(options) { } public FinRustDbContext( DbContextOptions<FinRustDbContext> options, ICurrentUserService currentUserService, IDateTime dateTime) : base(options) { _currentUserService = currentUserService; _dateTime = dateTime; } public DbSet<Visualization> Visualizations { get; set; } public DbSet<Customer> Customers { get; set; } public override Task<int> SaveChangesAsync(CancellationToken cancellationToken = new CancellationToken()) { foreach (var entry in ChangeTracker.Entries<AuditableEntity>()) { switch (entry.State) { case EntityState.Added: entry.Entity.CreatedBy = _currentUserService.UserId; entry.Entity.Created = _dateTime.Now; break; case EntityState.Modified: entry.Entity.LastModifiedBy = _currentUserService.UserId; entry.Entity.LastModified = _dateTime.Now; break; } } return base.SaveChangesAsync(cancellationToken); } protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.ApplyConfigurationsFromAssembly(typeof(FinRustDbContext).Assembly); } } }
32.868852
113
0.612968
[ "MIT" ]
rapideinternet/finrust.api
Src/Persistence/FinRustDbContext.cs
2,007
C#
namespace DjvuNet.DjvuLibre { /// <summary> /// Various ways to render a page. /// </summary> public enum RenderMode { Color = 0, /* color page or stencil */ Black, /* stencil or color page */ ColorOnly, /* color page or fail */ MaskOnly, /* stencil or fail */ Background, /* color background layer */ Foreground, /* color foreground layer */ } }
28.6875
53
0.511983
[ "MIT" ]
ivs/DjvuNet
DjvuNet.DjvuLibre/Enums/RenderMode.cs
461
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging; namespace CrcDotNetCoreHomeworkWebApi { public class Program { public static void Main(string[] args) { CreateWebHostBuilder(args).Build().Run(); } public static IWebHostBuilder CreateWebHostBuilder(string[] args) => WebHost.CreateDefaultBuilder(args) .UseStartup<Startup>(); } }
24.92
76
0.701445
[ "MIT" ]
Badyl96/CrcDotNetCoreHomework
CrcDotNetCoreHomework/src/CrcDotNetCoreHomeworkWebApi/Program.cs
625
C#
using FluentAssertions; using NUnit.Framework; namespace PurityAnalyzer.Tests.IsPureAttributeOnClass { [TestFixture] public class PropertyInitializerTests { [Test] public void PurePropertyInitializerKeepsClassPure() { string code = @" using System; public class IsPureAttribute : Attribute { } [IsPure] public class Class1 { int property {get;} = AnotherClass.PureMethod(); } public static class AnotherClass { public static int PureMethod() => 1; } "; var dignostics = Utilities.RunPurityAnalyzer(code); dignostics.Length.Should().Be(0); } [Test] public void ImpurePropertyInitializerMakesClassImpure() { string code = @" using System; public class IsPureAttribute : Attribute { } [IsPure] public class Class1 { int property {get;} = AnotherClass.ImpureMethod(); } public static class AnotherClass { static int state; public static int ImpureMethod() => state++; } "; var dignostics = Utilities.RunPurityAnalyzer(code); dignostics.Length.Should().BePositive(); } [Test] public void PureStaticPropertyInitializerKeepsClassPure() { string code = @" using System; public class IsPureAttribute : Attribute { } [IsPure] public class Class1 { static int property {get;} = AnotherClass.PureMethod(); } public static class AnotherClass { public static int PureMethod() => 1; } "; var dignostics = Utilities.RunPurityAnalyzer(code); dignostics.Length.Should().Be(0); } [Test] public void ImpureStaticPropertyInitializerMakesClassImpure() { string code = @" using System; public class IsPureAttribute : Attribute { } [IsPure] public class Class1 { static int property {get;} = AnotherClass.ImpureMethod(); } public static class AnotherClass { static int state; public static int ImpureMethod() => state++; } "; var dignostics = Utilities.RunPurityAnalyzer(code); dignostics.Length.Should().BePositive(); } } }
17.536585
69
0.640705
[ "MIT" ]
seerek/PurityAnalyzer
PurityAnalyzer.Tests/IsPureAttributeOnClass/PropertyInitializerTests.cs
2,159
C#
using System; using Microsoft.VisualStudio.TestTools.UnitTesting; using TriggerCommandLineConsole; namespace TriggerCommandLineConsoleTest { [TestClass] public class JSONValueSwapperTest { private const string JSON = "{\"config_version\":\"4\",\"author\":\"AuthorValue\",\"modules\":{\"name\":\"testName\",\"geolocation\":{\"version\":\"2.0\"}}}"; [TestMethod] public void TestSwap() { string keyLevel1 = "config_version", newValueLevel1 = "5", keyLevel2 = "modules\\name", newValueLevel2 = "newName", keyLevel3 = "modules\\geolocation\\version", newValueLevel3 = "6.1", JSONAfter = "{\"config_version\":\"5\",\"author\":\"AuthorValue\",\"modules\":{\"name\":\"newName\",\"geolocation\":{\"version\":\"6.1\"}}}"; IJSONValueSwapper swapper = new JSONValueSwapper(JSON); swapper.Swap(keyLevel1, newValueLevel1); swapper.Swap(keyLevel2, newValueLevel2); swapper.Swap(keyLevel3, newValueLevel3); Assert.AreEqual(JSONAfter, swapper.ToString()); } [TestMethod] public void PrimativeTypeValuesAreNotWrappedInQuotes() { string jsonBefore = "{\"test_string\":\"beforeValue\",\"test_number\":1,\"test_bool\":true}", jsonAfter = "{\"test_string\":\"afterValue\",\"test_number\":2,\"test_bool\":false}"; IJSONValueSwapper swapper = new JSONValueSwapper(jsonBefore); swapper.Swap("test_string", "afterValue"); swapper.Swap("test_number", 2); swapper.Swap("test_bool", false); Assert.AreEqual(jsonAfter, swapper.ToString()); } [TestMethod] public void TestSwapFail() { IJSONValueSwapper swapper = new JSONValueSwapper(JSON); try { swapper.Swap("NoExist", "value"); Assert.Fail("Swapper should throw exception for undefined key"); } catch (ArgumentException) { } try { swapper.Swap("NoExist\\Another\\Level", "value"); Assert.Fail("Swapper should throw exception for undefined key"); } catch (ArgumentException) { } } } }
34.014085
166
0.549896
[ "Unlicense", "MIT" ]
scottiemc7/TriggerCommandLineBuild
TriggerCommandLineConsole/TriggerCommandLineConsoleTest/JSONValueSwapperTest.cs
2,417
C#
using System.Net.Http.Formatting; using System.Web.Http; using System.Web.Http.Cors; using Newtonsoft.Json.Serialization; namespace Guests.Api { public static class WebApiConfig { public static void Register(HttpConfiguration config) { var cors = new EnableCorsAttribute("http://localhost:9000", "*", "*"); config.EnableCors(cors); config.Formatters.Clear(); config.Formatters.Add(new JsonMediaTypeFormatter()); config.Formatters .JsonFormatter .SerializerSettings .ContractResolver = new CamelCasePropertyNamesContractResolver(); // Web API routes config.MapHttpAttributeRoutes(); config.Routes.MapHttpRoute( "DefaultApi", "api/{controller}/{id}", new {id = RouteParameter.Optional} ); } } }
22.969697
73
0.718997
[ "MIT" ]
alfonsovgs/hotel-management-system
src/Guests.Api/App_Start/WebApiConfig.cs
760
C#
/* * OpenAPI Petstore * * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://github.com/openapitools/openapi-generator.git */ using Xunit; using System; using System.Linq; using System.IO; using System.Collections.Generic; using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; using Newtonsoft.Json; namespace Org.OpenAPITools.Test.Model { /// <summary> /// Class for testing ChildCatAllOf /// </summary> /// <remarks> /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). /// Please update the test case below to test the model. /// </remarks> public class ChildCatAllOfTests : IDisposable { // TODO uncomment below to declare an instance variable for ChildCatAllOf //private ChildCatAllOf instance; public ChildCatAllOfTests() { // TODO uncomment below to create an instance of ChildCatAllOf //instance = new ChildCatAllOf(); } public void Dispose() { // Cleanup when everything is done. } /// <summary> /// Test an instance of ChildCatAllOf /// </summary> [Fact] public void ChildCatAllOfInstanceTest() { // TODO uncomment below to test "IsType" ChildCatAllOf //Assert.IsType<ChildCatAllOf>(instance); } /// <summary> /// Test the property 'Name' /// </summary> [Fact] public void NameTest() { // TODO unit test for the property 'Name' } /// <summary> /// Test the property 'PetType' /// </summary> [Fact] public void PetTypeTest() { // TODO unit test for the property 'PetType' } } }
25.848101
159
0.60431
[ "Apache-2.0" ]
0x0c/openapi-generator
samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/ChildCatAllOfTests.cs
2,042
C#
using UnityEngine; [CreateAssetMenu(fileName ="MeleeAttack", menuName = "Attacks/MeleeAttack")] public class MeleeAttack : Attack { [SerializeField] float knockbackY = 0.9f; [SerializeField] protected int damage = 1; [SerializeField] protected float damageDiameter = 1f; [SerializeField] protected float knockbackForce = 5f; public float DamageRadius => damageDiameter / 2; Vector2 origin; public override void Action(Vector2 origin, Vector2 target, Being owner) { LayerMask layermask = 0; if (owner.BeingType == BeingType.ENEMY) layermask = LayerMask.GetMask("Player"); else if (owner.BeingType == BeingType.PLAYER) layermask = LayerMask.GetMask("Enemy"); Collider2D hit = Physics2D.OverlapCircle(origin, DamageRadius, layermask); if (hit) { Vector2 knockbackDirection = ((Vector2)hit.transform.position - origin).normalized; if (knockbackDirection.y < knockbackY) knockbackDirection.y = knockbackY; hit.transform.GetComponent<Being>().GetDamage(damage, knockbackDirection * knockbackForce); } } }
37.774194
103
0.669513
[ "MIT" ]
Sunderer325/DigitalOxygenTest
Assets/Scripts/Core/Attacks/MeleeAttack.cs
1,173
C#
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ using System.Collections.Generic; using Aliyun.Acs.Core; using Aliyun.Acs.Core.Http; using Aliyun.Acs.Core.Transform; using Aliyun.Acs.Core.Utils; using Aliyun.Acs.CCC; using Aliyun.Acs.CCC.Transform; using Aliyun.Acs.CCC.Transform.V20170705; namespace Aliyun.Acs.CCC.Model.V20170705 { public class GetInstanceRequest : RpcAcsRequest<GetInstanceResponse> { public GetInstanceRequest() : base("CCC", "2017-07-05", "GetInstance") { if (this.GetType().GetProperty("ProductEndpointMap") != null && this.GetType().GetProperty("ProductEndpointType") != null) { this.GetType().GetProperty("ProductEndpointMap").SetValue(this, Endpoint.endpointMap, null); this.GetType().GetProperty("ProductEndpointType").SetValue(this, Endpoint.endpointRegionalType, null); } } private string instanceId; public string InstanceId { get { return instanceId; } set { instanceId = value; DictionaryUtil.Add(QueryParameters, "InstanceId", value); } } public override GetInstanceResponse GetResponse(UnmarshallerContext unmarshallerContext) { return GetInstanceResponseUnmarshaller.Unmarshall(unmarshallerContext); } } }
33.03125
134
0.699149
[ "Apache-2.0" ]
bbs168/aliyun-openapi-net-sdk
aliyun-net-sdk-ccc/CCC/Model/V20170705/GetInstanceRequest.cs
2,114
C#
using Manga.Application.Boundaries.Login; using System; using System.Collections.Generic; using System.Text; namespace Manga.Application.Services { public interface ILogin { LoginOutput Execute(string username, string password); } }
19.615385
62
0.74902
[ "Apache-2.0" ]
darshitachavda/Clean-Architecture-manga-pro
source/Manga.Application/Login-register/ILogin.cs
257
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis.Host; namespace Microsoft.CodeAnalysis.SolutionCrawler { /// <summary> /// Register a solution crawler for a particular workspace /// </summary> internal interface ISolutionCrawlerRegistrationService : IWorkspaceService { void Register(Workspace workspace); void Unregister(Workspace workspace, bool blockingShutdown = false); void AddAnalyzerProvider( IIncrementalAnalyzerProvider provider, IncrementalAnalyzerProviderMetadata metadata ); } }
31.16
78
0.725289
[ "MIT" ]
belav/roslyn
src/Workspaces/Core/Portable/SolutionCrawler/ISolutionCrawlerRegistrationService.cs
781
C#
using Tibia.Constants; namespace Tibia.Packets.Incoming { public class ProjectilePacket : IncomingPacket { public Objects.Location FromPosition { get; set; } public Objects.Location ToPosition { get; set; } public ProjectileType Effect { get; set; } public ProjectilePacket(Objects.Client c) : base(c) { Type = IncomingPacketType.Projectile; Destination = PacketDestination.Client; } public override bool ParseMessage(NetworkMessage msg, PacketDestination destination) { int position = msg.Position; if (msg.GetByte() != (byte)IncomingPacketType.Projectile) return false; Destination = destination; Type = IncomingPacketType.Projectile; FromPosition = msg.GetLocation(); ToPosition = msg.GetLocation(); Effect = (ProjectileType)msg.GetByte(); return true; } public override void ToNetworkMessage(NetworkMessage msg) { msg.AddByte((byte)Type); msg.AddLocation(FromPosition); msg.AddLocation(ToPosition); msg.AddByte((byte)Effect); } public static bool Send(Objects.Client client, Objects.Location fromLocation, Objects.Location toLocation, ProjectileType effect) { ProjectilePacket p = new ProjectilePacket(client); p.FromPosition = fromLocation; p.ToPosition = toLocation; p.Effect = effect; return p.Send(); } } }
31.415094
138
0.577778
[ "MIT" ]
BeldenGit/tibiaapi
tibiaapi/Packets/Incoming/ProjectilePacket.cs
1,667
C#
/* ======================================================================= Copyright 2017 Technische Universitaet Darmstadt, Fachgebiet fuer Stroemungsdynamik (chair of fluid dynamics) Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using BoSSS.Foundation; using BoSSS.Solution; using BoSSS.Solution.CompressibleFlowCommon; using ilPSP; using System.Collections.Generic; using System.Linq; namespace CNS.EquationSystem { /// <summary> /// A generic operator that helps with the construction of a /// <see cref="SpatialOperator"/>. The main purpose of this class is the /// simplification of the process of error-prone merging different /// operators (like the convective and the diffusive operator) /// </summary> public class Operator { /// <summary> /// Configuration options /// </summary> private CNSControl config; /// <summary> /// The parameter ordering that is constructed from the the parameters /// defined by the operator factory since it should know what the /// operators need /// </summary> private IList<string> GetParameterOrdering(CNSFieldSet fieldSet) { return fieldSet.ParameterFields.Select(f => f.Identification).ToList(); } /// <summary> /// Constructs and empty operator. /// </summary> public Operator(CNSControl config) { this.config = config; DensityComponents = new List<IEquationComponent>(); MomentumComponents = new IList<IEquationComponent>[ CompressibleEnvironment.NumberOfDimensions]; for (int d = 0; d < CompressibleEnvironment.NumberOfDimensions; d++) { MomentumComponents[d] = new List<IEquationComponent>(); } EnergyComponents = new List<IEquationComponent>(); CFLConstraints = new List<TimeStepConstraint>(); } /// <summary> /// A list of components related to the continuity equation. /// </summary> public IList<IEquationComponent> DensityComponents { get; private set; } /// <summary> /// A list of lists of components related to the [1-3] momentum /// equations. /// </summary> public IList<IEquationComponent>[] MomentumComponents { get; private set; } /// <summary> /// A list of components related to the energy equation. /// </summary> public IList<IEquationComponent> EnergyComponents { get; private set; } /// <summary> /// A list of CFL constraint provides (e.g., stemming from different /// operators that have been merged) that limit the admissible /// step-size for explicit time-integrators. /// </summary> public IList<TimeStepConstraint> CFLConstraints { get; private set; } /// <summary> /// Determines whether any components have been registered /// </summary> public bool IsEmpty { get { return !DensityComponents.Any() && !MomentumComponents.Any(m => m.Any()) && !EnergyComponents.Any(); } } /// <summary> /// Merges <paramref name="other"/> into this operator but adding the /// respective compatible components (see /// <see cref="DensityComponents"/>, <see cref="MomentumComponents"/> /// and <see cref="EnergyComponents"/>) as well as the defined CFL /// constraints (if any) to this object /// </summary> /// <param name="other"></param> /// <returns> /// A new operator containing the components and CFL constraints of /// this object and the merged object <paramref name="other"/>. /// </returns> public Operator Union(Operator other) { Operator union = new Operator(other.config); union.DensityComponents = this.DensityComponents.Concat(other.DensityComponents).ToList(); // It might not be readable, but lambdas are soooo tempting :) union.MomentumComponents = this.MomentumComponents.Select( (l, i) => l.Concat(other.MomentumComponents[i]).ToList()).ToArray(); union.EnergyComponents = this.EnergyComponents.Concat(other.EnergyComponents).ToList(); union.CFLConstraints = this.CFLConstraints.Concat(other.CFLConstraints).ToList(); return union; } /// <summary> /// Creates a <see cref="SpatialOperator"/> with the equation /// components that have been assigned to this operator. /// </summary> /// <returns></returns> public SpatialOperator ToSpatialOperator(CNSFieldSet fieldSet) { SpatialOperator spatialOp = new SpatialOperator( CompressibleEnvironment.PrimalArgumentOrdering, GetParameterOrdering(fieldSet), CompressibleEnvironment.PrimalArgumentOrdering, QuadOrderFunc.NonLinearWithoutParameters(2)); MapComponents(spatialOp); spatialOp.Commit(); return spatialOp; } /// <summary> /// Maps the <see cref="IEquationComponent"/>s in /// <paramref name="op"/> to the relevant equation components in /// the <paramref name="op"/>. /// </summary> /// <param name="op"> /// The operator onto which the components of /// <paramref name="op"/> should be mapped. /// </param> private void MapComponents(SpatialOperator op) { DensityComponents.ForEach(component => op.EquationComponents[CompressibleVariables.Density].Add(component)); for (int d = 0; d < CompressibleEnvironment.NumberOfDimensions; d++) { MomentumComponents[d].ForEach(component => op.EquationComponents[CompressibleVariables.Momentum[d]].Add(component)); } EnergyComponents.ForEach(component => op.EquationComponents[CompressibleVariables.Energy].Add(component)); } } }
39.542373
110
0.586369
[ "Apache-2.0" ]
FDYdarmstadt/BoSSS
src/L4-application/CNS/EquationSystem/Operator.cs
6,825
C#
using System; using Xunit; namespace ChallengesTests { public class UnitTest1 { [Fact] public void Test1() { } } }
10.733333
27
0.521739
[ "MIT" ]
Vavyo/Code-401-Lab03
ChallengesTests/UnitTest1.cs
161
C#
using System.Windows.Controls; namespace TLCGen.Views { /// <summary> /// Interaction logic for PrioriteitInUitmeldenTabView.xaml /// </summary> public partial class PrioriteitInUitmeldenTabView : UserControl { public PrioriteitInUitmeldenTabView() { InitializeComponent(); } } }
21.375
67
0.646199
[ "MIT" ]
PeterSnijders/TLCGen
TLCGen/Views/Tabs/PrioriteitsTab - Copy/Tabs/PrioriteitInUitmeldenTabView.xaml.cs
344
C#
using UnityEngine.Networking; class PingMessage: MessageBase { public double timestamp; }
13.714286
30
0.770833
[ "MIT" ]
FabbyD/Office-Royale
Assets/Scripts/PingMessage.cs
98
C#
/* * Copyright 2018 JDCLOUD.COM * * 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. * * Message * Message相关接口 * * OpenAPI spec version: v1 * Contact: * * NOTE: This class is auto generated by the jdcloud code generator program. */ using System; using System.Collections.Generic; using System.Text; using JDCloudSDK.Core.Service; namespace JDCloudSDK.Jcq.Apis { /// <summary> /// 查询消息轨迹 /// </summary> public class DescribeMessageTraceResponse : JdcloudResponse<DescribeMessageTraceResult> { } }
25.365854
91
0.722115
[ "Apache-2.0" ]
jdcloud-api/jdcloud-sdk-net
sdk/src/Service/Jcq/Apis/DescribeMessageTraceResponse.cs
1,060
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Collections; using Microsoft.CodeAnalysis.Structure; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CSharp.Structure { internal class BlockSyntaxStructureProvider : AbstractSyntaxNodeStructureProvider<BlockSyntax> { protected override void CollectBlockSpans( SyntaxToken previousToken, BlockSyntax node, ref TemporaryArray<BlockSpan> spans, BlockStructureOptionProvider optionProvider, CancellationToken cancellationToken) { var parentKind = node.Parent.Kind(); // For most types of statements, just consider the block 'attached' to the // parent node. That means we'll show the parent node header when doing // things like hovering over the indent guide. // // This also works nicely as the close brace for these constructs will always // align with the start of these statements. if (IsNonBlockStatement(node.Parent) || parentKind == SyntaxKind.ElseClause) { var type = GetType(node.Parent); if (type != null) { spans.Add(new BlockSpan( isCollapsible: true, textSpan: GetTextSpan(node), hintSpan: GetHintSpan(node), type: type, autoCollapse: parentKind == SyntaxKind.LocalFunctionStatement && node.Parent.IsParentKind(SyntaxKind.GlobalStatement))); } } // Nested blocks aren't attached to anything. Just collapse them as is. // Switch sections are also special. Say you have the following: // // case 0: // { // // } // // We don't want to consider the block parented by the case, because // that would cause us to draw the following: // // case 0: // | { // | // | } // // Which would obviously be wonky. So in this case, we just use the // spanof the block alone, without consideration for the case clause. if (parentKind == SyntaxKind.Block || parentKind == SyntaxKind.SwitchSection) { var type = GetType(node.Parent); spans.Add(new BlockSpan( isCollapsible: true, textSpan: node.Span, hintSpan: node.Span, type: type)); } } private static bool IsNonBlockStatement(SyntaxNode node) => node is StatementSyntax && !node.IsKind(SyntaxKind.Block); private static TextSpan GetHintSpan(BlockSyntax node) { var parent = node.Parent; if (parent.IsKind(SyntaxKind.IfStatement) && parent.IsParentKind(SyntaxKind.ElseClause)) { parent = parent.Parent; } var start = parent.Span.Start; var end = GetEnd(node); return TextSpan.FromBounds(start, end); } private static TextSpan GetTextSpan(BlockSyntax node) { var previousToken = node.GetFirstToken().GetPreviousToken(); if (previousToken.IsKind(SyntaxKind.None)) { return node.Span; } return TextSpan.FromBounds(previousToken.Span.End, GetEnd(node)); } private static int GetEnd(BlockSyntax node) { if (node.Parent.IsKind(SyntaxKind.IfStatement)) { // For an if-statement, just collapse up to the end of the block. // We don't want collapse the whole statement just for the 'true' // portion. Also, while outlining might be ok, the Indent-Guide // would look very strange for nodes like: // // if (goo) // { // } // else // return a || // b; return node.Span.End; } else { // For all other constructs, we collapse up to the end of the parent // construct. return node.Parent.Span.End; } } private static string GetType(SyntaxNode parent) { switch (parent.Kind()) { case SyntaxKind.ForStatement: return BlockTypes.Loop; case SyntaxKind.ForEachStatement: return BlockTypes.Loop; case SyntaxKind.ForEachVariableStatement: return BlockTypes.Loop; case SyntaxKind.WhileStatement: return BlockTypes.Loop; case SyntaxKind.DoStatement: return BlockTypes.Loop; case SyntaxKind.TryStatement: return BlockTypes.Statement; case SyntaxKind.CatchClause: return BlockTypes.Statement; case SyntaxKind.FinallyClause: return BlockTypes.Statement; case SyntaxKind.UnsafeStatement: return BlockTypes.Statement; case SyntaxKind.FixedStatement: return BlockTypes.Statement; case SyntaxKind.LockStatement: return BlockTypes.Statement; case SyntaxKind.UsingStatement: return BlockTypes.Statement; case SyntaxKind.IfStatement: return BlockTypes.Conditional; case SyntaxKind.ElseClause: return BlockTypes.Conditional; case SyntaxKind.SwitchSection: return BlockTypes.Conditional; case SyntaxKind.Block: return BlockTypes.Statement; case SyntaxKind.LocalFunctionStatement: return BlockTypes.Statement; } return null; } } }
39.472393
144
0.559372
[ "MIT" ]
333fred/roslyn
src/Features/CSharp/Portable/Structure/Providers/BlockSyntaxStructureProvider.cs
6,436
C#
using System; using System.Xml.Serialization; namespace dk.nita.saml20.Schema.XmlDSig { /// <summary> /// The optional Transforms element contains an ordered list of Transform elements; these describe how the /// signer obtained the data object that was digested. The output of each Transform serves as input to the /// next Transform. The input to the first Transform is the result of dereferencing the URI attribute of the /// Reference element. The output from the last Transform is the input for the DigestMethod algorithm. When /// transforms are applied the signer is not signing the native (original) document but the resulting /// (transformed) document. (See Only What is Signed is Secure (section 8.1).) /// /// Each Transform consists of an Algorithm attribute and content parameters, if any, appropriate for the /// given algorithm. The Algorithm attribute value specifies the name of the algorithm to be performed, and /// the Transform content provides additional data to govern the algorithm's processing of the transform /// input. (See Algorithm Identifiers and Implementation Requirements (section 6).) /// /// As described in The Reference Processing Model (section 4.3.3.2), some transforms take an XPath node-set /// as input, while others require an octet stream. If the actual input matches the input needs of the /// transform, then the transform operates on the unaltered input. If the transform input requirement differs /// from the format of the actual input, then the input must be converted. /// /// Some Transforms may require explicit MIME type, charset (IANA registered "character set"), or other such /// information concerning the data they are receiving from an earlier Transform or the source data, although /// no Transform algorithm specified in this document needs such explicit information. Such data /// characteristics are provided as parameters to the Transform algorithm and should be described in the /// specification for the algorithm. /// /// Examples of transforms include but are not limited to base64 decoding [MIME], canonicalization [XML-C14N], /// XPath filtering [XPath], and XSLT [XSLT]. The generic definition of the Transform element also allows /// application-specific transform algorithms. For example, the transform could be a decompression routine /// given by a Java class appearing as a base64 encoded parameter to a Java Transform algorithm. However, /// applications should refrain from using application-specific transforms if they wish their signatures to /// be verifiable outside of their application domain. Transform Algorithms (section 6.6) defines the list /// of standard transformations. /// /// </summary> [Serializable] [XmlType(Namespace=Saml2Constants.XMLDSIG)] [XmlRoot(ELEMENT_NAME, Namespace=Saml2Constants.XMLDSIG, IsNullable=false)] public class Transform { /// <summary> /// The XML Element name of this class /// </summary> public const string ELEMENT_NAME = "Transform"; private string algorithmField; private object[] itemsField; private string[] textField; /// <summary> /// Gets or sets the items. /// </summary> /// <value>The items.</value> [XmlAnyElement] [XmlElement("XPath", typeof (string))] public object[] Items { get { return itemsField; } set { itemsField = value; } } /// <summary> /// Gets or sets the text. /// </summary> /// <value>The text.</value> [XmlText] public string[] Text { get { return textField; } set { textField = value; } } /// <summary> /// Gets or sets the algorithm. /// </summary> /// <value>The algorithm.</value> [XmlAttribute(DataType="anyURI")] public string Algorithm { get { return algorithmField; } set { algorithmField = value; } } } }
46.076923
115
0.663725
[ "MPL-2.0", "MPL-2.0-no-copyleft-exception" ]
LeeTrent/Saml2.Authentication.Core
Source/Saml2.Authentication.Core/Schema/XmlDSig/Transform.cs
4,193
C#
using System; using System.IO; using System.Linq; using System.Text; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http.Features; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using System.Threading; using System.Threading.Tasks; using tusdotnet; using tusdotnet.Helpers; using tusdotnet.Interfaces; using tusdotnet.Models; using tusdotnet.Models.Concatenation; using tusdotnet.Models.Configuration; using tusdotnet.Stores; namespace LargeFileUpload { public class Startup { private readonly IWebHostEnvironment _environment; public Startup(IConfiguration configuration, IWebHostEnvironment environment) { Configuration = configuration; _environment = environment; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddRazorPages(); services.AddCors(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { app.Use((context, next) => { // Default limit was changed some time ago. Should work by setting MaxRequestBodySize to null using ConfigureKestrel but this does not seem to work for IISExpress. // Source: https://github.com/aspnet/Announcements/issues/267 context.Features.Get<IHttpMaxRequestBodySizeFeature>() .MaxRequestBodySize = null; return next.Invoke(); }); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Error"); // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. app.UseHsts(); } app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseCors(builder => builder .AllowAnyHeader() .AllowAnyMethod() .AllowAnyOrigin() .WithExposedHeaders(CorsHelper.GetExposedHeaders() )); app.UseTus(httpContext => new DefaultTusConfiguration { Store = new TusDiskStore(@$"{_environment.WebRootPath}/tusfiles/"), UrlPath = "/files", Events = new Events { // OnFileCompleteAsync = async eventContext => { // // eventContext.FileId is the id of the file that was uploaded. // // eventContext.Store is the data store that was used (in this case an instance of the TusDiskStore) // // // A normal use case here would be to read the file and do some processing on it. // ITusFile file = await eventContext.GetFileAsync(); // var result = await DoSomeProcessing(file, eventContext.CancellationToken) // .ConfigureAwait(false); // // if (!result) { // //throw new MyProcessingException("Something went wrong during processing"); // } // }, OnBeforeCreateAsync = async ctx => { // Partial files are not complete so we do not need to validate // the metadata in our example. if (ctx.FileConcatenation is FileConcatPartial) { return; } if (!ctx.Metadata.ContainsKey("filename") || ctx.Metadata["filename"] .HasEmptyValue) { ctx.FailRequest("name metadata must be specified. "); } var metaData = ctx.Metadata; metaData.TryGetValue("filename", out var fileName); var name = Encoding.UTF8.GetString(fileName!.GetBytes()); if (ctx.HttpContext.User.Identity is {IsAuthenticated: true}) { var claims = ctx.HttpContext.User.Claims.ToList(); var userId = Guid.Parse(claims.FirstOrDefault(predicate: c => c.Type == "id") ?.Value!); } return; }, OnFileCompleteAsync = async ctx => { var file = await ctx.GetFileAsync(); var metaData = await file.GetMetadataAsync(new CancellationToken()); metaData.TryGetValue("filename", out var fileName); var name = Encoding.UTF8.GetString(fileName!.GetBytes()); metaData.TryGetValue("postid", out var postId); var post = Guid.Parse(Encoding.UTF8.GetString(postId!.GetBytes())); var path= await HandleAfterUpload.SaveFileInPostFolder(Environment.WebRootPath, file.Id, name, post); Console.WriteLine(""); logger.LogInformation($"Upload of {ctx.FileId} completed using {ctx.Store.GetType().FullName} additional info is"); // If the store implements ITusReadableStore one could access the completed file here. // The default TusDiskStore implements this interface: //var file = await ctx.GetFileAsync(); return; }, } }); app.UseRouting(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapRazorPages(); }); } private Task<bool> DoSomeProcessing(ITusFile file, CancellationToken cancellationToken) { return Task.FromResult(true); } } public static class HandleAfterUpload { public static async Task<bool> CheckDirectoryName(Guid postId) { return false; } public static async Task<string> SaveFileInPostFolder(string webRootPath, string fileId, string fileName, Guid postId) { var post = GetPostById(postId); int i = 1; while (File.Exists(@$"{post.StorageDrive.Path}/CompletedFiles/{post!.Id}/{fileName}")) { var n = fileName.Split('.'); n[n.Length-2] += "-"+i; var newName = ""; foreach (var s in n) { newName += "."+s; } if (!File.Exists(@$"{post.StorageDrive.Path}/CompletedFiles/{post.Id}/{newName}")) { fileName = newName; } i++; } File.Move(@$"{webRootPath}/tempFiles/tusFiles/{fileId}", @$"{post.StorageDrive.Path}/CompletedFiles/{post.Id}/{fileName}"); FileInfo fi = new FileInfo(@$"{post.StorageDrive.Path}/CompletedFiles/{post.Id}/{fileName}"); var postFile = new PostFiles() { DownloadsCount = 0, FileName = fileName, FileUrl = @$"/CompletedFiles/{post.Id}/{fileName}", PostId = postId, UploadDate = DateTime.Now, Size = fi.Length }; await dbContext.PostFiles.AddAsync(postFile); await dbContext.SaveChangesAsync(); return @$"/CompletedFiles/{post.Id}/{fileName}"; } public static bool CheckPostOwner(Guid postId, Guid userId) { return false; } } }
43.43617
179
0.53588
[ "MIT" ]
FalahHAbbas/react
dotnet/Startup.cs
8,166
C#