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; namespace Tiandao.Plugins { /// <summary> /// 封装了有关插件特定的信息。 /// </summary> #if !CORE_CLR public class PluginContext : MarshalByRefObject #else public class PluginContext #endif { #region 私有字段 private PluginTree _pluginTree; private PluginSetup _settings; private PluginApplicationContext _applicationContext; #endregion #region 公共属性 /// <summary> /// 获取当前插件运行时的唯一插件树对象。 /// </summary> public PluginTree PluginTree { get { return _pluginTree; } } /// <summary> /// 获取加载的根插件集。 /// </summary> public IEnumerable<Plugin> Plugins { get { return _pluginTree.Plugins; } } /// <summary> /// 获取当前插件运行时所属的应用程序上下文对象。 /// </summary> public PluginApplicationContext ApplicationContext { get { return _applicationContext; } } /// <summary> /// 获取当前插件运行时的服务供应程序工厂。 /// </summary> public Tiandao.Services.IServiceProviderFactory ServiceFactory { get { return _applicationContext.ServiceFactory; } } /// <summary> /// 获取当前插件上下文对应的设置。 /// </summary> public PluginSetup Settings { get { return _settings; } } /// <summary> /// 获取插件的隔离级别。 /// </summary> public IsolationLevel IsolationLevel { get { return _settings.IsolationLevel; } } /// <summary> /// 获取当前工作台(主界面)对象。 /// </summary> public IWorkbenchBase Workbench { get { return this.ResolvePath(this.Settings.WorkbenchPath, ObtainMode.Auto) as IWorkbenchBase; } } #endregion #region 构造方法 internal PluginContext(PluginSetup settings, PluginApplicationContext applicationContext) { if(settings == null) throw new ArgumentNullException("settings"); if(applicationContext == null) throw new ArgumentNullException("applicationContext"); _settings = (PluginSetup)settings.Clone(); _pluginTree = new PluginTree(this); _applicationContext = applicationContext; _settings.PropertyChanged += delegate { if(_pluginTree != null && _pluginTree.Status != PluginTreeStatus.None) throw new InvalidOperationException(); }; } #endregion #region 解析路径 /// <summary> /// 根据指定的路径文本获取其对应的缓存对象或该对象的成员值。 /// </summary> /// <param name="pathText">要获取的路径文本,该文本可以用过句点符号(.)表示缓存对象的成员名。</param> /// <returns>返回获取的缓存对象或其成员值。</returns> /// <exception cref="System.ArgumentNullException"><paramref name="pathText"/>参数为空或全空字符串。</exception> /// <exception cref="System.ArgumentException">参数中包含成员名,但是在该缓存对象中并没找到其成员。</exception> /// <remarks> /// 注意:成员名只能是公共的实例属性或字段。 /// <example>/Workspace/Environment/ApplicationContext.ApplicationId</example> /// </remarks> public object ResolvePath(string pathText) { return this.ResolvePath(pathText, ObtainMode.Auto); } public object ResolvePath(string pathText, ObtainMode obtainMode) { return this.ResolvePath(pathText, null, obtainMode); } internal object ResolvePath(string text, PluginTreeNode current, ObtainMode obtainMode) { PluginPathType pathType; string path; string[] memberNames; if(!PluginPath.TryResolvePath(text, out pathType, out path, out memberNames)) throw new PluginException(string.Format("Resolve ‘{0}’ plugin-path was failed.", text)); PluginTreeNode node = null; switch(pathType) { case PluginPathType.Rooted: node = _pluginTree.RootNode; break; case PluginPathType.Parent: node = current.Parent; break; case PluginPathType.Current: node = current; break; } if(node != null && (!string.IsNullOrWhiteSpace(path))) node = node.Find(path); //注意:如果没有找到指定路径的对象不需要写日志,在ServicesParser解析中需要先在默认工厂查询指定路径的服务如果查找失败则查找服务工厂集 if(node == null) return null; try { //获取指定路径的目标对象 object target = node.UnwrapValue(obtainMode, this, null); if(target != null && memberNames.Length > 0) return Tiandao.Common.Converter.GetValue(target, memberNames); return target; } catch(Exception ex) { var fileName = string.Empty; if(current != null && current.Plugin != null) fileName = System.IO.Path.GetFileName(current.Plugin.FilePath); throw new PluginException(FailureCodes.InvalidPath, string.Format("Resolve target error from '{0}' path in '{1}' plugin file.", text, fileName), ex); } } #endregion } }
21.273171
153
0.681724
[ "MIT" ]
jonfee/Tiandao.Plugins
src/Tiandao.Plugins/PluginContext.cs
5,039
C#
#pragma checksum "C:\Users\Trung\Downloads\email-attachments-aspnet-core-master\EmailApp\MailTH\Views\Home\Index.cshtml" "{ff1816ec-aa5e-4d10-87f7-6f4963833460}" "99464617055fdb505bb0bb7fd91f9b14f7b0d030" // <auto-generated/> #pragma warning disable 1591 [assembly: global::Microsoft.AspNetCore.Razor.Hosting.RazorCompiledItemAttribute(typeof(AspNetCore.Views_Home_Index), @"mvc.1.0.view", @"/Views/Home/Index.cshtml")] namespace AspNetCore { #line hidden using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Rendering; using Microsoft.AspNetCore.Mvc.ViewFeatures; #nullable restore #line 1 "C:\Users\Trung\Downloads\email-attachments-aspnet-core-master\EmailApp\MailTH\Views\_ViewImports.cshtml" using MailTH; #line default #line hidden #nullable disable #nullable restore #line 2 "C:\Users\Trung\Downloads\email-attachments-aspnet-core-master\EmailApp\MailTH\Views\_ViewImports.cshtml" using MailTH.Models; #line default #line hidden #nullable disable [global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"99464617055fdb505bb0bb7fd91f9b14f7b0d030", @"/Views/Home/Index.cshtml")] [global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"2a438d874c6e27bffa57e622ae6ae8fc6eca81f0", @"/Views/_ViewImports.cshtml")] public class Views_Home_Index : global::Microsoft.AspNetCore.Mvc.Razor.RazorPage<dynamic> { #pragma warning disable 1998 public async override global::System.Threading.Tasks.Task ExecuteAsync() { #nullable restore #line 1 "C:\Users\Trung\Downloads\email-attachments-aspnet-core-master\EmailApp\MailTH\Views\Home\Index.cshtml" ViewData["Title"] = "Home Page"; #line default #line hidden #nullable disable WriteLiteral("\r\n<div class=\"text-center\">\r\n <h1 class=\"display-4\">Welcome</h1>\r\n <p>Learn about <a href=\"https://docs.microsoft.com/aspnet/core\">building Web apps with ASP.NET Core</a>.</p>\r\n</div>\r\n"); } #pragma warning restore 1998 [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.ViewFeatures.IModelExpressionProvider ModelExpressionProvider { get; private set; } [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.IUrlHelper Url { get; private set; } [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.IViewComponentHelper Component { get; private set; } [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.Rendering.IJsonHelper Json { get; private set; } [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.Rendering.IHtmlHelper<dynamic> Html { get; private set; } } } #pragma warning restore 1591
51.666667
236
0.756129
[ "MIT" ]
alexhanhnguyenms/mail_netcore3
EmailApp/MailTH/obj/Debug/netcoreapp3.1/Razor/Views/Home/Index.cshtml.g.cs
3,100
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("03CorrectBrackets")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("03CorrectBrackets")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("eaa4c195-5da8-4224-9004-e3c2e9fd2d37")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
38.027027
84
0.746979
[ "MIT" ]
Vladeff/TelerikAcademy
C#2 Homework/Strings and Text Processing/03CorrectBrackets/Properties/AssemblyInfo.cs
1,410
C#
using System; using System.Collections.Generic; namespace Downloader { public class MultiPartDownloadBuilder : IDownloadBuilder { private readonly int numberOfParts; private readonly IDownloadBuilder downloadBuilder; private readonly IWebRequestBuilder requestBuilder; private readonly IDownloadChecker downloadChecker; private readonly List<DownloadRange> alreadyDownloadedRanges; public MultiPartDownloadBuilder( int numberOfParts, IDownloadBuilder downloadBuilder, IWebRequestBuilder requestBuilder, IDownloadChecker downloadChecker, List<DownloadRange> alreadyDownloadedRanges) { if (numberOfParts <= 0) throw new ArgumentException("numberOfParts <= 0"); if (downloadBuilder == null) throw new ArgumentNullException("downloadBuilder"); if (requestBuilder == null) throw new ArgumentNullException("requestBuilder"); if (downloadChecker == null) throw new ArgumentNullException("downloadChecker"); this.numberOfParts = numberOfParts; this.downloadBuilder = downloadBuilder; this.requestBuilder = requestBuilder; this.downloadChecker = downloadChecker; this.alreadyDownloadedRanges = alreadyDownloadedRanges ?? new List<DownloadRange>(); } public IDownload Build(Uri url, int bufferSize, long? offset, long? maxReadBytes) { return new MultiPartDownload(url, bufferSize, this.numberOfParts, this.downloadBuilder, this.requestBuilder, this.downloadChecker, this.alreadyDownloadedRanges); } } }
35.673469
173
0.66762
[ "MIT" ]
suntabu/UnityDownloader
Assets/Downloader/MultiPartDownloadBuilder.cs
1,750
C#
/* Copyright 2019 Vivien Baguio. * Subject to the MIT License License. * See https://mit-license.org/ */ using UnityEngine; using UnityEngine.UI; using TMPro; /// <summary> /// Compound view for the buttons in a dialog /// </summary> public class DialogButton : MonoBehaviour { public Button m_button; public TextMeshProUGUI m_text; }
19.388889
45
0.716332
[ "MIT" ]
hollowspecter/trackracerAR
Assets/__Scripts/View/ModalDialog/DialogButton.cs
351
C#
using UnityEngine; using UnityEditor; using AKSaigyouji.Modules.MapGeneration; using AKSaigyouji.Maps; public sealed class PreviewWindow : EditorWindow { Texture texture; void OnGUI() { GUI.DrawTexture(new Rect(Vector2.zero, position.size), texture); } public void UpdateWindow(MapGenCompound module) { Map map = module.GenerateWithSubmoduleSeeds(); texture = map.ToTexture(); } }
21.8
72
0.694954
[ "MIT" ]
AK-Saigyouji/Procedural-Cave-Generator
Project/Scripts/Modules - MapGeneration/Editor/Map Gen Window/Windows/PreviewWindow.cs
438
C#
using Signum.Entities.Authorization; using Signum.Utilities; using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq.Expressions; using Signum.Entities.Dynamic; using Signum.Entities.Scheduler; using Signum.Entities.Processes; namespace Signum.Entities.Workflow { [Serializable, EntityKind(EntityKind.System, EntityData.Transactional), InTypeScript(Undefined = false)] public class CaseActivityEntity : Entity { public CaseEntity Case { get; set; } [ImplementedBy(typeof(WorkflowActivityEntity), typeof(WorkflowEventEntity))] public IWorkflowNodeEntity WorkflowActivity { get; set; } [StringLengthValidator(Min = 3, Max = 255)] public string OriginalWorkflowActivityName { get; set; } public DateTime StartDate { get; set; } = TimeZoneManager.Now; public Lite<CaseActivityEntity>? Previous { get; set; } [StringLengthValidator(MultiLine = true)] public string? Note { get; set; } public DateTime? DoneDate { get; set; } [Unit("min")] public double? Duration { get; set; } [AutoExpressionField] public double? DurationRealTime => As.Expression(() => Duration ?? (double?)(TimeZoneManager.Now - StartDate).TotalMinutes); [AutoExpressionField] public double? DurationRatio => As.Expression(() => Duration / ((WorkflowActivityEntity)WorkflowActivity).EstimatedDuration); [AutoExpressionField] public double? DurationRealTimeRatio => As.Expression(() => DurationRealTime / ((WorkflowActivityEntity)WorkflowActivity).EstimatedDuration); public Lite<UserEntity>? DoneBy { get; set; } public DoneType? DoneType { get; set; } public ScriptExecutionEmbedded? ScriptExecution { get; set; } static Expression<Func<CaseActivityEntity, CaseActivityState>> StateExpression = @this => @this.DoneDate.HasValue ? CaseActivityState.Done : (@this.WorkflowActivity is WorkflowEventEntity) ? CaseActivityState.PendingNext : ((WorkflowActivityEntity)@this.WorkflowActivity).Type == WorkflowActivityType.Decision ? CaseActivityState.PendingDecision : CaseActivityState.PendingNext; [ExpressionField("StateExpression")] public CaseActivityState State { get { if (this.IsNew) return CaseActivityState.New; return StateExpression.Evaluate(this); } } [AutoExpressionField] public override string ToString() => As.Expression(() => WorkflowActivity + " " + DoneBy); protected override void PreSaving(PreSavingContext ctx) { base.PreSaving(ctx); this.Duration = this.DoneDate == null ? (double?)null : (this.DoneDate.Value - this.StartDate).TotalMinutes; } } [Serializable] public class ScriptExecutionEmbedded : EmbeddedEntity { public DateTime NextExecution { get; set; } public int RetryCount { get; set; } public Guid? ProcessIdentifier { get; set; } } public enum DoneType { Next, Approve, Decline, Jump, Timeout, ScriptSuccess, ScriptFailure, Recompose, } public enum CaseActivityState { [Ignore] New, PendingNext, PendingDecision, Done, } [AutoInit] public static class CaseActivityOperation { public static readonly ConstructSymbol<CaseActivityEntity>.From<WorkflowEntity> CreateCaseActivityFromWorkflow; public static readonly ConstructSymbol<CaseEntity>.From<WorkflowEventTaskEntity> CreateCaseFromWorkflowEventTask; public static readonly ExecuteSymbol<CaseActivityEntity> Register; public static readonly DeleteSymbol<CaseActivityEntity> Delete; public static readonly ExecuteSymbol<CaseActivityEntity> Next; public static readonly ExecuteSymbol<CaseActivityEntity> Approve; public static readonly ExecuteSymbol<CaseActivityEntity> Decline; public static readonly ExecuteSymbol<CaseActivityEntity> Jump; public static readonly ExecuteSymbol<CaseActivityEntity> Timer; public static readonly ExecuteSymbol<CaseActivityEntity> MarkAsUnread; public static readonly ExecuteSymbol<CaseActivityEntity> Undo; public static readonly ExecuteSymbol<CaseActivityEntity> ScriptExecute; public static readonly ExecuteSymbol<CaseActivityEntity> ScriptScheduleRetry; public static readonly ExecuteSymbol<CaseActivityEntity> ScriptFailureJump; public static readonly ExecuteSymbol<DynamicTypeEntity> FixCaseDescriptions; } [AutoInit] public static class CaseActivityTask { public static readonly SimpleTaskSymbol Timeout; } [AutoInit] public static class CaseActivityProcessAlgorithm { public static readonly ProcessAlgorithmSymbol Timeout; } public enum CaseActivityMessage { CaseContainsOtherActivities, NoNextConnectionThatSatisfiesTheConditionsFound, [Description("Case is a decomposition of {0}")] CaseIsADecompositionOf0, [Description("From {0} on {1}")] From0On1, [Description("Done by {0} on {1}")] DoneBy0On1, PersonalRemarksForThisNotification, [Description("The activity '{0}' requires to be opened")] TheActivity0RequiresToBeOpened, NoOpenedOrInProgressNotificationsFound, NextActivityAlreadyInProgress, NextActivityOfDecompositionSurrogateAlreadyInProgress, [Description("Only '{0}' can undo this operation")] Only0CanUndoThisOperation, [Description("Activity '{0}' has no jumps")] Activity0HasNoJumps, [Description("Activity '{0}' has no timeout")] Activity0HasNoTimers, ThereIsNoPreviousActivity, OnlyForScriptWorkflowActivities, Pending, NoWorkflowActivity, [Description("Impossible to delete Case Activity {0} (on Workflow Activity '{1}') because has no previouos activity")] ImpossibleToDeleteCaseActivity0OnWorkflowActivity1BecauseHasNoPreviousActivity, LastCaseActivity, CurrentUserHasNotification, NoNewOrOpenedOrInProgressNotificationsFound, NoActorsFoundToInsertCaseActivityNotifications, ThereAreInprogressActivities, } public enum CaseActivityQuery { Inbox } [Serializable] public class ActivityWithRemarks : ModelEntity { public Lite<WorkflowActivityEntity>? WorkflowActivity { get; set; } public Lite<CaseEntity> Case { get; set; } public Lite<CaseActivityEntity>? CaseActivity { get; set; } public Lite<CaseNotificationEntity>? Notification { get; set; } public string? Remarks { get; set; } public int Alerts { get; set; } public List<CaseTagTypeEntity> Tags { get; set; } } [Serializable, EntityKind(EntityKind.System, EntityData.Transactional)] public class CaseActivityExecutedTimerEntity : Entity { public DateTime CreationDate { get; private set; } = TimeZoneManager.Now; public Lite<CaseActivityEntity> CaseActivity { get; set; } public Lite<WorkflowEventEntity> BoundaryEvent { get; set; } } }
36.885167
150
0.660656
[ "MIT" ]
ControlExpert/extensions
Signum.Entities.Extensions/Workflow/CaseActivity.cs
7,709
C#
// Copyright 2013-2016 Serilog Contributors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. namespace RxBim.Logs.Settings.Configuration.Assemblies { /// <summary> /// Defines how the package will identify the assemblies which are scanned for sinks and other Type information. /// </summary> public enum ConfigurationAssemblySource { /// <summary> /// Try to scan the assemblies already in memory. This is the default. If GetEntryAssembly is null, fallback to DLL scanning. /// </summary> UseLoadedAssemblies, /// <summary> /// Scan for assemblies in DLLs from the working directory. This is the fallback when GetEntryAssembly is null. /// </summary> AlwaysScanDllFiles } }
38.606061
133
0.702512
[ "MIT" ]
AlexNik235/RxBim
src/RxBim.Logs/Settings/Configuration/Assemblies/ConfigurationAssemblySource.cs
1,276
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace LanguageProcessor { public abstract class QueryFactory { public abstract IQuery GetQueryType(string query); } }
18.571429
58
0.75
[ "Apache-2.0" ]
paraspatidar/Merchant-Guide-To-Galaxy-CSharp
Merchant_Of_Galaxy/LanguageProcessor/QueryFactory.cs
262
C#
using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Chapter06.Activities.Activity01 { public static class Demo { public static void Run() { var db = new TruckDispatchDbContext(); SeedData(db); var dispatches = GetAll(db); Print(dispatches); db.Dispose(); } private static void SeedData(TruckDispatchDbContext db) { var wasSeeded = db.Trucks.Any(); if(!wasSeeded) { var person = new Person { DoB = DateTime.Now, Id = 1, Name = "Stephen King" }; db.People.Add(person); var truck = new Truck() { Id = 1, Brand = "Scania", Model = "R 500 LA6x2HHA", YearOfMaking = 2009 }; db.Trucks.Add(truck); var dispatch = new TruckDispatch() { CurrentLocation = "1,1,1", Deadline = DateTime.Now.AddDays(100), Driver = person, Truck = truck }; db.TruckDispatches.Add(dispatch); db.SaveChanges(); } } private static IEnumerable<TruckDispatch> GetAll(TruckDispatchDbContext db) { var dispatches = db .TruckDispatches .Include(td => td.Driver) .Include(td => td.Truck) .ToList(); return dispatches; } private static void Print(IEnumerable<TruckDispatch> truckDispatches) { foreach(var dispatch in truckDispatches) { Console.WriteLine($"Dispatch: {dispatch.Id} {dispatch.CurrentLocation} {dispatch.Deadline}"); Console.WriteLine($"Driver: {dispatch.Driver.Name} {dispatch.Driver.DoB}"); Console.WriteLine($"Truck: {dispatch.Truck.Brand} {dispatch.Truck.Model} {dispatch.Truck.YearOfMaking}"); } } } }
31.530303
121
0.524748
[ "MIT" ]
PacktWorkshops/The-C-Sharp-Workshop
Chapter06/Activities/Activity01/Demo.cs
2,083
C#
using Zinnia.Rule; using Zinnia.Tracking.Collision; namespace Test.Zinnia.Tracking.Collision { using NUnit.Framework; using System.Collections; using Test.Zinnia.Utility.Mock; using UnityEngine; using UnityEngine.TestTools; using Assert = UnityEngine.Assertions.Assert; public class CollisionTrackerTest { [UnityTest] public IEnumerator CollisionStates() { WaitForFixedUpdate yieldInstruction = new WaitForFixedUpdate(); GameObject trackerContainer = GameObject.CreatePrimitive(PrimitiveType.Cube); trackerContainer.GetComponent<Collider>().isTrigger = true; trackerContainer.AddComponent<Rigidbody>().isKinematic = true; trackerContainer.transform.position = Vector3.forward; CollisionTracker tracker = trackerContainer.AddComponent<CollisionTracker>(); GameObject notifierContainer = GameObject.CreatePrimitive(PrimitiveType.Cube); notifierContainer.GetComponent<Collider>().isTrigger = true; notifierContainer.AddComponent<Rigidbody>().isKinematic = true; notifierContainer.transform.position = Vector3.back; CollisionNotifier notifier = notifierContainer.AddComponent<CollisionNotifier>(); UnityEventListenerMock trackerCollisionStartedListenerMock = new UnityEventListenerMock(); UnityEventListenerMock trackerCollisionChangedListenerMock = new UnityEventListenerMock(); UnityEventListenerMock trackerCollisionStoppedListenerMock = new UnityEventListenerMock(); tracker.CollisionStarted.AddListener(trackerCollisionStartedListenerMock.Listen); tracker.CollisionChanged.AddListener(trackerCollisionChangedListenerMock.Listen); tracker.CollisionStopped.AddListener(trackerCollisionStoppedListenerMock.Listen); UnityEventListenerMock notifierCollisionStartedListenerMock = new UnityEventListenerMock(); UnityEventListenerMock notifierCollisionChangedListenerMock = new UnityEventListenerMock(); UnityEventListenerMock notifierCollisionStoppedListenerMock = new UnityEventListenerMock(); notifier.CollisionStarted.AddListener(notifierCollisionStartedListenerMock.Listen); notifier.CollisionChanged.AddListener(notifierCollisionChangedListenerMock.Listen); notifier.CollisionStopped.AddListener(notifierCollisionStoppedListenerMock.Listen); yield return yieldInstruction; Assert.IsFalse(trackerCollisionStartedListenerMock.Received); Assert.IsFalse(trackerCollisionChangedListenerMock.Received); Assert.IsFalse(trackerCollisionStoppedListenerMock.Received); Assert.IsFalse(notifierCollisionStartedListenerMock.Received); Assert.IsFalse(notifierCollisionChangedListenerMock.Received); Assert.IsFalse(notifierCollisionStoppedListenerMock.Received); trackerCollisionStartedListenerMock.Reset(); trackerCollisionChangedListenerMock.Reset(); trackerCollisionStoppedListenerMock.Reset(); notifierCollisionStartedListenerMock.Reset(); notifierCollisionChangedListenerMock.Reset(); notifierCollisionStoppedListenerMock.Reset(); trackerContainer.transform.position = Vector3.zero; notifierContainer.transform.position = Vector3.zero; yield return yieldInstruction; Assert.IsTrue(trackerCollisionStartedListenerMock.Received); Assert.IsTrue(trackerCollisionChangedListenerMock.Received); Assert.IsFalse(trackerCollisionStoppedListenerMock.Received); Assert.IsTrue(notifierCollisionStartedListenerMock.Received); Assert.IsTrue(notifierCollisionChangedListenerMock.Received); Assert.IsFalse(notifierCollisionStoppedListenerMock.Received); trackerCollisionStartedListenerMock.Reset(); trackerCollisionChangedListenerMock.Reset(); trackerCollisionStoppedListenerMock.Reset(); notifierCollisionStartedListenerMock.Reset(); notifierCollisionChangedListenerMock.Reset(); notifierCollisionStoppedListenerMock.Reset(); yield return yieldInstruction; Assert.IsFalse(trackerCollisionStartedListenerMock.Received); Assert.IsTrue(trackerCollisionChangedListenerMock.Received); Assert.IsFalse(trackerCollisionStoppedListenerMock.Received); Assert.IsFalse(notifierCollisionStartedListenerMock.Received); Assert.IsTrue(notifierCollisionChangedListenerMock.Received); Assert.IsFalse(notifierCollisionStoppedListenerMock.Received); trackerCollisionStartedListenerMock.Reset(); trackerCollisionChangedListenerMock.Reset(); trackerCollisionStoppedListenerMock.Reset(); notifierCollisionStartedListenerMock.Reset(); notifierCollisionChangedListenerMock.Reset(); notifierCollisionStoppedListenerMock.Reset(); trackerContainer.transform.position = Vector3.one * 0.25f; notifierContainer.transform.position = Vector3.one * -0.25f; yield return yieldInstruction; Assert.IsFalse(trackerCollisionStartedListenerMock.Received); Assert.IsTrue(trackerCollisionChangedListenerMock.Received); Assert.IsFalse(trackerCollisionStoppedListenerMock.Received); Assert.IsFalse(notifierCollisionStartedListenerMock.Received); Assert.IsTrue(notifierCollisionChangedListenerMock.Received); Assert.IsFalse(notifierCollisionStoppedListenerMock.Received); trackerCollisionStartedListenerMock.Reset(); trackerCollisionChangedListenerMock.Reset(); trackerCollisionStoppedListenerMock.Reset(); notifierCollisionStartedListenerMock.Reset(); notifierCollisionChangedListenerMock.Reset(); notifierCollisionStoppedListenerMock.Reset(); trackerContainer.transform.position = Vector3.forward; notifierContainer.transform.position = Vector3.back; yield return yieldInstruction; Assert.IsFalse(trackerCollisionStartedListenerMock.Received); Assert.IsFalse(trackerCollisionChangedListenerMock.Received); Assert.IsTrue(trackerCollisionStoppedListenerMock.Received); Assert.IsFalse(notifierCollisionStartedListenerMock.Received); Assert.IsFalse(notifierCollisionChangedListenerMock.Received); Assert.IsTrue(notifierCollisionStoppedListenerMock.Received); Object.DestroyImmediate(trackerContainer); Object.DestroyImmediate(notifierContainer); } [UnityTest] public IEnumerator CollisionStatesIgnoreEnter() { WaitForFixedUpdate yieldInstruction = new WaitForFixedUpdate(); GameObject trackerContainer = GameObject.CreatePrimitive(PrimitiveType.Cube); trackerContainer.GetComponent<Collider>().isTrigger = true; trackerContainer.AddComponent<Rigidbody>().isKinematic = true; trackerContainer.transform.position = Vector3.forward; CollisionTracker tracker = trackerContainer.AddComponent<CollisionTracker>(); tracker.StatesToProcess = CollisionTracker.CollisionStates.Stay | CollisionTracker.CollisionStates.Exit; GameObject notifierContainer = GameObject.CreatePrimitive(PrimitiveType.Cube); notifierContainer.GetComponent<Collider>().isTrigger = true; notifierContainer.AddComponent<Rigidbody>().isKinematic = true; notifierContainer.transform.position = Vector3.back; CollisionNotifier notifier = notifierContainer.AddComponent<CollisionNotifier>(); UnityEventListenerMock trackerCollisionStartedListenerMock = new UnityEventListenerMock(); UnityEventListenerMock trackerCollisionChangedListenerMock = new UnityEventListenerMock(); UnityEventListenerMock trackerCollisionStoppedListenerMock = new UnityEventListenerMock(); tracker.CollisionStarted.AddListener(trackerCollisionStartedListenerMock.Listen); tracker.CollisionChanged.AddListener(trackerCollisionChangedListenerMock.Listen); tracker.CollisionStopped.AddListener(trackerCollisionStoppedListenerMock.Listen); UnityEventListenerMock notifierCollisionStartedListenerMock = new UnityEventListenerMock(); UnityEventListenerMock notifierCollisionChangedListenerMock = new UnityEventListenerMock(); UnityEventListenerMock notifierCollisionStoppedListenerMock = new UnityEventListenerMock(); notifier.CollisionStarted.AddListener(notifierCollisionStartedListenerMock.Listen); notifier.CollisionChanged.AddListener(notifierCollisionChangedListenerMock.Listen); notifier.CollisionStopped.AddListener(notifierCollisionStoppedListenerMock.Listen); yield return yieldInstruction; Assert.IsFalse(trackerCollisionStartedListenerMock.Received); Assert.IsFalse(trackerCollisionChangedListenerMock.Received); Assert.IsFalse(trackerCollisionStoppedListenerMock.Received); Assert.IsFalse(notifierCollisionStartedListenerMock.Received); Assert.IsFalse(notifierCollisionChangedListenerMock.Received); Assert.IsFalse(notifierCollisionStoppedListenerMock.Received); trackerCollisionStartedListenerMock.Reset(); trackerCollisionChangedListenerMock.Reset(); trackerCollisionStoppedListenerMock.Reset(); notifierCollisionStartedListenerMock.Reset(); notifierCollisionChangedListenerMock.Reset(); notifierCollisionStoppedListenerMock.Reset(); trackerContainer.transform.position = Vector3.zero; notifierContainer.transform.position = Vector3.zero; yield return yieldInstruction; Assert.IsFalse(trackerCollisionStartedListenerMock.Received); Assert.IsTrue(trackerCollisionChangedListenerMock.Received); Assert.IsFalse(trackerCollisionStoppedListenerMock.Received); Assert.IsFalse(notifierCollisionStartedListenerMock.Received); Assert.IsTrue(notifierCollisionChangedListenerMock.Received); Assert.IsFalse(notifierCollisionStoppedListenerMock.Received); Object.DestroyImmediate(trackerContainer); Object.DestroyImmediate(notifierContainer); } [UnityTest] public IEnumerator CollisionStatesIgnoreStay() { WaitForFixedUpdate yieldInstruction = new WaitForFixedUpdate(); GameObject trackerContainer = GameObject.CreatePrimitive(PrimitiveType.Cube); trackerContainer.GetComponent<Collider>().isTrigger = true; trackerContainer.AddComponent<Rigidbody>().isKinematic = true; trackerContainer.transform.position = Vector3.forward; CollisionTracker tracker = trackerContainer.AddComponent<CollisionTracker>(); tracker.StatesToProcess = CollisionTracker.CollisionStates.Enter | CollisionTracker.CollisionStates.Exit; GameObject notifierContainer = GameObject.CreatePrimitive(PrimitiveType.Cube); notifierContainer.GetComponent<Collider>().isTrigger = true; notifierContainer.AddComponent<Rigidbody>().isKinematic = true; notifierContainer.transform.position = Vector3.back; CollisionNotifier notifier = notifierContainer.AddComponent<CollisionNotifier>(); UnityEventListenerMock trackerCollisionStartedListenerMock = new UnityEventListenerMock(); UnityEventListenerMock trackerCollisionChangedListenerMock = new UnityEventListenerMock(); UnityEventListenerMock trackerCollisionStoppedListenerMock = new UnityEventListenerMock(); tracker.CollisionStarted.AddListener(trackerCollisionStartedListenerMock.Listen); tracker.CollisionChanged.AddListener(trackerCollisionChangedListenerMock.Listen); tracker.CollisionStopped.AddListener(trackerCollisionStoppedListenerMock.Listen); UnityEventListenerMock notifierCollisionStartedListenerMock = new UnityEventListenerMock(); UnityEventListenerMock notifierCollisionChangedListenerMock = new UnityEventListenerMock(); UnityEventListenerMock notifierCollisionStoppedListenerMock = new UnityEventListenerMock(); notifier.CollisionStarted.AddListener(notifierCollisionStartedListenerMock.Listen); notifier.CollisionChanged.AddListener(notifierCollisionChangedListenerMock.Listen); notifier.CollisionStopped.AddListener(notifierCollisionStoppedListenerMock.Listen); yield return yieldInstruction; Assert.IsFalse(trackerCollisionStartedListenerMock.Received); Assert.IsFalse(trackerCollisionChangedListenerMock.Received); Assert.IsFalse(trackerCollisionStoppedListenerMock.Received); Assert.IsFalse(notifierCollisionStartedListenerMock.Received); Assert.IsFalse(notifierCollisionChangedListenerMock.Received); Assert.IsFalse(notifierCollisionStoppedListenerMock.Received); trackerCollisionStartedListenerMock.Reset(); trackerCollisionChangedListenerMock.Reset(); trackerCollisionStoppedListenerMock.Reset(); notifierCollisionStartedListenerMock.Reset(); notifierCollisionChangedListenerMock.Reset(); notifierCollisionStoppedListenerMock.Reset(); trackerContainer.transform.position = Vector3.zero; notifierContainer.transform.position = Vector3.zero; yield return yieldInstruction; Assert.IsTrue(trackerCollisionStartedListenerMock.Received); Assert.IsFalse(trackerCollisionChangedListenerMock.Received); Assert.IsFalse(trackerCollisionStoppedListenerMock.Received); Assert.IsTrue(notifierCollisionStartedListenerMock.Received); Assert.IsFalse(notifierCollisionChangedListenerMock.Received); Assert.IsFalse(notifierCollisionStoppedListenerMock.Received); Object.DestroyImmediate(trackerContainer); Object.DestroyImmediate(notifierContainer); } [UnityTest] public IEnumerator CollisionStatesIgnoreExit() { WaitForFixedUpdate yieldInstruction = new WaitForFixedUpdate(); GameObject trackerContainer = GameObject.CreatePrimitive(PrimitiveType.Cube); trackerContainer.GetComponent<Collider>().isTrigger = true; trackerContainer.AddComponent<Rigidbody>().isKinematic = true; trackerContainer.transform.position = Vector3.forward; CollisionTracker tracker = trackerContainer.AddComponent<CollisionTracker>(); tracker.StatesToProcess = CollisionTracker.CollisionStates.Enter | CollisionTracker.CollisionStates.Stay; GameObject notifierContainer = GameObject.CreatePrimitive(PrimitiveType.Cube); notifierContainer.GetComponent<Collider>().isTrigger = true; notifierContainer.AddComponent<Rigidbody>().isKinematic = true; notifierContainer.transform.position = Vector3.back; CollisionNotifier notifier = notifierContainer.AddComponent<CollisionNotifier>(); UnityEventListenerMock trackerCollisionStartedListenerMock = new UnityEventListenerMock(); UnityEventListenerMock trackerCollisionChangedListenerMock = new UnityEventListenerMock(); UnityEventListenerMock trackerCollisionStoppedListenerMock = new UnityEventListenerMock(); tracker.CollisionStarted.AddListener(trackerCollisionStartedListenerMock.Listen); tracker.CollisionChanged.AddListener(trackerCollisionChangedListenerMock.Listen); tracker.CollisionStopped.AddListener(trackerCollisionStoppedListenerMock.Listen); UnityEventListenerMock notifierCollisionStartedListenerMock = new UnityEventListenerMock(); UnityEventListenerMock notifierCollisionChangedListenerMock = new UnityEventListenerMock(); UnityEventListenerMock notifierCollisionStoppedListenerMock = new UnityEventListenerMock(); notifier.CollisionStarted.AddListener(notifierCollisionStartedListenerMock.Listen); notifier.CollisionChanged.AddListener(notifierCollisionChangedListenerMock.Listen); notifier.CollisionStopped.AddListener(notifierCollisionStoppedListenerMock.Listen); yield return yieldInstruction; Assert.IsFalse(trackerCollisionStartedListenerMock.Received); Assert.IsFalse(trackerCollisionChangedListenerMock.Received); Assert.IsFalse(trackerCollisionStoppedListenerMock.Received); Assert.IsFalse(notifierCollisionStartedListenerMock.Received); Assert.IsFalse(notifierCollisionChangedListenerMock.Received); Assert.IsFalse(notifierCollisionStoppedListenerMock.Received); trackerCollisionStartedListenerMock.Reset(); trackerCollisionChangedListenerMock.Reset(); trackerCollisionStoppedListenerMock.Reset(); notifierCollisionStartedListenerMock.Reset(); notifierCollisionChangedListenerMock.Reset(); notifierCollisionStoppedListenerMock.Reset(); trackerContainer.transform.position = Vector3.zero; notifierContainer.transform.position = Vector3.zero; yield return yieldInstruction; Assert.IsTrue(trackerCollisionStartedListenerMock.Received); Assert.IsTrue(trackerCollisionChangedListenerMock.Received); Assert.IsFalse(trackerCollisionStoppedListenerMock.Received); Assert.IsTrue(notifierCollisionStartedListenerMock.Received); Assert.IsTrue(notifierCollisionChangedListenerMock.Received); Assert.IsFalse(notifierCollisionStoppedListenerMock.Received); trackerCollisionStartedListenerMock.Reset(); trackerCollisionChangedListenerMock.Reset(); trackerCollisionStoppedListenerMock.Reset(); notifierCollisionStartedListenerMock.Reset(); notifierCollisionChangedListenerMock.Reset(); notifierCollisionStoppedListenerMock.Reset(); trackerContainer.transform.position = Vector3.forward; notifierContainer.transform.position = Vector3.back; yield return yieldInstruction; Assert.IsFalse(trackerCollisionStartedListenerMock.Received); Assert.IsFalse(trackerCollisionChangedListenerMock.Received); Assert.IsFalse(trackerCollisionStoppedListenerMock.Received); Assert.IsFalse(notifierCollisionStartedListenerMock.Received); Assert.IsFalse(notifierCollisionChangedListenerMock.Received); Assert.IsFalse(notifierCollisionStoppedListenerMock.Received); Object.DestroyImmediate(trackerContainer); Object.DestroyImmediate(notifierContainer); } [UnityTest] public IEnumerator CollisionEndsOnNotifierGameObjectDisable() { WaitForFixedUpdate yieldInstruction = new WaitForFixedUpdate(); GameObject trackerContainer = GameObject.CreatePrimitive(PrimitiveType.Cube); trackerContainer.GetComponent<Collider>().isTrigger = true; trackerContainer.AddComponent<Rigidbody>().isKinematic = true; trackerContainer.transform.position = Vector3.forward; CollisionTracker tracker = trackerContainer.AddComponent<CollisionTracker>(); GameObject notifierContainer = GameObject.CreatePrimitive(PrimitiveType.Cube); notifierContainer.GetComponent<Collider>().isTrigger = true; notifierContainer.AddComponent<Rigidbody>().isKinematic = true; notifierContainer.transform.position = Vector3.back; CollisionNotifier notifier = notifierContainer.AddComponent<CollisionNotifier>(); UnityEventListenerMock trackerCollisionStartedListenerMock = new UnityEventListenerMock(); UnityEventListenerMock trackerCollisionChangedListenerMock = new UnityEventListenerMock(); UnityEventListenerMock trackerCollisionStoppedListenerMock = new UnityEventListenerMock(); tracker.CollisionStarted.AddListener(trackerCollisionStartedListenerMock.Listen); tracker.CollisionChanged.AddListener(trackerCollisionChangedListenerMock.Listen); tracker.CollisionStopped.AddListener(trackerCollisionStoppedListenerMock.Listen); UnityEventListenerMock notifierCollisionStartedListenerMock = new UnityEventListenerMock(); UnityEventListenerMock notifierCollisionChangedListenerMock = new UnityEventListenerMock(); UnityEventListenerMock notifierCollisionStoppedListenerMock = new UnityEventListenerMock(); notifier.CollisionStarted.AddListener(notifierCollisionStartedListenerMock.Listen); notifier.CollisionChanged.AddListener(notifierCollisionChangedListenerMock.Listen); notifier.CollisionStopped.AddListener(notifierCollisionStoppedListenerMock.Listen); yield return yieldInstruction; Assert.IsFalse(trackerCollisionStartedListenerMock.Received); Assert.IsFalse(trackerCollisionChangedListenerMock.Received); Assert.IsFalse(trackerCollisionStoppedListenerMock.Received); Assert.IsFalse(notifierCollisionStartedListenerMock.Received); Assert.IsFalse(notifierCollisionChangedListenerMock.Received); Assert.IsFalse(notifierCollisionStoppedListenerMock.Received); trackerCollisionStartedListenerMock.Reset(); trackerCollisionChangedListenerMock.Reset(); trackerCollisionStoppedListenerMock.Reset(); notifierCollisionStartedListenerMock.Reset(); notifierCollisionChangedListenerMock.Reset(); notifierCollisionStoppedListenerMock.Reset(); trackerContainer.transform.position = Vector3.zero; notifierContainer.transform.position = Vector3.zero; yield return yieldInstruction; Assert.IsTrue(trackerCollisionStartedListenerMock.Received); Assert.IsTrue(trackerCollisionChangedListenerMock.Received); Assert.IsFalse(trackerCollisionStoppedListenerMock.Received); Assert.IsTrue(notifierCollisionStartedListenerMock.Received); Assert.IsTrue(notifierCollisionChangedListenerMock.Received); Assert.IsFalse(notifierCollisionStoppedListenerMock.Received); trackerCollisionStartedListenerMock.Reset(); trackerCollisionChangedListenerMock.Reset(); trackerCollisionStoppedListenerMock.Reset(); notifierCollisionStartedListenerMock.Reset(); notifierCollisionChangedListenerMock.Reset(); notifierCollisionStoppedListenerMock.Reset(); notifierContainer.SetActive(false); yield return yieldInstruction; Assert.IsFalse(trackerCollisionStartedListenerMock.Received); Assert.IsFalse(trackerCollisionChangedListenerMock.Received); Assert.IsTrue(trackerCollisionStoppedListenerMock.Received); Assert.IsFalse(notifierCollisionStartedListenerMock.Received); Assert.IsFalse(notifierCollisionChangedListenerMock.Received); Assert.IsTrue(notifierCollisionStoppedListenerMock.Received); Object.DestroyImmediate(trackerContainer); Object.DestroyImmediate(notifierContainer); } [UnityTest] public IEnumerator CollisionEndsOnTrackerGameObjectDisable() { WaitForFixedUpdate yieldInstruction = new WaitForFixedUpdate(); GameObject trackerContainer = GameObject.CreatePrimitive(PrimitiveType.Cube); trackerContainer.GetComponent<Collider>().isTrigger = true; trackerContainer.AddComponent<Rigidbody>().isKinematic = true; trackerContainer.transform.position = Vector3.forward; CollisionTracker tracker = trackerContainer.AddComponent<CollisionTracker>(); GameObject notifierContainer = GameObject.CreatePrimitive(PrimitiveType.Cube); notifierContainer.GetComponent<Collider>().isTrigger = true; notifierContainer.AddComponent<Rigidbody>().isKinematic = true; notifierContainer.transform.position = Vector3.back; CollisionNotifier notifier = notifierContainer.AddComponent<CollisionNotifier>(); UnityEventListenerMock trackerCollisionStartedListenerMock = new UnityEventListenerMock(); UnityEventListenerMock trackerCollisionChangedListenerMock = new UnityEventListenerMock(); UnityEventListenerMock trackerCollisionStoppedListenerMock = new UnityEventListenerMock(); tracker.CollisionStarted.AddListener(trackerCollisionStartedListenerMock.Listen); tracker.CollisionChanged.AddListener(trackerCollisionChangedListenerMock.Listen); tracker.CollisionStopped.AddListener(trackerCollisionStoppedListenerMock.Listen); UnityEventListenerMock notifierCollisionStartedListenerMock = new UnityEventListenerMock(); UnityEventListenerMock notifierCollisionChangedListenerMock = new UnityEventListenerMock(); UnityEventListenerMock notifierCollisionStoppedListenerMock = new UnityEventListenerMock(); notifier.CollisionStarted.AddListener(notifierCollisionStartedListenerMock.Listen); notifier.CollisionChanged.AddListener(notifierCollisionChangedListenerMock.Listen); notifier.CollisionStopped.AddListener(notifierCollisionStoppedListenerMock.Listen); yield return yieldInstruction; Assert.IsFalse(trackerCollisionStartedListenerMock.Received); Assert.IsFalse(trackerCollisionChangedListenerMock.Received); Assert.IsFalse(trackerCollisionStoppedListenerMock.Received); Assert.IsFalse(notifierCollisionStartedListenerMock.Received); Assert.IsFalse(notifierCollisionChangedListenerMock.Received); Assert.IsFalse(notifierCollisionStoppedListenerMock.Received); trackerCollisionStartedListenerMock.Reset(); trackerCollisionChangedListenerMock.Reset(); trackerCollisionStoppedListenerMock.Reset(); notifierCollisionStartedListenerMock.Reset(); notifierCollisionChangedListenerMock.Reset(); notifierCollisionStoppedListenerMock.Reset(); trackerContainer.transform.position = Vector3.zero; notifierContainer.transform.position = Vector3.zero; yield return yieldInstruction; Assert.IsTrue(trackerCollisionStartedListenerMock.Received); Assert.IsTrue(trackerCollisionChangedListenerMock.Received); Assert.IsFalse(trackerCollisionStoppedListenerMock.Received); Assert.IsTrue(notifierCollisionStartedListenerMock.Received); Assert.IsTrue(notifierCollisionChangedListenerMock.Received); Assert.IsFalse(notifierCollisionStoppedListenerMock.Received); trackerCollisionStartedListenerMock.Reset(); trackerCollisionChangedListenerMock.Reset(); trackerCollisionStoppedListenerMock.Reset(); notifierCollisionStartedListenerMock.Reset(); notifierCollisionChangedListenerMock.Reset(); notifierCollisionStoppedListenerMock.Reset(); trackerContainer.SetActive(false); yield return yieldInstruction; Assert.IsFalse(trackerCollisionStartedListenerMock.Received); Assert.IsFalse(trackerCollisionChangedListenerMock.Received); Assert.IsTrue(trackerCollisionStoppedListenerMock.Received); Assert.IsFalse(notifierCollisionStartedListenerMock.Received); Assert.IsFalse(notifierCollisionChangedListenerMock.Received); Assert.IsTrue(notifierCollisionStoppedListenerMock.Received); Object.DestroyImmediate(trackerContainer); Object.DestroyImmediate(notifierContainer); } [UnityTest] public IEnumerator CollisionDoesNotEndOnNotifierGameObjectDisable() { WaitForFixedUpdate yieldInstruction = new WaitForFixedUpdate(); GameObject trackerContainer = GameObject.CreatePrimitive(PrimitiveType.Cube); trackerContainer.GetComponent<Collider>().isTrigger = true; trackerContainer.AddComponent<Rigidbody>().isKinematic = true; trackerContainer.transform.position = Vector3.forward; CollisionTrackerMock tracker = trackerContainer.AddComponent<CollisionTrackerMock>(); tracker.SetStopCollisionsOnDisable(false); GameObject notifierContainer = GameObject.CreatePrimitive(PrimitiveType.Cube); notifierContainer.GetComponent<Collider>().isTrigger = true; notifierContainer.AddComponent<Rigidbody>().isKinematic = true; notifierContainer.transform.position = Vector3.back; CollisionNotifier notifier = notifierContainer.AddComponent<CollisionNotifier>(); UnityEventListenerMock trackerCollisionStartedListenerMock = new UnityEventListenerMock(); UnityEventListenerMock trackerCollisionChangedListenerMock = new UnityEventListenerMock(); UnityEventListenerMock trackerCollisionStoppedListenerMock = new UnityEventListenerMock(); tracker.CollisionStarted.AddListener(trackerCollisionStartedListenerMock.Listen); tracker.CollisionChanged.AddListener(trackerCollisionChangedListenerMock.Listen); tracker.CollisionStopped.AddListener(trackerCollisionStoppedListenerMock.Listen); UnityEventListenerMock notifierCollisionStartedListenerMock = new UnityEventListenerMock(); UnityEventListenerMock notifierCollisionChangedListenerMock = new UnityEventListenerMock(); UnityEventListenerMock notifierCollisionStoppedListenerMock = new UnityEventListenerMock(); notifier.CollisionStarted.AddListener(notifierCollisionStartedListenerMock.Listen); notifier.CollisionChanged.AddListener(notifierCollisionChangedListenerMock.Listen); notifier.CollisionStopped.AddListener(notifierCollisionStoppedListenerMock.Listen); yield return yieldInstruction; Assert.IsFalse(trackerCollisionStartedListenerMock.Received); Assert.IsFalse(trackerCollisionChangedListenerMock.Received); Assert.IsFalse(trackerCollisionStoppedListenerMock.Received); Assert.IsFalse(notifierCollisionStartedListenerMock.Received); Assert.IsFalse(notifierCollisionChangedListenerMock.Received); Assert.IsFalse(notifierCollisionStoppedListenerMock.Received); trackerCollisionStartedListenerMock.Reset(); trackerCollisionChangedListenerMock.Reset(); trackerCollisionStoppedListenerMock.Reset(); notifierCollisionStartedListenerMock.Reset(); notifierCollisionChangedListenerMock.Reset(); notifierCollisionStoppedListenerMock.Reset(); trackerContainer.transform.position = Vector3.zero; notifierContainer.transform.position = Vector3.zero; yield return yieldInstruction; Assert.IsTrue(trackerCollisionStartedListenerMock.Received); Assert.IsTrue(trackerCollisionChangedListenerMock.Received); Assert.IsFalse(trackerCollisionStoppedListenerMock.Received); Assert.IsTrue(notifierCollisionStartedListenerMock.Received); Assert.IsTrue(notifierCollisionChangedListenerMock.Received); Assert.IsFalse(notifierCollisionStoppedListenerMock.Received); trackerCollisionStartedListenerMock.Reset(); trackerCollisionChangedListenerMock.Reset(); trackerCollisionStoppedListenerMock.Reset(); notifierCollisionStartedListenerMock.Reset(); notifierCollisionChangedListenerMock.Reset(); notifierCollisionStoppedListenerMock.Reset(); notifierContainer.SetActive(false); yield return yieldInstruction; Assert.IsFalse(trackerCollisionStartedListenerMock.Received); Assert.IsFalse(trackerCollisionChangedListenerMock.Received); Assert.IsFalse(trackerCollisionStoppedListenerMock.Received); Assert.IsFalse(notifierCollisionStartedListenerMock.Received); Assert.IsFalse(notifierCollisionChangedListenerMock.Received); Assert.IsFalse(notifierCollisionStoppedListenerMock.Received); Object.DestroyImmediate(trackerContainer); Object.DestroyImmediate(notifierContainer); } [UnityTest] public IEnumerator CollisionDoesNotEndOnTrackerGameObjectDisable() { WaitForFixedUpdate yieldInstruction = new WaitForFixedUpdate(); GameObject trackerContainer = GameObject.CreatePrimitive(PrimitiveType.Cube); trackerContainer.GetComponent<Collider>().isTrigger = true; trackerContainer.AddComponent<Rigidbody>().isKinematic = true; trackerContainer.transform.position = Vector3.forward; CollisionTrackerMock tracker = trackerContainer.AddComponent<CollisionTrackerMock>(); tracker.SetStopCollisionsOnDisable(false); GameObject notifierContainer = GameObject.CreatePrimitive(PrimitiveType.Cube); notifierContainer.GetComponent<Collider>().isTrigger = true; notifierContainer.AddComponent<Rigidbody>().isKinematic = true; notifierContainer.transform.position = Vector3.back; CollisionNotifier notifier = notifierContainer.AddComponent<CollisionNotifier>(); UnityEventListenerMock trackerCollisionStartedListenerMock = new UnityEventListenerMock(); UnityEventListenerMock trackerCollisionChangedListenerMock = new UnityEventListenerMock(); UnityEventListenerMock trackerCollisionStoppedListenerMock = new UnityEventListenerMock(); tracker.CollisionStarted.AddListener(trackerCollisionStartedListenerMock.Listen); tracker.CollisionChanged.AddListener(trackerCollisionChangedListenerMock.Listen); tracker.CollisionStopped.AddListener(trackerCollisionStoppedListenerMock.Listen); UnityEventListenerMock notifierCollisionStartedListenerMock = new UnityEventListenerMock(); UnityEventListenerMock notifierCollisionChangedListenerMock = new UnityEventListenerMock(); UnityEventListenerMock notifierCollisionStoppedListenerMock = new UnityEventListenerMock(); notifier.CollisionStarted.AddListener(notifierCollisionStartedListenerMock.Listen); notifier.CollisionChanged.AddListener(notifierCollisionChangedListenerMock.Listen); notifier.CollisionStopped.AddListener(notifierCollisionStoppedListenerMock.Listen); yield return yieldInstruction; Assert.IsFalse(trackerCollisionStartedListenerMock.Received); Assert.IsFalse(trackerCollisionChangedListenerMock.Received); Assert.IsFalse(trackerCollisionStoppedListenerMock.Received); Assert.IsFalse(notifierCollisionStartedListenerMock.Received); Assert.IsFalse(notifierCollisionChangedListenerMock.Received); Assert.IsFalse(notifierCollisionStoppedListenerMock.Received); trackerCollisionStartedListenerMock.Reset(); trackerCollisionChangedListenerMock.Reset(); trackerCollisionStoppedListenerMock.Reset(); notifierCollisionStartedListenerMock.Reset(); notifierCollisionChangedListenerMock.Reset(); notifierCollisionStoppedListenerMock.Reset(); trackerContainer.transform.position = Vector3.zero; notifierContainer.transform.position = Vector3.zero; yield return yieldInstruction; Assert.IsTrue(trackerCollisionStartedListenerMock.Received); Assert.IsTrue(trackerCollisionChangedListenerMock.Received); Assert.IsFalse(trackerCollisionStoppedListenerMock.Received); Assert.IsTrue(notifierCollisionStartedListenerMock.Received); Assert.IsTrue(notifierCollisionChangedListenerMock.Received); Assert.IsFalse(notifierCollisionStoppedListenerMock.Received); trackerCollisionStartedListenerMock.Reset(); trackerCollisionChangedListenerMock.Reset(); trackerCollisionStoppedListenerMock.Reset(); notifierCollisionStartedListenerMock.Reset(); notifierCollisionChangedListenerMock.Reset(); notifierCollisionStoppedListenerMock.Reset(); trackerContainer.SetActive(false); yield return yieldInstruction; Assert.IsFalse(trackerCollisionStartedListenerMock.Received); Assert.IsFalse(trackerCollisionChangedListenerMock.Received); Assert.IsFalse(trackerCollisionStoppedListenerMock.Received); Assert.IsFalse(notifierCollisionStartedListenerMock.Received); Assert.IsFalse(notifierCollisionChangedListenerMock.Received); Assert.IsFalse(notifierCollisionStoppedListenerMock.Received); Object.DestroyImmediate(trackerContainer); Object.DestroyImmediate(notifierContainer); } [UnityTest] public IEnumerator CollisionCheckExitEnterOnKinematicChange() { WaitForFixedUpdate yieldInstruction = new WaitForFixedUpdate(); GameObject trackerContainer = GameObject.CreatePrimitive(PrimitiveType.Cube); trackerContainer.name = "TrackerContainer"; trackerContainer.GetComponent<Collider>().isTrigger = true; trackerContainer.AddComponent<Rigidbody>().isKinematic = true; trackerContainer.transform.position = Vector3.forward; trackerContainer.transform.localScale = Vector3.one * 0.1f; CollisionTrackerMock tracker = trackerContainer.AddComponent<CollisionTrackerMock>(); UnityEventListenerMock trackerCollisionStartedListenerMock = new UnityEventListenerMock(); UnityEventListenerMock trackerCollisionStoppedListenerMock = new UnityEventListenerMock(); tracker.CollisionStarted.AddListener(trackerCollisionStartedListenerMock.Listen); tracker.CollisionStopped.AddListener(trackerCollisionStoppedListenerMock.Listen); GameObject targetContainer = new GameObject("TargetContainer"); targetContainer.transform.localPosition = Vector3.zero; targetContainer.transform.localScale = Vector3.one; GameObject childOne = GameObject.CreatePrimitive(PrimitiveType.Cube); childOne.name = "childOne"; childOne.transform.SetParent(targetContainer.transform); childOne.transform.localPosition = Vector3.zero; childOne.transform.localScale = Vector3.one * 0.2f; GameObject childTwo = GameObject.CreatePrimitive(PrimitiveType.Cube); childTwo.name = "childTwo"; childTwo.transform.SetParent(targetContainer.transform); childTwo.transform.localPosition = Vector3.left * 0.2f; childTwo.transform.localScale = Vector3.one * 0.2f; Rigidbody targetRigidbody = targetContainer.AddComponent<Rigidbody>(); targetRigidbody.useGravity = false; yield return yieldInstruction; Assert.IsFalse(trackerCollisionStartedListenerMock.Received); Assert.IsFalse(trackerCollisionStoppedListenerMock.Received); trackerCollisionStartedListenerMock.Reset(); trackerCollisionStoppedListenerMock.Reset(); tracker.LatestStartedEventData.Clear(); tracker.LatestStoppedEventData.Clear(); /// 1. First do a simple touch childOne to check started is called. trackerContainer.transform.position = childOne.transform.position; yield return yieldInstruction; Assert.IsTrue(trackerCollisionStartedListenerMock.Received); Assert.IsFalse(trackerCollisionStoppedListenerMock.Received); trackerCollisionStartedListenerMock.Reset(); trackerCollisionStoppedListenerMock.Reset(); Assert.AreEqual(childOne.transform, tracker.LatestStartedEventData.ColliderData.transform); Assert.AreEqual(targetRigidbody, tracker.LatestStartedEventData.ColliderData.attachedRigidbody); Assert.IsTrue(tracker.IsEventDataEmpty(tracker.LatestStoppedEventData)); tracker.LatestStartedEventData.Clear(); tracker.LatestStoppedEventData.Clear(); /// 1. Then untouch childOne to check stopped is called trackerContainer.transform.position = Vector3.forward; yield return yieldInstruction; Assert.IsFalse(trackerCollisionStartedListenerMock.Received); Assert.IsTrue(trackerCollisionStoppedListenerMock.Received); trackerCollisionStartedListenerMock.Reset(); trackerCollisionStoppedListenerMock.Reset(); Assert.AreEqual(childOne.transform, tracker.LatestStoppedEventData.ColliderData.transform); Assert.AreEqual(targetRigidbody, tracker.LatestStoppedEventData.ColliderData.attachedRigidbody); Assert.IsTrue(tracker.IsEventDataEmpty(tracker.LatestStartedEventData)); tracker.LatestStartedEventData.Clear(); tracker.LatestStoppedEventData.Clear(); yield return yieldInstruction; /// 1. Now touch childOne, check start is called, then switch target to kinematic trackerContainer.transform.position = childOne.transform.position; yield return yieldInstruction; Assert.IsTrue(trackerCollisionStartedListenerMock.Received); Assert.IsFalse(trackerCollisionStoppedListenerMock.Received); trackerCollisionStartedListenerMock.Reset(); trackerCollisionStoppedListenerMock.Reset(); tracker.PrepareKinematicStateChange(targetRigidbody); targetRigidbody.isKinematic = true; yield return yieldInstruction; Assert.IsFalse(trackerCollisionStartedListenerMock.Received); Assert.IsFalse(trackerCollisionStoppedListenerMock.Received); trackerCollisionStartedListenerMock.Reset(); trackerCollisionStoppedListenerMock.Reset(); Assert.AreEqual(childOne.transform, tracker.LatestStartedEventData.ColliderData.transform); Assert.AreEqual(targetRigidbody, tracker.LatestStartedEventData.ColliderData.attachedRigidbody); Assert.IsTrue(tracker.IsEventDataEmpty(tracker.LatestStoppedEventData)); tracker.LatestStartedEventData.Clear(); tracker.LatestStoppedEventData.Clear(); /// 1. Then untouch childOne but remove kinematic state first tracker.PrepareKinematicStateChange(targetRigidbody); targetRigidbody.isKinematic = false; yield return yieldInstruction; Assert.IsFalse(trackerCollisionStartedListenerMock.Received); Assert.IsFalse(trackerCollisionStoppedListenerMock.Received); trackerCollisionStartedListenerMock.Reset(); trackerCollisionStoppedListenerMock.Reset(); trackerContainer.transform.position = Vector3.forward; yield return yieldInstruction; Assert.IsFalse(trackerCollisionStartedListenerMock.Received); Assert.IsTrue(trackerCollisionStoppedListenerMock.Received); trackerCollisionStartedListenerMock.Reset(); trackerCollisionStoppedListenerMock.Reset(); Assert.AreEqual(childOne.transform, tracker.LatestStoppedEventData.ColliderData.transform); Assert.AreEqual(targetRigidbody, tracker.LatestStoppedEventData.ColliderData.attachedRigidbody); Assert.IsTrue(tracker.IsEventDataEmpty(tracker.LatestStartedEventData)); tracker.LatestStartedEventData.Clear(); tracker.LatestStoppedEventData.Clear(); /// 2. Now do a simple touch childTwo to check started is called. trackerContainer.transform.position = childTwo.transform.position; yield return yieldInstruction; Assert.IsTrue(trackerCollisionStartedListenerMock.Received); Assert.IsFalse(trackerCollisionStoppedListenerMock.Received); trackerCollisionStartedListenerMock.Reset(); trackerCollisionStoppedListenerMock.Reset(); Assert.AreEqual(childTwo.transform, tracker.LatestStartedEventData.ColliderData.transform); Assert.AreEqual(targetRigidbody, tracker.LatestStartedEventData.ColliderData.attachedRigidbody); Assert.IsTrue(tracker.IsEventDataEmpty(tracker.LatestStoppedEventData)); tracker.LatestStartedEventData.Clear(); tracker.LatestStoppedEventData.Clear(); /// 2. Then untouch childTwo to check stopped is called trackerContainer.transform.position = Vector3.forward; yield return yieldInstruction; Assert.IsFalse(trackerCollisionStartedListenerMock.Received); Assert.IsTrue(trackerCollisionStoppedListenerMock.Received); trackerCollisionStartedListenerMock.Reset(); trackerCollisionStoppedListenerMock.Reset(); Assert.AreEqual(childTwo.transform, tracker.LatestStoppedEventData.ColliderData.transform); Assert.AreEqual(targetRigidbody, tracker.LatestStoppedEventData.ColliderData.attachedRigidbody); Assert.IsTrue(tracker.IsEventDataEmpty(tracker.LatestStartedEventData)); tracker.LatestStartedEventData.Clear(); tracker.LatestStoppedEventData.Clear(); /// 2. Now touch childTwo, check start is called, then switch target to kinematic trackerContainer.transform.position = childTwo.transform.position; yield return yieldInstruction; Assert.IsTrue(trackerCollisionStartedListenerMock.Received); Assert.IsFalse(trackerCollisionStoppedListenerMock.Received); trackerCollisionStartedListenerMock.Reset(); trackerCollisionStoppedListenerMock.Reset(); tracker.PrepareKinematicStateChange(targetRigidbody); targetRigidbody.isKinematic = true; yield return yieldInstruction; Assert.IsFalse(trackerCollisionStartedListenerMock.Received); Assert.IsFalse(trackerCollisionStoppedListenerMock.Received); trackerCollisionStartedListenerMock.Reset(); trackerCollisionStoppedListenerMock.Reset(); Assert.AreEqual(childTwo.transform, tracker.LatestStartedEventData.ColliderData.transform); Assert.AreEqual(targetRigidbody, tracker.LatestStartedEventData.ColliderData.attachedRigidbody); Assert.IsTrue(tracker.IsEventDataEmpty(tracker.LatestStoppedEventData)); tracker.LatestStartedEventData.Clear(); tracker.LatestStoppedEventData.Clear(); /// 2. Then untouch childTwo but remove kinematic state first tracker.PrepareKinematicStateChange(targetRigidbody); targetRigidbody.isKinematic = false; yield return yieldInstruction; Assert.IsFalse(trackerCollisionStartedListenerMock.Received); Assert.IsFalse(trackerCollisionStoppedListenerMock.Received); trackerCollisionStartedListenerMock.Reset(); trackerCollisionStoppedListenerMock.Reset(); trackerContainer.transform.position = Vector3.forward; yield return yieldInstruction; Assert.IsFalse(trackerCollisionStartedListenerMock.Received); Assert.IsTrue(trackerCollisionStoppedListenerMock.Received); trackerCollisionStartedListenerMock.Reset(); trackerCollisionStoppedListenerMock.Reset(); Assert.AreEqual(childTwo.transform, tracker.LatestStoppedEventData.ColliderData.transform); Assert.AreEqual(targetRigidbody, tracker.LatestStoppedEventData.ColliderData.attachedRigidbody); Assert.IsTrue(tracker.IsEventDataEmpty(tracker.LatestStartedEventData)); tracker.LatestStartedEventData.Clear(); tracker.LatestStoppedEventData.Clear(); /// 3. Now touch childTwo, but when kinematic is changed, in the same frame move the touch to childOne trackerContainer.transform.position = childTwo.transform.position; yield return yieldInstruction; Assert.IsTrue(trackerCollisionStartedListenerMock.Received); Assert.IsFalse(trackerCollisionStoppedListenerMock.Received); trackerCollisionStartedListenerMock.Reset(); trackerCollisionStoppedListenerMock.Reset(); Assert.AreEqual(childTwo.transform, tracker.LatestStartedEventData.ColliderData.transform); Assert.AreEqual(targetRigidbody, tracker.LatestStartedEventData.ColliderData.attachedRigidbody); Assert.IsTrue(tracker.IsEventDataEmpty(tracker.LatestStoppedEventData)); tracker.LatestStartedEventData.Clear(); tracker.LatestStoppedEventData.Clear(); tracker.PrepareKinematicStateChange(targetRigidbody); targetRigidbody.isKinematic = true; trackerContainer.transform.position = childOne.transform.position; yield return yieldInstruction; Assert.IsTrue(trackerCollisionStartedListenerMock.Received); /// Wait a frame for the trigger exit fix in 2019 yield return yieldInstruction; Assert.IsTrue(trackerCollisionStoppedListenerMock.Received); trackerCollisionStartedListenerMock.Reset(); trackerCollisionStoppedListenerMock.Reset(); Assert.AreEqual(childOne.transform, tracker.LatestStartedEventData.ColliderData.transform); Assert.AreEqual(targetRigidbody, tracker.LatestStartedEventData.ColliderData.attachedRigidbody); Assert.AreEqual(childTwo.transform, tracker.LatestStoppedEventData.ColliderData.transform); tracker.LatestStartedEventData.Clear(); tracker.LatestStoppedEventData.Clear(); /// 3. Then untouch childOne but remove kinematic state first tracker.PrepareKinematicStateChange(targetRigidbody); targetRigidbody.isKinematic = false; trackerContainer.transform.position = Vector3.forward; yield return yieldInstruction; Assert.IsFalse(trackerCollisionStartedListenerMock.Received); /// Wait a frame for the trigger exit fix in 2019 yield return yieldInstruction; Assert.IsTrue(trackerCollisionStoppedListenerMock.Received); trackerCollisionStartedListenerMock.Reset(); trackerCollisionStoppedListenerMock.Reset(); Assert.AreEqual(childOne.transform, tracker.LatestStoppedEventData.ColliderData.transform); Assert.AreEqual(targetRigidbody, tracker.LatestStoppedEventData.ColliderData.attachedRigidbody); Assert.IsTrue(tracker.IsEventDataEmpty(tracker.LatestStartedEventData)); tracker.LatestStartedEventData.Clear(); tracker.LatestStoppedEventData.Clear(); /// Clean up Object.DestroyImmediate(trackerContainer); Object.DestroyImmediate(targetContainer); } [Test] public void ClearColliderValidity() { GameObject containingObject = new GameObject(); CollisionTracker subject = containingObject.AddComponent<CollisionTracker>(); Assert.IsNull(subject.ColliderValidity); RuleContainer rule = new RuleContainer(); subject.ColliderValidity = rule; Assert.AreEqual(rule, subject.ColliderValidity); subject.ClearColliderValidity(); Assert.IsNull(subject.ColliderValidity); Object.DestroyImmediate(containingObject); } [Test] public void ClearColliderValidityInactiveGameObject() { GameObject containingObject = new GameObject(); CollisionTracker subject = containingObject.AddComponent<CollisionTracker>(); Assert.IsNull(subject.ColliderValidity); RuleContainer rule = new RuleContainer(); subject.ColliderValidity = rule; Assert.AreEqual(rule, subject.ColliderValidity); subject.gameObject.SetActive(false); subject.ClearColliderValidity(); Assert.AreEqual(rule, subject.ColliderValidity); Object.DestroyImmediate(containingObject); } [Test] public void ClearColliderValidityInactiveComponent() { GameObject containingObject = new GameObject(); CollisionTracker subject = containingObject.AddComponent<CollisionTracker>(); Assert.IsNull(subject.ColliderValidity); RuleContainer rule = new RuleContainer(); subject.ColliderValidity = rule; Assert.AreEqual(rule, subject.ColliderValidity); subject.enabled = false; subject.ClearColliderValidity(); Assert.AreEqual(rule, subject.ColliderValidity); Object.DestroyImmediate(containingObject); } [Test] public void ClearContainingTransformValidity() { GameObject containingObject = new GameObject(); CollisionTracker subject = containingObject.AddComponent<CollisionTracker>(); Assert.IsNull(subject.ContainingTransformValidity); RuleContainer rule = new RuleContainer(); subject.ContainingTransformValidity = rule; Assert.AreEqual(rule, subject.ContainingTransformValidity); subject.ClearContainingTransformValidity(); Assert.IsNull(subject.ContainingTransformValidity); Object.DestroyImmediate(containingObject); } [Test] public void ClearContainingTransformValidityInactiveGameObject() { GameObject containingObject = new GameObject(); CollisionTracker subject = containingObject.AddComponent<CollisionTracker>(); Assert.IsNull(subject.ContainingTransformValidity); RuleContainer rule = new RuleContainer(); subject.ContainingTransformValidity = rule; Assert.AreEqual(rule, subject.ContainingTransformValidity); subject.gameObject.SetActive(false); subject.ClearContainingTransformValidity(); Assert.AreEqual(rule, subject.ContainingTransformValidity); Object.DestroyImmediate(containingObject); } [Test] public void ClearContainingTransformValidityInactiveComponent() { GameObject containingObject = new GameObject(); CollisionTracker subject = containingObject.AddComponent<CollisionTracker>(); Assert.IsNull(subject.ContainingTransformValidity); RuleContainer rule = new RuleContainer(); subject.ContainingTransformValidity = rule; Assert.AreEqual(rule, subject.ContainingTransformValidity); subject.enabled = false; subject.ClearContainingTransformValidity(); Assert.AreEqual(rule, subject.ContainingTransformValidity); Object.DestroyImmediate(containingObject); } [Test] public void CollisionTrackerDisabledObserver_ClearSource() { GameObject containingObject = new GameObject(); CollisionTrackerDisabledObserver subject = containingObject.AddComponent<CollisionTrackerDisabledObserver>(); CollisionTracker tracker = containingObject.AddComponent<CollisionTracker>(); Assert.IsNull(subject.Source); subject.Source = tracker; Assert.AreEqual(tracker, subject.Source); subject.ClearSource(); Assert.IsNull(subject.Source); Object.DestroyImmediate(containingObject); } [Test] public void CollisionTrackerDisabledObserver_ClearSourceInactiveGameObject() { GameObject containingObject = new GameObject(); CollisionTrackerDisabledObserver subject = containingObject.AddComponent<CollisionTrackerDisabledObserver>(); CollisionTracker tracker = containingObject.AddComponent<CollisionTracker>(); Assert.IsNull(subject.Source); subject.Source = tracker; Assert.AreEqual(tracker, subject.Source); subject.gameObject.SetActive(false); subject.ClearSource(); Assert.AreEqual(tracker, subject.Source); Object.DestroyImmediate(containingObject); } [Test] public void CollisionTrackerDisabledObserver_ClearSourceInactiveComponent() { GameObject containingObject = new GameObject(); CollisionTrackerDisabledObserver subject = containingObject.AddComponent<CollisionTrackerDisabledObserver>(); CollisionTracker tracker = containingObject.AddComponent<CollisionTracker>(); Assert.IsNull(subject.Source); subject.Source = tracker; Assert.AreEqual(tracker, subject.Source); subject.enabled = false; subject.ClearSource(); Assert.AreEqual(tracker, subject.Source); Object.DestroyImmediate(containingObject); } [Test] public void CollisionTrackerDisabledObserver_ClearTarget() { GameObject containingObject = new GameObject(); CollisionTrackerDisabledObserver subject = containingObject.AddComponent<CollisionTrackerDisabledObserver>(); BoxCollider collider = containingObject.AddComponent<BoxCollider>(); Assert.IsNull(subject.Target); subject.Target = collider; Assert.AreEqual(collider, subject.Target); subject.ClearTarget(); Assert.IsNull(subject.Target); Object.DestroyImmediate(containingObject); } [Test] public void CollisionTrackerDisabledObserver_ClearTargetInactiveGameObject() { GameObject containingObject = new GameObject(); CollisionTrackerDisabledObserver subject = containingObject.AddComponent<CollisionTrackerDisabledObserver>(); BoxCollider collider = containingObject.AddComponent<BoxCollider>(); Assert.IsNull(subject.Target); subject.Target = collider; Assert.AreEqual(collider, subject.Target); subject.gameObject.SetActive(false); subject.ClearTarget(); Assert.AreEqual(collider, subject.Target); Object.DestroyImmediate(containingObject); } [Test] public void CollisionTrackerDisabledObserver_ClearTargetInactiveComponent() { GameObject containingObject = new GameObject(); CollisionTrackerDisabledObserver subject = containingObject.AddComponent<CollisionTrackerDisabledObserver>(); BoxCollider collider = containingObject.AddComponent<BoxCollider>(); Assert.IsNull(subject.Target); subject.Target = collider; Assert.AreEqual(collider, subject.Target); subject.enabled = false; subject.ClearTarget(); Assert.AreEqual(collider, subject.Target); Object.DestroyImmediate(containingObject); } public class CollisionTrackerMock : CollisionTracker { public EventData LatestStartedEventData { get; set; } = new EventData(); public EventData LatestStoppedEventData { get; set; } = new EventData(); public virtual void SetStopCollisionsOnDisable(bool state) { StopCollisionsOnDisable = state; } public override void OnCollisionStarted(EventData data) { base.OnCollisionStarted(data); LatestStartedEventData = new EventData(); LatestStartedEventData.Set(data); } public override void OnCollisionStopped(EventData data) { base.OnCollisionStopped(data); LatestStoppedEventData = new EventData(); LatestStoppedEventData.Set(data); } public virtual bool IsEventDataEmpty(EventData data) { return (data.ForwardSource == default && data.IsTrigger == default && data.CollisionData == default && data.ColliderData == default); } } } }
49.480353
149
0.717724
[ "MIT" ]
ExtendRealityLtd/VRTK.Unity.Core
Tests/Editor/Tracking/Collision/CollisionTrackerTest.cs
61,704
C#
// dnlib: See LICENSE.txt for more info using System; using System.Collections.Generic; namespace dnlib.DotNet { enum ClrAssembly { Mscorlib, SystemNumericsVectors, SystemObjectModel, SystemRuntime, SystemRuntimeInteropServicesWindowsRuntime, SystemRuntimeWindowsRuntime, SystemRuntimeWindowsRuntimeUIXaml, } static class WinMDHelpers { struct ClassName : IEquatable<ClassName> { public readonly UTF8String Namespace; public readonly UTF8String Name; // Not used when comparing for equality etc public readonly bool IsValueType; public ClassName(UTF8String ns, UTF8String name, bool isValueType = false) { this.Namespace = ns; this.Name = name; this.IsValueType = isValueType; } public ClassName(string ns, string name, bool isValueType = false) { this.Namespace = ns; this.Name = name; this.IsValueType = isValueType; } public static bool operator ==(ClassName a, ClassName b) { return a.Equals(b); } public static bool operator !=(ClassName a, ClassName b) { return !a.Equals(b); } public bool Equals(ClassName other) { // Don't check IsValueType return UTF8String.Equals(Namespace, other.Namespace) && UTF8String.Equals(Name, other.Name); } public override bool Equals(object obj) { if (!(obj is ClassName)) return false; return Equals((ClassName)obj); } public override int GetHashCode() { // Don't use IsValueType return UTF8String.GetHashCode(Namespace) ^ UTF8String.GetHashCode(Name); } public override string ToString() { return string.Format("{0}.{1}", Namespace, Name); } } sealed class ProjectedClass { public readonly ClassName WinMDClass; public readonly ClassName ClrClass; public readonly ClrAssembly ClrAssembly; public readonly ClrAssembly ContractAssembly; public ProjectedClass(string mdns, string mdname, string clrns, string clrname, ClrAssembly clrAsm, ClrAssembly contractAsm, bool winMDValueType, bool clrValueType) { this.WinMDClass = new ClassName(mdns, mdname, winMDValueType); this.ClrClass = new ClassName(clrns, clrname, clrValueType); this.ClrAssembly = clrAsm; this.ContractAssembly = contractAsm; } public override string ToString() { return string.Format("{0} <-> {1}, {2}", WinMDClass, ClrClass, CreateAssembly(null, ContractAssembly)); } } // See https://github.com/dotnet/coreclr/blob/master/src/inc/winrtprojectedtypes.h // To generate this code replace the contents of src/inc/winrtprojectedtypes.h with: // DEFINE_PROJECTED_ENUM // => DEFINE_PROJECTED_STRUCT // ^DEFINE_PROJECTED\w*_STRUCT\s*\(("[^"]+"),\s*("[^"]+"),\s*("[^"]+"),\s*("[^"]+"),\s*(\w+),\s*(\w+).*$ // => \t\t\tnew ProjectedClass(\1, \2, \3, \4, ClrAssembly.\5, ClrAssembly.\6, true, true), // ^DEFINE_PROJECTED\w+\s*\(("[^"]+"),\s*("[^"]+"),\s*("[^"]+"),\s*("[^"]+"),\s*(\w+),\s*(\w+).*$ // => \t\t\tnew ProjectedClass(\1, \2, \3, \4, ClrAssembly.\5, ClrAssembly.\6, false, false), // Sometimes the types aren't both structs or both classes. Known cases: // IReference`1 (class) vs Nullable`1 (struct) // IKeyValuePair`2 (class) vs KeyValuePair`2 (struct) // TypeName (struct) vs Type (class) // HResult (struct) vs Exception (class) // See md/winmd/adapter.cpp WinMDAdapter::RewriteTypeInSignature() or check the types // in a decompiler. static readonly ProjectedClass[] ProjectedClasses = new ProjectedClass[] { new ProjectedClass("Windows.Foundation.Metadata", "AttributeUsageAttribute", "System", "AttributeUsageAttribute", ClrAssembly.Mscorlib, ClrAssembly.SystemRuntime, false, false), new ProjectedClass("Windows.Foundation.Metadata", "AttributeTargets", "System", "AttributeTargets", ClrAssembly.Mscorlib, ClrAssembly.SystemRuntime, true, true), new ProjectedClass("Windows.UI", "Color", "Windows.UI", "Color", ClrAssembly.SystemRuntimeWindowsRuntime, ClrAssembly.SystemRuntimeWindowsRuntime, true, true), new ProjectedClass("Windows.Foundation", "DateTime", "System", "DateTimeOffset", ClrAssembly.Mscorlib, ClrAssembly.SystemRuntime, true, true), new ProjectedClass("Windows.Foundation", "EventHandler`1", "System", "EventHandler`1", ClrAssembly.Mscorlib, ClrAssembly.SystemRuntime, false, false), new ProjectedClass("Windows.Foundation", "EventRegistrationToken", "System.Runtime.InteropServices.WindowsRuntime", "EventRegistrationToken", ClrAssembly.Mscorlib, ClrAssembly.SystemRuntimeInteropServicesWindowsRuntime, true, true), new ProjectedClass("Windows.Foundation", "HResult", "System", "Exception", ClrAssembly.Mscorlib, ClrAssembly.SystemRuntime, true, false), new ProjectedClass("Windows.Foundation", "IReference`1", "System", "Nullable`1", ClrAssembly.Mscorlib, ClrAssembly.SystemRuntime, false, true), new ProjectedClass("Windows.Foundation", "Point", "Windows.Foundation", "Point", ClrAssembly.SystemRuntimeWindowsRuntime, ClrAssembly.SystemRuntimeWindowsRuntime, true, true), new ProjectedClass("Windows.Foundation", "Rect", "Windows.Foundation", "Rect", ClrAssembly.SystemRuntimeWindowsRuntime, ClrAssembly.SystemRuntimeWindowsRuntime, true, true), new ProjectedClass("Windows.Foundation", "Size", "Windows.Foundation", "Size", ClrAssembly.SystemRuntimeWindowsRuntime, ClrAssembly.SystemRuntimeWindowsRuntime, true, true), new ProjectedClass("Windows.Foundation", "TimeSpan", "System", "TimeSpan", ClrAssembly.Mscorlib, ClrAssembly.SystemRuntime, true, true), new ProjectedClass("Windows.Foundation", "Uri", "System", "Uri", ClrAssembly.SystemRuntime, ClrAssembly.SystemRuntime, false, false), new ProjectedClass("Windows.Foundation", "IClosable", "System", "IDisposable", ClrAssembly.Mscorlib, ClrAssembly.SystemRuntime, false, false), new ProjectedClass("Windows.Foundation.Collections", "IIterable`1", "System.Collections.Generic", "IEnumerable`1", ClrAssembly.Mscorlib, ClrAssembly.SystemRuntime, false, false), new ProjectedClass("Windows.Foundation.Collections", "IVector`1", "System.Collections.Generic", "IList`1", ClrAssembly.Mscorlib, ClrAssembly.SystemRuntime, false, false), new ProjectedClass("Windows.Foundation.Collections", "IVectorView`1", "System.Collections.Generic", "IReadOnlyList`1", ClrAssembly.Mscorlib, ClrAssembly.SystemRuntime, false, false), new ProjectedClass("Windows.Foundation.Collections", "IMap`2", "System.Collections.Generic", "IDictionary`2", ClrAssembly.Mscorlib, ClrAssembly.SystemRuntime, false, false), new ProjectedClass("Windows.Foundation.Collections", "IMapView`2", "System.Collections.Generic", "IReadOnlyDictionary`2", ClrAssembly.Mscorlib, ClrAssembly.SystemRuntime, false, false), new ProjectedClass("Windows.Foundation.Collections", "IKeyValuePair`2", "System.Collections.Generic", "KeyValuePair`2", ClrAssembly.Mscorlib, ClrAssembly.SystemRuntime, false, true), new ProjectedClass("Windows.UI.Xaml.Input", "ICommand", "System.Windows.Input", "ICommand", ClrAssembly.SystemObjectModel, ClrAssembly.SystemObjectModel, false, false), new ProjectedClass("Windows.UI.Xaml.Interop", "IBindableIterable", "System.Collections", "IEnumerable", ClrAssembly.Mscorlib, ClrAssembly.SystemRuntime, false, false), new ProjectedClass("Windows.UI.Xaml.Interop", "IBindableVector", "System.Collections", "IList", ClrAssembly.Mscorlib, ClrAssembly.SystemRuntime, false, false), new ProjectedClass("Windows.UI.Xaml.Interop", "INotifyCollectionChanged", "System.Collections.Specialized", "INotifyCollectionChanged", ClrAssembly.SystemObjectModel, ClrAssembly.SystemObjectModel, false, false), new ProjectedClass("Windows.UI.Xaml.Interop", "NotifyCollectionChangedEventHandler", "System.Collections.Specialized", "NotifyCollectionChangedEventHandler", ClrAssembly.SystemObjectModel, ClrAssembly.SystemObjectModel, false, false), new ProjectedClass("Windows.UI.Xaml.Interop", "NotifyCollectionChangedEventArgs", "System.Collections.Specialized", "NotifyCollectionChangedEventArgs", ClrAssembly.SystemObjectModel, ClrAssembly.SystemObjectModel, false, false), new ProjectedClass("Windows.UI.Xaml.Interop", "NotifyCollectionChangedAction", "System.Collections.Specialized", "NotifyCollectionChangedAction", ClrAssembly.SystemObjectModel, ClrAssembly.SystemObjectModel, true, true), new ProjectedClass("Windows.UI.Xaml.Data", "INotifyPropertyChanged", "System.ComponentModel", "INotifyPropertyChanged", ClrAssembly.SystemObjectModel, ClrAssembly.SystemObjectModel, false, false), new ProjectedClass("Windows.UI.Xaml.Data", "PropertyChangedEventHandler", "System.ComponentModel", "PropertyChangedEventHandler", ClrAssembly.SystemObjectModel, ClrAssembly.SystemObjectModel, false, false), new ProjectedClass("Windows.UI.Xaml.Data", "PropertyChangedEventArgs", "System.ComponentModel", "PropertyChangedEventArgs", ClrAssembly.SystemObjectModel, ClrAssembly.SystemObjectModel, false, false), new ProjectedClass("Windows.UI.Xaml", "CornerRadius", "Windows.UI.Xaml", "CornerRadius", ClrAssembly.SystemRuntimeWindowsRuntimeUIXaml, ClrAssembly.SystemRuntimeWindowsRuntimeUIXaml, true, true), new ProjectedClass("Windows.UI.Xaml", "Duration", "Windows.UI.Xaml", "Duration", ClrAssembly.SystemRuntimeWindowsRuntimeUIXaml, ClrAssembly.SystemRuntimeWindowsRuntimeUIXaml, true, true), new ProjectedClass("Windows.UI.Xaml", "DurationType", "Windows.UI.Xaml", "DurationType", ClrAssembly.SystemRuntimeWindowsRuntimeUIXaml, ClrAssembly.SystemRuntimeWindowsRuntimeUIXaml, true, true), new ProjectedClass("Windows.UI.Xaml", "GridLength", "Windows.UI.Xaml", "GridLength", ClrAssembly.SystemRuntimeWindowsRuntimeUIXaml, ClrAssembly.SystemRuntimeWindowsRuntimeUIXaml, true, true), new ProjectedClass("Windows.UI.Xaml", "GridUnitType", "Windows.UI.Xaml", "GridUnitType", ClrAssembly.SystemRuntimeWindowsRuntimeUIXaml, ClrAssembly.SystemRuntimeWindowsRuntimeUIXaml, true, true), new ProjectedClass("Windows.UI.Xaml", "Thickness", "Windows.UI.Xaml", "Thickness", ClrAssembly.SystemRuntimeWindowsRuntimeUIXaml, ClrAssembly.SystemRuntimeWindowsRuntimeUIXaml, true, true), new ProjectedClass("Windows.UI.Xaml.Interop", "TypeName", "System", "Type", ClrAssembly.Mscorlib, ClrAssembly.SystemRuntime, true, false), new ProjectedClass("Windows.UI.Xaml.Controls.Primitives", "GeneratorPosition", "Windows.UI.Xaml.Controls.Primitives", "GeneratorPosition", ClrAssembly.SystemRuntimeWindowsRuntimeUIXaml, ClrAssembly.SystemRuntimeWindowsRuntimeUIXaml, true, true), new ProjectedClass("Windows.UI.Xaml.Media", "Matrix", "Windows.UI.Xaml.Media", "Matrix", ClrAssembly.SystemRuntimeWindowsRuntimeUIXaml, ClrAssembly.SystemRuntimeWindowsRuntimeUIXaml, true, true), new ProjectedClass("Windows.UI.Xaml.Media.Animation", "KeyTime", "Windows.UI.Xaml.Media.Animation", "KeyTime", ClrAssembly.SystemRuntimeWindowsRuntimeUIXaml, ClrAssembly.SystemRuntimeWindowsRuntimeUIXaml, true, true), new ProjectedClass("Windows.UI.Xaml.Media.Animation", "RepeatBehavior", "Windows.UI.Xaml.Media.Animation", "RepeatBehavior", ClrAssembly.SystemRuntimeWindowsRuntimeUIXaml, ClrAssembly.SystemRuntimeWindowsRuntimeUIXaml, true, true), new ProjectedClass("Windows.UI.Xaml.Media.Animation", "RepeatBehaviorType", "Windows.UI.Xaml.Media.Animation", "RepeatBehaviorType", ClrAssembly.SystemRuntimeWindowsRuntimeUIXaml, ClrAssembly.SystemRuntimeWindowsRuntimeUIXaml, true, true), new ProjectedClass("Windows.UI.Xaml.Media.Media3D", "Matrix3D", "Windows.UI.Xaml.Media.Media3D", "Matrix3D", ClrAssembly.SystemRuntimeWindowsRuntimeUIXaml, ClrAssembly.SystemRuntimeWindowsRuntimeUIXaml, true, true), new ProjectedClass("Windows.Foundation.Numerics", "Vector2", "System.Numerics", "Vector2", ClrAssembly.SystemNumericsVectors, ClrAssembly.SystemNumericsVectors, true, true), new ProjectedClass("Windows.Foundation.Numerics", "Vector3", "System.Numerics", "Vector3", ClrAssembly.SystemNumericsVectors, ClrAssembly.SystemNumericsVectors, true, true), new ProjectedClass("Windows.Foundation.Numerics", "Vector4", "System.Numerics", "Vector4", ClrAssembly.SystemNumericsVectors, ClrAssembly.SystemNumericsVectors, true, true), new ProjectedClass("Windows.Foundation.Numerics", "Matrix3x2", "System.Numerics", "Matrix3x2", ClrAssembly.SystemNumericsVectors, ClrAssembly.SystemNumericsVectors, true, true), new ProjectedClass("Windows.Foundation.Numerics", "Matrix4x4", "System.Numerics", "Matrix4x4", ClrAssembly.SystemNumericsVectors, ClrAssembly.SystemNumericsVectors, true, true), new ProjectedClass("Windows.Foundation.Numerics", "Plane", "System.Numerics", "Plane", ClrAssembly.SystemNumericsVectors, ClrAssembly.SystemNumericsVectors, true, true), new ProjectedClass("Windows.Foundation.Numerics", "Quaternion", "System.Numerics", "Quaternion", ClrAssembly.SystemNumericsVectors, ClrAssembly.SystemNumericsVectors, true, true), }; static readonly Dictionary<ClassName, ProjectedClass> winMDToCLR = new Dictionary<ClassName, ProjectedClass>(); static WinMDHelpers() { foreach (var projClass in ProjectedClasses) winMDToCLR.Add(projClass.WinMDClass, projClass); } static AssemblyRef ToCLR(ModuleDef module, ref UTF8String ns, ref UTF8String name) { ProjectedClass pc; if (!winMDToCLR.TryGetValue(new ClassName(ns, name), out pc)) return null; ns = pc.ClrClass.Namespace; name = pc.ClrClass.Name; return CreateAssembly(module, pc.ContractAssembly); } static AssemblyRef CreateAssembly(ModuleDef module, ClrAssembly clrAsm) { var mscorlib = module == null ? null : module.CorLibTypes.AssemblyRef; var asm = new AssemblyRefUser(GetName(clrAsm), contractAsmVersion, new PublicKeyToken(GetPublicKeyToken(clrAsm)), UTF8String.Empty); if (mscorlib != null && mscorlib.Name == mscorlibName && mscorlib.Version != invalidWinMDVersion) asm.Version = mscorlib.Version; var mod = module as ModuleDefMD; if (mod != null) { Version ver = null; foreach (var asmRef in mod.GetAssemblyRefs()) { if (asmRef.IsContentTypeWindowsRuntime) continue; if (asmRef.Name != asm.Name) continue; if (asmRef.Culture != asm.Culture) continue; if (!PublicKeyBase.TokenEquals(asmRef.PublicKeyOrToken, asm.PublicKeyOrToken)) continue; if (asmRef.Version == invalidWinMDVersion) continue; if (ver == null || asmRef.Version > ver) ver = asmRef.Version; } if (ver != null) asm.Version = ver; } return asm; } static readonly Version contractAsmVersion = new Version(4, 0, 0, 0); static readonly Version invalidWinMDVersion = new Version(255, 255, 255, 255); static readonly UTF8String mscorlibName = new UTF8String("mscorlib"); static UTF8String GetName(ClrAssembly clrAsm) { switch (clrAsm) { case ClrAssembly.Mscorlib: return clrAsmName_Mscorlib; case ClrAssembly.SystemNumericsVectors: return clrAsmName_SystemNumericsVectors; case ClrAssembly.SystemObjectModel: return clrAsmName_SystemObjectModel; case ClrAssembly.SystemRuntime: return clrAsmName_SystemRuntime; case ClrAssembly.SystemRuntimeInteropServicesWindowsRuntime: return clrAsmName_SystemRuntimeInteropServicesWindowsRuntime; case ClrAssembly.SystemRuntimeWindowsRuntime: return clrAsmName_SystemRuntimeWindowsRuntime; case ClrAssembly.SystemRuntimeWindowsRuntimeUIXaml: return clrAsmName_SystemRuntimeWindowsRuntimeUIXaml; default: throw new InvalidOperationException(); } } static readonly UTF8String clrAsmName_Mscorlib = new UTF8String("mscorlib"); static readonly UTF8String clrAsmName_SystemNumericsVectors = new UTF8String("System.Numerics.Vectors"); static readonly UTF8String clrAsmName_SystemObjectModel = new UTF8String("System.ObjectModel"); static readonly UTF8String clrAsmName_SystemRuntime = new UTF8String("System.Runtime"); static readonly UTF8String clrAsmName_SystemRuntimeInteropServicesWindowsRuntime = new UTF8String("System.Runtime.InteropServices.WindowsRuntime"); static readonly UTF8String clrAsmName_SystemRuntimeWindowsRuntime = new UTF8String("System.Runtime.WindowsRuntime"); static readonly UTF8String clrAsmName_SystemRuntimeWindowsRuntimeUIXaml = new UTF8String("System.Runtime.WindowsRuntime.UI.Xaml"); static byte[] GetPublicKeyToken(ClrAssembly clrAsm) { switch (clrAsm) { case ClrAssembly.Mscorlib: return neutralPublicKey; case ClrAssembly.SystemNumericsVectors: return contractPublicKeyToken; case ClrAssembly.SystemObjectModel: return contractPublicKeyToken; case ClrAssembly.SystemRuntime: return contractPublicKeyToken; case ClrAssembly.SystemRuntimeInteropServicesWindowsRuntime: return contractPublicKeyToken; case ClrAssembly.SystemRuntimeWindowsRuntime: return neutralPublicKey; case ClrAssembly.SystemRuntimeWindowsRuntimeUIXaml: return neutralPublicKey; default: throw new InvalidOperationException(); } } static readonly byte[] contractPublicKeyToken = new byte[] { 0xB0, 0x3F, 0x5F, 0x7F, 0x11, 0xD5, 0x0A, 0x3A }; static readonly byte[] neutralPublicKey = new byte[] { 0xb7, 0x7a, 0x5c, 0x56, 0x19, 0x34, 0xe0, 0x89 }; /// <summary> /// Converts WinMD type <paramref name="td"/> to a CLR type. Returns <c>null</c> /// if it's not a CLR compatible WinMD type. /// </summary> /// <param name="module">Owner module or <c>null</c></param> /// <param name="td">Type</param> /// <returns></returns> public static TypeRef ToCLR(ModuleDef module, TypeDef td) { bool isClrValueType; return ToCLR(module, td, out isClrValueType); } /// <summary> /// Converts WinMD type <paramref name="td"/> to a CLR type. Returns <c>null</c> /// if it's not a CLR compatible WinMD type. /// </summary> /// <param name="module">Owner module or <c>null</c></param> /// <param name="td">Type</param> /// <param name="isClrValueType"><c>true</c> if the returned type is a value type</param> /// <returns></returns> public static TypeRef ToCLR(ModuleDef module, TypeDef td, out bool isClrValueType) { isClrValueType = false; if (td == null || !td.IsWindowsRuntime) return null; var asm = td.DefinitionAssembly; if (asm == null || !asm.IsContentTypeWindowsRuntime) return null; ProjectedClass pc; if (!winMDToCLR.TryGetValue(new ClassName(td.Namespace, td.Name), out pc)) return null; isClrValueType = pc.ClrClass.IsValueType; return new TypeRefUser(module, pc.ClrClass.Namespace, pc.ClrClass.Name, CreateAssembly(module, pc.ContractAssembly)); } /// <summary> /// Converts WinMD type <paramref name="tr"/> to a CLR type. Returns <c>null</c> /// if it's not a CLR compatible WinMD type. /// </summary> /// <param name="module">Owner module or <c>null</c></param> /// <param name="tr">Type</param> /// <returns></returns> public static TypeRef ToCLR(ModuleDef module, TypeRef tr) { bool isClrValueType; return ToCLR(module, tr, out isClrValueType); } /// <summary> /// Converts WinMD type <paramref name="tr"/> to a CLR type. Returns <c>null</c> /// if it's not a CLR compatible WinMD type. /// </summary> /// <param name="module">Owner module or <c>null</c></param> /// <param name="tr">Type</param> /// <param name="isClrValueType"><c>true</c> if the returned type is a value type</param> /// <returns></returns> public static TypeRef ToCLR(ModuleDef module, TypeRef tr, out bool isClrValueType) { isClrValueType = false; if (tr == null) return null; var defAsm = tr.DefinitionAssembly; if (defAsm == null || !defAsm.IsContentTypeWindowsRuntime) return null; if (tr.DeclaringType != null) return null; ProjectedClass pc; if (!winMDToCLR.TryGetValue(new ClassName(tr.Namespace, tr.Name), out pc)) return null; isClrValueType = pc.ClrClass.IsValueType; return new TypeRefUser(module, pc.ClrClass.Namespace, pc.ClrClass.Name, CreateAssembly(module, pc.ContractAssembly)); } /// <summary> /// Converts WinMD type <paramref name="et"/> to a CLR type. Returns <c>null</c> /// if it's not a CLR compatible WinMD type. /// </summary> /// <param name="module">Owner module or <c>null</c></param> /// <param name="et">Type</param> /// <returns></returns> public static ExportedType ToCLR(ModuleDef module, ExportedType et) { if (et == null) return null; var defAsm = et.DefinitionAssembly; if (defAsm == null || !defAsm.IsContentTypeWindowsRuntime) return null; if (et.DeclaringType != null) return null; ProjectedClass pc; if (!winMDToCLR.TryGetValue(new ClassName(et.TypeNamespace, et.TypeName), out pc)) return null; return new ExportedTypeUser(module, 0, pc.ClrClass.Namespace, pc.ClrClass.Name, et.Attributes, CreateAssembly(module, pc.ContractAssembly)); } /// <summary> /// Converts WinMD type <paramref name="ts"/> to a CLR type. Returns <c>null</c> /// if it's not a CLR compatible WinMD type. /// </summary> /// <param name="module">Owner module or <c>null</c></param> /// <param name="ts">Type</param> /// <returns></returns> public static TypeSig ToCLR(ModuleDef module, TypeSig ts) { if (ts == null) return null; var et = ts.ElementType; if (et != ElementType.Class && et != ElementType.ValueType) return null; var tdr = ((ClassOrValueTypeSig)ts).TypeDefOrRef; TypeDef td; TypeRef tr, newTr; bool isClrValueType; if ((td = tdr as TypeDef) != null) { newTr = ToCLR(module, td, out isClrValueType); if (newTr == null) return null; } else if ((tr = tdr as TypeRef) != null) { newTr = ToCLR(module, tr, out isClrValueType); if (newTr == null) return null; } else return null; return isClrValueType ? (TypeSig)new ValueTypeSig(newTr) : new ClassSig(newTr); } /// <summary> /// Converts WinMD member reference <paramref name="mr"/> to a CLR member reference. Returns /// <c>null</c> if it's not a CLR compatible WinMD member reference. /// </summary> /// <param name="module">Owner module or <c>null</c></param> /// <param name="mr">Member reference</param> /// <returns></returns> public static MemberRef ToCLR(ModuleDef module, MemberRef mr) { // See WinMDAdapter::CheckIfMethodImplImplementsARedirectedInterface // in coreclr: md/winmd/adapter.cpp if (mr == null) return null; if (mr.Name != CloseName) return null; var msig = mr.MethodSig; if (msig == null) return null; var cl = mr.Class; IMemberRefParent newCl; TypeRef tr; TypeSpec ts; if ((tr = cl as TypeRef) != null) { var newTr = ToCLR(module, tr); if (newTr == null || !IsIDisposable(newTr)) return null; newCl = newTr; } else if ((ts = cl as TypeSpec) != null) { var gis = ts.TypeSig as GenericInstSig; if (gis == null || !(gis.GenericType is ClassSig)) return null; tr = gis.GenericType.TypeRef; if (tr == null) return null; bool isClrValueType; var newTr = ToCLR(module, tr, out isClrValueType); if (newTr == null || !IsIDisposable(newTr)) return null; newCl = new TypeSpecUser(new GenericInstSig(isClrValueType ? (ClassOrValueTypeSig)new ValueTypeSig(newTr) : new ClassSig(newTr), gis.GenericArguments)); } else return null; return new MemberRefUser(mr.Module, DisposeName, msig, newCl); } static readonly UTF8String CloseName = new UTF8String("Close"); static readonly UTF8String DisposeName = new UTF8String("Dispose"); static bool IsIDisposable(TypeRef tr) { return tr.Name == IDisposableName && tr.Namespace == IDisposableNamespace; } static readonly UTF8String IDisposableNamespace = new UTF8String("System"); static readonly UTF8String IDisposableName = new UTF8String("IDisposable"); /// <summary> /// Converts WinMD method <paramref name="md"/> to a CLR member reference. Returns /// <c>null</c> if it's not a CLR compatible WinMD method /// </summary> /// <param name="module">Owner module or <c>null</c></param> /// <param name="md">Method</param> /// <returns></returns> public static MemberRef ToCLR(ModuleDef module, MethodDef md) { if (md == null) return null; if (md.Name != CloseName) return null; var declType = md.DeclaringType; if (declType == null) return null; var tr = ToCLR(module, declType); if (tr == null || !IsIDisposable(tr)) return null; return new MemberRefUser(md.Module, DisposeName, md.MethodSig, tr); } } }
55.635294
257
0.635617
[ "MIT" ]
Owen0225/ConfuserEx-Plus
dnlib/src/DotNet/WinMDHelpers.cs
28,376
C#
namespace HmxLabs.SmtpUnit.Test { public static class SmtpServerResponses { public const string Welcome = "220 Test Simple Mail Transfer Service Ready\r\n"; public const string Ok = "250 OK\r\n"; public const string StartMailInput = "354 Start mail input; end with <CRLF>.<CRLF>\r\n"; public const string BadCommandSequence = "503 Bad sequence of commands\r\n"; public const string Goodbye = "221 Mock SMTP Server closing transmission channel\r\n"; public const string UnknownCommand = "502 Command not implemented by Mock SMTP server\r\n"; public static string Greeting(string clientId_) { return $"250 Mock SMTP Service greets {clientId_}\r\n"; } } }
41.722222
99
0.669774
[ "MIT" ]
hmxlabs/smtpunit
SMTPUnit.Tests/SmtpServerResponses.cs
753
C#
using EasyModular.Utils; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Filters; using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Text; namespace EasyModular.Auth { /// <summary> /// 权限验证 /// </summary> [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true)] public class PermissionValidateAttribute : AuthorizeAttribute, IAuthorizationFilter { public void OnAuthorization(AuthorizationFilterContext context) { //排除匿名访问 if (context.ActionDescriptor.EndpointMetadata.Any(m => m.GetType() == typeof(AllowAnonymousAttribute))) return; var config = context.HttpContext.RequestServices.GetService(typeof(WebConfigModel)) as WebConfigModel; if (config != null) { //是否开启权限认证 if (!config.IsValidate) return; //是否启用单账户登录 if (config.IsSingleAccount) { var singleAccountLoginHandler = context.HttpContext.RequestServices.GetService(typeof(ISingleAccountLoginHandler)) as ISingleAccountLoginHandler; if (singleAccountLoginHandler != null && singleAccountLoginHandler.Validate().GetAwaiter().GetResult()) { context.Result = new ContentResult(); context.HttpContext.Response.StatusCode = 622;//自定义状态码来判断是否是在其他地方登录 return; } } } //未登录 var loginInfo = context.HttpContext.RequestServices.GetService(typeof(ILoginInfo)) as ILoginInfo; if (loginInfo == null || string.IsNullOrEmpty(loginInfo.UserName)) { context.Result = new ChallengeResult(); return; } //排除通用接口 if (context.ActionDescriptor.EndpointMetadata.Any(m => m.GetType() == typeof(CommonAttribute))) return; var handler = context.HttpContext.RequestServices.GetService(typeof(IPermissionValidateHandler)) as IPermissionValidateHandler; if (!handler.Validate(context.ActionDescriptor.RouteValues, context.HttpContext.Request.Method)) { //无权访问 context.Result = new ForbidResult(); } } } }
37.893939
165
0.603359
[ "MIT" ]
doordie1991/EasyModular
src/EasyModular.Auth/Attributes/PermissionValidateAttribute.cs
2,621
C#
using DSM.API.Plugins.Base; using DSM.API.Utilities; using Relua.AST; using System; using System.Collections.Generic; using System.IO; using System.Text; namespace DSM.API.Plugins { [PluginEntryFile("description.lua")] public class Livery : Plugin { public string Name { get; set; } // detecting which module a livery is for should be as easy as simply creating a database by scanning CoreMods/ or Mods/ liveries to see what keys are related to what module public Livery(string path, bool installed) : base(path, installed) { } protected override void InitFromEntryFileBlock(Block block) { this.Name = LuaHelper.GetExpressionStringValue(LuaHelper.FindVariableValue(block, "name", null, null)); } } }
23.580645
175
0.746922
[ "MPL-2.0", "MPL-2.0-no-copyleft-exception" ]
nootshell/DSM
DSM.API/Plugins/Livery.cs
731
C#
using BusinessAccessLayer; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Threading.Tasks; using System.Web.Http; namespace OnlineTestApplication.Controllers { public class StudentController : ApiController { private readonly IBStudent _iBStudent; public StudentController(IBStudent iBStudent) { _iBStudent = iBStudent; } [HttpGet] [Route("api/GetStudent", Name = "GetStudent")] public async Task<HttpResponseMessage> GetStudent() { var response = Request.CreateResponse(HttpStatusCode.OK, JsonConvert.SerializeObject(_iBStudent.GetStudent())); return response; } } }
27.233333
124
0.660955
[ "MIT" ]
vilasholkar/OnlineTest
OnlineTestAPI/OnlineTestApplication/Controllers/StudentController.cs
819
C#
using NHapi.Base.Parser; using NHapi.Base; using NHapi.Base.Log; using System; using System.Collections.Generic; using NHapi.Model.V27.Segment; using NHapi.Model.V27.Datatype; using NHapi.Base.Model; namespace NHapi.Model.V27.Group { ///<summary> ///Represents the RRE_O12_RESPONSE Group. A Group is an ordered collection of message /// segments that can repeat together or be optionally in/excluded together. /// This Group contains the following elements: ///<ol> ///<li>0: RRE_O12_PATIENT (a Group object) optional </li> ///<li>1: RRE_O12_ORDER (a Group object) repeating</li> ///</ol> ///</summary> [Serializable] public class RRE_O12_RESPONSE : AbstractGroup { ///<summary> /// Creates a new RRE_O12_RESPONSE Group. ///</summary> public RRE_O12_RESPONSE(IGroup parent, IModelClassFactory factory) : base(parent, factory){ try { this.add(typeof(RRE_O12_PATIENT), false, false); this.add(typeof(RRE_O12_ORDER), true, true); } catch(HL7Exception e) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected error creating RRE_O12_RESPONSE - this is probably a bug in the source code generator.", e); } } ///<summary> /// Returns RRE_O12_PATIENT (a Group object) - creates it if necessary ///</summary> public RRE_O12_PATIENT PATIENT { get{ RRE_O12_PATIENT ret = null; try { ret = (RRE_O12_PATIENT)this.GetStructure("PATIENT"); } catch(HL7Exception e) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected error accessing data - this is probably a bug in the source code generator.", e); throw new System.Exception("An unexpected error ocurred",e); } return ret; } } ///<summary> /// Returns first repetition of RRE_O12_ORDER (a Group object) - creates it if necessary ///</summary> public RRE_O12_ORDER GetORDER() { RRE_O12_ORDER ret = null; try { ret = (RRE_O12_ORDER)this.GetStructure("ORDER"); } catch(HL7Exception e) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected error accessing data - this is probably a bug in the source code generator.", e); throw new System.Exception("An unexpected error ocurred",e); } return ret; } ///<summary> ///Returns a specific repetition of RRE_O12_ORDER /// * (a Group object) - creates it if necessary /// throws HL7Exception if the repetition requested is more than one /// greater than the number of existing repetitions. ///</summary> public RRE_O12_ORDER GetORDER(int rep) { return (RRE_O12_ORDER)this.GetStructure("ORDER", rep); } /** * Returns the number of existing repetitions of RRE_O12_ORDER */ public int ORDERRepetitionsUsed { get{ int reps = -1; try { reps = this.GetAll("ORDER").Length; } catch (HL7Exception e) { string message = "Unexpected error accessing data - this is probably a bug in the source code generator."; HapiLogFactory.GetHapiLog(GetType()).Error(message, e); throw new System.Exception(message); } return reps; } } /** * Enumerate over the RRE_O12_ORDER results */ public IEnumerable<RRE_O12_ORDER> ORDERs { get { for (int rep = 0; rep < ORDERRepetitionsUsed; rep++) { yield return (RRE_O12_ORDER)this.GetStructure("ORDER", rep); } } } ///<summary> ///Adds a new RRE_O12_ORDER ///</summary> public RRE_O12_ORDER AddORDER() { return this.AddStructure("ORDER") as RRE_O12_ORDER; } ///<summary> ///Removes the given RRE_O12_ORDER ///</summary> public void RemoveORDER(RRE_O12_ORDER toRemove) { this.RemoveStructure("ORDER", toRemove); } ///<summary> ///Removes the RRE_O12_ORDER at the given index ///</summary> public void RemoveORDERAt(int index) { this.RemoveRepetition("ORDER", index); } } }
28.421053
154
0.685979
[ "MPL-2.0", "MPL-2.0-no-copyleft-exception" ]
AMCN41R/nHapi
src/NHapi.Model.V27/Group/RRE_O12_RESPONSE.cs
3,780
C#
namespace CoCSharp.Data { /// <summary> /// Defines data from achievements.csv. /// </summary> public class AchievementData : CoCData { /// <summary> /// Initializes a new instance of the <see cref="AchievementData"/> class. /// </summary> public AchievementData() { // Space } public string Name { get; set; } public int Level { get; set; } public string TID { get; set; } public string InfoTID { get; set; } public string Action { get; set; } public int ActionCount { get; set; } public string ActionData { get; set; } public int ExpReward { get; set; } public int DiamondReward { get; set; } public string IconSWF { get; set; } public string IconExportName { get; set; } public string CompletedTID { get; set; } public bool ShowValue { get; set; } public string AndroidID { get; set; } } }
30.96875
82
0.554995
[ "MIT" ]
Ricardo253/Clash-of-Galaxy
CoCSharp/Data/AchievementData.cs
993
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace _03.VariableInHexadecimalFormat { class Program { static void Main(string[] args) { int someInt = 254; string someHex = someInt.ToString("X"); Console.WriteLine("The in 254 in Hexadecimal form is: " +someHex); } } }
21.894737
78
0.629808
[ "MIT" ]
KrasimirStoyanov/Telerik-Academy
Homeworks/C# 1/Primitive-Data-Types-and-Variables-Homework2/01.DeclareVariable/03.VariableInHexadecimalFormat/Program.cs
418
C#
namespace Myra.Extended.Samples.Widgets { class Program { static void Main(string[] args) { using (var game = new WidgetsGame()) game.Run(); } } }
13.666667
40
0.634146
[ "MIT" ]
rds1983/Myra.Extended
samples/Myra.Extended.Samples.Widgets/Program.cs
166
C#
using System; using System.Collections.Generic; using System.Linq; using System.Net.WebSockets; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Web; using System.Web.WebSockets; using Newtonsoft.Json; namespace Pong.PongHandler { /// <summary> /// Represents a player and wraps his websocket operations /// </summary> public class PongPlayer { private PongGame _game; private object _syncRoot = new object(); private AspNetWebSocketContext _context; public event Action<PongPlayer, PlayerPositionMessage> PlayerMoved; public event Action<PongPlayer> PlayerDisconnected; // player vertical positon public int YPos { get; private set; } public void SetGame(PongGame game) { if (_game != null) throw new InvalidOperationException(); _game = game; } /// <summary> /// This method is used as delegate to accept WebSocket connection /// </summary> public async Task Receiver(AspNetWebSocketContext context) { _context = context; var socket = _context.WebSocket as AspNetWebSocket; // prepare buffer for reading messages var inputBuffer = new ArraySegment<byte>(new byte[1024]); // send player number to player SendMessage(new PlayerNumberMessage { PlayerNumber = _game.GetPlayerIndex(this) }); try { while (true) { // read from socket var result = await socket.ReceiveAsync(inputBuffer, CancellationToken.None); if (socket.State != WebSocketState.Open) { if (PlayerDisconnected != null) PlayerDisconnected(this); break; } // convert bytes to text var messageString = Encoding.UTF8.GetString(inputBuffer.Array, 0, result.Count); // only PlayerPositionMessage is expected, deserialize var positionMessage = JsonConvert.DeserializeObject<PlayerPositionMessage>(messageString); // save new position and notify game YPos = positionMessage.YPos; if (PlayerMoved != null) PlayerMoved(this, positionMessage); } } catch (Exception ex) { if (PlayerDisconnected != null) PlayerDisconnected(this); } } /// <summary> /// Sends message through web socket to player's rowser /// </summary> public async Task SendMessage(object message) { // serialize and send var messageString = JsonConvert.SerializeObject(message); if (_context != null && _context.WebSocket.State == WebSocketState.Open) { var outputBuffer = new ArraySegment<byte>(Encoding.UTF8.GetBytes(messageString)); await _context.WebSocket.SendAsync(outputBuffer, WebSocketMessageType.Text, true, CancellationToken.None); } } /// <summary> /// Closes player's web socket /// </summary> public void Close() { if (_context != null && _context.WebSocket.State == WebSocketState.Open) { _context.WebSocket.CloseOutputAsync(WebSocketCloseStatus.NormalClosure, "Closing...", CancellationToken.None).Wait(); } } } }
34.886792
133
0.563818
[ "MIT" ]
git-thinh/WebSocketPong
Pong/PongHandler/PongPlayer.cs
3,700
C#
using Mirror; using PropHunt.Utils; using UnityEngine; namespace PropHunt.Character { public class CharacterAnimator : NetworkBehaviour { /// <summary> /// Dead zone to consider movement as stopped /// </summary> public float movementDeadZone = 0.01f; /// <summary> /// Dead zone to consider turning action as stopped /// </summary> public float turningDeadZone = 0.01f; /// <summary> /// Amount of time falling to switch to falling animation /// </summary> public float fallingThreshold = 0.1f; /// <summary> /// Network service for managing network calls /// </summary> public INetworkService networkService; /// <summary> /// Character controller for getting character motion information /// </summary> public KinematicCharacterController kcc; /// <summary> /// Camera controller for getting player rotation information /// </summary> public CameraController cameraController; /// <summary> /// Character controller to move character /// </summary> private CharacterController characterController; /// <summary> /// Animator for controlling character /// </summary> public Animator animator; public void Start() { this.networkService = new NetworkService(this); this.characterController = this.GetComponent<CharacterController>(); } public void LateUpdate() { // If local player if (!networkService.isLocalPlayer) { return; } bool jumping = kcc.Velocity.y >= 0.1f; bool falling = kcc.FallingTime >= fallingThreshold; bool jumpingOrFalling = jumping || falling; bool moving = !jumpingOrFalling && kcc.InputMovement.magnitude > this.movementDeadZone; // Set animator fields based on information animator.SetFloat("MoveX", kcc.InputMovement.x); animator.SetFloat("MoveY", kcc.InputMovement.z); // Set moving if movement is greater than dead zone animator.SetBool("Moving", moving); animator.SetBool("Sprinting", moving && kcc.Sprinting); // Set turning value based on turning direction animator.SetFloat("Rotation", cameraController.frameRotation > 0 ? 1 : -1); animator.SetBool("Turning", !moving && !jumpingOrFalling && Mathf.Abs(cameraController.frameRotation) > this.turningDeadZone); animator.SetBool("Jumping", jumping); animator.SetBool("Falling", falling); } } }
33.361446
138
0.5948
[ "MIT" ]
nicholas-maltbie/PropHunt-Mirror
Assets/Scripts/Character/CharacterAnimator.cs
2,771
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. // Changes may cause incorrect behavior and will be lost if the code is regenerated. namespace Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Models.Api20211001Preview { using static Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Runtime.Extensions; public partial class ScanProperties { /// <summary> /// <c>AfterFromJson</c> will be called after the json deserialization has finished, allowing customization of the object /// before it is returned. Implement this method in a partial class to enable this behavior /// </summary> /// <param name="json">The JsonNode that should be deserialized into this object.</param> partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Runtime.Json.JsonObject json); /// <summary> /// <c>AfterToJson</c> will be called after the json erialization has finished, allowing customization of the <see cref="Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Runtime.Json.JsonObject" /// /> before it is returned. Implement this method in a partial class to enable this behavior /// </summary> /// <param name="container">The JSON container that the serialization result will be placed in.</param> partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Runtime.Json.JsonObject container); /// <summary> /// <c>BeforeFromJson</c> will be called before the json deserialization has commenced, allowing complete customization of /// the object before it is deserialized. /// If you wish to disable the default deserialization entirely, return <c>true</c> in the <see "returnNow" /> output parameter. /// Implement this method in a partial class to enable this behavior. /// </summary> /// <param name="json">The JsonNode that should be deserialized into this object.</param> /// <param name="returnNow">Determines if the rest of the deserialization should be processed, or if the method should return /// instantly.</param> partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Runtime.Json.JsonObject json, ref bool returnNow); /// <summary> /// <c>BeforeToJson</c> will be called before the json serialization has commenced, allowing complete customization of the /// object before it is serialized. /// If you wish to disable the default serialization entirely, return <c>true</c> in the <see "returnNow" /> output parameter. /// Implement this method in a partial class to enable this behavior. /// </summary> /// <param name="container">The JSON container that the serialization result will be placed in.</param> /// <param name="returnNow">Determines if the rest of the serialization should be processed, or if the method should return /// instantly.</param> partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Runtime.Json.JsonObject container, ref bool returnNow); /// <summary> /// Deserializes a <see cref="Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Runtime.Json.JsonNode"/> into an instance of Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Models.Api20211001Preview.IScanProperties. /// </summary> /// <param name="node">a <see cref="Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Runtime.Json.JsonNode" /> to deserialize from.</param> /// <returns> /// an instance of Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Models.Api20211001Preview.IScanProperties. /// </returns> public static Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Models.Api20211001Preview.IScanProperties FromJson(Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Runtime.Json.JsonNode node) { return node is Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Runtime.Json.JsonObject json ? new ScanProperties(json) : null; } /// <summary> /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Runtime.Json.JsonObject into a new instance of <see cref="ScanProperties" />. /// </summary> /// <param name="json">A Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Runtime.Json.JsonObject instance to deserialize from.</param> internal ScanProperties(Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Runtime.Json.JsonObject json) { bool returnNow = false; BeforeFromJson(json, ref returnNow); if (returnNow) { return; } {_collection = If( json?.PropertyT<Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Runtime.Json.JsonObject>("collection"), out var __jsonCollection) ? Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Models.Api20211001Preview.CollectionReference.FromJson(__jsonCollection) : Collection;} {_connectedVia = If( json?.PropertyT<Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Runtime.Json.JsonObject>("connectedVia"), out var __jsonConnectedVia) ? Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Models.Api20211001Preview.ConnectedVia.FromJson(__jsonConnectedVia) : ConnectedVia;} {_scanRulesetName = If( json?.PropertyT<Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Runtime.Json.JsonString>("scanRulesetName"), out var __jsonScanRulesetName) ? (string)__jsonScanRulesetName : (string)ScanRulesetName;} {_scanRulesetType = If( json?.PropertyT<Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Runtime.Json.JsonString>("scanRulesetType"), out var __jsonScanRulesetType) ? (string)__jsonScanRulesetType : (string)ScanRulesetType;} {_worker = If( json?.PropertyT<Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Runtime.Json.JsonNumber>("workers"), out var __jsonWorkers) ? (int?)__jsonWorkers : Worker;} {_createdAt = If( json?.PropertyT<Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Runtime.Json.JsonString>("createdAt"), out var __jsonCreatedAt) ? global::System.DateTime.TryParse((string)__jsonCreatedAt, global::System.Globalization.CultureInfo.InvariantCulture, global::System.Globalization.DateTimeStyles.AdjustToUniversal, out var __jsonCreatedAtValue) ? __jsonCreatedAtValue : CreatedAt : CreatedAt;} {_lastModifiedAt = If( json?.PropertyT<Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Runtime.Json.JsonString>("lastModifiedAt"), out var __jsonLastModifiedAt) ? global::System.DateTime.TryParse((string)__jsonLastModifiedAt, global::System.Globalization.CultureInfo.InvariantCulture, global::System.Globalization.DateTimeStyles.AdjustToUniversal, out var __jsonLastModifiedAtValue) ? __jsonLastModifiedAtValue : LastModifiedAt : LastModifiedAt;} AfterFromJson(json); } /// <summary> /// Serializes this instance of <see cref="ScanProperties" /> into a <see cref="Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Runtime.Json.JsonNode" />. /// </summary> /// <param name="container">The <see cref="Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Runtime.Json.JsonObject"/> container to serialize this object into. If the caller /// passes in <c>null</c>, a new instance will be created and returned to the caller.</param> /// <param name="serializationMode">Allows the caller to choose the depth of the serialization. See <see cref="Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Runtime.SerializationMode"/>.</param> /// <returns> /// a serialized instance of <see cref="ScanProperties" /> as a <see cref="Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Runtime.Json.JsonNode" />. /// </returns> public Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Runtime.SerializationMode serializationMode) { container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Runtime.Json.JsonObject(); bool returnNow = false; BeforeToJson(ref container, ref returnNow); if (returnNow) { return container; } AddIf( null != this._collection ? (Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Runtime.Json.JsonNode) this._collection.ToJson(null,serializationMode) : null, "collection" ,container.Add ); AddIf( null != this._connectedVia ? (Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Runtime.Json.JsonNode) this._connectedVia.ToJson(null,serializationMode) : null, "connectedVia" ,container.Add ); AddIf( null != (((object)this._scanRulesetName)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Runtime.Json.JsonString(this._scanRulesetName.ToString()) : null, "scanRulesetName" ,container.Add ); AddIf( null != (((object)this._scanRulesetType)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Runtime.Json.JsonString(this._scanRulesetType.ToString()) : null, "scanRulesetType" ,container.Add ); AddIf( null != this._worker ? (Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Runtime.Json.JsonNode)new Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Runtime.Json.JsonNumber((int)this._worker) : null, "workers" ,container.Add ); if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Runtime.SerializationMode.IncludeReadOnly)) { AddIf( null != this._createdAt ? (Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Runtime.Json.JsonString(this._createdAt?.ToString(@"yyyy'-'MM'-'dd'T'HH':'mm':'ss.fffffffK",global::System.Globalization.CultureInfo.InvariantCulture)) : null, "createdAt" ,container.Add ); } if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Runtime.SerializationMode.IncludeReadOnly)) { AddIf( null != this._lastModifiedAt ? (Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Runtime.Json.JsonString(this._lastModifiedAt?.ToString(@"yyyy'-'MM'-'dd'T'HH':'mm':'ss.fffffffK",global::System.Globalization.CultureInfo.InvariantCulture)) : null, "lastModifiedAt" ,container.Add ); } AfterToJson(ref container); return container; } } }
89.349593
458
0.718653
[ "MIT" ]
Agazoth/azure-powershell
src/Purview/Purviewdata.Autorest/generated/api/Models/Api20211001Preview/ScanProperties.json.cs
10,868
C#
using System.Collections.Generic; using System.Threading.Tasks; using CodexBank.Services.Models.BankAccount; namespace CodexBank.Services.Contracts { public interface IBankAccountService { Task<IEnumerable<T>> GetAllAccountsByUserIdAsync<T>(string userId) where T : BankAccountBaseServiceModel; Task<string> CreateAsync(BankAccountCreateServiceModel model); Task<T> GetByUniqueIdAsync<T>(string uniqueId) where T : BankAccountBaseServiceModel; Task<T> GetByIdAsync<T>(string id) where T : BankAccountBaseServiceModel; Task<bool> ChangeAccountNameAsync(string accountId, string newName); Task<IEnumerable<T>> GetAccountsAsync<T>(int pageIndex = 1, int count = int.MaxValue) where T : BankAccountBaseServiceModel; Task<int> GetCountOfAccountsAsync(); } }
31.321429
93
0.709236
[ "MIT" ]
Dimulski/CodexBank
src/Services/CodexBank/CodexBank.Services/Contracts/IBankAccountService.cs
879
C#
// // (C) Copyright 2003-2011 by Autodesk, Inc. // // Permission to use, copy, modify, and distribute this software in // object code form for any purpose and without fee is hereby granted, // provided that the above copyright notice appears in all copies and // that both that copyright notice and the limited warranty and // restricted rights notice below appear in all supporting // documentation. // // AUTODESK PROVIDES THIS PROGRAM "AS IS" AND WITH ALL FAULTS. // AUTODESK SPECIFICALLY DISCLAIMS ANY IMPLIED WARRANTY OF // MERCHANTABILITY OR FITNESS FOR A PARTICULAR USE. AUTODESK, INC. // DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE // UNINTERRUPTED OR ERROR FREE. // // Use, duplication, or disclosure by the U.S. Government is subject to // restrictions set forth in FAR 52.227-19 (Commercial Computer // Software - Restricted Rights) and DFAR 252.227-7013(c)(1)(ii) // (Rights in Technical Data and Computer Software), as applicable. // using System; using System.IO; using System.Collections; using System.Windows.Forms; using System.Collections.Generic; using System.Text; using Autodesk; using Autodesk.Revit; using Autodesk.Revit.DB; using Autodesk.Revit.UI; using Autodesk.Revit.DB.Structure; namespace Revit.SDK.Samples.CreateDimensions.CS { /// <summary> /// Implements the Revit add-in interface IExternalCommand /// </summary> [Autodesk.Revit.Attributes.Transaction(Autodesk.Revit.Attributes.TransactionMode.Manual)] [Autodesk.Revit.Attributes.Regeneration(Autodesk.Revit.Attributes.RegenerationOption.Manual)] [Autodesk.Revit.Attributes.Journaling(Autodesk.Revit.Attributes.JournalingMode.NoCommandData)] public class Command : IExternalCommand { ExternalCommandData m_revit = null; //store external command string m_errorMessage = " "; // store error message ArrayList m_walls = new ArrayList(); //store the wall of selected const double precision = 0.0000001; //store the precision /// <summary> /// Implement this method as an external command for Revit. /// </summary> /// <param name="commandData">An object that is passed to the external application /// which contains data related to the command, /// such as the application object and active view.</param> /// <param name="message">A message that can be set by the external application /// which will be displayed if a failure or cancellation is returned by /// the external command.</param> /// <param name="elements">A set of elements to which the external application /// can add elements that are to be highlighted in case of failure or cancellation.</param> /// <returns>Return the status of the external command. /// A result of Succeeded means that the API external method functioned as expected. /// Cancelled can be used to signify that the user cancelled the external operation /// at some point. Failure should be returned if the application is unable to proceed with /// the operation.</returns> public Autodesk.Revit.UI.Result Execute(ExternalCommandData revit, ref string message, Autodesk.Revit.DB.ElementSet elements) { try { m_revit = revit; Autodesk.Revit.DB.View view = m_revit.Application.ActiveUIDocument.Document.ActiveView; View3D view3D = view as View3D; if (null != view3D) { message += "Only create dimensions in 2D"; return Autodesk.Revit.UI.Result.Failed; } ViewSheet viewSheet = view as ViewSheet; if (null != viewSheet) { message += "Only create dimensions in 2D"; return Autodesk.Revit.UI.Result.Failed; } //try too adds a dimension from the start of the wall to the end of the wall into the project if (!AddDimension()) { message = m_errorMessage; return Autodesk.Revit.UI.Result.Failed; } return Autodesk.Revit.UI.Result.Succeeded; } catch (Exception e) { message = e.Message; return Autodesk.Revit.UI.Result.Failed; } } /// <summary> /// find out the wall, insert it into a array list /// </summary> bool initialize() { ElementSet selections = m_revit.Application.ActiveUIDocument.Selection.Elements; //nothing was selected if (0 == selections.Size) { m_errorMessage += "Please select Basic walls"; return false; } //find out wall foreach (Autodesk.Revit.DB.Element e in selections) { Wall wall = e as Wall; if (null != wall) { if ("Basic" != wall.WallType.Kind.ToString()) { continue; } m_walls.Add(wall); } } //no wall was selected if (0 == m_walls.Count) { m_errorMessage += "Please select Basic walls"; return false; } return true; } /// <summary> /// find out every wall in the selection and add a dimension from the start of the wall to its end /// </summary> /// <returns>if add successfully, true will be retured, else false will be returned</returns> public bool AddDimension() { if (!initialize()) { return false; } Transaction transaction = new Transaction(m_revit.Application.ActiveUIDocument.Document, "Add Dimensions"); transaction.Start(); //get out all the walls in this array, and create a dimension from its start to its end for (int i = 0; i < m_walls.Count; i++) { Wall wallTemp = m_walls[i] as Wall; if (null == wallTemp) { continue; } //get location curve Location location = wallTemp.Location; LocationCurve locationline = location as LocationCurve; if (null == locationline) { continue; } //New Line Autodesk.Revit.DB.XYZ locationEndPoint = locationline.Curve.get_EndPoint(1); Autodesk.Revit.DB.XYZ locationStartPoint = locationline.Curve.get_EndPoint(0); Line newLine = m_revit.Application.Application.Create.NewLine(locationStartPoint, locationEndPoint, true); //get reference ReferenceArray referenceArray = new ReferenceArray(); Options options = m_revit.Application.Application.Create.NewGeometryOptions(); options.ComputeReferences = true; options.View = m_revit.Application.ActiveUIDocument.Document.ActiveView; Autodesk.Revit.DB.GeometryElement element = wallTemp.get_Geometry(options); GeometryObjectArray geoObjectArray = element.Objects; //enum the geometry element for (int j = 0; j < geoObjectArray.Size; j++) { GeometryObject geoObject = geoObjectArray.get_Item(j); Curve curve = geoObject as Curve; if (null != curve) { //find the two upright lines beside the line if (Validata(newLine, curve as Line)) { referenceArray.Append(curve.Reference); } if (2 == referenceArray.Size) { break; } } } try { //try to new a dimension Autodesk.Revit.UI.UIApplication app = m_revit.Application; Document doc = app.ActiveUIDocument.Document; Autodesk.Revit.DB.XYZ p1 = new XYZ( newLine.get_EndPoint(0).X + 5, newLine.get_EndPoint(0).Y + 5, newLine.get_EndPoint(0).Z); Autodesk.Revit.DB.XYZ p2 = new XYZ( newLine.get_EndPoint(1).X + 5, newLine.get_EndPoint(1).Y + 5, newLine.get_EndPoint(1).Z); Line newLine2 = app.Application.Create.NewLine(p1, p2, true); Dimension newDimension = doc.Create.NewDimension( doc.ActiveView, newLine2, referenceArray); } // catch the exceptions catch (Exception ex) { m_errorMessage += ex.ToString(); return false; } } m_revit.Application.ActiveUIDocument.Document.Regenerate(); transaction.Commit(); return true; } /// <summary> /// make sure the line we get from the its geometry is upright to the location line /// </summary> /// <param name="line1">the first line</param> /// <param name="line2">the second line</param> /// <returns>if the two line is upright, true will be retured</returns> bool Validata(Line line1, Line line2) { //if it is not a linear line if (null == line1 || null == line2) { return false; } //get the first line's length Autodesk.Revit.DB.XYZ newLine = new Autodesk.Revit.DB.XYZ (line1.get_EndPoint(1).X - line1.get_EndPoint(0).X, line1.get_EndPoint(1).Y - line1.get_EndPoint(0).Y, line1.get_EndPoint(1).Z - line1.get_EndPoint(0).Z); double x1 = newLine.X * newLine.X; double y1 = newLine.Y * newLine.Y; double z1 = newLine.Z * newLine.Z; double sqrt1 = Math.Sqrt(x1 + y1 + z1); //get the second line's length Autodesk.Revit.DB.XYZ vTemp = new Autodesk.Revit.DB.XYZ (line2.get_EndPoint(1).X - line2.get_EndPoint(0).X, line2.get_EndPoint(1).Y - line2.get_EndPoint(0).Y, line2.get_EndPoint(1).Z - line2.get_EndPoint(0).Z); double x2 = vTemp.X * vTemp.X; double y2 = vTemp.Y * vTemp.Y; double z2 = vTemp.Z * vTemp.Z; double sqrt2 = Math.Sqrt(x1 + y1 + z1); double VP = newLine.X * vTemp.X + newLine.Y * vTemp.Y + newLine.Z * vTemp.Z; double compare = VP / (sqrt1 * sqrt2); if ((-precision <= compare) && (precision >= compare)) { return true; } return false; } } }
41.82971
133
0.538675
[ "BSD-3-Clause" ]
AMEE/rev
samples/Revit 2012 SDK/Samples/CreateDimensions/CS/Command.cs
11,545
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. using System; using System.Runtime.InteropServices; using System.Threading; using Windows.ApplicationModel.Core; using Windows.Foundation; using Windows.UI.Core; using Windows.UI.Xaml; using Windows.UI.Xaml.Media; namespace MUXControls.TestAppUtils { class IdleSynchronizer { const uint s_idleTimeoutMs = 100000; const string s_hasAnimationsHandleName = "HasAnimations"; const string s_animationsCompleteHandleName = "AnimationsComplete"; const string s_hasDeferredAnimationOperationsHandleName = "HasDeferredAnimationOperations"; const string s_deferredAnimationOperationsCompleteHandleName = "DeferredAnimationOperationsComplete"; const string s_rootVisualResetHandleName = "RootVisualReset"; const string s_imageDecodingIdleHandleName = "ImageDecodingIdle"; const string s_fontDownloadsIdleHandleName = "FontDownloadsIdle"; const string s_hasBuildTreeWorksHandleName = "HasBuildTreeWorks"; const string s_buildTreeServiceDrainedHandleName = "BuildTreeServiceDrained"; private CoreDispatcher m_coreDispatcher = null; private Handle m_hasAnimationsHandle; private Handle m_animationsCompleteHandle; private Handle m_hasDeferredAnimationOperationsHandle; private Handle m_deferredAnimationOperationsCompleteHandle; private Handle m_rootVisualResetHandle; private Handle m_imageDecodingIdleHandle; private Handle m_fontDownloadsIdleHandle; private Handle m_hasBuildTreeWorksHandle; private Handle m_buildTreeServiceDrainedHandle; private bool m_waitForAnimationsIsDisabled = false; private bool m_isRS2OrHigherInitialized = false; private bool m_isRS2OrHigher = false; private Handle OpenNamedEvent(uint processId, uint threadId, string eventNamePrefix) { string eventName = string.Format("{0}.{1}.{2}", eventNamePrefix, processId, threadId); Handle handle = new Handle( NativeMethods.OpenEvent( (uint)(SyncObjectAccess.EVENT_MODIFY_STATE | SyncObjectAccess.SYNCHRONIZE), false /* inherit handle */, eventName)); if (!handle.IsValid) { // Warning: Opening a session wide event handle, test may listen for events coming from the wrong process handle = new Handle( NativeMethods.OpenEvent( (uint)(SyncObjectAccess.EVENT_MODIFY_STATE | SyncObjectAccess.SYNCHRONIZE), false /* inherit handle */, eventNamePrefix)); } if (!handle.IsValid) { throw new Exception("Failed to open " + eventName + " handle."); } return handle; } private Handle OpenNamedEvent(uint threadId, string eventNamePrefix) { return OpenNamedEvent(NativeMethods.GetCurrentProcessId(), threadId, eventNamePrefix); } private Handle OpenNamedEvent(CoreDispatcher dispatcher, string eventNamePrefix) { return OpenNamedEvent(NativeMethods.GetCurrentProcessId(), GetUIThreadId(dispatcher), eventNamePrefix); } private uint GetUIThreadId(CoreDispatcher dispatcher) { uint threadId = 0; if (dispatcher.HasThreadAccess) { threadId = NativeMethods.GetCurrentThreadId(); } else { dispatcher.RunAsync( CoreDispatcherPriority.Normal, new DispatchedHandler(() => { threadId = NativeMethods.GetCurrentThreadId(); })).AsTask().Wait(); } return threadId; } private static IdleSynchronizer instance = null; public static IdleSynchronizer Instance { get { if (instance == null) { instance = new IdleSynchronizer(CoreApplication.MainView.Dispatcher); } return instance; } } public string Log { get; set; } public int TickCountBegin { get; set; } public IdleSynchronizer(CoreDispatcher dispatcher) { m_coreDispatcher = dispatcher; m_hasAnimationsHandle = OpenNamedEvent(m_coreDispatcher, s_hasAnimationsHandleName); m_animationsCompleteHandle = OpenNamedEvent(m_coreDispatcher, s_animationsCompleteHandleName); m_hasDeferredAnimationOperationsHandle = OpenNamedEvent(m_coreDispatcher, s_hasDeferredAnimationOperationsHandleName); m_deferredAnimationOperationsCompleteHandle = OpenNamedEvent(m_coreDispatcher, s_deferredAnimationOperationsCompleteHandleName); m_rootVisualResetHandle = OpenNamedEvent(m_coreDispatcher, s_rootVisualResetHandleName); m_imageDecodingIdleHandle = OpenNamedEvent(m_coreDispatcher, s_imageDecodingIdleHandleName); m_fontDownloadsIdleHandle = OpenNamedEvent(m_coreDispatcher, s_fontDownloadsIdleHandleName); m_hasBuildTreeWorksHandle = OpenNamedEvent(m_coreDispatcher, s_hasBuildTreeWorksHandleName); m_buildTreeServiceDrainedHandle = OpenNamedEvent(m_coreDispatcher, s_buildTreeServiceDrainedHandleName); } public static void Wait() { string logMessage; Wait(out logMessage); } public static void Wait(out string logMessage) { string errorString = Instance.WaitInternal(out logMessage); if (errorString.Length > 0) { throw new Exception(errorString); } } public static string TryWait() { string logMessage; return Instance.WaitInternal(out logMessage); } public static string TryWait(out string logMessage) { return Instance.WaitInternal(out logMessage); } public void AddLog(string message) { if (Log != null && Log != "LOG: ") { Log += "; "; } Log += (Environment.TickCount - TickCountBegin).ToString() + ": "; Log += message; } private string WaitInternal(out string logMessage) { logMessage = string.Empty; string errorString = string.Empty; if (m_coreDispatcher.HasThreadAccess) { return "Cannot wait for UI thread idle from the UI thread."; } Log = "LOG: "; TickCountBegin = Environment.TickCount; bool isIdle = false; while (!isIdle) { bool hadAnimations = true; bool hadDeferredAnimationOperations = true; bool hadBuildTreeWork = false; errorString = WaitForRootVisualReset(); if (errorString.Length > 0) { return errorString; } AddLog("After WaitForRootVisualReset"); errorString = WaitForImageDecodingIdle(); if (errorString.Length > 0) { return errorString; } AddLog("After WaitForImageDecodingIdle"); SynchronouslyTickUIThread(1); AddLog("After SynchronouslyTickUIThread(1)"); errorString = WaitForFontDownloadsIdle(); if (errorString.Length > 0) { return errorString; } AddLog("After WaitForFontDownloadsIdle"); WaitForIdleDispatcher(); AddLog("After WaitForIdleDispatcher"); // At this point, we know that the UI thread is idle - now we need to make sure // that XAML isn't animating anything. errorString = WaitForBuildTreeServiceWork(out hadBuildTreeWork); if (errorString.Length > 0) { return errorString; } AddLog("After WaitForBuildTreeServiceWork"); // The AnimationsComplete handle sometimes is never set in RS1, // so we'll skip waiting for animations to complete // if we've timed out once while waiting for animations in RS1. if (!m_waitForAnimationsIsDisabled) { errorString = WaitForAnimationsComplete(out hadAnimations); if (errorString.Length > 0) { return errorString; } AddLog("After WaitForAnimationsComplete"); } else { hadAnimations = false; } errorString = WaitForDeferredAnimationOperationsComplete(out hadDeferredAnimationOperations); if (errorString.Length > 0) { return errorString; } AddLog("After WaitForDeferredAnimationOperationsComplete"); // In the case where we waited for an animation to complete there's a possibility that // XAML, at the completion of the animation, scheduled a new tick. We will loop // for as long as needed until we complete an idle dispatcher callback without // waiting for a pending animation to complete. isIdle = !hadAnimations && !hadDeferredAnimationOperations && !hadBuildTreeWork; AddLog("IsIdle? " + isIdle); } AddLog("End"); logMessage = Log; return string.Empty; } private string WaitForRootVisualReset() { uint waitResult = NativeMethods.WaitForSingleObject(m_rootVisualResetHandle.NativeHandle, 5000); if (waitResult != NativeMethods.WAIT_OBJECT_0 && waitResult != NativeMethods.WAIT_TIMEOUT) { return "Waiting for root visual reset handle returned an invalid value."; } return string.Empty; } private string WaitForImageDecodingIdle() { uint waitResult = NativeMethods.WaitForSingleObject(m_imageDecodingIdleHandle.NativeHandle, 5000); if (waitResult != NativeMethods.WAIT_OBJECT_0 && waitResult != NativeMethods.WAIT_TIMEOUT) { return "Waiting for image decoding idle handle returned an invalid value."; } return string.Empty; } string WaitForFontDownloadsIdle() { uint waitResult = NativeMethods.WaitForSingleObject(m_fontDownloadsIdleHandle.NativeHandle, 5000); if (waitResult != NativeMethods.WAIT_OBJECT_0 && waitResult != NativeMethods.WAIT_TIMEOUT) { return "Waiting for font downloads handle returned an invalid value."; } return string.Empty; } void WaitForIdleDispatcher() { bool isDispatcherIdle = false; AutoResetEvent shouldContinueEvent = new AutoResetEvent(false); while (!isDispatcherIdle) { IAsyncAction action = m_coreDispatcher.RunIdleAsync(new IdleDispatchedHandler((IdleDispatchedHandlerArgs args) => { isDispatcherIdle = args.IsDispatcherIdle; })); action.Completed = new AsyncActionCompletedHandler((IAsyncAction, AsyncStatus) => { shouldContinueEvent.Set(); }); shouldContinueEvent.WaitOne(10000); } } string WaitForBuildTreeServiceWork(out bool hadBuildTreeWork) { hadBuildTreeWork = false; bool hasBuildTreeWork = true; // We want to avoid an infinite loop, so we'll iterate 20 times before concluding that // we probably are never going to become idle. int waitCount = 20; while (hasBuildTreeWork && waitCount-- > 0) { if (!NativeMethods.ResetEvent(m_buildTreeServiceDrainedHandle.NativeHandle)) { return "Failed to reset BuildTreeServiceDrained handle."; } m_coreDispatcher.RunAsync( CoreDispatcherPriority.Normal, new DispatchedHandler(() => { if (Window.Current != null && Window.Current.Content != null) { Window.Current.Content.UpdateLayout(); } })).AsTask().Wait(); // This will be signaled if and only if Jupiter plans to at some point in the near // future set the BuildTreeServiceDrained event. uint waitResult = NativeMethods.WaitForSingleObject(m_hasBuildTreeWorksHandle.NativeHandle, 0); if (waitResult != NativeMethods.WAIT_OBJECT_0 && waitResult != NativeMethods.WAIT_TIMEOUT) { return "HasBuildTreeWork handle wait returned an invalid value."; } hasBuildTreeWork = (waitResult == NativeMethods.WAIT_OBJECT_0); if (hasBuildTreeWork) { waitResult = NativeMethods.WaitForSingleObject(m_buildTreeServiceDrainedHandle.NativeHandle, 10000); if (waitResult != NativeMethods.WAIT_OBJECT_0 && waitResult != NativeMethods.WAIT_TIMEOUT) { return "Wait for build tree service failed"; } } } hadBuildTreeWork = hasBuildTreeWork; return string.Empty; } string WaitForAnimationsComplete(out bool hadAnimations) { hadAnimations = false; if (!NativeMethods.ResetEvent(m_animationsCompleteHandle.NativeHandle)) { return "Failed to reset AnimationsComplete handle."; } AddLog("WaitForAnimationsComplete: After ResetEvent"); // This will be signaled if and only if XAML plans to at some point in the near // future set the animations complete event. uint waitResult = NativeMethods.WaitForSingleObject(m_hasAnimationsHandle.NativeHandle, 0); if (waitResult != NativeMethods.WAIT_OBJECT_0 && waitResult != NativeMethods.WAIT_TIMEOUT) { return "HasAnimations handle wait returned an invalid value."; } AddLog("WaitForAnimationsComplete: After Wait(m_hasAnimationsHandle)"); bool hasAnimations = (waitResult == NativeMethods.WAIT_OBJECT_0); if (hasAnimations) { uint animationCompleteWaitResult = NativeMethods.WaitForSingleObject(m_animationsCompleteHandle.NativeHandle, s_idleTimeoutMs); AddLog("WaitForAnimationsComplete: HasAnimations, After Wait(m_animationsCompleteHandle)"); if (animationCompleteWaitResult != NativeMethods.WAIT_OBJECT_0) { if (!IsRS2OrHigher()) { // The AnimationsComplete handle is sometimes just never signaled on RS1, ever. // If we run into this problem, we'll just disable waiting for animations to complete // and continue execution. When the current test completes, we'll then close and reopen // the test app to minimize the effects of this problem. m_waitForAnimationsIsDisabled = true; hadAnimations = false; } return "Animation complete wait took longer than idle timeout."; } } hadAnimations = hasAnimations; return string.Empty; } string WaitForDeferredAnimationOperationsComplete(out bool hadDeferredAnimationOperations) { hadDeferredAnimationOperations = false; if (!NativeMethods.ResetEvent(m_deferredAnimationOperationsCompleteHandle.NativeHandle)) { return "Failed to reset DeferredAnimationOperations handle."; } // This will be signaled if and only if XAML plans to at some point in the near // future set the animations complete event. uint waitResult = NativeMethods.WaitForSingleObject(m_hasDeferredAnimationOperationsHandle.NativeHandle, 0); if (waitResult != NativeMethods.WAIT_OBJECT_0 && waitResult != NativeMethods.WAIT_TIMEOUT) { return "HasDeferredAnimationOperations handle wait returned an invalid value."; } bool hasDeferredAnimationOperations = (waitResult == NativeMethods.WAIT_OBJECT_0); if (hasDeferredAnimationOperations) { uint animationCompleteWaitResult = NativeMethods.WaitForSingleObject(m_deferredAnimationOperationsCompleteHandle.NativeHandle, s_idleTimeoutMs); if (animationCompleteWaitResult != NativeMethods.WAIT_OBJECT_0 && animationCompleteWaitResult != NativeMethods.WAIT_TIMEOUT) { return "Deferred animation operations complete wait took longer than idle timeout."; } } hadDeferredAnimationOperations = hasDeferredAnimationOperations; return string.Empty; } private void SynchronouslyTickUIThread(uint ticks) { AutoResetEvent tickCompleteEvent = new AutoResetEvent(false); for (uint i = 0; i < ticks; i++) { m_coreDispatcher.RunAsync( CoreDispatcherPriority.Normal, new DispatchedHandler(() => { EventHandler<object> renderingHandler = null; renderingHandler = (object sender, object args) => { CompositionTarget.Rendering -= renderingHandler; }; CompositionTarget.Rendering += renderingHandler; })).AsTask().Wait(); } } private bool IsRS2OrHigher() { if (!m_isRS2OrHigherInitialized) { m_isRS2OrHigherInitialized = true; m_isRS2OrHigher = Windows.Foundation.Metadata.ApiInformation.IsApiContractPresent("Windows.Foundation.UniversalApiContract", 4); } return m_isRS2OrHigher; } } internal class Handle { public IntPtr NativeHandle { get; private set; } public bool IsValid { get { return NativeHandle != IntPtr.Zero; } } public Handle(IntPtr nativeHandle) { Attach(nativeHandle); } ~Handle() { Release(); } public void Attach(IntPtr nativeHandle) { Release(); NativeHandle = nativeHandle; } public IntPtr Detach() { IntPtr returnValue = NativeHandle; NativeHandle = IntPtr.Zero; return returnValue; } public void Release() { NativeMethods.CloseHandle(NativeHandle); NativeHandle = IntPtr.Zero; } } internal static class NativeMethods { [DllImport("Kernel32.dll", SetLastError = true)] public static extern IntPtr OpenEvent(uint dwDesiredAccess, bool bInheritHandle, string lpName); [DllImport("kernel32.dll", SetLastError = true)] public static extern UInt32 WaitForSingleObject(IntPtr hHandle, UInt32 dwMilliseconds); public const UInt32 INFINITE = 0xFFFFFFFF; public const UInt32 WAIT_ABANDONED = 0x00000080; public const UInt32 WAIT_OBJECT_0 = 0x00000000; public const UInt32 WAIT_TIMEOUT = 0x00000102; [DllImport("kernel32.dll", SetLastError = true)] public static extern bool ResetEvent(IntPtr hEvent); [DllImport("kernel32.dll", SetLastError = true)] public static extern bool CloseHandle(IntPtr hObject); [DllImport("kernel32.dll")] public static extern uint GetCurrentProcessId(); [DllImport("kernel32.dll")] public static extern uint GetCurrentThreadId(); } [Flags] public enum SyncObjectAccess : uint { DELETE = 0x00010000, READ_CONTROL = 0x00020000, WRITE_DAC = 0x00040000, WRITE_OWNER = 0x00080000, SYNCHRONIZE = 0x00100000, EVENT_ALL_ACCESS = 0x001F0003, EVENT_MODIFY_STATE = 0x00000002, MUTEX_ALL_ACCESS = 0x001F0001, MUTEX_MODIFY_STATE = 0x00000001, SEMAPHORE_ALL_ACCESS = 0x001F0003, SEMAPHORE_MODIFY_STATE = 0x00000002, TIMER_ALL_ACCESS = 0x001F0003, TIMER_MODIFY_STATE = 0x00000002, TIMER_QUERY_STATE = 0x00000001 } }
38.176157
160
0.595153
[ "MIT" ]
07101994/microsoft-ui-xaml
test/TestAppUtils/IdleSynchronizer.cs
21,457
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. // Template Source: Templates\CSharp\Requests\MethodRequestBuilder.cs.tt namespace Microsoft.Graph { using System; using System.Collections.Generic; using System.IO; /// <summary> /// The type WorkbookFunctionsFisherInvRequestBuilder. /// </summary> public partial class WorkbookFunctionsFisherInvRequestBuilder : BaseActionMethodRequestBuilder<IWorkbookFunctionsFisherInvRequest>, IWorkbookFunctionsFisherInvRequestBuilder { /// <summary> /// Constructs a new <see cref="WorkbookFunctionsFisherInvRequestBuilder"/>. /// </summary> /// <param name="requestUrl">The URL for the request.</param> /// <param name="client">The <see cref="IBaseClient"/> for handling requests.</param> /// <param name="y">A y parameter for the OData method call.</param> public WorkbookFunctionsFisherInvRequestBuilder( string requestUrl, IBaseClient client, Newtonsoft.Json.Linq.JToken y) : base(requestUrl, client) { this.SetParameter("y", y, true); } /// <summary> /// A method used by the base class to construct a request class instance. /// </summary> /// <param name="functionUrl">The request URL to </param> /// <param name="options">The query and header options for the request.</param> /// <returns>An instance of a specific request class.</returns> protected override IWorkbookFunctionsFisherInvRequest CreateRequest(string functionUrl, IEnumerable<Option> options) { var request = new WorkbookFunctionsFisherInvRequest(functionUrl, this.Client, options); if (this.HasParameter("y")) { request.RequestBody.Y = this.GetParameter<Newtonsoft.Json.Linq.JToken>("y"); } return request; } } }
42.592593
177
0.608696
[ "MIT" ]
AzureMentor/msgraph-sdk-dotnet
src/Microsoft.Graph/Requests/Generated/WorkbookFunctionsFisherInvRequestBuilder.cs
2,300
C#
using System.Collections.Generic; using System.Threading.Tasks; using Deployer.Core; namespace Deployer.Tests { public class TestPrompt { public Task<Option> PickOptions(string markdown, IEnumerable<Option> options) { return Task.FromResult((Option)null); } } }
22.214286
85
0.672026
[ "MIT" ]
0-Xanthium/WOA-Deployer
Source/Deployer.Tests/TestPrompt.cs
313
C#
using System; using System.Collections.Generic; using System.Text; using System.Web; using System.Web.Caching; using System.Collections.ObjectModel; namespace Core.Web.CacheManage { /// <summary> /// 网站缓存管理类 /// </summary> public class WebCache : ICache { private static readonly object lockObj = new object(); /// <summary> /// 当前的缓存是否可用 /// </summary> private bool enable = false; /// <summary> /// 默认实例 /// </summary> private static WebCache instance = null; /// <summary> /// 返回默认WebCache缓存实例 /// </summary> /// <param name="enable">是否可用最好放到配置项里配置下</param> public static WebCache GetCacheService(bool enable) { if (instance == null) { lock (lockObj) { if (instance == null) { instance = new WebCache(enable); } } } return instance; } /// <summary> /// 构造方法 /// </summary> private WebCache(bool enable) { this.enable = enable; } /// <summary> /// 获取一个值,指示当前的缓存是否可用 /// </summary> public bool EnableCache { get { return this.enable; } } /// <summary> /// 获取缓存的类型 /// </summary> public CacheType Type { get { return CacheType.Web; } } /// <summary> /// 检查缓存中是否存在指定的键 /// </summary> /// <param name="key">要检查的键</param> /// <returns>返回一个值,指示检查的键是否存在</returns> public bool Contains(string key) { if (this.enable) { return HttpRuntime.Cache[key] != null; } return false; } /// <summary> /// 检查系统中是否存在指定的缓存 /// </summary> /// <typeparam name="T">类型</typeparam> /// <param name="key">缓存key</param> /// <returns>返回这个类型的值是否存在</returns> public bool Contains<T>(string key) { object value = HttpRuntime.Cache[key]; if (value is T) { return true; } return false; } /// <summary> /// 从缓存中获取指定键的值 /// </summary> /// <param name="key">要获取的键</param> /// <returns>返回指定键的值</returns> public T Get<T>(string key) { if (this.enable) { return (T)HttpRuntime.Cache[key]; } return default(T); } /// <summary> /// 获取缓存中键值的数量 /// </summary> public int Count { get { if (this.enable) { return HttpRuntime.Cache.Count; } return 0; } } /// <summary> /// 添加缓存 /// </summary> /// <param name="key">关键字</param> /// <param name="value">缓存值</param> public void Add<T>(string key, T value) { if (this.enable) { HttpRuntime.Cache.Insert(key, value); } return; } /// <summary> /// 添加缓存 /// </summary> /// <param name="key">关键字</param> /// <param name="value">缓存值</param> /// <param name="absoluteExpiration">过期时间</param> public void Add<T>(string key, T value, DateTime absoluteExpiration) { if (this.enable) { HttpRuntime.Cache.Insert(key, value, null, absoluteExpiration, System.Web.Caching.Cache.NoSlidingExpiration); } return; } /// <summary> /// 添加缓存 /// </summary> /// <param name="key">关键字</param> /// <param name="value">缓存值</param> /// <param name="slidingExpiration">保存时间</param> public void Add<T>(string key, T value, TimeSpan slidingExpiration) { if (this.enable) { HttpRuntime.Cache.Insert(key, value, null, System.Web.Caching.Cache.NoAbsoluteExpiration, slidingExpiration); } return; } /// <summary> /// 添加缓存 /// </summary> /// <param name="key">关键字</param> /// <param name="value">缓存值</param> /// <param name="minutes">保存时间(分钟)</param> public void Add<T>(string key, T value, int minutes) { if (this.enable) { HttpRuntime.Cache.Insert(key, value, null, System.Web.Caching.Cache.NoAbsoluteExpiration, new TimeSpan(0, minutes, 0)); } return; } /// <summary> /// 添加缓存 /// </summary> /// <param name="key">关键字</param> /// <param name="value">缓存值</param> /// <param name="priority">优先级</param> /// <param name="slidingExpiration">保存时间</param> public void Add<T>(string key, T value, CachePriority priority, TimeSpan slidingExpiration) { if (this.enable) { HttpRuntime.Cache.Insert(key, value, null, System.Web.Caching.Cache.NoAbsoluteExpiration, slidingExpiration, CacheItemPriorityConvert(priority), null); } return; } /// <summary> /// 添加缓存 /// </summary> /// <param name="key">关键字</param> /// <param name="value">缓存值</param> /// <param name="priority">优先级</param> /// <param name="absoluteExpiration">过期时间</param> public void Add<T>(string key, T value, CachePriority priority, DateTime absoluteExpiration) { if (this.enable) { HttpRuntime.Cache.Insert(key, value, null, absoluteExpiration, System.Web.Caching.Cache.NoSlidingExpiration, CacheItemPriorityConvert(priority), null); } return; } /// <summary> /// 尝试返回指定的缓存 /// </summary> /// <typeparam name="T">缓存内容的类型</typeparam> /// <param name="key">缓存的key</param> /// <param name="value">缓存的内容</param> /// <returns>是否存在这个缓存</returns> public bool TryGetValue<T>(string key, out T value) { object temp = HttpRuntime.Cache[key]; if (temp != null && temp is T) { value = (T)temp; return true; } value = default(T); return false; } /// <summary> /// 移除键中某关键字的缓存并返回相应的值 /// </summary> /// <param name="key">关键字</param> public void Remove(string key) { object result = null; if (this.enable) { if (HttpRuntime.Cache[key] != null) { result = HttpRuntime.Cache.Remove(key); } } return; } /// <summary> /// 移除键中带某关键字的缓存 /// </summary> /// <param name="key">关键字</param> public int RemoveContains(string key) { int result = 0; if (this.enable) { System.Collections.IDictionaryEnumerator CacheEnum = HttpRuntime.Cache.GetEnumerator(); while (CacheEnum.MoveNext()) { if (CacheEnum.Key.ToString().Contains(key)) { HttpRuntime.Cache.Remove(CacheEnum.Key.ToString()); result++; } } } return result; } /// <summary> /// 移除键中以某关键字开头的缓存 /// </summary> /// <param name="key">关键字</param> public int RemoveStartWith(string key) { int result = 0; if (this.enable) { System.Collections.IDictionaryEnumerator CacheEnum = HttpRuntime.Cache.GetEnumerator(); while (CacheEnum.MoveNext()) { if (CacheEnum.Key.ToString().StartsWith(key)) { HttpRuntime.Cache.Remove(CacheEnum.Key.ToString()); result++; } } } return result; } /// <summary> /// 移除键中以某关键字结尾的缓存 /// </summary> /// <param name="key">关键字</param> public int RemoveEndWith(string key) { int result = 0; if (this.enable) { System.Collections.IDictionaryEnumerator CacheEnum = HttpRuntime.Cache.GetEnumerator(); while (CacheEnum.MoveNext()) { if (CacheEnum.Key.ToString().EndsWith(key)) { HttpRuntime.Cache.Remove(CacheEnum.Key.ToString()); result++; } } } return result; } /// <summary> /// 移除键中所有的缓存 /// </summary> public int Clear() { int result = 0; if (this.enable) { System.Collections.IDictionaryEnumerator CacheEnum = HttpRuntime.Cache.GetEnumerator(); while (CacheEnum.MoveNext()) { HttpRuntime.Cache.Remove(CacheEnum.Key.ToString()); result++; } keys.Clear(); } return result; } private List<string> keys = new List<string>(); /// <summary> /// 缓存中所有的键列表 /// </summary> public ReadOnlyCollection<string> Keys { get { if (this.enable) { lock (keys) { keys.Clear(); System.Collections.IDictionaryEnumerator CacheEnum = HttpRuntime.Cache.GetEnumerator(); while (CacheEnum.MoveNext()) { keys.Add(CacheEnum.Key.ToString()); } } } return new ReadOnlyCollection<string>(keys); } } /// <summary> /// 对缓存优先级做一个默认的转换 /// </summary> /// <param name="priority">原始的优先级</param> /// <returns>目标优先级</returns> private CacheItemPriority CacheItemPriorityConvert(CachePriority priority) { CacheItemPriority p = CacheItemPriority.Default; switch (priority) { case CachePriority.Low: { p = CacheItemPriority.Low; break; } case CachePriority.Normal: { p = CacheItemPriority.Normal; break; } case CachePriority.High: { p = CacheItemPriority.High; break; } case CachePriority.NotRemovable: { p = CacheItemPriority.NotRemovable; break; } } return p; } } }
30.425587
167
0.437055
[ "MIT" ]
lvgithub/DotNetUtilities
Core.Web/CacheManage/WebCache.cs
12,453
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/vssym32.h in the Windows SDK for Windows 10.0.20348.0 // Original source is Copyright © Microsoft. All rights reserved. namespace TerraFX.Interop.Windows; /// <include file='VALIGN.xml' path='doc/member[@name="VALIGN"]/*' /> public enum VALIGN { /// <include file='VALIGN.xml' path='doc/member[@name="VALIGN.VA_TOP"]/*' /> VA_TOP = 0, /// <include file='VALIGN.xml' path='doc/member[@name="VALIGN.VA_CENTER"]/*' /> VA_CENTER = 1, /// <include file='VALIGN.xml' path='doc/member[@name="VALIGN.VA_BOTTOM"]/*' /> VA_BOTTOM = 2, }
36
145
0.679167
[ "MIT" ]
IngmarBitter/terrafx.interop.windows
sources/Interop/Windows/Windows/um/vssym32/VALIGN.cs
722
C#
#if !ONPREMISES using SharePointPnP.PowerShell.CmdletHelpAttributes; using SharePointPnP.PowerShell.Commands.Base; using System; using System.Collections.Generic; using System.Linq; using System.Management.Automation; namespace SharePointPnP.PowerShell.Commands.Graph { [Cmdlet(VerbsCommon.Remove, "PnPSiteClassification")] [CmdletHelp("Removes one or more existing site classification values from the list of available values. Requires a connection to the Microsoft Graph", Category = CmdletHelpCategory.Graph, SupportedPlatform = CmdletSupportedPlatform.Online)] [CmdletExample( Code = @"PS:> Connect-PnPOnline -Scopes ""Directory.ReadWrite.All"" PS:> Remove-PnPSiteClassification -Classifications ""HBI""", Remarks = @"Removes the ""HBI"" site classification from the list of available values.", SortOrder = 1)] [CmdletExample( Code = @"PS:> Connect-PnPOnline -Scopes ""Directory.ReadWrite.All"" PS:> Remove-PnPSiteClassification -Classifications ""HBI"", ""Top Secret""", Remarks = @"Removes the ""HBI"" site classification from the list of available values.", SortOrder = 2)] [CmdletMicrosoftGraphApiPermission(MicrosoftGraphApiPermission.Directory_ReadWrite_All)] public class RemoveSiteClassification : PnPGraphCmdlet { [Parameter(Mandatory = true)] public List<string> Classifications; [Parameter(Mandatory = false, HelpMessage = "Specifying the Confirm parameter will allow the confirmation question to be skipped")] public SwitchParameter Confirm; protected override void ExecuteCmdlet() { try { var existingSettings = OfficeDevPnP.Core.Framework.Graph.SiteClassificationsUtility.GetSiteClassificationsSettings(AccessToken); foreach (var classification in Classifications) { if (existingSettings.Classifications.Contains(classification)) { if (existingSettings.DefaultClassification == classification) { if ((ParameterSpecified("Confirm") && !bool.Parse(MyInvocation.BoundParameters["Confirm"].ToString())) || ShouldContinue(string.Format(Properties.Resources.RemoveDefaultClassification0, classification), Properties.Resources.Confirm)) { existingSettings.DefaultClassification = ""; existingSettings.Classifications.Remove(classification); } } else { existingSettings.Classifications.Remove(classification); } } } if (existingSettings.Classifications.Any()) { OfficeDevPnP.Core.Framework.Graph.SiteClassificationsUtility.UpdateSiteClassificationsSettings(AccessToken, existingSettings); } else { WriteError(new ErrorRecord(new InvalidOperationException("At least one classification is required. If you want to disable classifications, use Disable-PnPSiteClassification."), "SITECLASSIFICATIONS_ARE_REQUIRED", ErrorCategory.InvalidOperation, null)); } } catch (ApplicationException ex) { if (ex.Message == @"Missing DirectorySettingTemplate for ""Group.Unified""") { WriteError(new ErrorRecord(new InvalidOperationException("Site Classification is not enabled for this tenant"), "SITECLASSIFICATION_NOT_ENABLED", ErrorCategory.ResourceUnavailable, null)); } } } } } #endif
49.5
272
0.62963
[ "MIT" ]
MrTantum/PnP-PowerShell
Commands/Graph/RemoveSiteClassification.cs
3,863
C#
using System.Threading.Tasks; namespace MCPackEditor.App.Data.Assets { public class LangFile : BaseJsonAsset { public static async Task<LangFile> Load( string path ) => await LoadFromJsonFile<LangFile>( path ); } }
27.625
101
0.755656
[ "MIT" ]
FallenAvatar/mc-pack-editor
App/Data/Assets/LangFile.cs
223
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. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics.Arm\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.Arm; namespace JIT.HardwareIntrinsics.Arm { public static partial class Program { private static void AddReturningHighNarrowLower_Vector64_Int16() { var test = new SimpleBinaryOpTest__AddReturningHighNarrowLower_Vector64_Int16(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); } // Validates passing a static member works test.RunClsVarScenario(); if (AdvSimd.IsSupported) { // Validates passing a static member works, using pinning and Load test.RunClsVarScenario_Load(); } // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); if (AdvSimd.IsSupported) { // Validates passing the field of a local class works, using pinning and Load test.RunClassLclFldScenario_Load(); } // Validates passing an instance member of a class works test.RunClassFldScenario(); if (AdvSimd.IsSupported) { // Validates passing an instance member of a class works, using pinning and Load test.RunClassFldScenario_Load(); } // Validates passing the field of a local struct works test.RunStructLclFldScenario(); if (AdvSimd.IsSupported) { // Validates passing the field of a local struct works, using pinning and Load test.RunStructLclFldScenario_Load(); } // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (AdvSimd.IsSupported) { // Validates passing an instance member of a struct works, using pinning and Load test.RunStructFldScenario_Load(); } } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleBinaryOpTest__AddReturningHighNarrowLower_Vector64_Int16 { private struct DataTable { private byte[] inArray1; private byte[] inArray2; private byte[] outArray; private GCHandle inHandle1; private GCHandle inHandle2; private GCHandle outHandle; private ulong alignment; public DataTable(Int32[] inArray1, Int32[] inArray2, Int16[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Int32>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Int32>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Int16>(); if ((alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.inArray2 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Int32, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Int32, byte>(ref inArray2[0]), (uint)sizeOfinArray2); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); inHandle2.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector128<Int32> _fld1; public Vector128<Int32> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref testStruct._fld1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref testStruct._fld2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>()); return testStruct; } public void RunStructFldScenario(SimpleBinaryOpTest__AddReturningHighNarrowLower_Vector64_Int16 testClass) { var result = AdvSimd.AddReturningHighNarrowLower(_fld1, _fld2); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleBinaryOpTest__AddReturningHighNarrowLower_Vector64_Int16 testClass) { fixed (Vector128<Int32>* pFld1 = &_fld1) fixed (Vector128<Int32>* pFld2 = &_fld2) { var result = AdvSimd.AddReturningHighNarrowLower( AdvSimd.LoadVector128((Int32*)(pFld1)), AdvSimd.LoadVector128((Int32*)(pFld2)) ); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } } } private static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Int32>>() / sizeof(Int32); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<Int32>>() / sizeof(Int32); private static readonly int RetElementCount = Unsafe.SizeOf<Vector64<Int16>>() / sizeof(Int16); private static Int32[] _data1 = new Int32[Op1ElementCount]; private static Int32[] _data2 = new Int32[Op2ElementCount]; private static Vector128<Int32> _clsVar1; private static Vector128<Int32> _clsVar2; private Vector128<Int32> _fld1; private Vector128<Int32> _fld2; private DataTable _dataTable; static SimpleBinaryOpTest__AddReturningHighNarrowLower_Vector64_Int16() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _clsVar1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _clsVar2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>()); } public SimpleBinaryOpTest__AddReturningHighNarrowLower_Vector64_Int16() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _fld1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _fld2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); } _dataTable = new DataTable(_data1, _data2, new Int16[RetElementCount], LargestVectorSize); } public bool IsSupported => AdvSimd.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = AdvSimd.AddReturningHighNarrowLower( Unsafe.Read<Vector128<Int32>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Int32>>(_dataTable.inArray2Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = AdvSimd.AddReturningHighNarrowLower( AdvSimd.LoadVector128((Int32*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector128((Int32*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.AddReturningHighNarrowLower), new Type[] { typeof(Vector128<Int32>), typeof(Vector128<Int32>) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<Int32>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Int32>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector64<Int16>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.AddReturningHighNarrowLower), new Type[] { typeof(Vector128<Int32>), typeof(Vector128<Int32>) }) .Invoke(null, new object[] { AdvSimd.LoadVector128((Int32*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector128((Int32*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector64<Int16>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = AdvSimd.AddReturningHighNarrowLower( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector128<Int32>* pClsVar1 = &_clsVar1) fixed (Vector128<Int32>* pClsVar2 = &_clsVar2) { var result = AdvSimd.AddReturningHighNarrowLower( AdvSimd.LoadVector128((Int32*)(pClsVar1)), AdvSimd.LoadVector128((Int32*)(pClsVar2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector128<Int32>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector128<Int32>>(_dataTable.inArray2Ptr); var result = AdvSimd.AddReturningHighNarrowLower(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = AdvSimd.LoadVector128((Int32*)(_dataTable.inArray1Ptr)); var op2 = AdvSimd.LoadVector128((Int32*)(_dataTable.inArray2Ptr)); var result = AdvSimd.AddReturningHighNarrowLower(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleBinaryOpTest__AddReturningHighNarrowLower_Vector64_Int16(); var result = AdvSimd.AddReturningHighNarrowLower(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load)); var test = new SimpleBinaryOpTest__AddReturningHighNarrowLower_Vector64_Int16(); fixed (Vector128<Int32>* pFld1 = &test._fld1) fixed (Vector128<Int32>* pFld2 = &test._fld2) { var result = AdvSimd.AddReturningHighNarrowLower( AdvSimd.LoadVector128((Int32*)(pFld1)), AdvSimd.LoadVector128((Int32*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = AdvSimd.AddReturningHighNarrowLower(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector128<Int32>* pFld1 = &_fld1) fixed (Vector128<Int32>* pFld2 = &_fld2) { var result = AdvSimd.AddReturningHighNarrowLower( AdvSimd.LoadVector128((Int32*)(pFld1)), AdvSimd.LoadVector128((Int32*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = AdvSimd.AddReturningHighNarrowLower(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = AdvSimd.AddReturningHighNarrowLower( AdvSimd.LoadVector128((Int32*)(&test._fld1)), AdvSimd.LoadVector128((Int32*)(&test._fld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunStructFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load)); var test = TestStruct.Create(); test.RunStructFldScenario_Load(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector128<Int32> op1, Vector128<Int32> op2, void* result, [CallerMemberName] string method = "") { Int32[] inArray1 = new Int32[Op1ElementCount]; Int32[] inArray2 = new Int32[Op2ElementCount]; Int16[] outArray = new Int16[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref inArray2[0]), op2); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<Int16>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "") { Int32[] inArray1 = new Int32[Op1ElementCount]; Int32[] inArray2 = new Int32[Op2ElementCount]; Int16[] outArray = new Int16[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<Int32>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<Int32>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<Int16>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Int32[] left, Int32[] right, Int16[] result, [CallerMemberName] string method = "") { bool succeeded = true; for (var i = 0; i < RetElementCount; i++) { if (Helpers.AddReturningHighNarrow(left[i], right[i]) != result[i]) { succeeded = false; break; } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd)}.{nameof(AdvSimd.AddReturningHighNarrowLower)}<Int16>(Vector128<Int32>, Vector128<Int32>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})"); TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
42.898305
187
0.592827
[ "MIT" ]
ThorstenReichert/runtime
src/coreclr/tests/src/JIT/HardwareIntrinsics/Arm/AdvSimd/AddReturningHighNarrowLower.Vector64.Int16.cs
22,779
C#
using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Athena.Core.Exceptions; using Athena.Core.Models; using Athena.Data.Repositories; using AutoFixture.Xunit2; using Xunit; namespace Athena.Data.Tests.Repositories { public class InstitutionRepositoryTests : DataTest { private readonly InstitutionRepository _sut; public InstitutionRepositoryTests() => _sut = new InstitutionRepository(_db); [Theory, AutoData] public async Task AddValid(Institution institution) { await _sut.AddAsync(institution); var result = await _sut.GetAsync(institution.Id); Assert.Equal(institution, result); } [Theory, AutoData] public async Task Add_ThrowsForDuplicate(Institution institution) { await _sut.AddAsync(institution); await Assert.ThrowsAsync<DuplicateObjectException>(async () => await _sut.AddAsync(institution)); } [Theory, AutoData] public async Task EditValid(Institution institution, Institution changes) { await _sut.AddAsync(institution); changes.Id = institution.Id; await _sut.EditAsync(changes); var result = await _sut.GetAsync(changes.Id); Assert.Equal(changes, result); } [Theory, AutoData] public async Task DeleteValid(Institution institution) { await _sut.AddAsync(institution); Assert.NotNull(await _sut.GetAsync(institution.Id)); await _sut.DeleteAsync(institution); Assert.Null(await _sut.GetAsync(institution.Id)); } [Theory, AutoData] public async Task Search_Empty(List<Institution> institutions) { foreach (var p in institutions) { await _sut.AddAsync(p); } var result = await _sut.SearchAsync("bAr"); Assert.Empty(result); } [Theory, AutoData] public async Task Search_Valid(List<Institution> institutions, Institution target) { target.Name = "foo bar baz"; foreach (var p in institutions.Union(new []{target})) { await _sut.AddAsync(p); } var result = (await _sut.SearchAsync("bAr")).ToList(); Assert.Single(result); Assert.Equal(target, result[0]); } [Theory, AutoData] public async Task TracksCampuses(Campus campus, List<Institution> institutions) { var campusRepo = new CampusRepository(_db); await campusRepo.AddAsync(campus); foreach (var institution in institutions) { await _sut.AddAsync(institution); await campusRepo.AssociateCampusWithInstitutionAsync(campus, institution); } var results = (await _sut.GetInstitutionsOnCampusAsync(campus)).ToList(); Assert.Equal(institutions.Count, results.Count); Assert.All(institutions, i => Assert.Contains(i, results)); foreach (var institution in institutions) { await campusRepo.DissassociateCampusWithInstitutionAsync(campus, institution); } Assert.Empty(await _sut.GetInstitutionsOnCampusAsync(campus)); } [Theory, AutoData] public async Task TracksStudents(List<Institution> institutions, Student student) { var studentRepo = new StudentRepository(_db); await studentRepo.AddAsync(student); foreach (var i in institutions) { await _sut.AddAsync(i); await _sut.EnrollStudentAsync(i, student); } var results = (await _sut.GetInstitutionsForStudentAsync(student)).ToList(); Assert.Equal(institutions.Count, results.Count); Assert.All(institutions, i => Assert.Contains(i, results)); foreach (var i in institutions) { await _sut.UnenrollStudentAsync(i, student); } Assert.Empty(await _sut.GetInstitutionsForStudentAsync(student)); } [Theory, AutoData] public async Task Students_ThrowsForDuplicate(Institution institution, Student student) { var studentRepo = new StudentRepository(_db); await studentRepo.AddAsync(student); await _sut.AddAsync(institution); await _sut.EnrollStudentAsync(institution, student); await Assert.ThrowsAsync<DuplicateObjectException>(async () => await _sut.EnrollStudentAsync(institution, student)); } } }
32.583893
109
0.599794
[ "MIT" ]
athena-scheduler/athena
test/Integration/Athena.Data.Tests/Repositories/InstitutionRepositoryTests.cs
4,857
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("TestSetup")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("TestSetup")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("acb1a988-0822-4243-85cf-d30748972801")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
37.594595
84
0.744069
[ "BSD-3-Clause" ]
DynamoDS/RevitTestFramework
src/TestSetup/Properties/AssemblyInfo.cs
1,394
C#
namespace maestropanel.plesklib.Models { using System.Xml.Serialization; [XmlRoot("packet")] public class DatabaseUserGetPacket { public DatabaseUserGetPacket() { this.database = new DatabaseUserGetDatabaseNode(); } [XmlElement("database")] public DatabaseUserGetDatabaseNode database { get; set; } } public class DatabaseUserGetDatabaseNode { public DatabaseUserGetDatabaseNode() { this.users = new DatabaseUserGetDbUsersNode(); } [XmlElement("get-db-users")] public DatabaseUserGetDbUsersNode users { get; set; } } public class DatabaseUserGetDbUsersNode { public DatabaseUserGetDbUsersNode() { this.filter = new DatabaseUserGetFilterNode(); } [XmlElement("filter")] public DatabaseUserGetFilterNode filter { get; set; } } public class DatabaseUserGetFilterNode { [XmlElement("db-id")] public int databaseId { get; set; } } }
23.822222
65
0.610075
[ "Apache-2.0" ]
c1982/plesklib
src/plesklib/Models/DatabaseUserGet.cs
1,074
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class BuildingController : MonoBehaviour { [SerializeField] private GameObject buildingPoint; [SerializeField] private List<GameObject> defenses; public bool BuildingState { get { return buildingPoint.activeSelf; } } private int currentDefense = 0; private GameUiManager uiManager; private Inventory inventory; private void Start() { desactivateAllDefenses(); defenses[currentDefense].SetActive(true); uiManager = FindObjectOfType<GameUiManager>(); inventory = FindObjectOfType<Inventory>(); } void Update() { if (!buildingPoint.activeSelf) return; if (Input.GetButtonUp("Fire2")) { Building build = defenses[currentDefense].GetComponent<Building>(); if (build.stoneCost > inventory.stone) return; if (build.woodCost > inventory.wood) return; if (build.specialCost > inventory.special) return; if (build.Build()) { inventory.removeResource(Resource.ResourceType.stone, build.stoneCost); inventory.removeResource(Resource.ResourceType.wood, build.woodCost); inventory.removeResource(Resource.ResourceType.special, build.specialCost); } } if (Input.GetAxis("Mouse ScrollWheel") == 0f) return; if (Input.GetAxis("Mouse ScrollWheel") > 0f) // forward { currentDefense++; if (currentDefense >= defenses.Count) { currentDefense = 0; } desactivateAllDefenses(); SFXManager.SharedInstance.PlaySFX(SFXType.SoundType.SWITCH_OPTION); } else if (Input.GetAxis("Mouse ScrollWheel") < 0f) // backwards { currentDefense--; if (currentDefense < 0) { currentDefense = defenses.Count - 1; } desactivateAllDefenses(); SFXManager.SharedInstance.PlaySFX(SFXType.SoundType.SWITCH_OPTION); } defenses[currentDefense].SetActive(true); Building buildS = defenses[currentDefense].GetComponent<Building>(); uiManager.updateCost(buildS.woodCost, buildS.stoneCost, buildS.specialCost); //TODO: Hacer dinamico. if (currentDefense == 0) uiManager.setObstacleBuild(); if (currentDefense == 1) uiManager.setCrossbowBuild(); if (currentDefense == 2) uiManager.setTowerBuild(); } public void toggleBuilding() { buildingPoint.SetActive(!buildingPoint.activeSelf); uiManager.setBuildingUiState(buildingPoint.activeSelf); } void desactivateAllDefenses() { foreach (GameObject build in defenses) { build.SetActive(false); } } }
26.780702
91
0.589256
[ "MIT" ]
Cundalf/Stalhvik
Assets/Scripts/Player/BuildingController.cs
3,053
C#
using System; using System.Linq; using System.Threading.Tasks; using OrchardCore.Setup.Events; using OrchardCore.Users.Services; using SeedCore.Data; using SeedModules.Account.Domain; namespace SeedModules.Account.Users { public class SetupEventHandler : ISetupEventHandler { private readonly IUserService _userService; private readonly IDbContext _dbcontext; public SetupEventHandler(IUserService userService, IDbContext dbcontext) { _userService = userService; _dbcontext = dbcontext; } public async Task Setup( string siteName, string userName, string email, string password, string dbProvider, string dbConnectionString, string dbTablePrefix, string siteTimeZone, Action<string, string> reportError ) { var role = _dbcontext.Set<RoleInfo>().FirstOrDefault(e => e.RoleName == "Administrator"); var user = new User { UserName = userName, Email = email, EmailConfirmed = true }; if (role != null) { user.Roles.Add(new UserRole() { RoleId = role.Id }); } await _userService.CreateUserAsync(user, password, reportError); } } }
27.092593
101
0.556391
[ "MIT" ]
fyl080801/SeedCore
SeedCore.Modules/SeedModules.Account/Users/SetupEventHandler.cs
1,463
C#
/* * Honeybee Model Schema * * Documentation for Honeybee model schema * * Contact: info@ladybug.tools * Generated by: https://github.com/openapitools/openapi-generator.git */ using System; using System.Linq; using System.IO; using System.Text; using System.Text.RegularExpressions; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using System.ComponentModel.DataAnnotations; namespace HoneybeeSchema { /// <summary> /// Base class for all objects that are not extensible with additional keys. This effectively includes all objects except for the Properties classes that are assigned to geometry objects. /// </summary> [Serializable] [DataContract(Name = "Autosize")] public partial class Autosize : OpenAPIGenBaseModel, IEquatable<Autosize>, IValidatableObject { /// <summary> /// Initializes a new instance of the <see cref="Autosize" /> class. /// </summary> [JsonConstructorAttribute] public Autosize ( // Required parameters // Optional parameters ) : base()// BaseClass { // Set non-required readonly properties with defaultValue this.Type = "Autosize"; // check if object is valid, only check for inherited class if (this.GetType() == typeof(Autosize)) this.IsValid(throwException: true); } //============================================== is ReadOnly /// <summary> /// Gets or Sets Type /// </summary> [DataMember(Name = "type")] public override string Type { get; protected set; } = "Autosize"; /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { return "Autosize"; } /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString(bool detailed) { if (!detailed) return this.ToString(); var sb = new StringBuilder(); sb.Append("Autosize:\n"); sb.Append(" Type: ").Append(Type).Append("\n"); return sb.ToString(); } /// <summary> /// Returns the object from JSON string /// </summary> /// <returns>Autosize object</returns> public static Autosize FromJson(string json) { var obj = JsonConvert.DeserializeObject<Autosize>(json, JsonSetting.AnyOfConvertSetting); if (obj == null) return null; return obj.Type.ToLower() == obj.GetType().Name.ToLower() && obj.IsValid(throwException: true) ? obj : null; } /// <summary> /// Creates a new instance with the same properties. /// </summary> /// <returns>Autosize object</returns> public virtual Autosize DuplicateAutosize() { return FromJson(this.ToJson()); } /// <summary> /// Creates a new instance with the same properties. /// </summary> /// <returns>OpenAPIGenBaseModel</returns> public override OpenAPIGenBaseModel Duplicate() { return DuplicateAutosize(); } /// <summary> /// Creates a new instance with the same properties. /// </summary> /// <returns>OpenAPIGenBaseModel</returns> public override OpenAPIGenBaseModel DuplicateOpenAPIGenBaseModel() { return DuplicateAutosize(); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="input">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object input) { input = input is AnyOf anyOf ? anyOf.Obj : input; return this.Equals(input as Autosize); } /// <summary> /// Returns true if Autosize instances are equal /// </summary> /// <param name="input">Instance of Autosize to be compared</param> /// <returns>Boolean</returns> public bool Equals(Autosize input) { if (input == null) return false; return base.Equals(input) && ( Extension.Equals(this.Type, input.Type) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { unchecked // Overflow is fine, just wrap { int hashCode = base.GetHashCode(); if (this.Type != null) hashCode = hashCode * 59 + this.Type.GetHashCode(); return hashCode; } } /// <summary> /// To validate all properties of the instance /// </summary> /// <param name="validationContext">Validation context</param> /// <returns>Validation Result</returns> IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> IValidatableObject.Validate(ValidationContext validationContext) { foreach(var x in base.BaseValidate(validationContext)) yield return x; // Type (string) pattern Regex regexType = new Regex(@"^Autosize$", RegexOptions.CultureInvariant); if (this.Type != null && false == regexType.Match(this.Type).Success) { yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Type, must match a pattern of " + regexType, new [] { "Type" }); } yield break; } } }
33.145946
192
0.565884
[ "MIT" ]
MingboPeng/honeybee-schema-dotnet
src/HoneybeeSchema/Model/Autosize.cs
6,132
C#
using DAL; using Entity; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace BLL { public class UnitOfWork { public OgrenciContext db; public EgitimRepository egitimRep; public BaseRepository<Ogrenci> ogrenciRep; public UnitOfWork() { db = new OgrenciContext(); egitimRep = new EgitimRepository(db); ogrenciRep = new BaseRepository<Ogrenci>(db); } } }
21
57
0.64381
[ "MIT" ]
Gestotudor/MVC_Ntier_Arch
BLL/UnitOfWork.cs
527
C#
using Android.App; using Android.Content; namespace App.Platform.Android.Server.Receivers { [BroadcastReceiver] [IntentFilter(new[] {Intent.ActionMyPackageReplaced})] public sealed class MyPackageReplacedReceiver : BroadcastReceiver { public override void OnReceive(Context context, Intent intent) { ServerService.StartService(context); } } }
26.666667
70
0.7025
[ "MIT" ]
mangaloyalty/mangaloyalty-app
app/App.Platform.Android/Server/Receivers/MyPackageReplacedReceiver.cs
402
C#
using System; using System.Xml.Serialization; using SevenDigital.Api.Schema.Artists; using SevenDigital.Api.Schema.Attributes; using SevenDigital.Api.Schema.Packages; using SevenDigital.Api.Schema.ParameterDefinitions.Get; namespace SevenDigital.Api.Schema.Releases { [Serializable] [XmlRoot("release")] [ApiEndpoint("release/details")] public class Release : HasReleaseIdParameter, HasUsageTypesParameter { [XmlAttribute("id")] public int Id { get; set; } [XmlElement("title")] public string Title { get; set; } [XmlElement("version")] public string Version { get; set; } [XmlElement("type")] public ReleaseType Type { get; set; } [XmlElement("barcode")] public string Barcode { get; set; } [XmlElement("year")] public string Year { get; set; } [XmlElement("explicitContent")] public bool ExplicitContent { get; set; } [XmlElement("artist")] public Artist Artist { get; set; } [XmlElement("image")] public string Image { get; set; } [XmlElement("label")] public Label Label { get; set; } [XmlElement("licensor")] public Licensor Licensor { get; set; } [XmlElement("duration")] public int Duration { get; set; } [XmlElement("trackCount")] public int? TrackCount { get; set; } [XmlElement("download")] public Download Download { get; set; } [XmlElement("subscriptionStreaming")] public Streaming SubscriptionStreaming { get; set; } [XmlElement("adSupportedStreaming")] public Streaming AdSupportedStreaming { get; set; } [XmlElement("slug")] public string Slug { get; set; } [XmlElement("cline")] public string Cline { get; set; } [XmlElement("pline")] public string Pline { get; set; } public override string ToString() { return string.Format("{0}: {1} {2} {3}, Barcode {4}", Id, Title, Version, Type, Barcode); } } }
24.448718
93
0.659675
[ "MIT" ]
7digital/SevenDigital.Api.Schema
src/Schema/Releases/Release.cs
1,909
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. // ------------------------------------------------------------------------------ // Changes to this file must follow the http://aka.ms/api-review process. // ------------------------------------------------------------------------------ namespace System.Security.Cryptography { public abstract partial class Aes : System.Security.Cryptography.SymmetricAlgorithm { protected Aes() { } public override System.Security.Cryptography.KeySizes[] LegalBlockSizes { get { return default(System.Security.Cryptography.KeySizes[]); } } public override System.Security.Cryptography.KeySizes[] LegalKeySizes { get { return default(System.Security.Cryptography.KeySizes[]); } } public static System.Security.Cryptography.Aes Create() { return default(System.Security.Cryptography.Aes); } } public abstract partial class DeriveBytes : System.IDisposable { protected DeriveBytes() { } public void Dispose() { } protected virtual void Dispose(bool disposing) { } public abstract byte[] GetBytes(int cb); public abstract void Reset(); } public abstract partial class DSA : System.Security.Cryptography.AsymmetricAlgorithm { protected DSA() { } public static System.Security.Cryptography.DSA Create() { return default(System.Security.Cryptography.DSA); } public abstract byte[] CreateSignature(byte[] hash); public abstract System.Security.Cryptography.DSAParameters ExportParameters(bool includePrivateParameters); protected virtual byte[] HashData(byte[] data, int offset, int count, System.Security.Cryptography.HashAlgorithmName hashAlgorithm) { return default(byte[]); } protected virtual byte[] HashData(System.IO.Stream data, System.Security.Cryptography.HashAlgorithmName hashAlgorithm) { return default(byte[]); } public abstract void ImportParameters(System.Security.Cryptography.DSAParameters parameters); public virtual byte[] SignData(byte[] data, int offset, int count, System.Security.Cryptography.HashAlgorithmName hashAlgorithm) { return default(byte[]); } public byte[] SignData(byte[] data, System.Security.Cryptography.HashAlgorithmName hashAlgorithm) { return default(byte[]); } public virtual byte[] SignData(System.IO.Stream data, System.Security.Cryptography.HashAlgorithmName hashAlgorithm) { return default(byte[]); } public bool VerifyData(byte[] data, byte[] signature, System.Security.Cryptography.HashAlgorithmName hashAlgorithm) { return default(bool); } public virtual bool VerifyData(byte[] data, int offset, int count, byte[] signature, System.Security.Cryptography.HashAlgorithmName hashAlgorithm) { return default(bool); } public virtual bool VerifyData(System.IO.Stream data, byte[] signature, System.Security.Cryptography.HashAlgorithmName hashAlgorithm) { return default(bool); } public abstract bool VerifySignature(byte[] hash, byte[] signature); } [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct DSAParameters { public int Counter; public byte[] G; public byte[] J; public byte[] P; public byte[] Q; public byte[] Seed; public byte[] X; public byte[] Y; } [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct ECCurve { public byte[] A; public byte[] B; public byte[] Cofactor; public System.Security.Cryptography.ECCurve.ECCurveType CurveType; public System.Security.Cryptography.ECPoint G; public System.Nullable<System.Security.Cryptography.HashAlgorithmName> Hash; public byte[] Order; public byte[] Polynomial; public byte[] Prime; public byte[] Seed; public bool IsCharacteristic2 { get { return default(bool); } } public bool IsExplicit { get { return default(bool); } } public bool IsNamed { get { return default(bool); } } public bool IsPrime { get { return default(bool); } } public System.Security.Cryptography.Oid Oid { get { return default(System.Security.Cryptography.Oid); } } public static System.Security.Cryptography.ECCurve CreateFromFriendlyName(string oidFriendlyName) { return default(System.Security.Cryptography.ECCurve); } public static System.Security.Cryptography.ECCurve CreateFromOid(System.Security.Cryptography.Oid curveOid) { return default(System.Security.Cryptography.ECCurve); } public static System.Security.Cryptography.ECCurve CreateFromValue(string oidValue) { return default(System.Security.Cryptography.ECCurve); } public void Validate() { } public enum ECCurveType { Characteristic2 = 4, Implicit = 0, Named = 5, PrimeMontgomery = 3, PrimeShortWeierstrass = 1, PrimeTwistedEdwards = 2, } public static partial class NamedCurves { public static System.Security.Cryptography.ECCurve brainpoolP160r1 { get { return default(System.Security.Cryptography.ECCurve); } } public static System.Security.Cryptography.ECCurve brainpoolP160t1 { get { return default(System.Security.Cryptography.ECCurve); } } public static System.Security.Cryptography.ECCurve brainpoolP192r1 { get { return default(System.Security.Cryptography.ECCurve); } } public static System.Security.Cryptography.ECCurve brainpoolP192t1 { get { return default(System.Security.Cryptography.ECCurve); } } public static System.Security.Cryptography.ECCurve brainpoolP224r1 { get { return default(System.Security.Cryptography.ECCurve); } } public static System.Security.Cryptography.ECCurve brainpoolP224t1 { get { return default(System.Security.Cryptography.ECCurve); } } public static System.Security.Cryptography.ECCurve brainpoolP256r1 { get { return default(System.Security.Cryptography.ECCurve); } } public static System.Security.Cryptography.ECCurve brainpoolP256t1 { get { return default(System.Security.Cryptography.ECCurve); } } public static System.Security.Cryptography.ECCurve brainpoolP320r1 { get { return default(System.Security.Cryptography.ECCurve); } } public static System.Security.Cryptography.ECCurve brainpoolP320t1 { get { return default(System.Security.Cryptography.ECCurve); } } public static System.Security.Cryptography.ECCurve brainpoolP384r1 { get { return default(System.Security.Cryptography.ECCurve); } } public static System.Security.Cryptography.ECCurve brainpoolP384t1 { get { return default(System.Security.Cryptography.ECCurve); } } public static System.Security.Cryptography.ECCurve brainpoolP512r1 { get { return default(System.Security.Cryptography.ECCurve); } } public static System.Security.Cryptography.ECCurve brainpoolP512t1 { get { return default(System.Security.Cryptography.ECCurve); } } public static System.Security.Cryptography.ECCurve nistP256 { get { return default(System.Security.Cryptography.ECCurve); } } public static System.Security.Cryptography.ECCurve nistP384 { get { return default(System.Security.Cryptography.ECCurve); } } public static System.Security.Cryptography.ECCurve nistP521 { get { return default(System.Security.Cryptography.ECCurve); } } } } public abstract partial class ECDsa : System.Security.Cryptography.AsymmetricAlgorithm { protected ECDsa() { } public static System.Security.Cryptography.ECDsa Create() { return default(System.Security.Cryptography.ECDsa); } public static System.Security.Cryptography.ECDsa Create(System.Security.Cryptography.ECCurve curve) { return default(System.Security.Cryptography.ECDsa); } public static System.Security.Cryptography.ECDsa Create(System.Security.Cryptography.ECParameters parameters) { return default(System.Security.Cryptography.ECDsa); } public virtual System.Security.Cryptography.ECParameters ExportExplicitParameters(bool includePrivateParameters) { return default(System.Security.Cryptography.ECParameters); } public virtual System.Security.Cryptography.ECParameters ExportParameters(bool includePrivateParameters) { return default(System.Security.Cryptography.ECParameters); } public virtual void GenerateKey(System.Security.Cryptography.ECCurve curve) { } protected abstract byte[] HashData(byte[] data, int offset, int count, System.Security.Cryptography.HashAlgorithmName hashAlgorithm); protected abstract byte[] HashData(System.IO.Stream data, System.Security.Cryptography.HashAlgorithmName hashAlgorithm); public virtual void ImportParameters(System.Security.Cryptography.ECParameters parameters) { } public virtual byte[] SignData(byte[] data, int offset, int count, System.Security.Cryptography.HashAlgorithmName hashAlgorithm) { return default(byte[]); } public virtual byte[] SignData(byte[] data, System.Security.Cryptography.HashAlgorithmName hashAlgorithm) { return default(byte[]); } public virtual byte[] SignData(System.IO.Stream data, System.Security.Cryptography.HashAlgorithmName hashAlgorithm) { return default(byte[]); } public abstract byte[] SignHash(byte[] hash); public bool VerifyData(byte[] data, byte[] signature, System.Security.Cryptography.HashAlgorithmName hashAlgorithm) { return default(bool); } public virtual bool VerifyData(byte[] data, int offset, int count, byte[] signature, System.Security.Cryptography.HashAlgorithmName hashAlgorithm) { return default(bool); } public bool VerifyData(System.IO.Stream data, byte[] signature, System.Security.Cryptography.HashAlgorithmName hashAlgorithm) { return default(bool); } public abstract bool VerifyHash(byte[] hash, byte[] signature); } [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct ECParameters { public System.Security.Cryptography.ECCurve Curve; public byte[] D; public System.Security.Cryptography.ECPoint Q; public void Validate() { } } [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct ECPoint { public byte[] X; public byte[] Y; } public partial class HMACMD5 : System.Security.Cryptography.HMAC { public HMACMD5() { } public HMACMD5(byte[] key) { } public override int HashSize { get { return default(int); } } public override byte[] Key { get { return default(byte[]); } set { } } protected override void Dispose(bool disposing) { } protected override void HashCore(byte[] rgb, int ib, int cb) { } protected override byte[] HashFinal() { return default(byte[]); } public override void Initialize() { } } public partial class HMACSHA1 : System.Security.Cryptography.HMAC { public HMACSHA1() { } public HMACSHA1(byte[] key) { } public override int HashSize { get { return default(int); } } public override byte[] Key { get { return default(byte[]); } set { } } protected override void Dispose(bool disposing) { } protected override void HashCore(byte[] rgb, int ib, int cb) { } protected override byte[] HashFinal() { return default(byte[]); } public override void Initialize() { } } public partial class HMACSHA256 : System.Security.Cryptography.HMAC { public HMACSHA256() { } public HMACSHA256(byte[] key) { } public override int HashSize { get { return default(int); } } public override byte[] Key { get { return default(byte[]); } set { } } protected override void Dispose(bool disposing) { } protected override void HashCore(byte[] rgb, int ib, int cb) { } protected override byte[] HashFinal() { return default(byte[]); } public override void Initialize() { } } public partial class HMACSHA384 : System.Security.Cryptography.HMAC { public HMACSHA384() { } public HMACSHA384(byte[] key) { } public override int HashSize { get { return default(int); } } public override byte[] Key { get { return default(byte[]); } set { } } protected override void Dispose(bool disposing) { } protected override void HashCore(byte[] rgb, int ib, int cb) { } protected override byte[] HashFinal() { return default(byte[]); } public override void Initialize() { } } public partial class HMACSHA512 : System.Security.Cryptography.HMAC { public HMACSHA512() { } public HMACSHA512(byte[] key) { } public override int HashSize { get { return default(int); } } public override byte[] Key { get { return default(byte[]); } set { } } protected override void Dispose(bool disposing) { } protected override void HashCore(byte[] rgb, int ib, int cb) { } protected override byte[] HashFinal() { return default(byte[]); } public override void Initialize() { } } public sealed partial class IncrementalHash : System.IDisposable { internal IncrementalHash() { } public System.Security.Cryptography.HashAlgorithmName AlgorithmName { get { return default(System.Security.Cryptography.HashAlgorithmName); } } public void AppendData(byte[] data) { } public void AppendData(byte[] data, int offset, int count) { } public static System.Security.Cryptography.IncrementalHash CreateHash(System.Security.Cryptography.HashAlgorithmName hashAlgorithm) { return default(System.Security.Cryptography.IncrementalHash); } public static System.Security.Cryptography.IncrementalHash CreateHMAC(System.Security.Cryptography.HashAlgorithmName hashAlgorithm, byte[] key) { return default(System.Security.Cryptography.IncrementalHash); } public void Dispose() { } public byte[] GetHashAndReset() { return default(byte[]); } } public abstract partial class MD5 : System.Security.Cryptography.HashAlgorithm { protected MD5() { } public static System.Security.Cryptography.MD5 Create() { return default(System.Security.Cryptography.MD5); } } public abstract partial class RandomNumberGenerator : System.IDisposable { protected RandomNumberGenerator() { } public static System.Security.Cryptography.RandomNumberGenerator Create() { return default(System.Security.Cryptography.RandomNumberGenerator); } public void Dispose() { } protected virtual void Dispose(bool disposing) { } public abstract void GetBytes(byte[] data); } public partial class Rfc2898DeriveBytes : System.Security.Cryptography.DeriveBytes { public Rfc2898DeriveBytes(byte[] password, byte[] salt, int iterations) { } public Rfc2898DeriveBytes(string password, byte[] salt) { } public Rfc2898DeriveBytes(string password, byte[] salt, int iterations) { } public Rfc2898DeriveBytes(string password, int saltSize) { } public Rfc2898DeriveBytes(string password, int saltSize, int iterations) { } public int IterationCount { get { return default(int); } set { } } public byte[] Salt { get { return default(byte[]); } set { } } protected override void Dispose(bool disposing) { } public override byte[] GetBytes(int cb) { return default(byte[]); } public override void Reset() { } } public abstract partial class RSA : System.Security.Cryptography.AsymmetricAlgorithm { protected RSA() { } public static System.Security.Cryptography.RSA Create() { return default(System.Security.Cryptography.RSA); } public abstract byte[] Decrypt(byte[] data, System.Security.Cryptography.RSAEncryptionPadding padding); public abstract byte[] Encrypt(byte[] data, System.Security.Cryptography.RSAEncryptionPadding padding); public abstract System.Security.Cryptography.RSAParameters ExportParameters(bool includePrivateParameters); protected abstract byte[] HashData(byte[] data, int offset, int count, System.Security.Cryptography.HashAlgorithmName hashAlgorithm); protected abstract byte[] HashData(System.IO.Stream data, System.Security.Cryptography.HashAlgorithmName hashAlgorithm); public abstract void ImportParameters(System.Security.Cryptography.RSAParameters parameters); public virtual byte[] SignData(byte[] data, int offset, int count, System.Security.Cryptography.HashAlgorithmName hashAlgorithm, System.Security.Cryptography.RSASignaturePadding padding) { return default(byte[]); } public byte[] SignData(byte[] data, System.Security.Cryptography.HashAlgorithmName hashAlgorithm, System.Security.Cryptography.RSASignaturePadding padding) { return default(byte[]); } public virtual byte[] SignData(System.IO.Stream data, System.Security.Cryptography.HashAlgorithmName hashAlgorithm, System.Security.Cryptography.RSASignaturePadding padding) { return default(byte[]); } public abstract byte[] SignHash(byte[] hash, System.Security.Cryptography.HashAlgorithmName hashAlgorithm, System.Security.Cryptography.RSASignaturePadding padding); public bool VerifyData(byte[] data, byte[] signature, System.Security.Cryptography.HashAlgorithmName hashAlgorithm, System.Security.Cryptography.RSASignaturePadding padding) { return default(bool); } public virtual bool VerifyData(byte[] data, int offset, int count, byte[] signature, System.Security.Cryptography.HashAlgorithmName hashAlgorithm, System.Security.Cryptography.RSASignaturePadding padding) { return default(bool); } public bool VerifyData(System.IO.Stream data, byte[] signature, System.Security.Cryptography.HashAlgorithmName hashAlgorithm, System.Security.Cryptography.RSASignaturePadding padding) { return default(bool); } public abstract bool VerifyHash(byte[] hash, byte[] signature, System.Security.Cryptography.HashAlgorithmName hashAlgorithm, System.Security.Cryptography.RSASignaturePadding padding); } public sealed partial class RSAEncryptionPadding : System.IEquatable<System.Security.Cryptography.RSAEncryptionPadding> { internal RSAEncryptionPadding() { } public System.Security.Cryptography.RSAEncryptionPaddingMode Mode { get { return default(System.Security.Cryptography.RSAEncryptionPaddingMode); } } public System.Security.Cryptography.HashAlgorithmName OaepHashAlgorithm { get { return default(System.Security.Cryptography.HashAlgorithmName); } } public static System.Security.Cryptography.RSAEncryptionPadding OaepSHA1 { get { return default(System.Security.Cryptography.RSAEncryptionPadding); } } public static System.Security.Cryptography.RSAEncryptionPadding OaepSHA256 { get { return default(System.Security.Cryptography.RSAEncryptionPadding); } } public static System.Security.Cryptography.RSAEncryptionPadding OaepSHA384 { get { return default(System.Security.Cryptography.RSAEncryptionPadding); } } public static System.Security.Cryptography.RSAEncryptionPadding OaepSHA512 { get { return default(System.Security.Cryptography.RSAEncryptionPadding); } } public static System.Security.Cryptography.RSAEncryptionPadding Pkcs1 { get { return default(System.Security.Cryptography.RSAEncryptionPadding); } } public static System.Security.Cryptography.RSAEncryptionPadding CreateOaep(System.Security.Cryptography.HashAlgorithmName hashAlgorithm) { return default(System.Security.Cryptography.RSAEncryptionPadding); } public override bool Equals(object obj) { return default(bool); } public bool Equals(System.Security.Cryptography.RSAEncryptionPadding other) { return default(bool); } public override int GetHashCode() { return default(int); } public static bool operator ==(System.Security.Cryptography.RSAEncryptionPadding left, System.Security.Cryptography.RSAEncryptionPadding right) { return default(bool); } public static bool operator !=(System.Security.Cryptography.RSAEncryptionPadding left, System.Security.Cryptography.RSAEncryptionPadding right) { return default(bool); } public override string ToString() { return default(string); } } public enum RSAEncryptionPaddingMode { Oaep = 1, Pkcs1 = 0, } [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct RSAParameters { public byte[] D; public byte[] DP; public byte[] DQ; public byte[] Exponent; public byte[] InverseQ; public byte[] Modulus; public byte[] P; public byte[] Q; } public sealed partial class RSASignaturePadding : System.IEquatable<System.Security.Cryptography.RSASignaturePadding> { internal RSASignaturePadding() { } public System.Security.Cryptography.RSASignaturePaddingMode Mode { get { return default(System.Security.Cryptography.RSASignaturePaddingMode); } } public static System.Security.Cryptography.RSASignaturePadding Pkcs1 { get { return default(System.Security.Cryptography.RSASignaturePadding); } } public static System.Security.Cryptography.RSASignaturePadding Pss { get { return default(System.Security.Cryptography.RSASignaturePadding); } } public override bool Equals(object obj) { return default(bool); } public bool Equals(System.Security.Cryptography.RSASignaturePadding other) { return default(bool); } public override int GetHashCode() { return default(int); } public static bool operator ==(System.Security.Cryptography.RSASignaturePadding left, System.Security.Cryptography.RSASignaturePadding right) { return default(bool); } public static bool operator !=(System.Security.Cryptography.RSASignaturePadding left, System.Security.Cryptography.RSASignaturePadding right) { return default(bool); } public override string ToString() { return default(string); } } public enum RSASignaturePaddingMode { Pkcs1 = 0, Pss = 1, } public abstract partial class SHA1 : System.Security.Cryptography.HashAlgorithm { protected SHA1() { } public static System.Security.Cryptography.SHA1 Create() { return default(System.Security.Cryptography.SHA1); } } public abstract partial class SHA256 : System.Security.Cryptography.HashAlgorithm { protected SHA256() { } public static System.Security.Cryptography.SHA256 Create() { return default(System.Security.Cryptography.SHA256); } } public abstract partial class SHA384 : System.Security.Cryptography.HashAlgorithm { protected SHA384() { } public static System.Security.Cryptography.SHA384 Create() { return default(System.Security.Cryptography.SHA384); } } public abstract partial class SHA512 : System.Security.Cryptography.HashAlgorithm { protected SHA512() { } public static System.Security.Cryptography.SHA512 Create() { return default(System.Security.Cryptography.SHA512); } } public abstract partial class TripleDES : System.Security.Cryptography.SymmetricAlgorithm { protected TripleDES() { } public override byte[] Key { get { return default(byte[]); } set { } } public override System.Security.Cryptography.KeySizes[] LegalBlockSizes { get { return default(System.Security.Cryptography.KeySizes[]); } } public override System.Security.Cryptography.KeySizes[] LegalKeySizes { get { return default(System.Security.Cryptography.KeySizes[]); } } public static System.Security.Cryptography.TripleDES Create() { return default(System.Security.Cryptography.TripleDES); } public static bool IsWeakKey(byte[] rgbKey) { return default(bool); } } }
72.723214
238
0.719255
[ "MIT" ]
robertmclaws/corefx
src/System.Security.Cryptography.Algorithms/ref/System.Security.Cryptography.Algorithms.cs
24,435
C#
/* * Camunda BPM REST API * * OpenApi Spec for Camunda BPM REST API. * * The version of the OpenAPI document: 7.13.0 * * Generated by: https://github.com/openapitools/openapi-generator.git */ using System; using System.Linq; using System.IO; using System.Text; using System.Text.RegularExpressions; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using System.ComponentModel.DataAnnotations; using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; namespace Org.OpenAPITools.Model { /// <summary> /// ParseExceptionDtoAllOf /// </summary> [DataContract] public partial class ParseExceptionDtoAllOf : IEquatable<ParseExceptionDtoAllOf>, IValidatableObject { /// <summary> /// Initializes a new instance of the <see cref="ParseExceptionDtoAllOf" /> class. /// </summary> /// <param name="details">A JSON Object containing list of errors and warnings occurred during deployment..</param> public ParseExceptionDtoAllOf(Dictionary<string, ResourceReportDto> details = default(Dictionary<string, ResourceReportDto>)) { this.Details = details; } /// <summary> /// A JSON Object containing list of errors and warnings occurred during deployment. /// </summary> /// <value>A JSON Object containing list of errors and warnings occurred during deployment.</value> [DataMember(Name="details", EmitDefaultValue=false)] public Dictionary<string, ResourceReportDto> Details { get; set; } /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { var sb = new StringBuilder(); sb.Append("class ParseExceptionDtoAllOf {\n"); sb.Append(" Details: ").Append(Details).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public virtual string ToJson() { return JsonConvert.SerializeObject(this, Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="input">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object input) { return this.Equals(input as ParseExceptionDtoAllOf); } /// <summary> /// Returns true if ParseExceptionDtoAllOf instances are equal /// </summary> /// <param name="input">Instance of ParseExceptionDtoAllOf to be compared</param> /// <returns>Boolean</returns> public bool Equals(ParseExceptionDtoAllOf input) { if (input == null) return false; return ( this.Details == input.Details || this.Details != null && input.Details != null && this.Details.SequenceEqual(input.Details) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { unchecked // Overflow is fine, just wrap { int hashCode = 41; if (this.Details != null) hashCode = hashCode * 59 + this.Details.GetHashCode(); return hashCode; } } /// <summary> /// To validate all properties of the instance /// </summary> /// <param name="validationContext">Validation context</param> /// <returns>Validation Result</returns> IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> IValidatableObject.Validate(ValidationContext validationContext) { yield break; } } }
33.944882
140
0.597309
[ "Apache-2.0" ]
yanavasileva/camunda-bpm-examples
openapi-python-client/src/Org.OpenAPITools/Model/ParseExceptionDtoAllOf.cs
4,311
C#
using Avalonia.Controls; using Tauron.Application.CommonUI; using Tauron.Application.CommonUI.UI; namespace Tauron.Application.Avalonia.UI { public sealed class WindowControlLogic : ControlLogicBase<Window> { public WindowControlLogic(Window userControl, IViewModel model) : base(userControl, model) { userControl.SizeToContent = SizeToContent.Manual; userControl.ShowInTaskbar = true; userControl.WindowStartupLocation = WindowStartupLocation.CenterScreen; } protected override void WireUpUnloaded() { UserControl.Closed += (_, _) => UserControlOnUnloaded(); } } }
32.190476
98
0.684911
[ "MIT" ]
Tauron1990/Project-Manager-Akka
Src/Shared/Tauron.Application.Avalonia/UI/WindowControlLogic.cs
678
C#
using Apim.DevOps.Toolkit.ApimEntities.Product; using Apim.DevOps.Toolkit.Core.DeploymentDefinitions.Entities; using AutoMapper; namespace Apim.DevOps.Toolkit.Core.Mapping { public static class ProductMapper { internal static void Map(IMapperConfigurationExpression cfg) { cfg.CreateMap<ProductDeploymentDefinition, ProductsProperties>() .ForMember(dst => dst.ApprovalRequired, opt => opt.MapFrom(src => src.SubscriptionRequired ? src.ApprovalRequired : null)) .ForMember(dst => dst.SubscriptionsLimit, opt => opt.MapFrom(src => src.SubscriptionRequired ? src.SubscriptionsLimit : null)); } } }
36.294118
131
0.776337
[ "MIT" ]
andrewdmoreno/dotnet-apim
src/apimtemplate/Core/Mapping/ProductMapper.cs
619
C#
using Rtmp.Net; using System; using System.Drawing; using System.Threading.Tasks; namespace GeForce { public static partial class Program { static RtmpClient botClient; static IntPtr botHandle; static async Task<RtmpClient> BotClientAsync() { try { Console.WriteLine("Client connecting..."); var options = new RtmpClient.Options { Url = "rtmp://localhost:4000", AppName = "bot", }; var client = await RtmpClient.ConnectAsync(options); Console.WriteLine("Client connected."); //client.Disconnected += (o, s) => { ((RtmpClient)o).InvokeAsync<object>("FCUnpublish").Wait(); }; client.DispatchInvoke = s => { switch (s.MethodName) { case "a": var windowName = (string)s.Arguments[0]; botHandle = Interop.GetHandleByWindow(windowName ?? "Star Citizen"); break; case "k": var key = (char)s.Arguments[0]; Interop.PressKey((byte)key); break; case "c": Interop.ClickMouseButton(botHandle, InteropMouseButton.Left, new Point(545, 300)); break; case "bf": Interop.BringToFront(botHandle); break; default: Console.WriteLine(s.MethodName); break; } }; return client; } catch (Exception e) { Console.WriteLine(e.Message); return null; } } } }
35.775862
115
0.400964
[ "MIT" ]
libcs/geforce.bot.net
geforcebot/BotClient.cs
2,075
C#
using System.IO; namespace Abp.IO { /// <summary> /// A helper class for File operations. /// </summary> public static class FileHelper { /// <summary> /// Checks and deletes given file if it does exists. /// </summary> /// <param name="filePath">Path of the file</param> public static void DeleteIfExists(string filePath) { if (File.Exists(filePath)) { File.Delete(filePath); } } } }
22.565217
60
0.514451
[ "MIT" ]
12321/aspnetboilerplate
src/Abp/IO/FileHelper.cs
521
C#
/* * The official C# API client for alpaca brokerage * Sourced from: https://github.com/alpacahq/alpaca-trade-api-csharp/commit/161b114b4b40d852a14a903bd6e69d26fe637922 */ using System; using System.Runtime.Serialization; using Newtonsoft.Json; namespace QuantConnect.Brokerages.Alpaca.Markets { internal sealed class JsonAccount : IAccount { [JsonProperty(PropertyName = "id", Required = Required.Always)] public Guid AccountId { get; set; } [JsonProperty(PropertyName = "status", Required = Required.Always)] public AccountStatus Status { get; set; } [JsonProperty(PropertyName = "currency", Required = Required.Default)] public String Currency { get; set; } [JsonProperty(PropertyName = "cash", Required = Required.Always)] public Decimal TradableCash { get; set; } [JsonProperty(PropertyName = "cash_withdrawable", Required = Required.Always)] public Decimal WithdrawableCash { get; set; } [JsonProperty(PropertyName = "portfolio_value", Required = Required.Always)] public Decimal PortfolioValue { get; set; } [JsonProperty(PropertyName = "pattern_day_trader", Required = Required.Always)] public Boolean IsDayPatternTrader { get; set; } [JsonProperty(PropertyName = "trading_blocked", Required = Required.Always)] public Boolean IsTradingBlocked { get; set; } [JsonProperty(PropertyName = "transfers_blocked", Required = Required.Always)] public Boolean IsTransfersBlocked { get; set; } [JsonProperty(PropertyName = "account_blocked", Required = Required.Always)] public Boolean IsAccountBlocked { get; set; } [JsonProperty(PropertyName = "created_at", Required = Required.Always)] public DateTime CreatedAt { get; set; } [OnDeserialized] internal void OnDeserializedMethod( StreamingContext context) { if (String.IsNullOrEmpty(Currency)) { Currency = "USD"; } } } }
36.350877
116
0.665058
[ "Apache-2.0" ]
Johannesduvenage/Lean
Brokerages/Alpaca/Markets/Messages/JsonAccount.cs
2,074
C#
using System.Web; using System.Web.Mvc; namespace Vidly.Web { public class FilterConfig { public static void RegisterGlobalFilters(GlobalFilterCollection filters) { filters.Add(new HandleErrorAttribute()); } } }
18.714286
80
0.648855
[ "MIT" ]
s-janjic/Vidly
Vidly.Web/App_Start/FilterConfig.cs
264
C#
using log4net; using System; using System.Net; using System.Net.Http; using System.Reflection; using System.Web.Http.Filters; namespace VehicleManagementSystemApi.Infrastructure { public class GenericExceptionFilterAttribute : ExceptionFilterAttribute, IExceptionFilter { private static readonly ILog logger = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); public override void OnException(HttpActionExecutedContext actionExecutedContext) { if (actionExecutedContext.Exception == null) return; try { logger.Error(actionExecutedContext.Exception); actionExecutedContext.Response = actionExecutedContext.Request.CreateErrorResponse(HttpStatusCode.BadRequest, actionExecutedContext.Exception); } catch (Exception ex) { logger.Error(ex); actionExecutedContext.Response = actionExecutedContext.Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex); } } } }
35.733333
159
0.693097
[ "MIT" ]
iAvinashVarma/VehicleManagementService
Service/VehicleManagementSystemApi/Infrastructure/GenericExceptionFilterAttribute.cs
1,074
C#
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; namespace ClosedXML.Excel { public partial class XLWorkbook { #region Nested type: SaveContext internal sealed class SaveContext { #region Private fields [DebuggerBrowsable(DebuggerBrowsableState.Never)] private readonly RelIdGenerator _relIdGenerator; [DebuggerBrowsable(DebuggerBrowsableState.Never)] private readonly Dictionary<Int32, StyleInfo> _sharedStyles; [DebuggerBrowsable(DebuggerBrowsableState.Never)] private readonly Dictionary<Int32, NumberFormatInfo> _sharedNumberFormats; [DebuggerBrowsable(DebuggerBrowsableState.Never)] private readonly Dictionary<IXLFont, FontInfo> _sharedFonts; [DebuggerBrowsable(DebuggerBrowsableState.Never)] private readonly HashSet<string> _tableNames; [DebuggerBrowsable(DebuggerBrowsableState.Never)] private uint _tableId; #endregion #region Constructor public SaveContext() { _relIdGenerator = new RelIdGenerator(); _sharedStyles = new Dictionary<Int32, StyleInfo>(); _sharedNumberFormats = new Dictionary<int, NumberFormatInfo>(); _sharedFonts = new Dictionary<IXLFont, FontInfo>(); _tableNames = new HashSet<String>(); _tableId = 0; } #endregion #region Public properties public RelIdGenerator RelIdGenerator { [DebuggerStepThrough] get { return _relIdGenerator; } } public Dictionary<Int32, StyleInfo> SharedStyles { [DebuggerStepThrough] get { return _sharedStyles; } } public Dictionary<Int32, NumberFormatInfo> SharedNumberFormats { [DebuggerStepThrough] get { return _sharedNumberFormats; } } public Dictionary<IXLFont, FontInfo> SharedFonts { [DebuggerStepThrough] get { return _sharedFonts; } } public HashSet<string> TableNames { [DebuggerStepThrough] get { return _tableNames; } } public uint TableId { [DebuggerStepThrough] get { return _tableId; } [DebuggerStepThrough] set { _tableId = value; } } public Dictionary<IXLStyle, Int32> DifferentialFormats = new Dictionary<IXLStyle, int>(); #endregion } #endregion #region Nested type: RelType internal enum RelType { Workbook//, Worksheet } #endregion #region Nested type: RelIdGenerator internal sealed class RelIdGenerator { private readonly Dictionary<RelType, List<String>> _relIds = new Dictionary<RelType, List<String>>(); public String GetNext() { return GetNext(RelType.Workbook); } public String GetNext(RelType relType) { if (!_relIds.ContainsKey(relType)) { _relIds.Add(relType, new List<String>()); } Int32 id = _relIds[relType].Count + 1; while (true) { String relId = String.Format("rId{0}", id); if (!_relIds[relType].Contains(relId)) { _relIds[relType].Add(relId); return relId; } id++; } } public void AddValues(IEnumerable<String> values, RelType relType) { if (!_relIds.ContainsKey(relType)) { _relIds.Add(relType, new List<String>()); } _relIds[relType].AddRange(values.Where(v => !_relIds[relType].Contains(v))); } public void Reset(RelType relType) { if (_relIds.ContainsKey(relType)) _relIds.Remove(relType); } } #endregion #region Nested type: FontInfo internal struct FontInfo { public UInt32 FontId; public XLFont Font; }; #endregion #region Nested type: FillInfo internal struct FillInfo { public UInt32 FillId; public XLFill Fill; } #endregion #region Nested type: BorderInfo internal struct BorderInfo { public UInt32 BorderId; public XLBorder Border; } #endregion #region Nested type: NumberFormatInfo internal struct NumberFormatInfo { public Int32 NumberFormatId; public IXLNumberFormatBase NumberFormat; } #endregion #region Nested type: StyleInfo internal struct StyleInfo { public UInt32 StyleId; public UInt32 FontId; public UInt32 FillId; public UInt32 BorderId; public Int32 NumberFormatId; public IXLStyle Style; } #endregion } }
34.475904
114
0.510746
[ "MIT" ]
monoblaine/ClosedXML
ClosedXML/Excel/XLWorkbook_Save.NestedTypes.cs
5,558
C#
using System; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; public class KeyboardEventSystem : MonoBehaviour { Array allKeyCodes; private static List<Transform> allTransforms = new List<Transform>(); private static List<GameObject> rootGameObjects = new List<GameObject>(); void Awake() { allKeyCodes = System.Enum.GetValues(typeof(KeyCode)); } void Update() { //Loop over all the keycodes foreach (KeyCode tempKey in allKeyCodes) { //Send event to key down if (Input.GetKeyDown(tempKey)) senEvent(tempKey, KeybrdEventType.keyDown); //Send event to key up if (Input.GetKeyUp(tempKey)) senEvent(tempKey, KeybrdEventType.KeyUp); //Send event to while key is held down if (Input.GetKey(tempKey)) senEvent(tempKey, KeybrdEventType.down); } } void senEvent(KeyCode keycode, KeybrdEventType evType) { GetAllRootObject(); GetAllComponents(); //Loop over all the interfaces and callthe appropriate function for (int i = 0; i < allTransforms.Count; i++) { GameObject obj = allTransforms[i].gameObject; //Invoke the appropriate interface function if not null IKeyboardEvent itfc = obj.GetComponent<IKeyboardEvent>(); if (itfc != null) { if (evType == KeybrdEventType.keyDown) itfc.OnKeyDown(keycode); if (evType == KeybrdEventType.KeyUp) itfc.OnKeyUP(keycode); if (evType == KeybrdEventType.down) itfc.OnKey(keycode); } } } private static void GetAllRootObject() { rootGameObjects.Clear(); Scene activeScene = SceneManager.GetActiveScene(); activeScene.GetRootGameObjects(rootGameObjects); } private static void GetAllComponents() { allTransforms.Clear(); for (int i = 0; i < rootGameObjects.Count; ++i) { GameObject obj = rootGameObjects[i]; //Get all child Transforms attached to this GameObject obj.GetComponentsInChildren<Transform>(true, allTransforms); } } } public enum KeybrdEventType { keyDown, KeyUp, down } public interface IKeyboardEvent { void OnKeyDown(KeyCode keycode); void OnKeyUP(KeyCode keycode); void OnKey(KeyCode keycode); }
26.010101
77
0.599223
[ "MIT" ]
salem-harvard/Musical-Learning
Assets/Scripts/Saving/KeyboardEventSystem.cs
2,577
C#
using Microsoft.AspNetCore.Authorization; using Microsoft.OpenApi.Models; using Swashbuckle.AspNetCore.Filters.Extensions; using Swashbuckle.AspNetCore.SwaggerGen; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Swashbuckle.AspNetCore.Filters { public class AppendAuthorizeToSummaryOperationFilter<T> : IOperationFilter where T : Attribute { private readonly IEnumerable<PolicySelectorWithLabel<T>> policySelectors; /// <summary> /// Constructor for AppendAuthorizeToSummaryOperationFilter /// </summary> /// <param name="policySelectionCondition">Selects which attributes have policies. e.g. (a => !string.IsNullOrEmpty(a.Policy))</param> /// <param name="policySelector">Used to select the authorization policy from the attribute e.g. (a => a.Policy)</param> public AppendAuthorizeToSummaryOperationFilter(IEnumerable<PolicySelectorWithLabel<T>> policySelectors) { this.policySelectors = policySelectors; } public void Apply(OpenApiOperation operation, OperationFilterContext context) { if (context.GetControllerAndActionAttributes<AllowAnonymousAttribute>().Any()) { return; } var authorizeAttributes = context.GetControllerAndActionAttributes<T>(); if (authorizeAttributes.Any()) { var authorizationDescription = new StringBuilder(" (Auth"); foreach (var policySelector in policySelectors) { AppendPolicies(authorizeAttributes, authorizationDescription, policySelector); } operation.Summary += authorizationDescription.ToString().TrimEnd(';') + ")"; } } private void AppendPolicies(IEnumerable<T> authorizeAttributes, StringBuilder authorizationDescription, PolicySelectorWithLabel<T> policySelector) { var policies = policySelector.Selector(authorizeAttributes) .OrderBy(policy => policy); if (policies.Any()) { authorizationDescription.Append($" {policySelector.Label}: {string.Join(", ", policies)};"); } } } }
38.316667
154
0.655067
[ "MIT" ]
BigYellowHammer/Swashbuckle.AspNetCore.Filters
src/Swashbuckle.AspNetCore.Filters/AppendAuthorizeToSummary/AppendAuthorizeToSummaryOperationFilterT.cs
2,299
C#
// <copyright file="CreateSellerRequest.cs" company="APIMatic"> // Copyright (c) APIMatic. All rights reserved. // </copyright> namespace PagarmeApiSDK.Standard.Models { using System; using System.Collections.Generic; using System.ComponentModel; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using JsonSubTypes; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using PagarmeApiSDK.Standard; using PagarmeApiSDK.Standard.Utilities; /// <summary> /// CreateSellerRequest. /// </summary> public class CreateSellerRequest { /// <summary> /// Initializes a new instance of the <see cref="CreateSellerRequest"/> class. /// </summary> public CreateSellerRequest() { } /// <summary> /// Initializes a new instance of the <see cref="CreateSellerRequest"/> class. /// </summary> /// <param name="name">name.</param> /// <param name="metadata">metadata.</param> /// <param name="code">code.</param> /// <param name="description">description.</param> /// <param name="document">document.</param> /// <param name="address">address.</param> /// <param name="type">type.</param> public CreateSellerRequest( string name, Dictionary<string, string> metadata, string code = null, string description = null, string document = null, Models.CreateAddressRequest address = null, string type = null) { this.Name = name; this.Code = code; this.Description = description; this.Document = document; this.Address = address; this.Type = type; this.Metadata = metadata; } /// <summary> /// Name /// </summary> [JsonProperty("name")] public string Name { get; set; } /// <summary> /// Seller's code identification /// </summary> [JsonProperty("code", NullValueHandling = NullValueHandling.Ignore)] public string Code { get; set; } /// <summary> /// Description /// </summary> [JsonProperty("description", NullValueHandling = NullValueHandling.Ignore)] public string Description { get; set; } /// <summary> /// Document number (individual / company) /// </summary> [JsonProperty("document", NullValueHandling = NullValueHandling.Ignore)] public string Document { get; set; } /// <summary> /// Address /// </summary> [JsonProperty("address", NullValueHandling = NullValueHandling.Ignore)] public Models.CreateAddressRequest Address { get; set; } /// <summary> /// Person type (individual / company) /// </summary> [JsonProperty("type", NullValueHandling = NullValueHandling.Ignore)] public string Type { get; set; } /// <summary> /// Metadata /// </summary> [JsonProperty("metadata")] public Dictionary<string, string> Metadata { get; set; } /// <inheritdoc/> public override string ToString() { var toStringOutput = new List<string>(); this.ToString(toStringOutput); return $"CreateSellerRequest : ({string.Join(", ", toStringOutput)})"; } /// <inheritdoc/> public override bool Equals(object obj) { if (obj == null) { return false; } if (obj == this) { return true; } return obj is CreateSellerRequest other && ((this.Name == null && other.Name == null) || (this.Name?.Equals(other.Name) == true)) && ((this.Code == null && other.Code == null) || (this.Code?.Equals(other.Code) == true)) && ((this.Description == null && other.Description == null) || (this.Description?.Equals(other.Description) == true)) && ((this.Document == null && other.Document == null) || (this.Document?.Equals(other.Document) == true)) && ((this.Address == null && other.Address == null) || (this.Address?.Equals(other.Address) == true)) && ((this.Type == null && other.Type == null) || (this.Type?.Equals(other.Type) == true)) && ((this.Metadata == null && other.Metadata == null) || (this.Metadata?.Equals(other.Metadata) == true)); } /// <summary> /// ToString overload. /// </summary> /// <param name="toStringOutput">List of strings.</param> protected void ToString(List<string> toStringOutput) { toStringOutput.Add($"this.Name = {(this.Name == null ? "null" : this.Name == string.Empty ? "" : this.Name)}"); toStringOutput.Add($"this.Code = {(this.Code == null ? "null" : this.Code == string.Empty ? "" : this.Code)}"); toStringOutput.Add($"this.Description = {(this.Description == null ? "null" : this.Description == string.Empty ? "" : this.Description)}"); toStringOutput.Add($"this.Document = {(this.Document == null ? "null" : this.Document == string.Empty ? "" : this.Document)}"); toStringOutput.Add($"this.Address = {(this.Address == null ? "null" : this.Address.ToString())}"); toStringOutput.Add($"this.Type = {(this.Type == null ? "null" : this.Type == string.Empty ? "" : this.Type)}"); toStringOutput.Add($"Metadata = {(this.Metadata == null ? "null" : this.Metadata.ToString())}"); } } }
39.433333
152
0.537109
[ "MIT" ]
pagarme/pagarme-net-standard-sdk
PagarmeApiSDK.Standard/Models/CreateSellerRequest.cs
5,915
C#
using Kentico.PageBuilder.Web.Mvc; using Kentico.Forms.Web.Mvc; namespace $rootnamespace$ { public class $safeitemname$ : ISectionProperties { // Defines a property and sets its default value // Assigns the default Kentico text input component, which allows users to enter // a string value for the property in the section's configuration dialog [EditingComponent(TextInputComponent.IDENTIFIER, Order = 0, Label = "Color")] public string Color { get; set; } = "#FFF"; } }
35.066667
88
0.688213
[ "MIT" ]
ondrabus/kentico-vs-extensions
Kentico.MVC.SectionItemTemplate/SampleSectionProperties.cs
528
C#
using Amazon.JSII.Runtime.Deputy; #pragma warning disable CS0672,CS0809,CS1591 namespace aws { [JsiiInterface(nativeType: typeof(IWafv2RuleGroupRuleStatementNotStatementStatementOrStatementStatementSizeConstraintStatementTextTransformation), fullyQualifiedName: "aws.Wafv2RuleGroupRuleStatementNotStatementStatementOrStatementStatementSizeConstraintStatementTextTransformation")] public interface IWafv2RuleGroupRuleStatementNotStatementStatementOrStatementStatementSizeConstraintStatementTextTransformation { [JsiiProperty(name: "priority", typeJson: "{\"primitive\":\"number\"}")] double Priority { get; } [JsiiProperty(name: "type", typeJson: "{\"primitive\":\"string\"}")] string Type { get; } [JsiiTypeProxy(nativeType: typeof(IWafv2RuleGroupRuleStatementNotStatementStatementOrStatementStatementSizeConstraintStatementTextTransformation), fullyQualifiedName: "aws.Wafv2RuleGroupRuleStatementNotStatementStatementOrStatementStatementSizeConstraintStatementTextTransformation")] internal sealed class _Proxy : DeputyBase, aws.IWafv2RuleGroupRuleStatementNotStatementStatementOrStatementStatementSizeConstraintStatementTextTransformation { private _Proxy(ByRefValue reference): base(reference) { } [JsiiProperty(name: "priority", typeJson: "{\"primitive\":\"number\"}")] public double Priority { get => GetInstanceProperty<double>()!; } [JsiiProperty(name: "type", typeJson: "{\"primitive\":\"string\"}")] public string Type { get => GetInstanceProperty<string>()!; } } } }
41.465116
292
0.693214
[ "MIT" ]
scottenriquez/cdktf-alpha-csharp-testing
resources/.gen/aws/aws/IWafv2RuleGroupRuleStatementNotStatementStatementOrStatementStatementSizeConstraintStatementTextTransformation.cs
1,783
C#
namespace DotNetAppSqlDb.Migrations { using System; using System.Data.Entity.Migrations; public partial class AddTwinsTodo5 : DbMigration { public override void Up() { AddColumn("dbo.KidsTodoes", "UserID", c => c.Int()); CreateIndex("dbo.KidsTodoes", "UserID"); AddForeignKey("dbo.KidsTodoes", "UserID", "dbo.Users", "UserID"); } public override void Down() { DropForeignKey("dbo.KidsTodoes", "UserID", "dbo.Users"); DropIndex("dbo.KidsTodoes", new[] { "UserID" }); DropColumn("dbo.KidsTodoes", "UserID"); } } }
28.956522
77
0.554054
[ "MIT" ]
philanderson888/kids-holiday-tasks
DotNetAppSqlDb/Migrations/201907121925448_AddTwinsTodo5.cs
666
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("ChainObj")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("ChainObj")] [assembly: AssemblyCopyright("Copyright © 2019")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("6eb0714c-3409-4272-8618-580f601ddf35")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: InternalsVisibleTo("ChainObj.UnitTests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100458afbd871505fe04577da2af8954eaacda956e9018688e269ba25ed9ef3b0954b5ca5106e1c0e2ffb2b1f1ef135e78f5d25a9574a343ab954d0eac88e833acffc51fb2911919641172a6865a4ad2542a6674b35a80b39c0c5c0a4d1acb95c2f1995721376e55f99025db21638358db35652392c6afe7fd7bd420a3b6237d7e1")]
46.552632
384
0.794234
[ "MIT" ]
oubenal/ChainObj
ChainObj/Properties/AssemblyInfo.cs
1,772
C#
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Net; // HttpWebRequest using System.Runtime.Serialization; // DataContract, DataMember using System.Runtime.Serialization.Json; // DataContractJsonSerializer using System.Windows; namespace IGExtensions.Common.Maps.Imagery // Infragistics.Controls.Maps { /// <summary> /// <para> Represents a connector class that sets up BingMaps REST imagery service </para> /// <para> and provides imagery tiles via Http web requests.</para> /// <remarks>Bing Maps REST Services: http://msdn.microsoft.com/en-us/library/ff701713.aspx </remarks> /// </summary> public class BingMapsConnector : DependencyObject, INotifyPropertyChanged { /// <summary> /// Constructs an instance of BingMapsConnector /// </summary> public BingMapsConnector() { this.IsInitialized = false; } #region Events public event EventHandler ImageryInitialized; public event PropertyChangedEventHandler PropertyChanged; #endregion #region Properties /// <summary> /// Gets or sets an API key required by the Bing Maps imagery service. /// <remarks>This key must be obtained from the http://www.bingmapsportal.com website. </remarks> /// </summary> public string ApiKey { get { return (string)GetValue(ApiKeyProperty); } set { SetValue(ApiKeyProperty, value); } } public const string ApiKeyPropertyName = "ApiKey"; public static readonly DependencyProperty ApiKeyProperty = DependencyProperty.Register(ApiKeyPropertyName, typeof(string), typeof(BingMapsConnector), new PropertyMetadata(string.Empty, (o, e) => (o as BingMapsConnector).OnApiKeyChanged((string)e.OldValue, (string)e.NewValue))); private void OnApiKeyChanged(string oldValue, string newValue) { this.Validate(); } public const string ImageryStylePropertyName = "ImageryStyle"; /// <summary> /// <para> Gets or sets a map style of the Bing Maps imagery tiles. </para> /// <para> For example: Aerial, AerialWithLabels, or Road map style. </para> /// </summary> public BingMapsImageryStyle ImageryStyle { get { return (BingMapsImageryStyle)GetValue(ImageryStyleProperty); } set { SetValue(ImageryStyleProperty, value); } } public static readonly DependencyProperty ImageryStyleProperty = DependencyProperty.Register(ImageryStylePropertyName, typeof(BingMapsImageryStyle), typeof(BingMapsConnector), new PropertyMetadata(BingMapsImageryStyle.StreetMapStyle, (o, e) => (o as BingMapsConnector).OnImageryStylePropertyChanged((BingMapsImageryStyle)e.OldValue, (BingMapsImageryStyle)e.NewValue))); private void OnImageryStylePropertyChanged(BingMapsImageryStyle oldValue, BingMapsImageryStyle newValue) { this.Validate(); } private string _tilePath; /// <summary> /// Gets an imagery tile path for the Bing Maps service. /// </summary> public string TilePath { get { return _tilePath; } private set { _tilePath = value; if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs("TilePath")); } } } private ObservableCollection<string> _subDomains; /// <summary> /// Gets a collection of image URI sub-domains for the Bing Maps service. /// </summary> public ObservableCollection<string> SubDomains { get { return _subDomains; } private set { _subDomains = value; if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs("SubDomains")); } } } /// <summary> /// Gets a status whether the Bing Maps service is initialized. /// </summary> public bool IsInitialized { get; private set; } /// <summary> /// Gets or sets whether the Bing Maps service should be auto-initialized upon valid property values. /// </summary> public bool IsAutoInitialized { get { return (bool)GetValue(IsAutoInitializedProperty); } set { SetValue(IsAutoInitializedProperty, value); } } public const string IsAutoInitializedPropertyName = "IsAutoInitialized"; public static readonly DependencyProperty IsAutoInitializedProperty = DependencyProperty.Register(IsAutoInitializedPropertyName, typeof(bool), typeof(BingMapsConnector), new PropertyMetadata(false, (o, e) => (o as BingMapsConnector).OnAutoInitializedChanged((bool)e.OldValue, (bool)e.NewValue))); private void OnAutoInitializedChanged(bool oldValue, bool newValue) { this.Validate(); } #endregion #region Methods private void Validate() { this.IsInitialized = false; if (!IsValidApiKey()) { return; } if (this.IsAutoInitialized) { Initialize(); } } public bool IsValidApiKey() { if (String.IsNullOrEmpty(this.ApiKey) || this.ApiKey.Length < 20) { return false; } return true; } public void Initialize() { if (!IsValidApiKey()) { this.IsInitialized = false; System.Diagnostics.Debug.WriteLine("<< WARNING >> Detected Invalid BingMaps API key: " + this.ApiKey); return; } this.IsInitialized = true; // for more info on setting up web requests to BingMaps REST imagery service // refer to: http://msdn.microsoft.com/en-us/library/ff701716.aspx var bingUrl = "http://dev.virtualearth.net/REST/v1/Imagery/Metadata/"; //var imagerySet = this.ImageryStyle; //bingUrl += imagerySet; bingUrl += GetImagerySet(this.ImageryStyle); var parms = "key=" + this.ApiKey + "&include=ImageryProviders"; var url = bingUrl + "?" + parms; var req = HttpWebRequest.Create(url); req.BeginGetResponse(GetResponseCompleted, req); } private static string GetImagerySet(BingMapsImageryStyle imageryStyle) { var imagerySet = "Road"; if (imageryStyle == BingMapsImageryStyle.StreetMapStyle) imagerySet = "Road"; else if (imageryStyle == BingMapsImageryStyle.SatelliteNoLabelsMapStyle) imagerySet = "Aerial"; else // if (imageryStyle == BingMapsImageryStyle.SatelliteMapStyle) imagerySet = "AerialWithLabels"; return imagerySet; } #endregion #region Event Handlers private void GetResponseCompleted(IAsyncResult res) { var req = (HttpWebRequest)res.AsyncState; var response = req.EndGetResponse(res); // alternatively, parsing of BingMapsResponse can be performed using LINQ to XML // instead of using JSON deserializer var json = new DataContractJsonSerializer(typeof(BingMapsResponse)); var resp = (BingMapsResponse)json.ReadObject(response.GetResponseStream()); if (resp.ResourceSets == null || resp.ResourceSets.Count < 1 || resp.ResourceSets[0].Resources == null || resp.ResourceSets[0].Resources.Count < 1) { return; } var imageUrl = resp.ResourceSets[0].Resources[0].ImageUrl; var subDomains = resp.ResourceSets[0].Resources[0].ImageUrlSubdomains; if (imageUrl == null || subDomains == null) { return; } TilePath = imageUrl; SubDomains = new ObservableCollection<string>(subDomains); if (ImageryInitialized != null) { ImageryInitialized(this, new EventArgs()); } } #endregion } [DataContract] public class BingMapsResponse { public BingMapsResponse() { ResourceSets = new List<BingMapsResourceSet>(); } [DataMember(Name = "resourceSets")] public List<BingMapsResourceSet> ResourceSets { get; set; } } [DataContract] public class BingMapsResourceSet { public BingMapsResourceSet() { Resources = new List<ImageryMetadata>(); } [DataMember(Name = "resources")] public List<ImageryMetadata> Resources { get; set; } } [DataContract(Namespace = "http://schemas.microsoft.com/search/local/ws/rest/v1")] public class ImageryMetadata { public ImageryMetadata() { ImageUrlSubdomains = new List<string>(); } [DataMember(Name = "imageUrl")] public string ImageUrl { get; set; } [DataMember(Name = "imageUrlSubdomains")] public List<string> ImageUrlSubdomains { get; set; } } }
38.573705
141
0.588411
[ "MIT" ]
Infragistics/wpf-samples
Applications/IGExtensions/IGExtensions.Common.Maps/Imagery/BingMapsConnector.cs
9,682
C#
using XamarinForms.Incidents.Demo.Services; using Xamarin.Forms; namespace XamarinForms.Incidents.Demo.Models { public class IncidentsEditDetailVM:BaseViewModel { IIncidentService service; Incident model; public const string ModelPropertyName = "Model"; public Incident Model { get { return model; } set { SetProperty (ref model, value, ModelPropertyName); } } bool isVisible; public const string IsVisiblePropertyName = "IsVisible"; public bool IsVisible { get { return isVisible; } set { SetProperty (ref isVisible, value, IsVisiblePropertyName); } } public IncidentsEditDetailVM() : this (null, new SQLiteIncidentService()) { } public IncidentsEditDetailVM(Incident incident) : this (incident, new SQLiteIncidentService()) { } public IncidentsEditDetailVM(Incident incident, IIncidentService svc) { Title = "Incident Information"; service = svc; IsVisible = incident != null; Model = incident?? new Incident(); } public virtual void SaveIncident() { service.UpdateIncident (model); MessagingCenter.Send<IncidentsEditDetailVM> (this, "incident-updated"); } public virtual void ResetModel() { Model = new Incident(); } } }
29.367347
106
0.609451
[ "CC0-1.0" ]
cecilphillip/xamarin-forms-demos
XamarinForms.Incidents.Demo/Models/IncidentsEditDetailVM.cs
1,439
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. * * yunding-rds * 云鼎-云数据库管理相关接口 * * OpenAPI spec version: v2 * 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; using JDCloudSDK.Common.Model; using JDCloudSDK.Core.Annotation; using Newtonsoft.Json; namespace JDCloudSDK.Yunding.Apis { /// <summary> /// 批量查询云数据库实例列表信息&lt;br&gt;此接口支持分页查询,默认每页20条。 /// </summary> public class DescribeRdsInstancesRequest : JdcloudRequest { ///<summary> /// 显示数据的页码,默认为1,取值范围:[-1,∞)。pageNumber为-1时,返回所有数据页码;超过总页数时,显示最后一页; ///</summary> public int? PageNumber{ get; set; } ///<summary> /// 每页显示的数据条数,默认为100,取值范围:[10,100],用于查询列表的接口 ///</summary> public int? PageSize{ get; set; } ///<summary> /// 过滤参数,多个过滤参数之间的关系为“与”(and) /// 支持以下属性的过滤: /// instanceId, 支持operator选项:eq /// instanceName, 支持operator选项:eq /// engine, 支持operator选项:eq /// engineVersion, 支持operator选项:eq /// instanceStatus, 支持operator选项:eq /// chargeMode, 支持operator选项:eq /// vpcId, 支持operator选项:eq /// ///</summary> public List<JDCloudSDK.Common.Model.Filter> Filters{ get; set; } ///<summary> /// 资源类型,MySQL:1,SqlServer:2 ///</summary> public int? Type{ get; set; } ///<summary> /// 地域代码,取值范围参见[《各地域及可用区对照表》](../Enum-Definitions/Regions-AZ.md) ///Required:true ///</summary> [Required] [JsonProperty("regionId")] public string RegionIdValue{ get; set; } } }
29.688312
76
0.629046
[ "Apache-2.0" ]
jdcloud-api/jdcloud-sdk-net
sdk/src/Service/Yunding/Apis/DescribeRdsInstancesRequest.cs
2,708
C#
using System.Threading; using System.Threading.Tasks; using MediatR; using SeparateModels.Domain; using SeparateModels.ReadModels; namespace SeparateModels.EventHandlers { public class PolicyTerminatedProjectionsHandler : INotificationHandler<PolicyTerminated> { private readonly PolicyInfoDtoProjection policyInfoDtoProjection; private readonly PolicyVersionDtoProjection policyVersionDtoProjection; public PolicyTerminatedProjectionsHandler(PolicyInfoDtoProjection policyInfoDtoProjection, PolicyVersionDtoProjection policyVersionDtoProjection) { this.policyInfoDtoProjection = policyInfoDtoProjection; this.policyVersionDtoProjection = policyVersionDtoProjection; } public Task Handle(PolicyTerminated @event, CancellationToken cancellationToken) { policyInfoDtoProjection.UpdatePolicyInfoDto(@event.TerminatedPolicy, @event.TerminatedVersion); policyVersionDtoProjection.CreatePolicyVersionDtoProjection(@event.TerminatedPolicy, @event.TerminatedVersion); return Task.CompletedTask; } } }
39.896552
153
0.760588
[ "Apache-2.0" ]
sharmasourabh/ddd
cqrs/SeparateModels/EventHandlers/PolicyTerminatedProjectionsHandler.cs
1,157
C#
using Anomalous.GuiFramework; using Engine; using Engine.ObjectManagement; using Engine.Saving; using Engine.Threads; using Medical; using Medical.Controller; using Medical.Controller.AnomalousMvc; using Medical.GUI; using MyGUIPlugin; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; namespace Lecture { public class SlideshowEditController { public event Action<Slideshow> SlideshowLoaded; public event Action SlideshowClosed; public event Action<Slide, int> SlideAdded; public event Action<Slide> SlideRemoved; public event Action<SlideshowEditController> VectorModeChanged; public event Action RequestRemoveSelected; public event Action<AnomalousMvcContext> SlideshowContextStarting; public event Action<AnomalousMvcContext> SlideshowContextBlurred; public delegate void SelectSlides(Slide primary, IEnumerable<Slide> secondary); public event SelectSlides SlideSelected; private UndoRedoBuffer undoBuffer = new UndoRedoBuffer(50); //Editor Contexts private SlideEditorContext slideEditorContext; private StandaloneController standaloneController; private PropEditController propEditController; private EditorController editorController; private ShowTypeController showTypeController; private LectureUICallback uiCallback; private Slideshow slideshow; private MedicalSlideItemTemplate medicalSlideTemplate; private SlideImageManager slideImageManager; private TimelineTypeController timelineTypeController; private TimelineEditorContext timelineEditorContext; private TimelineController timelineController; private bool allowUndoCreation = true; private Slide lastEditSlide = null; public SlideshowEditController(StandaloneController standaloneController, LectureUICallback uiCallback, PropEditController propEditController, EditorController editorController, TimelineController timelineController) { this.standaloneController = standaloneController; this.uiCallback = uiCallback; this.propEditController = propEditController; this.editorController = editorController; this.timelineController = timelineController; editorController.ProjectChanged += editorController_ProjectChanged; slideImageManager = new SlideImageManager(this); this.AllowSlideSceneSetup = true; //Show Type Controller showTypeController = new ShowTypeController(editorController); editorController.addTypeController(showTypeController); timelineTypeController = new TimelineTypeController(editorController); editorController.addTypeController(timelineTypeController); medicalSlideTemplate = new MedicalSlideItemTemplate(standaloneController.SceneViewController, standaloneController.MedicalStateController); medicalSlideTemplate.SlideCreated += (slide) => { if (lastEditSlide != null) { int insertIndex = slideshow.indexOf(lastEditSlide); if (insertIndex != -1) { ++insertIndex; } addSlide(slide, insertIndex); } else { addSlide(slide); } }; editorController.addItemTemplate(medicalSlideTemplate); } public void editSlide(Slide slide) { bool openedEditContext = false; if (slide != lastEditSlide) { openedEditContext = openEditorContextForSlide(slide); } else { if (slideEditorContext != null) { slideEditorContext.slideNameChanged("Slide " + (slideshow.indexOf(slide) + 1)); } else { openEditorContextForSlide(slide); //If the slide context is null the timeline editor is open, switch back to slide editing. //We ignore the context open result, because we do not care about undo in this situation } } if (openedEditContext) { if (lastEditSlide != null && allowUndoCreation) { undoBuffer.pushAndSkip(new TwoWayDelegateCommand<Slide, Slide>(slide, lastEditSlide, new TwoWayDelegateCommand<Slide, Slide>.Funcs() { ExecuteFunc = (redoItem) => { //Hacky, but we cannot modify the active slide without messing up the classes that triggered this. ThreadManager.invoke(new Action(delegate() { allowUndoCreation = false; if (SlideSelected != null) { SlideSelected.Invoke(redoItem, IEnumerableUtil<Slide>.EmptyIterator); } allowUndoCreation = true; })); }, UndoFunc = (undoItem) => { //Hacky, but we cannot modify the active slide without messing up the classes that triggered this. ThreadManager.invoke(new Action(delegate() { allowUndoCreation = false; if (SlideSelected != null) { SlideSelected.Invoke(undoItem, IEnumerableUtil<Slide>.EmptyIterator); } allowUndoCreation = true; })); }, }) ); } lastEditSlide = slide; uiCallback.CurrentDirectory = slide.UniqueName; } } internal void sceneLoading(SimScene scene) { if(slideEditorContext != null) { slideEditorContext.resetSlide(); } } public void sceneUnloading(SimScene scene) { if(timelineEditorContext != null) { timelineEditorContext.clearSelection(); } } private bool openEditorContextForSlide(Slide slide) { bool openedEditContext = false; slideEditorContext = new SlideEditorContext(slide, "Slide " + (slideshow.indexOf(slide) + 1), this, standaloneController, uiCallback, undoBuffer, medicalSlideTemplate, AllowSlideSceneSetup, (panelName, rml) => { slideEditorContext.setWysiwygRml(panelName, rml, true); }); if (standaloneController.SharePluginController != null) { CallbackTask cleanupBeforeShareTask = new CallbackTask("Lecture.SharePluginTask", standaloneController.SharePluginController.Name, standaloneController.SharePluginController.IconName, standaloneController.SharePluginController.Category, 0, false, (item) => { shareSlideshow(); }); slideEditorContext.addTask(cleanupBeforeShareTask); } slideEditorContext.Focus += (obj) => { slideEditorContext = obj; }; slideEditorContext.Blur += obj => { if (slideEditorContext == obj) { slideEditorContext.RecordResizeUndo -= slideEditorContext_RecordResizeUndo; slideEditorContext = null; } }; slideEditorContext.RecordResizeUndo += slideEditorContext_RecordResizeUndo; editorController.runEditorContext(slideEditorContext.MvcContext); openedEditContext = true; return openedEditContext; } void slideEditorContext_RecordResizeUndo(RmlEditorViewInfo view, int oldSize, int newSize) { String panelName = view.View.Name; Action<int> changeSize = (size) => { slideEditorContext.resizePanel(panelName, size); }; undoBuffer.pushAndSkip(new TwoWayDelegateCommand<int, int>(newSize, oldSize, new TwoWayDelegateCommand<int, int>.Funcs() { ExecuteFunc = changeSize, UndoFunc = changeSize })); } public void editTimeline(Slide slide, String fileName, String text) { try { Timeline timeline = null; String timelineFilePath = Path.Combine(slide.UniqueName, fileName); if (!ResourceProvider.exists(timelineFilePath)) { timelineTypeController.createNewTimeline(timelineFilePath); } timeline = editorController.loadFile<Timeline>(timelineFilePath); //By loading after creating we ensure this is in the cached resources propEditController.removeAllOpenProps(); timelineEditorContext = new TimelineEditorContext(timeline, slide, String.Format("Slide {0} - {1}", slideshow.indexOf(slide) + 1, text), this, propEditController, standaloneController.PropFactory, editorController, uiCallback, timelineController); timelineEditorContext.Focus += obj => { timelineEditorContext = obj; }; timelineEditorContext.Blur += obj => { if (obj == timelineEditorContext) { timelineEditorContext = null; } }; editorController.runEditorContext(timelineEditorContext.MvcContext); } catch (Exception ex) { MessageBox.show(String.Format("Error opening timeline for editing.\n{0}", ex.Message), "Load Error", MessageBoxStyle.IconError | MessageBoxStyle.Ok); } } class SlideInfo { public SlideInfo(Slide slide, int index) { this.Slide = slide; this.Index = index; } public Slide Slide { get; set; } public int Index { get; set; } public static int Sort(SlideInfo left, SlideInfo right) { return left.Index - right.Index; } } class RemoveSlideInfo : SlideInfo { public RemoveSlideInfo(Slide slide, int index, Slide changeToSlide) : base(slide, index) { this.ChangeToSlide = changeToSlide; } public Slide ChangeToSlide { get; set; } } public void removeSelectedSlides() { if (RequestRemoveSelected != null) { RequestRemoveSelected.Invoke(); } } public void removeSlides(IEnumerable<Slide> slides, Slide primarySelection) { int slideIndex = slideshow.indexOf(primarySelection); List<SlideInfo> removedSlides = new List<SlideInfo>(from slide in slides select new SlideInfo(slide, slideshow.indexOf(slide))); if (removedSlides.Count > 0) { removedSlides.Sort(SlideInfo.Sort); doRemoveSlides(removedSlides); Slide changeToSlide = null; if (primarySelection == lastEditSlide) { if (slideIndex < slideshow.Count) { changeToSlide = slideshow.get(slideIndex); } else if (slideIndex - 1 >= 0) { changeToSlide = slideshow.get(slideIndex - 1); } } bool wasAllowingUndo = allowUndoCreation; allowUndoCreation = false; if (changeToSlide != null && SlideSelected != null) { SlideSelected.Invoke(changeToSlide, IEnumerableUtil<Slide>.EmptyIterator); } allowUndoCreation = wasAllowingUndo; if (allowUndoCreation) { undoBuffer.pushAndSkip(new TwoWayDelegateCommand( new TwoWayDelegateCommand.Funcs() { ExecuteFunc = () => //Execute { ThreadManager.invoke(new Action(() => { allowUndoCreation = false; doRemoveSlides(removedSlides); if (changeToSlide != null && SlideSelected != null) { SlideSelected.Invoke(changeToSlide, IEnumerableUtil<Slide>.EmptyIterator); } allowUndoCreation = true; })); }, UndoFunc = () => //Undo { ThreadManager.invoke(new Action(() => { allowUndoCreation = false; foreach (SlideInfo slide in removedSlides) { slideshow.insertSlide(slide.Index, slide.Slide); if (SlideAdded != null) { SlideAdded.Invoke(slide.Slide, slide.Index); } } if (SlideSelected != null) { SlideSelected.Invoke(primarySelection, secondarySlideSelections(removedSlides, primarySelection)); } allowUndoCreation = true; })); }, PoppedFrontFunc = () => { foreach (SlideInfo slideInfo in removedSlides) { cleanupThumbnail(slideInfo); } } })); } } } private void doRemoveSlides(List<SlideInfo> removedSlides) { bool wasAllowingUndo = allowUndoCreation; allowUndoCreation = false; foreach (SlideInfo slideInfo in removedSlides) { slideshow.removeSlide(slideInfo.Slide); if (SlideRemoved != null) { SlideRemoved.Invoke(slideInfo.Slide); } } allowUndoCreation = wasAllowingUndo; } public void removeSlide(Slide slide) { int slideIndex = slideshow.indexOf(slide); if (slideIndex != -1) { slideshow.removeAt(slideIndex); if (SlideRemoved != null) { SlideRemoved.Invoke(slide); } Slide changeToSlide = null; if (slide == lastEditSlide) { if (slideIndex < slideshow.Count) { changeToSlide = slideshow.get(slideIndex); } else if (slideIndex - 1 >= 0) { changeToSlide = slideshow.get(slideIndex - 1); } } if (changeToSlide != null) { bool wasAllowingUndo = allowUndoCreation; allowUndoCreation = false; if (SlideSelected != null) { SlideSelected.Invoke(changeToSlide, IEnumerableUtil<Slide>.EmptyIterator); } allowUndoCreation = wasAllowingUndo; } if (allowUndoCreation) { if (changeToSlide == null) { undoBuffer.pushAndSkip(new TwoWayDelegateCommand<SlideInfo>(new SlideInfo(slide, slideIndex), new TwoWayDelegateCommand<SlideInfo>.Funcs() { ExecuteFunc = (executeSlide) => { allowUndoCreation = false; removeSlide(executeSlide.Slide); allowUndoCreation = true; }, UndoFunc = (undoSlide) => { allowUndoCreation = false; addSlide(undoSlide.Slide, undoSlide.Index); allowUndoCreation = true; }, } )); } else { undoBuffer.pushAndSkip(new TwoWayDelegateCommand<RemoveSlideInfo>(new RemoveSlideInfo(slide, slideIndex, changeToSlide), new TwoWayDelegateCommand<RemoveSlideInfo>.Funcs(){ ExecuteFunc = (executeSlide) => { //Hacky, but we cannot modify the active slide without messing up the classes that triggered this. ThreadManager.invoke(new Action(delegate() { allowUndoCreation = false; removeSlide(executeSlide.Slide); if (SlideSelected != null) { SlideSelected.Invoke(executeSlide.ChangeToSlide, IEnumerableUtil<Slide>.EmptyIterator); } allowUndoCreation = true; })); }, UndoFunc = (undoSlide) => { //Hacky, but we cannot modify the active slide without messing up the classes that triggered this. ThreadManager.invoke(new Action(delegate() { allowUndoCreation = false; addSlide(undoSlide.Slide, undoSlide.Index); if (SlideSelected != null) { SlideSelected.Invoke(undoSlide.Slide, IEnumerableUtil<Slide>.EmptyIterator); } allowUndoCreation = true; })); }, PoppedFrontFunc = cleanupThumbnail })); } } } } public void addSlide(Slide slide, int index = -1) { if (index == -1) { slideshow.addSlide(slide); } else { slideshow.insertSlide(index, slide); } if (!editorController.ResourceProvider.exists(slide.UniqueName)) { editorController.ResourceProvider.createDirectory("", slide.UniqueName); } if (SlideAdded != null) { SlideAdded.Invoke(slide, index); } //Delay this till the next frame, so the rml has actually been rendererd ThreadManager.invoke(new Action(delegate() { if (slideEditorContext != null) { slideEditorContext.updateThumbnail(); } })); if (allowUndoCreation) { if (lastEditSlide == null) { undoBuffer.pushAndSkip(new TwoWayDelegateCommand<SlideInfo>(new SlideInfo(slide, slideshow.indexOf(slide)), new TwoWayDelegateCommand<SlideInfo>.Funcs() { ExecuteFunc = (executeSlide) => { allowUndoCreation = false; addSlide(executeSlide.Slide, executeSlide.Index); allowUndoCreation = true; }, UndoFunc = (undoSlide) => { allowUndoCreation = false; removeSlide(undoSlide.Slide); allowUndoCreation = true; }, TrimmedFunc = cleanupThumbnail, } )); } else { undoBuffer.pushAndSkip(new TwoWayDelegateCommand<RemoveSlideInfo>(new RemoveSlideInfo(slide, index, lastEditSlide), new TwoWayDelegateCommand<RemoveSlideInfo>.Funcs() { ExecuteFunc = (executeSlide) => { //Hacky, but we cannot modify the active slide without messing up the classes that triggered this. ThreadManager.invoke(new Action(delegate() { allowUndoCreation = false; addSlide(executeSlide.Slide, executeSlide.Index); if (SlideSelected != null) { SlideSelected.Invoke(executeSlide.Slide, IEnumerableUtil<Slide>.EmptyIterator); } allowUndoCreation = true; })); }, UndoFunc = (undoSlide) => { //Hacky, but we cannot modify the active slide without messing up the classes that triggered this. ThreadManager.invoke(new Action(delegate() { allowUndoCreation = false; if (SlideSelected != null) { SlideSelected.Invoke(undoSlide.ChangeToSlide, IEnumerableUtil<Slide>.EmptyIterator); } removeSlide(undoSlide.Slide); allowUndoCreation = true; })); }, TrimmedFunc = cleanupThumbnail })); } } bool wasAllowingUndo = allowUndoCreation; allowUndoCreation = false; if (SlideSelected != null) { SlideSelected.Invoke(slide, IEnumerableUtil<Slide>.EmptyIterator); } allowUndoCreation = wasAllowingUndo; } public void moveSlides(IEnumerable<Slide> slides, int index) { List<SlideInfo> sortedSlides = new List<SlideInfo>(from slide in slides select new SlideInfo(slide, slideshow.indexOf(slide))); sortedSlides.Sort(SlideInfo.Sort); bool wasAllowingUndo = allowUndoCreation; allowUndoCreation = false; doMoveSlides(index, sortedSlides); allowUndoCreation = wasAllowingUndo; if (allowUndoCreation) { undoBuffer.pushAndSkip(new TwoWayDelegateCommand( new TwoWayDelegateCommand.Funcs() { ExecuteFunc = () => //Execute { allowUndoCreation = false; doMoveSlides(index, sortedSlides); allowUndoCreation = true; }, UndoFunc = () => //Undo { allowUndoCreation = false; foreach (SlideInfo info in sortedSlides) { int formerIndex = slideshow.indexOf(info.Slide); slideshow.removeAt(formerIndex); if (SlideRemoved != null) { SlideRemoved.Invoke(info.Slide); } } //Can't think of how to do this without two loops, have to compensate for other things //that need to be undone or else this won't put things back, two loops makes sure //all items are removed and we can just insert back to original indices. foreach (SlideInfo info in sortedSlides) { slideshow.insertSlide(info.Index, info.Slide); if (SlideAdded != null) { SlideAdded.Invoke(info.Slide, info.Index); } } if (SlideSelected != null) { SlideSelected.Invoke(lastEditSlide, secondarySlideSelections(sortedSlides, lastEditSlide)); } allowUndoCreation = true; } })); } } private void doMoveSlides(int index, List<SlideInfo> sortedSlides) { int actualInsertIndex = index; foreach (SlideInfo slideInfo in sortedSlides) { if (slideInfo.Index <= index && actualInsertIndex > 0) { --actualInsertIndex; } slideshow.removeSlide(slideInfo.Slide); if (SlideRemoved != null) { SlideRemoved.Invoke(slideInfo.Slide); } slideshow.insertSlide(actualInsertIndex, slideInfo.Slide); if (SlideAdded != null) { SlideAdded.Invoke(slideInfo.Slide, actualInsertIndex); } ++actualInsertIndex; } if (SlideSelected != null) { Slide primarySelection = lastEditSlide; if (primarySelection == null) { //Double check the last edit slide if the user moved a slide without actually clicking and releasing that slide will be null, //in this case use the slide that was moved. primarySelection = sortedSlides[0].Slide; } SlideSelected.Invoke(primarySelection, secondarySlideSelections(sortedSlides, primarySelection)); } } private static IEnumerable<Slide> secondarySlideSelections(IEnumerable<SlideInfo> movedSlides, Slide skipSlide) { foreach (SlideInfo info in movedSlides) { if (info.Slide != skipSlide) { yield return info.Slide; } } } public void cleanup() { //Cleanup slide trash CleanupInfo cleanupInfo = new CleanupInfo(); slideshow.cleanup(cleanupInfo, ResourceProvider); undoBuffer.clear(); //Can't really recover from this one, so just erase all undo List<Guid> cleanupSlides = new List<Guid>(projectGuidDirectories()); foreach (Slide slide in slideshow.Slides) { Guid guid; if (Guid.TryParse(slide.UniqueName, out guid)) { cleanupSlides.Remove(guid); } foreach (String file in ResourceProvider.listFiles("*", slide.UniqueName, true)) { if (!cleanupInfo.isClaimed(file)) { try { editorController.ResourceProvider.delete(file); } catch (Exception ex) { Logging.Log.Error("Cleanup -- Failed to delete file '{0}'. Reason: {1}", file, ex.Message); } } } } foreach (Guid dir in cleanupSlides) { try { editorController.ResourceProvider.delete(dir.ToString("D")); } catch (Exception ex) { Logging.Log.Error("Cleanup -- Failed to delete directory '{0}'. Reason: {1}", dir, ex.Message); } } PropFactory propFactory = standaloneController.PropFactory; DDAtlasPlugin plugin; using(Stream pluginFileStream = editorController.ResourceProvider.openFile("Plugin.ddp")) { plugin = SharedXmlSaver.Load<DDAtlasPlugin>(pluginFileStream); } plugin.setDependencyIds(cleanupInfo.getObjects<String>(ShowPropAction.PropClass) .Select(n => propFactory.getDependencyIdForProp(n)) .Where(id => id.HasValue) .Select(id => id.Value)); using(Stream pluginFileStream = editorController.ResourceProvider.openWriteStream("Plugin.ddp")) { SharedXmlSaver.Save(plugin, pluginFileStream); } } /// <summary> /// This save function handles any exceptions, use it from keyboard shortcuts or anywhere that you don't care /// about any exceptions that might be thrown, otherwise use unsafeSave. /// </summary> public void safeSave() { try { unsafeSave(); } catch (Exception ex) { MessageBox.show(String.Format("There was an error saving your project.\nException type: {0}\n{1}", ex.GetType().Name, ex.Message), "Save Error", MessageBoxStyle.Ok | MessageBoxStyle.IconError); } } /// <summary> /// This function saves the slideshow, it will not handle any exceptions related to this. /// </summary> public void unsafeSave() { editorController.saveAllCachedResources(); slideImageManager.saveThumbnails(); } public void saveAs(String destination) { destination = editorController.ProjectTypes.getProjectBasePath(destination); ResourceProvider clonedProvider; if (editorController.ProjectTypes.areSameProjectType(editorController.ResourceProvider.BackingProvider.BackingLocation, destination)) { editorController.ResourceProvider.cloneProviderTo(destination); clonedProvider = editorController.ProjectTypes.openResourceProvider(destination); } else { editorController.ProjectTypes.deleteProject(destination); editorController.ProjectTypes.ensureProjectExists(destination); clonedProvider = editorController.ProjectTypes.openResourceProvider(destination); ResourceProviderExtensions.cloneTo(editorController.ResourceProvider, clonedProvider); } libRocketPlugin.RocketInterface.Instance.SystemInterface.RemoveRootPath(editorController.ResourceProvider.BackingLocation); //Have to remove old backing location editorController.ProjectTypes.resourceProviderClosed(editorController.ResourceProvider.BackingProvider); editorController.changeActiveResourceProvider(clonedProvider); //Do the actual save unsafeSave(); //Reload the current slide if (lastEditSlide != null) { openEditorContextForSlide(lastEditSlide); } standaloneController.DocumentController.addToRecentDocuments(editorController.ResourceProvider.BackingLocation); } public void runSlideshow(int startIndex) { if (startIndex == -1) { startIndex = 0; } AnomalousMvcContext context = slideshow.createContext(ResourceProvider, standaloneController.GUIManager, startIndex); context.RuntimeName = editorController.EditorContextRuntimeName; context.setResourceProvider(ResourceProvider); context.BlurAction = "Common/Blur"; CallbackAction blurAction = new CallbackAction("Blur", blurContext => { NavigationModel model = blurContext.getModel<NavigationModel>(Medical.SlideshowProps.BaseContextProperties.NavigationModel); Slide slide = slideshow.get(model.CurrentIndex); if (SlideshowContextBlurred != null) { SlideshowContextBlurred.Invoke(blurContext); } ThreadManager.invoke(new Action(() => { if (lastEditSlide == slide) { if (SlideSelected != null) { SlideSelected.Invoke(null, IEnumerableUtil<Slide>.EmptyIterator); } } if (SlideSelected != null) { SlideSelected.Invoke(slide, IEnumerableUtil<Slide>.EmptyIterator); } })); }); context.Controllers["Common"].Actions.add(blurAction); if (SlideshowContextStarting != null) { SlideshowContextStarting.Invoke(context); } standaloneController.TimelineController.setResourceProvider(editorController.ResourceProvider); standaloneController.MvcCore.startRunningContext(context); } public void runSlideshow(Slide slide) { runSlideshow(slideshow.indexOf(slide)); } public void applySlideLayout(TemplateSlide template) { if (slideEditorContext != null) { slideEditorContext.applySlideLayout(template); } } private IEnumerable<Guid> projectGuidDirectories() { Guid guid; foreach (String file in editorController.ResourceProvider.listDirectories("*", "", false)) { if (Guid.TryParse(file, out guid)) { yield return guid; } } } public UndoRedoBuffer UndoBuffer { get { return undoBuffer; } } public EditorResourceProvider ResourceProvider { get { return editorController.ResourceProvider; } } public SlideImageManager SlideImageManager { get { return slideImageManager; } } /// <summary> /// Returns or sets the VectorMode of the current slideshow, /// if there is no slideshow this value will be true and your /// changes will not take effect. /// </summary> public bool VectorMode { get { if (slideshow != null) { return slideshow.VectorMode; } return true; } set { if (slideshow != null && slideshow.VectorMode != value) { slideshow.VectorMode = value; if (VectorModeChanged != null) { VectorModeChanged.Invoke(this); } } } } public bool AllowSlideSceneSetup { get; set; } void editorController_ProjectChanged(EditorController editorController) { closeEditors(); lastEditSlide = null; undoBuffer.clear(); if (editorController.ResourceProvider != null) { //Try to open a default slideshow String file = "Slides.show"; if (editorController.ResourceProvider.exists(file)) { loadSlideshow(file); } else { IEnumerable<String> files = editorController.ResourceProvider.listFiles("*.show", "", false); String firstFile = files.FirstOrDefault(); if (firstFile != null) { loadSlideshow(firstFile); } } } else if (SlideshowClosed != null) { SlideshowClosed.Invoke(); } } /// <summary> /// Load a slideshow. The SlideshowLoaded event will fire when it is done. /// </summary> /// <param name="file"></param> void loadSlideshow(String file) { standaloneController.DocumentController.addToRecentDocuments(editorController.ResourceProvider.BackingLocation); slideshow = editorController.loadFile<Slideshow>(file); if (updateSmartLecture()) { finishLoadingSlideshow(); } } public void capture() { if (slideEditorContext != null) { SlideSceneInfo undoInfoStack = slideEditorContext.getCurrentSceneInfo(); slideEditorContext.capture(); SlideSceneInfo redoInfoStack = slideEditorContext.getCurrentSceneInfo(); undoBuffer.pushAndSkip(new TwoWayDelegateCommand<SlideSceneInfo, SlideSceneInfo>(redoInfoStack, undoInfoStack, new TwoWayDelegateCommand<SlideSceneInfo, SlideSceneInfo>.Funcs() { ExecuteFunc = applySceneInfo, UndoFunc = applySceneInfo, RemovedFunc = IDisposableUtil.DisposeIfNotNull })); } } private void applySceneInfo(SlideSceneInfo info) { slideEditorContext.applySceneInfo(info); } internal void stopPlayingTimelines() { editorController.stopPlayingTimelines(); } internal void createNewProject(string projectDirectory, bool deleteOld, ProjectTemplate projectTemplate) { editorController.createNewProject(projectDirectory, deleteOld, projectTemplate); } internal void closeProject() { editorController.closeProject(); } internal void openProject(string fullFilePath) { editorController.openProject(editorController.ProjectTypes.getProjectBasePath(fullFilePath)); } /// <summary> /// Check a loaded slideshow to see if it needs updates or if the program does. /// Returns true if it is safe to finish loading or false if this function will /// handle that step somehow later. /// </summary> /// <returns></returns> private bool updateSmartLecture() { if (slideshow.Version < Slideshow.CurrentVersion) { MessageBox.show("This project is out of date, would you like to update it now?\nUpdating this project will allow you to edit it, however, it will be incompatible with older versions of Anomalous Medical.\nIt is reccomended that you do this update.", "Update Required", MessageBoxStyle.Yes | MessageBoxStyle.No | MessageBoxStyle.IconQuest, (result) => { if (result == MessageBoxStyle.Yes) { try { //First do the save as if needed to zip up old project String backingLoc = editorController.ResourceProvider.BackingProvider.BackingLocation; if (!backingLoc.EndsWith(".sl")) { saveAs(backingLoc + ".sl"); } if (slideshow.Version < 2) { EmbeddedResourceHelpers.CopyResourceToStream(EmbeddedTemplateNames.MasterTemplate_trml, "MasterTemplate.trml", editorController.ResourceProvider, EmbeddedTemplateNames.Assembly); EmbeddedResourceHelpers.CopyResourceToStream(EmbeddedTemplateNames.SlideMasterStyles_rcss, "SlideMasterStyles.rcss", editorController.ResourceProvider, EmbeddedTemplateNames.Assembly); } slideshow.updateToVersion(Slideshow.CurrentVersion, editorController.ResourceProvider); unsafeSave(); finishLoadingSlideshow(); } catch (Exception ex) { MessageBox.show(String.Format("There was an error updating your project.\nException type: {0}\n{1}", ex.GetType().Name, ex.Message), "Update Error", MessageBoxStyle.Ok | MessageBoxStyle.IconError); } } else { closeProject(); } InlineRmlUpgradeCache.removeSlideshowPanels(slideshow); }); return false; } else if (slideshow.Version > Slideshow.CurrentVersion) { MessageBox.show("This project was created in a newer version of Anomalous Medical.\nPlease update Anomalous Medical to be able to edit this file.", "Update Required", MessageBoxStyle.Ok | MessageBoxStyle.IconWarning); closeProject(); return false; } return true; } /// <summary> /// Complete the sequence of loading a slideshow. Called after the slideshow is loaded, or if it needed upgrading after its upgraded. /// </summary> private void finishLoadingSlideshow() { if (SlideshowLoaded != null) { SlideshowLoaded.Invoke(slideshow); } if (slideshow.Count > 0) { if (SlideSelected != null) { SlideSelected(slideshow.get(0), IEnumerableUtil<Slide>.EmptyIterator); } } else { medicalSlideTemplate.createItem("", editorController); //If we got here its because there were no slides in the slideshow, adding the slide on the //line above will cause an undo state to be created, since we know we have just loaded a fresh //slideshow with no changes, just clear the undo buffer so the user cannot undo to having no slides undoBuffer.clear(); } } internal void closeEditors() { if (slideEditorContext != null) { slideEditorContext.close(); } if (timelineEditorContext != null) { timelineEditorContext.close(); } } public void duplicateSlide(Slide slide) { try { Slide copied = CopySaver.Default.copy(slide); String oldName = copied.UniqueName; copied.generateNewUniqueName(); editorController.ResourceProvider.copyDirectory(oldName, copied.UniqueName); int index = slideshow.indexOf(slide) + 1; if (index >= slideshow.Count) { index = -1; } addSlide(copied, index); } catch (Exception ex) { MessageBox.show(String.Format("Error duplicating your slide.\nReason: {0} occured. {1}", ex.GetType().Name, ex.Message), "Duplicate Error", MessageBoxStyle.IconError | MessageBoxStyle.Ok); } } public void createSlide() { //Commented code will bring up the template dialog //AddItemDialog.AddItem(editorController.ItemTemplates, createItem); try { medicalSlideTemplate.createItem("", editorController); } catch (Exception ex) { MessageBox.show(String.Format("Error creating slide.\n{0}", ex.Message), "Error Creating Slide", MessageBoxStyle.IconError | MessageBoxStyle.Ok); } } private void cleanupThumbnail(SlideInfo slideInfo) { //Double check the slideshow to make sure the slide isn't in use. This was causing //big problems, but the double check fixed it. The root cause was actually that the add //slide undos were removing their thumbnails incorrectly, however, I will leave this guard here //to make this function a bit more robust anyway. Checking the slideshow quick before removing the //thumbnail won't take that long. // //Call it paranoia, we were stumped by this for days if (slideshow.indexOf(slideInfo.Slide) == -1) { slideImageManager.removeImage(slideInfo.Slide); } } internal bool projectExists(string fullProjectName) { return editorController.ProjectTypes.doesProjectExist(fullProjectName); } private void shareSlideshow() { MessageBox.show("Before sharing your project it will be cleaned and saved. Do you wish to continue?", "Share Project", MessageBoxStyle.IconQuest | MessageBoxStyle.Yes | MessageBoxStyle.No, (result) => { if (result == MessageBoxStyle.Yes) { try { slideEditorContext.commitText(); this.unsafeSave(); this.cleanup(); standaloneController.SharePluginController.sharePlugin(editorController.ResourceProvider.BackingProvider, PluginCreationTool.SmartLectureTools); } catch (Exception ex) { MessageBox.show(String.Format("There was an error cleaning your project.\nException type: {0}\n{1}", ex.GetType().Name, ex.Message), "Cleaning Error", MessageBoxStyle.Ok | MessageBoxStyle.IconError); } } }); } /// <summary> /// This will refresh the rml and thumbnail for the current slide editor context. /// </summary> public void refreshRmlAndThumbnail() { if (slideEditorContext != null) { slideEditorContext.refreshAllRml(); slideEditorContext.updateThumbnail(); } } } }
43.389125
367
0.476923
[ "MIT" ]
AnomalousMedical/Medical
Lecture/Controller/SlideshowEditController.cs
51,071
C#
/****************************************************************************** * Copyright (C) Leap Motion, Inc. 2011-2018. * * Leap Motion proprietary and confidential. * * * * Use subject to the terms of the Leap Motion SDK Agreement available at * * https://developer.leapmotion.com/sdk_agreement, or another agreement * * between Leap Motion and you, your company or other organization. * ******************************************************************************/ using System; using System.IO; using System.Linq; using System.Text.RegularExpressions; using System.Collections.Generic; using UnityEngine; using UnityEditor; public static class VariantEnabler { public const string EARLY_OUT_KEYWORD = "#pragma"; public static Regex isSurfaceShaderRegex = new Regex(@"#pragma\s+surface\s+surf"); public static Regex disabledVariantRegex = new Regex(@"/{2,}\s*#pragma\s+shader_feature\s+_\s+GRAPHIC_RENDERER"); public static Regex enabledVariantRegex = new Regex(@"^\s*#pragma\s+shader_feature\s+_\s+GRAPHIC_RENDERER"); public static bool IsSurfaceShader(Shader shader) { ShaderInfo info; if (tryGetShaderInfo(shader, out info)) { return info.isSurfaceShader; } else { return false; } } public static bool DoesShaderHaveVariantsDisabled(Shader shader) { ShaderInfo info; if (tryGetShaderInfo(shader, out info)) { return info.doesHaveShaderVariantsDisabled; } else { return false; } } public static void SetShaderVariantsEnabled(Shader shader, bool enable) { string path = AssetDatabase.GetAssetPath(shader); if (string.IsNullOrEmpty(path)) { return; } _infoCache.Remove(path); string[] lines = File.ReadAllLines(path); using (var writer = File.CreateText(path)) { foreach (var line in lines) { if (enable && disabledVariantRegex.IsMatch(line)) { writer.WriteLine(line.Replace("/", " ")); } else if (!enable && enabledVariantRegex.IsMatch(line)) { var startEnum = line.TakeWhile(c => char.IsWhiteSpace(c)); int count = Mathf.Max(0, startEnum.Count() - 2); var start = new string(startEnum.Take(count).ToArray()); writer.WriteLine(start + "//" + line.TrimStart()); } else { writer.WriteLine(line); } } } } private static Dictionary<string, ShaderInfo> _infoCache = new Dictionary<string, ShaderInfo>(); private static bool tryGetShaderInfo(Shader shader, out ShaderInfo info) { string path = AssetDatabase.GetAssetPath(shader); if (string.IsNullOrEmpty(path)) { info = default(ShaderInfo); return false; } DateTime modifiedTime = File.GetLastWriteTime(path); if (_infoCache.TryGetValue(path, out info)) { //If the check time is newer than the modified time, return cached results if (modifiedTime < info.checkTime) { return true; } } info.isSurfaceShader = false; info.doesHaveShaderVariantsDisabled = false; info.checkTime = modifiedTime; string[] lines = File.ReadAllLines(path); foreach (var line in lines) { if (!line.Contains(EARLY_OUT_KEYWORD)) { continue; } if (disabledVariantRegex.IsMatch(line)) { info.doesHaveShaderVariantsDisabled = true; } if (isSurfaceShaderRegex.IsMatch(line)) { info.isSurfaceShader = true; } } _infoCache[path] = info; return true; } private struct ShaderInfo { public bool doesHaveShaderVariantsDisabled; public bool isSurfaceShader; public DateTime checkTime; } }
33.157895
115
0.618254
[ "MIT" ]
LHuss/capstone
Virtual Modeller/Assets/ThirdParty/LeapMotion/Modules/GraphicRenderer/Scripts/Utility/Editor/VariantEnabler.cs
3,780
C#
namespace ClassLib104 { public class Class067 { public static string Property => "ClassLib104"; } }
15
55
0.633333
[ "MIT" ]
333fred/performance
src/scenarios/weblarge2.0/src/ClassLib104/Class067.cs
120
C#
namespace OneSky.CSharp.Json { using System.Collections.Generic; internal class PlatformProjectGroup : IPlatformProjectGroup { private readonly CSharp.IPlatformProjectGroup projectGroup; public PlatformProjectGroup(CSharp.IPlatformProjectGroup projectGroup) { this.projectGroup = projectGroup; } public IOneSkyResponse<IMetaPagedList, IEnumerable<IProjectGroup>> List(int page = 1, int perPage = 50) { var plain = this.projectGroup.List(page, perPage); return JsonHelper.PlatformCompose<IMetaPagedList, IEnumerable<IProjectGroup>, MetaPagedList, List<ProjectGroup>>(plain); } public IOneSkyResponse<IMeta, IProjectGroupDetails> Show(int projectGroupId) { var plain = this.projectGroup.Show(projectGroupId); return JsonHelper.PlatformCompose<IMeta, IProjectGroupDetails, Meta, ProjectGroupDetails>(plain); } public IOneSkyResponse<IMeta, IProjectGroupNew> Create(string name, string locale = "en") { var plain = this.projectGroup.Create(name, locale); return JsonHelper.PlatformCompose<IMeta, IProjectGroupNew, Meta, ProjectGroupNew>(plain); } public IOneSkyResponse<IMeta, INull> Delete(int projectGroupId) { var plain = this.projectGroup.Delete(projectGroupId); return JsonHelper.PlatformCompose<IMeta, INull, Meta, Null>(plain); } public IOneSkyResponse<IMetaList, IEnumerable<ILocaleGroup>> Languages(int projectGroupId) { var plain = this.projectGroup.Languages(projectGroupId); return JsonHelper.PlatformCompose<IMetaList, IEnumerable<ILocaleGroup>, MetaList, List<LocaleGroup>>(plain); } } }
41.022727
132
0.68144
[ "MIT" ]
QuadRatNewBy/OneSky-CSharp
OneSky.CSharp/OneSky.CSharp/Json/PlatformProjectGroup.cs
1,807
C#
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. namespace Microsoft.Data.Entity.FunctionalTests { public abstract class OneToOneQueryFixtureBase { protected virtual void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder .Entity<Address>(e => e.Reference(a => a.Resident).InverseReference(p => p.Address) .PrincipalKey<Person>(person => person.Id)); modelBuilder.Entity<Address2>().Property<int>("PersonId"); modelBuilder .Entity<Person2>( e => e.Reference(p => p.Address).InverseReference(a => a.Resident) .ForeignKey(typeof(Address2), "PersonId")); } protected static void AddTestData(DbContext context) { var address1 = new Address { Street = "3 Dragons Way", City = "Meereen" }; var address2 = new Address { Street = "42 Castle Black", City = "The Wall" }; var address3 = new Address { Street = "House of Black and White", City = "Braavos" }; context.Set<Person>().AddRange(new Person { Name = "Daenerys Targaryen", Address = address1 }, new Person { Name = "John Snow", Address = address2 }, new Person { Name = "Arya Stark", Address = address3 }, new Person { Name = "Harry Strickland" }); context.Set<Address>().AddRange(address1, address2, address3); var address21 = new Address2 { Id = "1", Street = "3 Dragons Way", City = "Meereen" }; var address22 = new Address2 { Id = "2", Street = "42 Castle Black", City = "The Wall" }; var address23 = new Address2 { Id = "3", Street = "House of Black and White", City = "Braavos" }; context.Set<Person2>().AddRange(new Person2 { Name = "Daenerys Targaryen", Address = address21 }, new Person2 { Name = "John Snow", Address = address22 }, new Person2 { Name = "Arya Stark", Address = address23 }); context.Set<Address2>().AddRange(address21, address22, address23); context.SaveChanges(); } } public class Person { public int Id { get; set; } public string Name { get; set; } public Address Address { get; set; } } public class Address { public int Id { get; set; } public string Street { get; set; } public string City { get; set; } public Person Resident { get; set; } } public class Person2 { public int Id { get; set; } public string Name { get; set; } public Address2 Address { get; set; } } public class Address2 { public string Id { get; set; } public string Street { get; set; } public string City { get; set; } public Person2 Resident { get; set; } } }
39.891892
260
0.589431
[ "Apache-2.0" ]
craiggwilson/EntityFramework
test/EntityFramework.Core.FunctionalTests/OneToOneQueryFixtureBase.cs
2,952
C#
/* * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the cognito-sync-2014-06-30.normal.json service model. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Text; using System.Xml.Serialization; using Amazon.CognitoSync.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; using ThirdParty.Json.LitJson; namespace Amazon.CognitoSync.Model.Internal.MarshallTransformations { /// <summary> /// RegisterDevice Request Marshaller /// </summary> public class RegisterDeviceRequestMarshaller : IMarshaller<IRequest, RegisterDeviceRequest> , IMarshaller<IRequest,AmazonWebServiceRequest> { /// <summary> /// Marshaller the request object to the HTTP request. /// </summary> /// <param name="input"></param> /// <returns></returns> public IRequest Marshall(AmazonWebServiceRequest input) { return this.Marshall((RegisterDeviceRequest)input); } /// <summary> /// Marshaller the request object to the HTTP request. /// </summary> /// <param name="publicRequest"></param> /// <returns></returns> public IRequest Marshall(RegisterDeviceRequest publicRequest) { IRequest request = new DefaultRequest(publicRequest, "Amazon.CognitoSync"); request.Headers["Content-Type"] = "application/x-amz-json-1.1"; request.HttpMethod = "POST"; string uriResourcePath = "/identitypools/{IdentityPoolId}/identity/{IdentityId}/device"; if (!publicRequest.IsSetIdentityId()) throw new AmazonCognitoSyncException("Request object does not have required field IdentityId set"); uriResourcePath = uriResourcePath.Replace("{IdentityId}", StringUtils.FromString(publicRequest.IdentityId)); if (!publicRequest.IsSetIdentityPoolId()) throw new AmazonCognitoSyncException("Request object does not have required field IdentityPoolId set"); uriResourcePath = uriResourcePath.Replace("{IdentityPoolId}", StringUtils.FromString(publicRequest.IdentityPoolId)); request.ResourcePath = uriResourcePath; using (StringWriter stringWriter = new StringWriter(CultureInfo.InvariantCulture)) { JsonWriter writer = new JsonWriter(stringWriter); writer.WriteObjectStart(); var context = new JsonMarshallerContext(request, writer); if(publicRequest.IsSetPlatform()) { context.Writer.WritePropertyName("Platform"); context.Writer.Write(publicRequest.Platform); } if(publicRequest.IsSetToken()) { context.Writer.WritePropertyName("Token"); context.Writer.Write(publicRequest.Token); } writer.WriteObjectEnd(); string snippet = stringWriter.ToString(); request.Content = System.Text.Encoding.UTF8.GetBytes(snippet); } return request; } private static RegisterDeviceRequestMarshaller _instance = new RegisterDeviceRequestMarshaller(); internal static RegisterDeviceRequestMarshaller GetInstance() { return _instance; } /// <summary> /// Gets the singleton. /// </summary> public static RegisterDeviceRequestMarshaller Instance { get { return _instance; } } } }
38.157895
143
0.63908
[ "Apache-2.0" ]
GitGaby/aws-sdk-net
sdk/src/Services/CognitoSync/Generated/Model/Internal/MarshallTransformations/RegisterDeviceRequestMarshaller.cs
4,350
C#
using System; using System.Diagnostics; #pragma warning disable 1591 // ReSharper disable UnusedMember.Global // ReSharper disable MemberCanBePrivate.Global // ReSharper disable UnusedAutoPropertyAccessor.Global // ReSharper disable IntroduceOptionalParameters.Global // ReSharper disable MemberCanBeProtected.Global // ReSharper disable InconsistentNaming namespace Packager.Annotations { /// <summary> /// Indicates that the value of the marked element could be <c>null</c> sometimes, /// so the check for <c>null</c> is necessary before its usage /// </summary> /// <example><code> /// [CanBeNull] public object Test() { return null; } /// public void UseTest() { /// var p = Test(); /// var s = p.ToString(); // Warning: Possible 'System.NullReferenceException' /// } /// </code></example> [AttributeUsage( AttributeTargets.Method | AttributeTargets.Parameter | AttributeTargets.Property | AttributeTargets.Delegate | AttributeTargets.Field | AttributeTargets.Event)] [Conditional("JETBRAINS_ANNOTATIONS")] public sealed class CanBeNullAttribute : Attribute { } /// <summary> /// Indicates that the value of the marked element could never be <c>null</c> /// </summary> /// <example><code> /// [NotNull] public object Foo() { /// return null; // Warning: Possible 'null' assignment /// } /// </code></example> [AttributeUsage( AttributeTargets.Method | AttributeTargets.Parameter | AttributeTargets.Property | AttributeTargets.Delegate | AttributeTargets.Field | AttributeTargets.Event)] [Conditional("JETBRAINS_ANNOTATIONS")] public sealed class NotNullAttribute : Attribute { } /// <summary> /// Indicates that collection or enumerable value does not contain null elements /// </summary> [AttributeUsage( AttributeTargets.Method | AttributeTargets.Parameter | AttributeTargets.Property | AttributeTargets.Delegate | AttributeTargets.Field)] [Conditional("JETBRAINS_ANNOTATIONS")] public sealed class ItemNotNullAttribute : Attribute { } /// <summary> /// Indicates that collection or enumerable value can contain null elements /// </summary> [AttributeUsage( AttributeTargets.Method | AttributeTargets.Parameter | AttributeTargets.Property | AttributeTargets.Delegate | AttributeTargets.Field)] [Conditional("JETBRAINS_ANNOTATIONS")] public sealed class ItemCanBeNullAttribute : Attribute { } /// <summary> /// Indicates that the marked method builds string by format pattern and (optional) arguments. /// Parameter, which contains format string, should be given in constructor. The format string /// should be in <see cref="string.Format(IFormatProvider,string,object[])"/>-like form /// </summary> /// <example><code> /// [StringFormatMethod("message")] /// public void ShowError(string message, params object[] args) { /* do something */ } /// public void Foo() { /// ShowError("Failed: {0}"); // Warning: Non-existing argument in format string /// } /// </code></example> [AttributeUsage( AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Delegate)] [Conditional("JETBRAINS_ANNOTATIONS")] public sealed class StringFormatMethodAttribute : Attribute { /// <param name="formatParameterName"> /// Specifies which parameter of an annotated method should be treated as format-string /// </param> public StringFormatMethodAttribute(string formatParameterName) { FormatParameterName = formatParameterName; } public string FormatParameterName { get; private set; } } /// <summary> /// For a parameter that is expected to be one of the limited set of values. /// Specify fields of which type should be used as values for this parameter. /// </summary> [AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Property | AttributeTargets.Field)] [Conditional("JETBRAINS_ANNOTATIONS")] public sealed class ValueProviderAttribute : Attribute { public ValueProviderAttribute(string name) { Name = name; } [NotNull] public string Name { get; private set; } } /// <summary> /// Indicates that the function argument should be string literal and match one /// of the parameters of the caller function. For example, ReSharper annotates /// the parameter of <see cref="System.ArgumentNullException"/> /// </summary> /// <example><code> /// public void Foo(string param) { /// if (param == null) /// throw new ArgumentNullException("par"); // Warning: Cannot resolve symbol /// } /// </code></example> [AttributeUsage(AttributeTargets.Parameter)] [Conditional("JETBRAINS_ANNOTATIONS")] public sealed class InvokerParameterNameAttribute : Attribute { } /// <summary> /// Indicates that the method is contained in a type that implements /// <c>System.ComponentModel.INotifyPropertyChanged</c> interface and this method /// is used to notify that some property value changed /// </summary> /// <remarks> /// The method should be non-static and conform to one of the supported signatures: /// <list> /// <item><c>NotifyChanged(string)</c></item> /// <item><c>NotifyChanged(params string[])</c></item> /// <item><c>NotifyChanged{T}(Expression{Func{T}})</c></item> /// <item><c>NotifyChanged{T,U}(Expression{Func{T,U}})</c></item> /// <item><c>SetProperty{T}(ref T, T, string)</c></item> /// </list> /// </remarks> /// <example><code> /// public class Foo : INotifyPropertyChanged { /// public event PropertyChangedEventHandler PropertyChanged; /// [NotifyPropertyChangedInvocator] /// protected virtual void NotifyChanged(string propertyName) { ... } /// /// private string _name; /// public string Name { /// get { return _name; } /// set { _name = value; NotifyChanged("LastName"); /* Warning */ } /// } /// } /// </code> /// Examples of generated notifications: /// <list> /// <item><c>NotifyChanged("Property")</c></item> /// <item><c>NotifyChanged(() =&gt; Property)</c></item> /// <item><c>NotifyChanged((VM x) =&gt; x.Property)</c></item> /// <item><c>SetProperty(ref myField, value, "Property")</c></item> /// </list> /// </example> [AttributeUsage(AttributeTargets.Method)] [Conditional("JETBRAINS_ANNOTATIONS")] public sealed class NotifyPropertyChangedInvocatorAttribute : Attribute { public NotifyPropertyChangedInvocatorAttribute() { } public NotifyPropertyChangedInvocatorAttribute(string parameterName) { ParameterName = parameterName; } public string ParameterName { get; private set; } } /// <summary> /// Describes dependency between method input and output /// </summary> /// <syntax> /// <p>Function Definition Table syntax:</p> /// <list> /// <item>FDT ::= FDTRow [;FDTRow]*</item> /// <item>FDTRow ::= Input =&gt; Output | Output &lt;= Input</item> /// <item>Input ::= ParameterName: Value [, Input]*</item> /// <item>Output ::= [ParameterName: Value]* {halt|stop|void|nothing|Value}</item> /// <item>Value ::= true | false | null | notnull | canbenull</item> /// </list> /// If method has single input parameter, it's name could be omitted.<br/> /// Using <c>halt</c> (or <c>void</c>/<c>nothing</c>, which is the same) /// for method output means that the methos doesn't return normally.<br/> /// <c>canbenull</c> annotation is only applicable for output parameters.<br/> /// You can use multiple <c>[ContractAnnotation]</c> for each FDT row, /// or use single attribute with rows separated by semicolon.<br/> /// </syntax> /// <examples><list> /// <item><code> /// [ContractAnnotation("=> halt")] /// public void TerminationMethod() /// </code></item> /// <item><code> /// [ContractAnnotation("halt &lt;= condition: false")] /// public void Assert(bool condition, string text) // regular assertion method /// </code></item> /// <item><code> /// [ContractAnnotation("s:null => true")] /// public bool IsNullOrEmpty(string s) // string.IsNullOrEmpty() /// </code></item> /// <item><code> /// // A method that returns null if the parameter is null, /// // and not null if the parameter is not null /// [ContractAnnotation("null => null; notnull => notnull")] /// public object Transform(object data) /// </code></item> /// <item><code> /// [ContractAnnotation("s:null=>false; =>true,result:notnull; =>false, result:null")] /// public bool TryParse(string s, out Person result) /// </code></item> /// </list></examples> [AttributeUsage(AttributeTargets.Method, AllowMultiple = true)] [Conditional("JETBRAINS_ANNOTATIONS")] public sealed class ContractAnnotationAttribute : Attribute { public ContractAnnotationAttribute([NotNull] string contract) : this(contract, false) { } public ContractAnnotationAttribute([NotNull] string contract, bool forceFullStates) { Contract = contract; ForceFullStates = forceFullStates; } public string Contract { get; private set; } public bool ForceFullStates { get; private set; } } /// <summary> /// Indicates that marked element should be localized or not /// </summary> /// <example><code> /// [LocalizationRequiredAttribute(true)] /// public class Foo { /// private string str = "my string"; // Warning: Localizable string /// } /// </code></example> [AttributeUsage(AttributeTargets.All)] [Conditional("JETBRAINS_ANNOTATIONS")] public sealed class LocalizationRequiredAttribute : Attribute { public LocalizationRequiredAttribute() : this(true) { } public LocalizationRequiredAttribute(bool required) { Required = required; } public bool Required { get; private set; } } /// <summary> /// Indicates that the value of the marked type (or its derivatives) /// cannot be compared using '==' or '!=' operators and <c>Equals()</c> /// should be used instead. However, using '==' or '!=' for comparison /// with <c>null</c> is always permitted. /// </summary> /// <example><code> /// [CannotApplyEqualityOperator] /// class NoEquality { } /// class UsesNoEquality { /// public void Test() { /// var ca1 = new NoEquality(); /// var ca2 = new NoEquality(); /// if (ca1 != null) { // OK /// bool condition = ca1 == ca2; // Warning /// } /// } /// } /// </code></example> [AttributeUsage( AttributeTargets.Interface | AttributeTargets.Class | AttributeTargets.Struct)] [Conditional("JETBRAINS_ANNOTATIONS")] public sealed class CannotApplyEqualityOperatorAttribute : Attribute { } /// <summary> /// When applied to a target attribute, specifies a requirement for any type marked /// with the target attribute to implement or inherit specific type or types. /// </summary> /// <example><code> /// [BaseTypeRequired(typeof(IComponent)] // Specify requirement /// public class ComponentAttribute : Attribute { } /// [Component] // ComponentAttribute requires implementing IComponent interface /// public class MyComponent : IComponent { } /// </code></example> [AttributeUsage(AttributeTargets.Class, AllowMultiple = true)] [BaseTypeRequired(typeof(Attribute))] [Conditional("JETBRAINS_ANNOTATIONS")] public sealed class BaseTypeRequiredAttribute : Attribute { public BaseTypeRequiredAttribute([NotNull] Type baseType) { BaseType = baseType; } [NotNull] public Type BaseType { get; private set; } } /// <summary> /// Indicates that the marked symbol is used implicitly /// (e.g. via reflection, in external library), so this symbol /// will not be marked as unused (as well as by other usage inspections) /// </summary> [AttributeUsage(AttributeTargets.All)] [Conditional("JETBRAINS_ANNOTATIONS")] public sealed class UsedImplicitlyAttribute : Attribute { public UsedImplicitlyAttribute() : this(ImplicitUseKindFlags.Default, ImplicitUseTargetFlags.Default) { } public UsedImplicitlyAttribute(ImplicitUseKindFlags useKindFlags) : this(useKindFlags, ImplicitUseTargetFlags.Default) { } public UsedImplicitlyAttribute(ImplicitUseTargetFlags targetFlags) : this(ImplicitUseKindFlags.Default, targetFlags) { } public UsedImplicitlyAttribute( ImplicitUseKindFlags useKindFlags, ImplicitUseTargetFlags targetFlags) { UseKindFlags = useKindFlags; TargetFlags = targetFlags; } public ImplicitUseKindFlags UseKindFlags { get; private set; } public ImplicitUseTargetFlags TargetFlags { get; private set; } } /// <summary> /// Should be used on attributes and causes ReSharper /// to not mark symbols marked with such attributes as unused /// (as well as by other usage inspections) /// </summary> [AttributeUsage(AttributeTargets.Class | AttributeTargets.GenericParameter)] [Conditional("JETBRAINS_ANNOTATIONS")] public sealed class MeansImplicitUseAttribute : Attribute { public MeansImplicitUseAttribute() : this(ImplicitUseKindFlags.Default, ImplicitUseTargetFlags.Default) { } public MeansImplicitUseAttribute(ImplicitUseKindFlags useKindFlags) : this(useKindFlags, ImplicitUseTargetFlags.Default) { } public MeansImplicitUseAttribute(ImplicitUseTargetFlags targetFlags) : this(ImplicitUseKindFlags.Default, targetFlags) { } public MeansImplicitUseAttribute( ImplicitUseKindFlags useKindFlags, ImplicitUseTargetFlags targetFlags) { UseKindFlags = useKindFlags; TargetFlags = targetFlags; } [UsedImplicitly] public ImplicitUseKindFlags UseKindFlags { get; private set; } [UsedImplicitly] public ImplicitUseTargetFlags TargetFlags { get; private set; } } [Flags] public enum ImplicitUseKindFlags { Default = Access | Assign | InstantiatedWithFixedConstructorSignature, /// <summary>Only entity marked with attribute considered used</summary> Access = 1, /// <summary>Indicates implicit assignment to a member</summary> Assign = 2, /// <summary> /// Indicates implicit instantiation of a type with fixed constructor signature. /// That means any unused constructor parameters won't be reported as such. /// </summary> InstantiatedWithFixedConstructorSignature = 4, /// <summary>Indicates implicit instantiation of a type</summary> InstantiatedNoFixedConstructorSignature = 8, } /// <summary> /// Specify what is considered used implicitly when marked /// with <see cref="MeansImplicitUseAttribute"/> or <see cref="UsedImplicitlyAttribute"/> /// </summary> [Flags] public enum ImplicitUseTargetFlags { Default = Itself, Itself = 1, /// <summary>Members of entity marked with attribute are considered used</summary> Members = 2, /// <summary>Entity marked with attribute and all its members considered used</summary> WithMembers = Itself | Members } /// <summary> /// This attribute is intended to mark publicly available API /// which should not be removed and so is treated as used /// </summary> [MeansImplicitUse] [Conditional("JETBRAINS_ANNOTATIONS")] public sealed class PublicAPIAttribute : Attribute { public PublicAPIAttribute() { } public PublicAPIAttribute([NotNull] string comment) { Comment = comment; } public string Comment { get; private set; } } /// <summary> /// Tells code analysis engine if the parameter is completely handled /// when the invoked method is on stack. If the parameter is a delegate, /// indicates that delegate is executed while the method is executed. /// If the parameter is an enumerable, indicates that it is enumerated /// while the method is executed /// </summary> [AttributeUsage(AttributeTargets.Parameter)] [Conditional("JETBRAINS_ANNOTATIONS")] public sealed class InstantHandleAttribute : Attribute { } /// <summary> /// Indicates that a method does not make any observable state changes. /// The same as <c>System.Diagnostics.Contracts.PureAttribute</c> /// </summary> /// <example><code> /// [Pure] private int Multiply(int x, int y) { return x * y; } /// public void Foo() { /// const int a = 2, b = 2; /// Multiply(a, b); // Waring: Return value of pure method is not used /// } /// </code></example> [AttributeUsage(AttributeTargets.Method)] [Conditional("JETBRAINS_ANNOTATIONS")] public sealed class PureAttribute : Attribute { } /// <summary> /// Indicates that a parameter is a path to a file or a folder within a web project. /// Path can be relative or absolute, starting from web root (~) /// </summary> [AttributeUsage(AttributeTargets.Parameter)] [Conditional("JETBRAINS_ANNOTATIONS")] public class PathReferenceAttribute : Attribute { public PathReferenceAttribute() { } public PathReferenceAttribute([PathReference] string basePath) { BasePath = basePath; } public string BasePath { get; private set; } } [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)] [Conditional("JETBRAINS_ANNOTATIONS")] public sealed class AspMvcAreaMasterLocationFormatAttribute : Attribute { public AspMvcAreaMasterLocationFormatAttribute(string format) { Format = format; } public string Format { get; private set; } } [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)] [Conditional("JETBRAINS_ANNOTATIONS")] public sealed class AspMvcAreaPartialViewLocationFormatAttribute : Attribute { public AspMvcAreaPartialViewLocationFormatAttribute(string format) { Format = format; } public string Format { get; private set; } } [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)] [Conditional("JETBRAINS_ANNOTATIONS")] public sealed class AspMvcAreaViewLocationFormatAttribute : Attribute { public AspMvcAreaViewLocationFormatAttribute(string format) { Format = format; } public string Format { get; private set; } } [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)] [Conditional("JETBRAINS_ANNOTATIONS")] public sealed class AspMvcMasterLocationFormatAttribute : Attribute { public AspMvcMasterLocationFormatAttribute(string format) { Format = format; } public string Format { get; private set; } } [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)] [Conditional("JETBRAINS_ANNOTATIONS")] public sealed class AspMvcPartialViewLocationFormatAttribute : Attribute { public AspMvcPartialViewLocationFormatAttribute(string format) { Format = format; } public string Format { get; private set; } } [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)] [Conditional("JETBRAINS_ANNOTATIONS")] public sealed class AspMvcViewLocationFormatAttribute : Attribute { public AspMvcViewLocationFormatAttribute(string format) { Format = format; } public string Format { get; private set; } } /// <summary> /// ASP.NET MVC attribute. If applied to a parameter, indicates that the parameter /// is an MVC action. If applied to a method, the MVC action name is calculated /// implicitly from the context. Use this attribute for custom wrappers similar to /// <c>System.Web.Mvc.Html.ChildActionExtensions.RenderAction(HtmlHelper, String)</c> /// </summary> [AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Method)] [Conditional("JETBRAINS_ANNOTATIONS")] public sealed class AspMvcActionAttribute : Attribute { public AspMvcActionAttribute() { } public AspMvcActionAttribute(string anonymousProperty) { AnonymousProperty = anonymousProperty; } public string AnonymousProperty { get; private set; } } /// <summary> /// ASP.NET MVC attribute. Indicates that a parameter is an MVC area. /// Use this attribute for custom wrappers similar to /// <c>System.Web.Mvc.Html.ChildActionExtensions.RenderAction(HtmlHelper, String)</c> /// </summary> [AttributeUsage(AttributeTargets.Parameter)] [Conditional("JETBRAINS_ANNOTATIONS")] public sealed class AspMvcAreaAttribute : PathReferenceAttribute { public AspMvcAreaAttribute() { } public AspMvcAreaAttribute(string anonymousProperty) { AnonymousProperty = anonymousProperty; } public string AnonymousProperty { get; private set; } } /// <summary> /// ASP.NET MVC attribute. If applied to a parameter, indicates that the parameter is /// an MVC controller. If applied to a method, the MVC controller name is calculated /// implicitly from the context. Use this attribute for custom wrappers similar to /// <c>System.Web.Mvc.Html.ChildActionExtensions.RenderAction(HtmlHelper, String, String)</c> /// </summary> [AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Method)] [Conditional("JETBRAINS_ANNOTATIONS")] public sealed class AspMvcControllerAttribute : Attribute { public AspMvcControllerAttribute() { } public AspMvcControllerAttribute(string anonymousProperty) { AnonymousProperty = anonymousProperty; } public string AnonymousProperty { get; private set; } } /// <summary> /// ASP.NET MVC attribute. Indicates that a parameter is an MVC Master. Use this attribute /// for custom wrappers similar to <c>System.Web.Mvc.Controller.View(String, String)</c> /// </summary> [AttributeUsage(AttributeTargets.Parameter)] [Conditional("JETBRAINS_ANNOTATIONS")] public sealed class AspMvcMasterAttribute : Attribute { } /// <summary> /// ASP.NET MVC attribute. Indicates that a parameter is an MVC model type. Use this attribute /// for custom wrappers similar to <c>System.Web.Mvc.Controller.View(String, Object)</c> /// </summary> [AttributeUsage(AttributeTargets.Parameter)] [Conditional("JETBRAINS_ANNOTATIONS")] public sealed class AspMvcModelTypeAttribute : Attribute { } /// <summary> /// ASP.NET MVC attribute. If applied to a parameter, indicates that the parameter is an MVC /// partial view. If applied to a method, the MVC partial view name is calculated implicitly /// from the context. Use this attribute for custom wrappers similar to /// <c>System.Web.Mvc.Html.RenderPartialExtensions.RenderPartial(HtmlHelper, String)</c> /// </summary> [AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Method)] [Conditional("JETBRAINS_ANNOTATIONS")] public sealed class AspMvcPartialViewAttribute : PathReferenceAttribute { } /// <summary> /// ASP.NET MVC attribute. Allows disabling inspections for MVC views within a class or a method /// </summary> [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)] [Conditional("JETBRAINS_ANNOTATIONS")] public sealed class AspMvcSupressViewErrorAttribute : Attribute { } /// <summary> /// ASP.NET MVC attribute. Indicates that a parameter is an MVC display template. /// Use this attribute for custom wrappers similar to /// <c>System.Web.Mvc.Html.DisplayExtensions.DisplayForModel(HtmlHelper, String)</c> /// </summary> [AttributeUsage(AttributeTargets.Parameter)] [Conditional("JETBRAINS_ANNOTATIONS")] public sealed class AspMvcDisplayTemplateAttribute : Attribute { } /// <summary> /// ASP.NET MVC attribute. Indicates that a parameter is an MVC editor template. /// Use this attribute for custom wrappers similar to /// <c>System.Web.Mvc.Html.EditorExtensions.EditorForModel(HtmlHelper, String)</c> /// </summary> [AttributeUsage(AttributeTargets.Parameter)] [Conditional("JETBRAINS_ANNOTATIONS")] public sealed class AspMvcEditorTemplateAttribute : Attribute { } /// <summary> /// ASP.NET MVC attribute. Indicates that a parameter is an MVC template. /// Use this attribute for custom wrappers similar to /// <c>System.ComponentModel.DataAnnotations.UIHintAttribute(System.String)</c> /// </summary> [AttributeUsage(AttributeTargets.Parameter)] [Conditional("JETBRAINS_ANNOTATIONS")] public sealed class AspMvcTemplateAttribute : Attribute { } /// <summary> /// ASP.NET MVC attribute. If applied to a parameter, indicates that the parameter /// is an MVC view. If applied to a method, the MVC view name is calculated implicitly /// from the context. Use this attribute for custom wrappers similar to /// <c>System.Web.Mvc.Controller.View(Object)</c> /// </summary> [AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Method)] [Conditional("JETBRAINS_ANNOTATIONS")] public sealed class AspMvcViewAttribute : PathReferenceAttribute { } /// <summary> /// ASP.NET MVC attribute. When applied to a parameter of an attribute, /// indicates that this parameter is an MVC action name /// </summary> /// <example><code> /// [ActionName("Foo")] /// public ActionResult Login(string returnUrl) { /// ViewBag.ReturnUrl = Url.Action("Foo"); // OK /// return RedirectToAction("Bar"); // Error: Cannot resolve action /// } /// </code></example> [AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Property)] [Conditional("JETBRAINS_ANNOTATIONS")] public sealed class AspMvcActionSelectorAttribute : Attribute { } [AttributeUsage( AttributeTargets.Parameter | AttributeTargets.Property | AttributeTargets.Field)] [Conditional("JETBRAINS_ANNOTATIONS")] public sealed class HtmlElementAttributesAttribute : Attribute { public HtmlElementAttributesAttribute() { } public HtmlElementAttributesAttribute(string name) { Name = name; } public string Name { get; private set; } } [AttributeUsage( AttributeTargets.Parameter | AttributeTargets.Field | AttributeTargets.Property)] [Conditional("JETBRAINS_ANNOTATIONS")] public sealed class HtmlAttributeValueAttribute : Attribute { public HtmlAttributeValueAttribute([NotNull] string name) { Name = name; } [NotNull] public string Name { get; private set; } } /// <summary> /// Razor attribute. Indicates that a parameter or a method is a Razor section. /// Use this attribute for custom wrappers similar to /// <c>System.Web.WebPages.WebPageBase.RenderSection(String)</c> /// </summary> [AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Method)] [Conditional("JETBRAINS_ANNOTATIONS")] public sealed class RazorSectionAttribute : Attribute { } /// <summary> /// Indicates how method invocation affects content of the collection /// </summary> [AttributeUsage(AttributeTargets.Method)] [Conditional("JETBRAINS_ANNOTATIONS")] public sealed class CollectionAccessAttribute : Attribute { public CollectionAccessAttribute(CollectionAccessType collectionAccessType) { CollectionAccessType = collectionAccessType; } public CollectionAccessType CollectionAccessType { get; private set; } } [Flags] public enum CollectionAccessType { /// <summary>Method does not use or modify content of the collection</summary> None = 0, /// <summary>Method only reads content of the collection but does not modify it</summary> Read = 1, /// <summary>Method can change content of the collection but does not add new elements</summary> ModifyExistingContent = 2, /// <summary>Method can add new elements to the collection</summary> UpdatedContent = ModifyExistingContent | 4 } /// <summary> /// Indicates that the marked method is assertion method, i.e. it halts control flow if /// one of the conditions is satisfied. To set the condition, mark one of the parameters with /// <see cref="AssertionConditionAttribute"/> attribute /// </summary> [AttributeUsage(AttributeTargets.Method)] [Conditional("JETBRAINS_ANNOTATIONS")] public sealed class AssertionMethodAttribute : Attribute { } /// <summary> /// Indicates the condition parameter of the assertion method. The method itself should be /// marked by <see cref="AssertionMethodAttribute"/> attribute. The mandatory argument of /// the attribute is the assertion type. /// </summary> [AttributeUsage(AttributeTargets.Parameter)] [Conditional("JETBRAINS_ANNOTATIONS")] public sealed class AssertionConditionAttribute : Attribute { public AssertionConditionAttribute(AssertionConditionType conditionType) { ConditionType = conditionType; } public AssertionConditionType ConditionType { get; private set; } } /// <summary> /// Specifies assertion type. If the assertion method argument satisfies the condition, /// then the execution continues. Otherwise, execution is assumed to be halted /// </summary> public enum AssertionConditionType { /// <summary>Marked parameter should be evaluated to true</summary> IS_TRUE = 0, /// <summary>Marked parameter should be evaluated to false</summary> IS_FALSE = 1, /// <summary>Marked parameter should be evaluated to null value</summary> IS_NULL = 2, /// <summary>Marked parameter should be evaluated to not null value</summary> IS_NOT_NULL = 3, } /// <summary> /// Indicates that the marked method unconditionally terminates control flow execution. /// For example, it could unconditionally throw exception /// </summary> [Obsolete("Use [ContractAnnotation('=> halt')] instead")] [AttributeUsage(AttributeTargets.Method)] [Conditional("JETBRAINS_ANNOTATIONS")] public sealed class TerminatesProgramAttribute : Attribute { } /// <summary> /// Indicates that method is pure LINQ method, with postponed enumeration (like Enumerable.Select, /// .Where). This annotation allows inference of [InstantHandle] annotation for parameters /// of delegate type by analyzing LINQ method chains. /// </summary> [AttributeUsage(AttributeTargets.Method)] [Conditional("JETBRAINS_ANNOTATIONS")] public sealed class LinqTunnelAttribute : Attribute { } /// <summary> /// Indicates that IEnumerable, passed as parameter, is not enumerated. /// </summary> [AttributeUsage(AttributeTargets.Parameter)] [Conditional("JETBRAINS_ANNOTATIONS")] public sealed class NoEnumerationAttribute : Attribute { } /// <summary> /// Indicates that parameter is regular expression pattern. /// </summary> [AttributeUsage(AttributeTargets.Parameter)] [Conditional("JETBRAINS_ANNOTATIONS")] public sealed class RegexPatternAttribute : Attribute { } /// <summary> /// XAML attribute. Indicates the type that has <c>ItemsSource</c> property and should be /// treated as <c>ItemsControl</c>-derived type, to enable inner items <c>DataContext</c> /// type resolve. /// </summary> [AttributeUsage(AttributeTargets.Class)] [Conditional("JETBRAINS_ANNOTATIONS")] public sealed class XamlItemsControlAttribute : Attribute { } /// <summary> /// XAML attibute. Indicates the property of some <c>BindingBase</c>-derived type, that /// is used to bind some item of <c>ItemsControl</c>-derived type. This annotation will /// enable the <c>DataContext</c> type resolve for XAML bindings for such properties. /// </summary> /// <remarks> /// Property should have the tree ancestor of the <c>ItemsControl</c> type or /// marked with the <see cref="XamlItemsControlAttribute"/> attribute. /// </remarks> [AttributeUsage(AttributeTargets.Property)] [Conditional("JETBRAINS_ANNOTATIONS")] public sealed class XamlItemBindingOfItemsControlAttribute : Attribute { } [AttributeUsage(AttributeTargets.Class, AllowMultiple = true)] [Conditional("JETBRAINS_ANNOTATIONS")] public sealed class AspChildControlTypeAttribute : Attribute { public AspChildControlTypeAttribute(string tagName, Type controlType) { TagName = tagName; ControlType = controlType; } public string TagName { get; private set; } public Type ControlType { get; private set; } } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Method)] [Conditional("JETBRAINS_ANNOTATIONS")] public sealed class AspDataFieldAttribute : Attribute { } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Method)] [Conditional("JETBRAINS_ANNOTATIONS")] public sealed class AspDataFieldsAttribute : Attribute { } [AttributeUsage(AttributeTargets.Property)] [Conditional("JETBRAINS_ANNOTATIONS")] public sealed class AspMethodPropertyAttribute : Attribute { } [AttributeUsage(AttributeTargets.Class, AllowMultiple = true)] [Conditional("JETBRAINS_ANNOTATIONS")] public sealed class AspRequiredAttributeAttribute : Attribute { public AspRequiredAttributeAttribute([NotNull] string attribute) { Attribute = attribute; } public string Attribute { get; private set; } } [AttributeUsage(AttributeTargets.Property)] [Conditional("JETBRAINS_ANNOTATIONS")] public sealed class AspTypePropertyAttribute : Attribute { public bool CreateConstructorReferences { get; private set; } public AspTypePropertyAttribute(bool createConstructorReferences) { CreateConstructorReferences = createConstructorReferences; } } [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)] [Conditional("JETBRAINS_ANNOTATIONS")] public sealed class RazorImportNamespaceAttribute : Attribute { public RazorImportNamespaceAttribute(string name) { Name = name; } public string Name { get; private set; } } [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)] [Conditional("JETBRAINS_ANNOTATIONS")] public sealed class RazorInjectionAttribute : Attribute { public RazorInjectionAttribute(string type, string fieldName) { Type = type; FieldName = fieldName; } public string Type { get; private set; } public string FieldName { get; private set; } } [AttributeUsage(AttributeTargets.Method)] [Conditional("JETBRAINS_ANNOTATIONS")] public sealed class RazorHelperCommonAttribute : Attribute { } [AttributeUsage(AttributeTargets.Property)] [Conditional("JETBRAINS_ANNOTATIONS")] public sealed class RazorLayoutAttribute : Attribute { } [AttributeUsage(AttributeTargets.Method)] [Conditional("JETBRAINS_ANNOTATIONS")] public sealed class RazorWriteLiteralMethodAttribute : Attribute { } [AttributeUsage(AttributeTargets.Method)] [Conditional("JETBRAINS_ANNOTATIONS")] public sealed class RazorWriteMethodAttribute : Attribute { } [AttributeUsage(AttributeTargets.Parameter)] [Conditional("JETBRAINS_ANNOTATIONS")] public sealed class RazorWriteMethodParameterAttribute : Attribute { } /// <summary> /// Prevents the Member Reordering feature from tossing members of the marked class. /// </summary> /// <remarks> /// The attribute must be mentioned in your member reordering patterns. /// </remarks> [AttributeUsage(AttributeTargets.All)] [Conditional("JETBRAINS_ANNOTATIONS")] public sealed class NoReorder : Attribute { } }
37.576509
100
0.713229
[ "Apache-2.0" ]
BrianMcGough/IUMediaHelperApps
Packager/Properties/Annotations.cs
34,873
C#
namespace WebAPIPeliculas.DTOS { public class RefaccionariaDTO { public int Id { get; set; } public string Nombre { get; set; } public double Latitud { get; set; } public double Longitud { get; set; } } }
22.727273
44
0.588
[ "MIT" ]
NSysX/CursoEF6
WebAPIPeliculas/WebAPIPeliculas/DTOS/RefaccionariaDTO.cs
252
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.Windows.Forms; using bugcLibrary.libraries; namespace bugcLibrary { static class Program { /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new LoginForm()); } } }
22.625
65
0.627993
[ "MIT" ]
EleaFederio/BiometricAttendance
bugcLibrary/Program.cs
545
C#
#region copyright // ----------------------------------------------------------------------- // <copyright file="TypeEx.cs" company="Akka.NET Team"> // Copyright (C) 2015-2016 AsynkronIT <https://github.com/AsynkronIT> // Copyright (C) 2016-2016 Akka.NET Team <https://github.com/akkadotnet> // </copyright> // ----------------------------------------------------------------------- #endregion using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Collections.ObjectModel; using System.IO; using System.Linq; using System.Reflection; using System.Text.RegularExpressions; using Hyperion.Internal; namespace Hyperion.Extensions { internal static class TypeEx { //Why not inline typeof you ask? //Because it actually generates calls to get the type. //We prefetch all primitives here public static readonly Type SystemObject = typeof(object); public static readonly Type Int32Type = typeof(int); public static readonly Type Int64Type = typeof(long); public static readonly Type Int16Type = typeof(short); public static readonly Type UInt32Type = typeof(uint); public static readonly Type UInt64Type = typeof(ulong); public static readonly Type UInt16Type = typeof(ushort); public static readonly Type ByteType = typeof(byte); public static readonly Type SByteType = typeof(sbyte); public static readonly Type BoolType = typeof(bool); public static readonly Type DateTimeType = typeof(DateTime); public static readonly Type DateTimeOffsetType = typeof(DateTimeOffset); public static readonly Type StringType = typeof(string); public static readonly Type GuidType = typeof(Guid); public static readonly Type FloatType = typeof(float); public static readonly Type DoubleType = typeof(double); public static readonly Type DecimalType = typeof(decimal); public static readonly Type CharType = typeof(char); public static readonly Type ByteArrayType = typeof(byte[]); public static readonly Type TypeType = typeof(Type); public static readonly Type RuntimeType = Type.GetType("System.RuntimeType"); private static readonly ReadOnlyCollection<string> UnsafeTypesDenySet = new ReadOnlyCollection<string>(new[] { "System.Security.Claims.ClaimsIdentity", "System.Windows.Forms.AxHost.State", "System.Windows.Data.ObjectDataProvider", "System.Management.Automation.PSObject", "System.Web.Security.RolePrincipal", "System.IdentityModel.Tokens.SessionSecurityToken", "SessionViewStateHistoryItem", "TextFormattingRunProperties", "ToolboxItemContainer", "System.Security.Principal.WindowsClaimsIdentity", "System.Security.Principal.WindowsIdentity", "System.Security.Principal.WindowsPrincipal", "System.CodeDom.Compiler.TempFileCollection", "System.IO.FileSystemInfo", "System.Activities.Presentation.WorkflowDesigner", "System.Windows.ResourceDictionary", "System.Windows.Forms.BindingSource", "Microsoft.Exchange.Management.SystemManager.WinForms.ExchangeSettingsProvider", "System.Diagnostics.Process", "System.Management.IWbemClassObjectFreeThreaded" }); public static bool IsHyperionPrimitive(this Type type) { return type == Int32Type || type == Int64Type || type == Int16Type || type == UInt32Type || type == UInt64Type || type == UInt16Type || type == ByteType || type == SByteType || type == DateTimeType || type == DateTimeOffsetType || type == BoolType || type == StringType || type == GuidType || type == FloatType || type == DoubleType || type == DecimalType || type == CharType; //add TypeSerializer with null support } #if NETSTANDARD16 //HACK: IsValueType does not exist for netstandard1.6 private static bool IsValueType(this Type type) => type.IsSubclassOf(typeof(ValueType)); private static bool IsSubclassOf(this Type p, Type c) => c.IsAssignableFrom(p); //HACK: the GetUnitializedObject actually exists in .NET Core, its just not public private static readonly Func<Type, object> GetUninitializedObjectDelegate = (Func<Type, object>) typeof(string) .GetTypeInfo() .Assembly .GetType("System.Runtime.Serialization.FormatterServices") ?.GetTypeInfo() ?.GetMethod("GetUninitializedObject", BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static) ?.CreateDelegate(typeof(Func<Type, object>)); public static object GetEmptyObject(this Type type) { return GetUninitializedObjectDelegate(type); } #else public static object GetEmptyObject(this Type type) => System.Runtime.Serialization.FormatterServices.GetUninitializedObject(type); #endif public static bool IsOneDimensionalArray(this Type type) { return type.IsArray && type.GetArrayRank() == 1; } public static bool IsOneDimensionalPrimitiveArray(this Type type) { return type.IsArray && type.GetArrayRank() == 1 && type.GetElementType().IsHyperionPrimitive(); } private static readonly ConcurrentDictionary<ByteArrayKey, Type> TypeNameLookup = new ConcurrentDictionary<ByteArrayKey, Type>(ByteArrayKeyComparer.Instance); public static byte[] GetTypeManifest(IReadOnlyCollection<byte[]> fieldNames) { IEnumerable<byte> result = new[] { (byte)fieldNames.Count }; foreach (var name in fieldNames) { var encodedLength = BitConverter.GetBytes(name.Length); result = result.Concat(encodedLength); result = result.Concat(name); } var versionTolerantHeader = result.ToArray(); return versionTolerantHeader; } private static Type GetTypeFromManifestName(Stream stream, DeserializerSession session) { var bytes = stream.ReadLengthEncodedByteArray(session); var byteArr = ByteArrayKey.Create(bytes); return TypeNameLookup.GetOrAdd(byteArr, b => { var shortName = StringEx.FromUtf8Bytes(b.Bytes, 0, b.Bytes.Length); var overrides = session.Serializer.Options.CrossFrameworkPackageNameOverrides; var oldName = shortName; foreach (var adapter in overrides) { shortName = adapter(shortName); if (!ReferenceEquals(oldName, shortName)) break; } return LoadTypeByName(shortName, session.Serializer.Options.DisallowUnsafeTypes); }); } private static bool UnsafeInheritanceCheck(Type type) { #if NETSTANDARD1_6 if (type.IsValueType()) return false; var currentBase = type.DeclaringType; #else if (type.IsValueType) return false; var currentBase = type.BaseType; #endif while (currentBase != null) { if (UnsafeTypesDenySet.Any(r => currentBase.FullName?.Contains(r) ?? false)) return true; #if NETSTANDARD1_6 currentBase = currentBase.DeclaringType; #else currentBase = currentBase.BaseType; #endif } return false; } public static Type LoadTypeByName(string name, bool disallowUnsafeTypes) { if (disallowUnsafeTypes && UnsafeTypesDenySet.Any(name.Contains)) { throw new EvilDeserializationException( "Unsafe Type Deserialization Detected!", name); } try { // Try to load type name using strict version to avoid possible conflicts // i.e. if there are different version available in GAC and locally var typename = ToQualifiedAssemblyName(name, ignoreAssemblyVersion: false); var type = Type.GetType(typename, true); if (UnsafeInheritanceCheck(type)) throw new EvilDeserializationException( "Unsafe Type Deserialization Detected!", name); return type; } catch (FileLoadException) { var typename = ToQualifiedAssemblyName(name, ignoreAssemblyVersion: true); var type = Type.GetType(typename, true); if (UnsafeInheritanceCheck(type)) throw new EvilDeserializationException( "Unsafe Type Deserialization Detected!", name); return type; } } public static Type GetTypeFromManifestFull(Stream stream, DeserializerSession session) { var type = GetTypeFromManifestName(stream, session); session.TrackDeserializedType(type); return type; } public static Type GetTypeFromManifestVersion(Stream stream, DeserializerSession session) { var type = GetTypeFromManifestName(stream, session); var fieldCount = stream.ReadByte(); for (var i = 0; i < fieldCount; i++) { var fieldName = stream.ReadLengthEncodedByteArray(session); } session.TrackDeserializedTypeWithVersion(type, null); return type; } public static Type GetTypeFromManifestIndex(int typeId, DeserializerSession session) { var type = session.GetTypeFromTypeId(typeId); return type; } public static bool IsNullable(this Type type) { return type.GetTypeInfo().IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>); } public static Type GetNullableElement(this Type type) { return type.GetTypeInfo().GetGenericArguments()[0]; } public static bool IsFixedSizeType(this Type type) { return type == Int16Type || type == Int32Type || type == Int64Type || type == BoolType || type == UInt16Type || type == UInt32Type || type == UInt64Type || type == CharType; } public static int GetTypeSize(this Type type) { if (type == Int16Type) return sizeof(short); if (type == Int32Type) return sizeof (int); if (type == Int64Type) return sizeof (long); if (type == BoolType) return sizeof (bool); if (type == UInt16Type) return sizeof (ushort); if (type == UInt32Type) return sizeof (uint); if (type == UInt64Type) return sizeof (ulong); if (type == CharType) return sizeof(char); throw new NotSupportedException(); } private static readonly string CoreAssemblyQualifiedName = 1.GetType().AssemblyQualifiedName; private static readonly string CoreAssemblyName = GetCoreAssemblyName(); private static readonly Regex cleanAssemblyVersionRegex = new Regex( "(, Version=([\\d\\.]+))?(, Culture=[^,\\] \\t]+)?(, PublicKeyToken=(null|[\\da-f]+))?", RegexOptions.Compiled | RegexOptions.CultureInvariant | RegexOptions.IgnoreCase); private static string GetCoreAssemblyName() { var part = CoreAssemblyQualifiedName.Substring(CoreAssemblyQualifiedName.IndexOf(", Version", StringComparison.Ordinal)); return part; } public static string GetShortAssemblyQualifiedName(this Type self) { var name = self.AssemblyQualifiedName; name = name.Replace(CoreAssemblyName, ",%core%"); name = cleanAssemblyVersionRegex.Replace(name, string.Empty); return name; } public static string ToQualifiedAssemblyName(string shortName, bool ignoreAssemblyVersion) { // Strip out assembly version, if specified if (ignoreAssemblyVersion) { shortName = cleanAssemblyVersionRegex.Replace(shortName, string.Empty); } var res = shortName.Replace(",%core%", CoreAssemblyName); return res; } /// <summary> /// Search for a method by name, parameter types, and binding flags. /// Unlike GetMethod(), does 'loose' matching on generic /// parameter types, and searches base interfaces. /// </summary> /// <exception cref="AmbiguousMatchException"/> public static MethodInfo GetMethodExt(this Type thisType, string name, BindingFlags bindingFlags, params Type[] parameterTypes) { MethodInfo matchingMethod = null; // Check all methods with the specified name, including in base classes GetMethodExt(ref matchingMethod, thisType, name, bindingFlags, parameterTypes); // If we're searching an interface, we have to manually search base interfaces if (matchingMethod == null && thisType.GetTypeInfo().IsInterface) { foreach (Type interfaceType in thisType.GetInterfaces()) GetMethodExt(ref matchingMethod, interfaceType, name, bindingFlags, parameterTypes); } return matchingMethod; } private static void GetMethodExt(ref MethodInfo matchingMethod, Type type, string name, BindingFlags bindingFlags, params Type[] parameterTypes) { // Check all methods with the specified name, including in base classes foreach (MethodInfo methodInfo in type.GetTypeInfo().GetMember(name, MemberTypes.Method, bindingFlags)) { // Check that the parameter counts and types match, // with 'loose' matching on generic parameters ParameterInfo[] parameterInfos = methodInfo.GetParameters(); if (parameterInfos.Length == parameterTypes.Length) { int i = 0; for (; i < parameterInfos.Length; ++i) { if (!parameterInfos[i].ParameterType .IsSimilarType(parameterTypes[i])) break; } if (i == parameterInfos.Length) { if (matchingMethod == null) matchingMethod = methodInfo; else throw new AmbiguousMatchException( "More than one matching method found!"); } } } } /// <summary> /// Special type used to match any generic parameter type in GetMethodExt(). /// </summary> public class T { } /// <summary> /// Determines if the two types are either identical, or are both generic /// parameters or generic types with generic parameters in the same /// locations (generic parameters match any other generic paramter, /// and concrete types). /// </summary> private static bool IsSimilarType(this Type thisType, Type type) { if (thisType == null && type == null) return true; if (thisType == null || type == null) return false; // Ignore any 'ref' types if (thisType.IsByRef) thisType = thisType.GetElementType(); if (type.IsByRef) type = type.GetElementType(); // Handle array types if (thisType.IsArray && type.IsArray) return thisType.GetElementType().IsSimilarType(type.GetElementType()); // If the types are identical, or they're both generic parameters // or the special 'T' type, treat as a match if (thisType == type || thisType.IsGenericParameter || thisType == typeof(T) || type.IsGenericParameter || type == typeof(T)) return true; // Handle any generic arguments if (thisType.GetTypeInfo().IsGenericType && type.GetTypeInfo().IsGenericType) { Type[] thisArguments = thisType.GetGenericArguments(); Type[] arguments = type.GetGenericArguments(); if (thisArguments.Length == arguments.Length) { for (int i = 0; i < thisArguments.Length; ++i) { if (!thisArguments[i].IsSimilarType(arguments[i])) return false; } return true; } } return false; } } }
41.136161
139
0.553421
[ "Apache-2.0" ]
sean-gilliam/Hyperion
src/Hyperion/Extensions/TypeEx.cs
18,429
C#
namespace JackTheVideoRipper { partial class FrameSettings { /// <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.buttonCancel = new System.Windows.Forms.Button(); this.buttonSave = new System.Windows.Forms.Button(); this.groupBox2 = new System.Windows.Forms.GroupBox(); this.buttonLocationBrowse = new System.Windows.Forms.Button(); this.textLocation = new System.Windows.Forms.TextBox(); this.label1 = new System.Windows.Forms.Label(); this.groupBox1 = new System.Windows.Forms.GroupBox(); this.numMaxConcurrent = new System.Windows.Forms.NumericUpDown(); this.groupBox2.SuspendLayout(); this.groupBox1.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.numMaxConcurrent)).BeginInit(); this.SuspendLayout(); // // buttonCancel // this.buttonCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel; this.buttonCancel.Location = new System.Drawing.Point(318, 369); this.buttonCancel.Margin = new System.Windows.Forms.Padding(4); this.buttonCancel.Name = "buttonCancel"; this.buttonCancel.Size = new System.Drawing.Size(171, 48); this.buttonCancel.TabIndex = 15; this.buttonCancel.Text = "Cancel"; this.buttonCancel.UseVisualStyleBackColor = true; // // buttonSave // this.buttonSave.Location = new System.Drawing.Point(497, 369); this.buttonSave.Margin = new System.Windows.Forms.Padding(4); this.buttonSave.Name = "buttonSave"; this.buttonSave.Size = new System.Drawing.Size(171, 48); this.buttonSave.TabIndex = 14; this.buttonSave.Text = "Save"; this.buttonSave.UseVisualStyleBackColor = true; this.buttonSave.Click += new System.EventHandler(this.buttonSave_Click); // // groupBox2 // this.groupBox2.Controls.Add(this.buttonLocationBrowse); this.groupBox2.Controls.Add(this.textLocation); this.groupBox2.Location = new System.Drawing.Point(12, 251); this.groupBox2.Margin = new System.Windows.Forms.Padding(4); this.groupBox2.Name = "groupBox2"; this.groupBox2.Padding = new System.Windows.Forms.Padding(4); this.groupBox2.Size = new System.Drawing.Size(656, 110); this.groupBox2.TabIndex = 16; this.groupBox2.TabStop = false; this.groupBox2.Text = "Default Location"; // // buttonLocationBrowse // this.buttonLocationBrowse.Location = new System.Drawing.Point(531, 39); this.buttonLocationBrowse.Margin = new System.Windows.Forms.Padding(4); this.buttonLocationBrowse.Name = "buttonLocationBrowse"; this.buttonLocationBrowse.Size = new System.Drawing.Size(117, 46); this.buttonLocationBrowse.TabIndex = 1; this.buttonLocationBrowse.Text = "Browse"; this.buttonLocationBrowse.UseVisualStyleBackColor = true; this.buttonLocationBrowse.Click += new System.EventHandler(this.buttonLocationBrowse_Click); // // textLocation // this.textLocation.Location = new System.Drawing.Point(19, 45); this.textLocation.Margin = new System.Windows.Forms.Padding(4); this.textLocation.Name = "textLocation"; this.textLocation.ReadOnly = true; this.textLocation.Size = new System.Drawing.Size(503, 31); this.textLocation.TabIndex = 0; // // label1 // this.label1.AutoSize = true; this.label1.Location = new System.Drawing.Point(18, 64); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(283, 25); this.label1.TabIndex = 17; this.label1.Text = "Max Concurrent Downloads:"; // // groupBox1 // this.groupBox1.Controls.Add(this.numMaxConcurrent); this.groupBox1.Controls.Add(this.label1); this.groupBox1.Location = new System.Drawing.Point(12, 19); this.groupBox1.Name = "groupBox1"; this.groupBox1.Size = new System.Drawing.Size(656, 205); this.groupBox1.TabIndex = 18; this.groupBox1.TabStop = false; this.groupBox1.Text = "General"; // // numMaxConcurrent // this.numMaxConcurrent.Location = new System.Drawing.Point(307, 64); this.numMaxConcurrent.Name = "numMaxConcurrent"; this.numMaxConcurrent.Size = new System.Drawing.Size(120, 31); this.numMaxConcurrent.TabIndex = 18; // // FrameSettings // this.AcceptButton = this.buttonSave; this.AutoScaleDimensions = new System.Drawing.SizeF(12F, 25F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.CancelButton = this.buttonCancel; this.ClientSize = new System.Drawing.Size(686, 432); this.Controls.Add(this.groupBox1); this.Controls.Add(this.groupBox2); this.Controls.Add(this.buttonCancel); this.Controls.Add(this.buttonSave); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog; this.MaximizeBox = false; this.MinimizeBox = false; this.Name = "FrameSettings"; this.ShowInTaskbar = false; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent; this.Text = "Settings"; this.Load += new System.EventHandler(this.FrameSettings_Load); this.groupBox2.ResumeLayout(false); this.groupBox2.PerformLayout(); this.groupBox1.ResumeLayout(false); this.groupBox1.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.numMaxConcurrent)).EndInit(); this.ResumeLayout(false); } #endregion private System.Windows.Forms.Button buttonCancel; private System.Windows.Forms.Button buttonSave; private System.Windows.Forms.GroupBox groupBox2; private System.Windows.Forms.Button buttonLocationBrowse; private System.Windows.Forms.TextBox textLocation; private System.Windows.Forms.Label label1; private System.Windows.Forms.GroupBox groupBox1; private System.Windows.Forms.NumericUpDown numMaxConcurrent; } }
47.078788
108
0.589341
[ "Unlicense" ]
dantheman213/JackTheVideoRipper
JackTheVideoRipper/views/FrameSettings.Designer.cs
7,770
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using Models.DB; namespace API.Controllers.DB { [Route("api/[controller]")] [ApiController] public class EengineController : ControllerBase { private readonly DBContext _context; public EengineController(DBContext context) { _context = context; } // GET: api/Eengine [HttpGet] public async Task<ActionResult<IEnumerable<Eengine>>> GetEengine() { return await _context.Eengine.ToListAsync(); } // GET: api/Eengine/5 [HttpGet("{id}")] public async Task<ActionResult<Eengine>> GetEengine(short id) { var eengine = await _context.Eengine.FindAsync(id); if (eengine == null) { return NotFound(); } return eengine; } // PUT: api/Eengine/5 // To protect from overposting attacks, enable the specific properties you want to bind to, for // more details, see https://go.microsoft.com/fwlink/?linkid=2123754. [HttpPut("{id}")] public async Task<IActionResult> PutEengine(short id, Eengine eengine) { if (id != eengine.EengineId) { return BadRequest(); } _context.Entry(eengine).State = EntityState.Modified; try { await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!EengineExists(id)) { return NotFound(); } else { throw; } } return NoContent(); } // POST: api/Eengine // To protect from overposting attacks, enable the specific properties you want to bind to, for // more details, see https://go.microsoft.com/fwlink/?linkid=2123754. [HttpPost] public async Task<ActionResult<Eengine>> PostEengine(Eengine eengine) { _context.Eengine.Add(eengine); try { await _context.SaveChangesAsync(); } catch (DbUpdateException) { if (EengineExists(eengine.EengineId)) { return Conflict(); } else { throw; } } return CreatedAtAction("GetEengine", new { id = eengine.EengineId }, eengine); } // DELETE: api/Eengine/5 [HttpDelete("{id}")] public async Task<ActionResult<Eengine>> DeleteEengine(short id) { var eengine = await _context.Eengine.FindAsync(id); if (eengine == null) { return NotFound(); } _context.Eengine.Remove(eengine); await _context.SaveChangesAsync(); return eengine; } private bool EengineExists(short id) { return _context.Eengine.Any(e => e.EengineId == id); } } }
27.225806
103
0.513033
[ "Apache-2.0" ]
LightosLimited/RailML
v2.4/API/Controllers/DB/EengineController.cs
3,376
C#
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Diagnostics.Contracts; using System.Linq; using Validation; namespace System.Collections.Immutable { /// <summary> /// An immutable stack. /// </summary> /// <typeparam name="T">The type of element stored by the stack.</typeparam> [DebuggerDisplay("IsEmpty = {IsEmpty}; Top = {head}")] [DebuggerTypeProxy(typeof(ImmutableStackDebuggerProxy<>))] [SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix", Justification = "Ignored")] [SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix", Justification = "Ignored")] public sealed class ImmutableStack<T> : IImmutableStack<T> { /// <summary> /// The singleton empty stack. /// </summary> /// <remarks> /// Additional instances representing the empty stack may exist on deserialized stacks. /// </remarks> private static readonly ImmutableStack<T> EmptyField = new ImmutableStack<T>(); /// <summary> /// The element on the top of the stack. /// </summary> private readonly T head; /// <summary> /// A stack that contains the rest of the elements (under the top element). /// </summary> private readonly ImmutableStack<T> tail; /// <summary> /// Initializes a new instance of the <see cref="ImmutableStack&lt;T&gt;"/> class /// that acts as the empty stack. /// </summary> private ImmutableStack() { } /// <summary> /// Initializes a new instance of the <see cref="ImmutableStack&lt;T&gt;"/> class. /// </summary> /// <param name="head">The head element on the stack.</param> /// <param name="tail">The rest of the elements on the stack.</param> private ImmutableStack(T head, ImmutableStack<T> tail) { Requires.NotNull(tail, "tail"); this.head = head; this.tail = tail; } /// <summary> /// Gets the empty stack, upon which all stacks are built. /// </summary> public static ImmutableStack<T> Empty { get { Contract.Ensures(Contract.Result<ImmutableStack<T>>() != null); Contract.Ensures(Contract.Result<ImmutableStack<T>>().IsEmpty); Contract.Assume(EmptyField.IsEmpty); return EmptyField; } } /// <summary> /// Gets the empty stack, upon which all stacks are built. /// </summary> public ImmutableStack<T> Clear() { Contract.Ensures(Contract.Result<ImmutableStack<T>>() != null); Contract.Ensures(Contract.Result<ImmutableStack<T>>().IsEmpty); Contract.Assume(EmptyField.IsEmpty); return Empty; } /// <summary> /// Gets an empty stack. /// </summary> IImmutableStack<T> IImmutableStack<T>.Clear() { return this.Clear(); } /// <summary> /// Gets a value indicating whether this instance is empty. /// </summary> /// <value> /// <c>true</c> if this instance is empty; otherwise, <c>false</c>. /// </value> public bool IsEmpty { get { return this.tail == null; } } /// <summary> /// Gets the element on the top of the stack. /// </summary> /// <returns> /// The element on the top of the stack. /// </returns> /// <exception cref="InvalidOperationException">Thrown when the stack is empty.</exception> [Pure] public T Peek() { if (this.IsEmpty) { throw new InvalidOperationException(Strings.InvalidEmptyOperation); } return this.head; } /// <summary> /// Pushes an element onto a stack and returns the new stack. /// </summary> /// <param name="value">The element to push onto the stack.</param> /// <returns>The new stack.</returns> [Pure] public ImmutableStack<T> Push(T value) { Contract.Ensures(Contract.Result<ImmutableStack<T>>() != null); Contract.Ensures(!Contract.Result<ImmutableStack<T>>().IsEmpty); return new ImmutableStack<T>(value, this); } /// <summary> /// Pushes an element onto a stack and returns the new stack. /// </summary> /// <param name="value">The element to push onto the stack.</param> /// <returns>The new stack.</returns> [Pure] IImmutableStack<T> IImmutableStack<T>.Push(T value) { return this.Push(value); } /// <summary> /// Returns a stack that lacks the top element on this stack. /// </summary> /// <returns>A stack; never <c>null</c></returns> /// <exception cref="InvalidOperationException">Thrown when the stack is empty.</exception> [Pure] public ImmutableStack<T> Pop() { Contract.Ensures(Contract.Result<ImmutableStack<T>>() != null); if (this.IsEmpty) { throw new InvalidOperationException(Strings.InvalidEmptyOperation); } return this.tail; } /// <summary> /// Pops the top element off the stack. /// </summary> /// <param name="value">The value that was removed from the stack.</param> /// <returns> /// A stack; never <c>null</c> /// </returns> [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", MessageId = "0#")] [Pure] public ImmutableStack<T> Pop(out T value) { value = this.Peek(); return this.Pop(); } /// <summary> /// Returns a stack that lacks the top element on this stack. /// </summary> /// <returns>A stack; never <c>null</c></returns> /// <exception cref="InvalidOperationException">Thrown when the stack is empty.</exception> [Pure] IImmutableStack<T> IImmutableStack<T>.Pop() { return this.Pop(); } /// <summary> /// Returns an enumerator that iterates through the collection. /// </summary> /// <returns> /// An <see cref="T:Enumerator"/> that can be used to iterate through the collection. /// </returns> [Pure] public Enumerator GetEnumerator() { return new Enumerator(this); } /// <summary> /// Returns an enumerator that iterates through the collection. /// </summary> /// <returns> /// A <see cref="T:System.Collections.Generic.IEnumerator`1"/> that can be used to iterate through the collection. /// </returns> [Pure] IEnumerator<T> IEnumerable<T>.GetEnumerator() { return new EnumeratorObject(this); } /// <summary> /// Returns an enumerator that iterates through a collection. /// </summary> /// <returns> /// An <see cref="T:System.Collections.IEnumerator"/> object that can be used to iterate through the collection. /// </returns> [Pure] IEnumerator IEnumerable.GetEnumerator() { return new EnumeratorObject(this); } /// <summary> /// Reverses the order of a stack. /// </summary> /// <returns>The reversed stack.</returns> [Pure] internal ImmutableStack<T> Reverse() { Contract.Ensures(Contract.Result<ImmutableStack<T>>() != null); Contract.Ensures(Contract.Result<ImmutableStack<T>>().IsEmpty == this.IsEmpty); var r = this.Clear(); for (ImmutableStack<T> f = this; !f.IsEmpty; f = f.Pop()) { r = r.Push(f.Peek()); } return r; } /// <summary> /// Enumerates a stack with no memory allocations. /// </summary> [EditorBrowsable(EditorBrowsableState.Advanced)] public struct Enumerator { /// <summary> /// The original stack being enumerated. /// </summary> private readonly ImmutableStack<T> originalStack; /// <summary> /// The remaining stack not yet enumerated. /// </summary> private ImmutableStack<T> remainingStack; /// <summary> /// Initializes a new instance of the <see cref="Enumerator"/> struct. /// </summary> /// <param name="stack">The stack to enumerator.</param> internal Enumerator(ImmutableStack<T> stack) { Requires.NotNull(stack, "stack"); this.originalStack = stack; this.remainingStack = null; } /// <summary> /// Gets the current element. /// </summary> public T Current { get { if (this.remainingStack == null || this.remainingStack.IsEmpty) { throw new InvalidOperationException(); } else { return this.remainingStack.Peek(); } } } /// <summary> /// Moves to the first or next element. /// </summary> /// <returns>A value indicating whether there are any more elements.</returns> public bool MoveNext() { if (this.remainingStack == null) { // initial move this.remainingStack = this.originalStack; } else if (!this.remainingStack.IsEmpty) { this.remainingStack = this.remainingStack.Pop(); } return !this.remainingStack.IsEmpty; } } /// <summary> /// Enumerates a stack with no memory allocations. /// </summary> private class EnumeratorObject : IEnumerator<T> { /// <summary> /// The original stack being enumerated. /// </summary> private readonly ImmutableStack<T> originalStack; /// <summary> /// The remaining stack not yet enumerated. /// </summary> private ImmutableStack<T> remainingStack; /// <summary> /// A flag indicating whether this enumerator has been disposed. /// </summary> private bool disposed; /// <summary> /// Initializes a new instance of the <see cref="EnumeratorObject"/> class. /// </summary> /// <param name="stack">The stack to enumerator.</param> internal EnumeratorObject(ImmutableStack<T> stack) { Requires.NotNull(stack, "stack"); this.originalStack = stack; } /// <summary> /// Gets the current element. /// </summary> public T Current { get { this.ThrowIfDisposed(); if (this.remainingStack == null || this.remainingStack.IsEmpty) { throw new InvalidOperationException(); } else { return this.remainingStack.Peek(); } } } /// <summary> /// Gets the current element. /// </summary> object IEnumerator.Current { get { return this.Current; } } /// <summary> /// Moves to the first or next element. /// </summary> /// <returns>A value indicating whether there are any more elements.</returns> public bool MoveNext() { this.ThrowIfDisposed(); if (this.remainingStack == null) { // initial move this.remainingStack = this.originalStack; } else if (!this.remainingStack.IsEmpty) { this.remainingStack = this.remainingStack.Pop(); } return !this.remainingStack.IsEmpty; } /// <summary> /// Resets the position to just before the first element in the list. /// </summary> public void Reset() { this.ThrowIfDisposed(); this.remainingStack = null; } /// <summary> /// Disposes this instance. /// </summary> public void Dispose() { this.disposed = true; } /// <summary> /// Throws an <see cref="ObjectDisposedException"/> if this /// enumerator has already been disposed. /// </summary> private void ThrowIfDisposed() { if (this.disposed) { Validation.Requires.FailObjectDisposed(this); } } } } /// <summary> /// A simple view of the immutable collection that the debugger can show to the developer. /// </summary> [ExcludeFromCodeCoverage] internal class ImmutableStackDebuggerProxy<T> { /// <summary> /// The collection to be enumerated. /// </summary> private readonly ImmutableStack<T> stack; /// <summary> /// The simple view of the collection. /// </summary> private T[] contents; /// <summary> /// Initializes a new instance of the <see cref="ImmutableStackDebuggerProxy&lt;T&gt;"/> class. /// </summary> /// <param name="stack">The collection to display in the debugger</param> public ImmutableStackDebuggerProxy(ImmutableStack<T> stack) { Requires.NotNull(stack, "stack"); this.stack = stack; } /// <summary> /// Gets a simple debugger-viewable collection. /// </summary> [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] public T[] Contents { get { if (this.contents == null) { this.contents = this.stack.ToArray(); } return this.contents; } } } }
32.956897
122
0.508697
[ "MIT" ]
a7madAly/corefx
src/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableStack`1.cs
15,292
C#
//----------------------------------------------------------------------- // <copyright file="Extensions.cs" company="Akka.NET Project"> // Copyright (C) 2009-2015 Typesafe Inc. <http://www.typesafe.com> // Copyright (C) 2013-2015 Akka.NET project <https://github.com/akkadotnet/akka.net> // </copyright> //----------------------------------------------------------------------- using System; using System.Collections.Generic; using System.Linq; namespace Akka.Util.Internal { public static class Extensions { public static T AsInstanceOf<T>(this object self) { return (T) self; } /// <summary> /// Scala alias for Skip /// </summary> /// <typeparam name="T"></typeparam> /// <param name="self"></param> /// <param name="count"></param> /// <returns></returns> public static IEnumerable<T> Drop<T>(this IEnumerable<T> self, int count) { return self.Skip(count).ToList(); } /// <summary> /// Scala alias for FirstOrDefault /// </summary> /// <typeparam name="T"></typeparam> /// <param name="self"></param> /// <returns></returns> public static T Head<T>(this IEnumerable<T> self) { return self.FirstOrDefault(); } public static string Join(this IEnumerable<string> self, string separator) { return string.Join(separator, self); } /// <summary> /// Dictionary helper that allows for idempotent updates. You don't need to care whether or not /// this item is already in the collection in order to update it. /// </summary> public static void AddOrSet<TKey, TValue>(this IDictionary<TKey, TValue> hash, TKey key, TValue value) { if (hash.ContainsKey(key)) hash[key] = value; else hash.Add(key,value); } public static TValue GetOrElse<TKey, TValue>(this IDictionary<TKey, TValue> hash, TKey key, TValue elseValue) { if (hash.ContainsKey(key)) return hash[key]; return elseValue; } public static T GetOrElse<T>(this T obj, T elseValue) { if (obj.Equals(default(T))) return elseValue; return obj; } public static IDictionary<TKey, TValue> AddAndReturn<TKey, TValue>(this IDictionary<TKey, TValue> hash, TKey key, TValue value) { hash.AddOrSet(key, value); return hash; } public static TimeSpan Max(this TimeSpan @this, TimeSpan other) { return @this > other ? @this : other; } public static IEnumerable<T> Concat<T>(this IEnumerable<T> enumerable, T item) { var itemInArray = new[] {item}; if (enumerable == null) return itemInArray; return enumerable.Concat(itemInArray); } public static void ForEach<T>(this IEnumerable<T> enumerable, Action<T> action) { foreach (var item in enumerable) action(item); } } }
31.910891
135
0.52901
[ "Apache-2.0" ]
Chinchilla-Software-Com/akka.net
src/core/Akka/Util/Internal/Extensions.cs
3,225
C#
#pragma warning disable 108 // new keyword hiding #pragma warning disable 114 // new keyword hiding namespace Windows.UI.Xaml { #if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ || __MACOS__ public enum FontFraction { #if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ || __MACOS__ Normal = 0, #endif #if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ || __MACOS__ Stacked = 1, #endif #if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ || __MACOS__ Slashed = 2, #endif } #endif }
32.15
99
0.698289
[ "Apache-2.0" ]
AbdalaMask/uno
src/Uno.UI/Generated/3.0.0.0/Windows.UI.Xaml/FontFraction.cs
643
C#
using Cofoundry.Domain; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace SitemapExample { public class ProductPageDisplayModelMapper : ICustomEntityDisplayModelMapper<ProductDataModel, ProductPageDisplayModel> { public Task<ProductPageDisplayModel> MapDisplayModelAsync( CustomEntityRenderDetails renderDetails, ProductDataModel dataModel, PublishStatusQuery publishStatusQuery ) { var displayModel = new ProductPageDisplayModel() { PageTitle = renderDetails.Title, MetaDescription = dataModel.ShortDescription, ShortDescription = dataModel.ShortDescription }; return Task.FromResult(displayModel); } } }
30.285714
123
0.667453
[ "MIT" ]
cofoundry-cms/Cofoundry.Plugins.SiteMap
src/SitemapExample/Cofoundry/CustomEntities/Product/ProductPageDisplayModelMapper.cs
850
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // <auto-generated/> #nullable disable namespace Azure.ResourceManager.MachineLearning.Models { /// <summary> Reference to an asset via its path in a job output. </summary> internal partial class PartialOutputPathAssetReference : PartialAssetReferenceBase { /// <summary> Initializes a new instance of PartialOutputPathAssetReference. </summary> public PartialOutputPathAssetReference() { ReferenceType = ReferenceType.OutputPath; } /// <summary> ARM resource ID of the job. </summary> public string JobId { get; set; } /// <summary> The path of the file/directory in the job output. </summary> public string Path { get; set; } } }
32.96
95
0.675971
[ "MIT" ]
damodaravadhani/azure-sdk-for-net
sdk/machinelearningservices/Azure.ResourceManager.MachineLearning/src/Generated/Models/PartialOutputPathAssetReference.cs
824
C#
// Lucene version compatibility level 4.8.1 using J2N.Collections.Generic.Extensions; using Lucene.Net.Analysis.Util; using Lucene.Net.Support; using Lucene.Net.Util; using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Text; using JCG = J2N.Collections.Generic; namespace Lucene.Net.Analysis.Synonym { /* * 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. */ /// <summary> /// Mapping rules for use with <see cref="SlowSynonymFilter"/> /// </summary> /// @deprecated (3.4) use <see cref="SynonymFilterFactory"/> instead. only for precise index backwards compatibility. this factory will be removed in Lucene 5.0 [Obsolete("(3.4) use SynonymFilterFactory instead. only for precise index backwards compatibility. this factory will be removed in Lucene 5.0")] internal class SlowSynonymMap { /// <summary> /// @lucene.internal </summary> public CharArrayMap<SlowSynonymMap> Submap // recursive: Map<String, SynonymMap> { get => submap; set => submap = value; } private CharArrayMap<SlowSynonymMap> submap; /// <summary> /// @lucene.internal </summary> [WritableArray] [SuppressMessage("Microsoft.Performance", "CA1819", Justification = "Lucene's design requires some writable array properties")] public Token[] Synonyms { get => synonyms; set => synonyms = value; } private Token[] synonyms; internal int flags; internal const int INCLUDE_ORIG = 0x01; internal const int IGNORE_CASE = 0x02; public SlowSynonymMap() { } public SlowSynonymMap(bool ignoreCase) { if (ignoreCase) { flags |= IGNORE_CASE; } } public virtual bool IncludeOrig => (flags & INCLUDE_ORIG) != 0; public virtual bool IgnoreCase => (flags & IGNORE_CASE) != 0; /// <param name="singleMatch"> <see cref="IList{String}"/>, the sequence of strings to match </param> /// <param name="replacement"> <see cref="IList{Token}"/> the list of tokens to use on a match </param> /// <param name="includeOrig"> sets a flag on this mapping signaling the generation of matched tokens in addition to the replacement tokens </param> /// <param name="mergeExisting"> merge the replacement tokens with any other mappings that exist </param> public virtual void Add(IList<string> singleMatch, IList<Token> replacement, bool includeOrig, bool mergeExisting) { var currMap = this; foreach (string str in singleMatch) { if (currMap.submap is null) { // for now hardcode at 4.0, as its what the old code did. // would be nice to fix, but shouldn't store a version in each submap!!! currMap.submap = new CharArrayMap<SlowSynonymMap>(LuceneVersion.LUCENE_CURRENT, 1, IgnoreCase); } var map = currMap.submap.Get(str); if (map is null) { map = new SlowSynonymMap(); map.flags |= flags & IGNORE_CASE; currMap.submap.Put(str, map); } currMap = map; } if (currMap.synonyms != null && !mergeExisting) { throw new ArgumentException("SynonymFilter: there is already a mapping for " + singleMatch); } IList<Token> superset = currMap.synonyms is null ? replacement : MergeTokens(currMap.synonyms, replacement); currMap.synonyms = superset.ToArray(); if (includeOrig) { currMap.flags |= INCLUDE_ORIG; } } public override string ToString() { var sb = new StringBuilder("<"); if (synonyms != null) { sb.Append("["); for (int i = 0; i < synonyms.Length; i++) { if (i != 0) { sb.Append(','); } sb.Append(synonyms[i]); } if ((flags & INCLUDE_ORIG) != 0) { sb.Append(",ORIG"); } sb.Append("],"); } sb.Append(submap); sb.Append(">"); return sb.ToString(); } /// <summary> /// Produces a <see cref="IList{Token}"/> from a <see cref="IList{String}"/> /// </summary> public static IList<Token> MakeTokens(IList<string> strings) { IList<Token> ret = new JCG.List<Token>(strings.Count); foreach (string str in strings) { //Token newTok = new Token(str,0,0,"SYNONYM"); Token newTok = new Token(str, 0, 0, "SYNONYM"); ret.Add(newTok); } return ret; } /// <summary> /// Merge two lists of tokens, producing a single list with manipulated positionIncrements so that /// the tokens end up at the same position. /// /// Example: [a b] merged with [c d] produces [a/b c/d] ('/' denotes tokens in the same position) /// Example: [a,5 b,2] merged with [c d,4 e,4] produces [c a,5/d b,2 e,2] (a,n means a has posInc=n) /// </summary> public static IList<Token> MergeTokens(IList<Token> lst1, IList<Token> lst2) { var result = new JCG.List<Token>(); if (lst1 is null || lst2 is null) { if (lst2 != null) { result.AddRange(lst2); } if (lst1 != null) { result.AddRange(lst1); } return result; } int pos = 0; using (var iter1 = lst1.GetEnumerator()) using (var iter2 = lst2.GetEnumerator()) { var tok1 = iter1.MoveNext() ? iter1.Current : null; var tok2 = iter2.MoveNext() ? iter2.Current : null; int pos1 = tok1 != null ? tok1.PositionIncrement : 0; int pos2 = tok2 != null ? tok2.PositionIncrement : 0; while (tok1 != null || tok2 != null) { while (tok1 != null && (pos1 <= pos2 || tok2 is null)) { var tok = new Token(tok1.StartOffset, tok1.EndOffset, tok1.Type); tok.CopyBuffer(tok1.Buffer, 0, tok1.Length); tok.PositionIncrement = pos1 - pos; result.Add(tok); pos = pos1; tok1 = iter1.MoveNext() ? iter1.Current : null; pos1 += tok1 != null ? tok1.PositionIncrement : 0; } while (tok2 != null && (pos2 <= pos1 || tok1 is null)) { var tok = new Token(tok2.StartOffset, tok2.EndOffset, tok2.Type); tok.CopyBuffer(tok2.Buffer, 0, tok2.Length); tok.PositionIncrement = pos2 - pos; result.Add(tok); pos = pos2; tok2 = iter2.MoveNext() ? iter2.Current : null; pos2 += tok2 != null ? tok2.PositionIncrement : 0; } } return result; } } } }
40.694444
166
0.507964
[ "Apache-2.0" ]
10088/lucenenet
src/Lucene.Net.Analysis.Common/Analysis/Synonym/SlowSynonymMap.cs
8,577
C#
using System; using JetBrains.Annotations; namespace Framework.Core { public class CallProxy<T> { private readonly Func<T> func; public CallProxy([NotNull] Func<T> baseInstance) { this.func = baseInstance ?? throw new ArgumentNullException(nameof(baseInstance)); } public T Value => this.func(); } }
20.368421
95
0.591731
[ "MIT" ]
Luxoft/BSSFramework
src/Framework.Core.AnonymousTypeBuilder/CallProxy.cs
371
C#
// Import dosimetry datagrid elements from protocol. using System; using System.Collections.Generic; using System.Data; using System.Globalization; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; using VMS.TPS.Common.Model.API; using VMS.TPS.Common.Model.Types; namespace Dosimetry { /// <summary> /// Interaction logic for ImportFromProtocol.xaml /// </summary> public partial class ImportFromProtocol : Window { public Dosimetry dosimetry; public MainWindow dosimetryPanel; public Dictionary<string, List<string>> protocolgroupsDisplay; public Dictionary<string, List<string>> protocolgroupsFull; public int selectedindex = 0; public int selectedindex2 = 0; public bool checkBoxInclude = false; public List<DataGridOrgans> DataGridOrgansList = new List<DataGridOrgans>() { }; public ListCollectionView DataGridOrgansCollection { get; set; } public List<DataGridOrgans> DataGridOrgansListDialogResult = new List<DataGridOrgans>() { }; public ImportFromProtocol(Dosimetry dosimetry, MainWindow dosimetryPanel) { this.dosimetry = dosimetry; this.dosimetryPanel = dosimetryPanel; var protocolgroups = this.dosimetry.GetProtocolGroup(); this.protocolgroupsDisplay = protocolgroups.Item1; this.protocolgroupsFull = protocolgroups.Item2; this.MaxWidth = System.Windows.SystemParameters.FullPrimaryScreenWidth; this.MaxHeight = System.Windows.SystemParameters.FullPrimaryScreenHeight; this.WindowStartupLocation = WindowStartupLocation.CenterScreen; InitializeComponent(); this.TextBoxNumFractions.Text = this.dosimetry.numberoffractions.First().ToString(); SetupComboBoxes(); } public class DataGridOrgans { public int id { get; set; } public bool Include { get; set; } public string Organ { get; set; } public string Structure { get; set; } public string ObjectiveType { get; set; } public string AtValue { get; set; } public string AtUnit { get; set; } public string ObjectiveExp { get; set; } public string ThanValue { get; set; } public string ThanUnit { get; set; } public string Comment { get; set; } } protected void SetupComboBoxes() { this.ComboBox1.ItemsSource = this.protocolgroupsDisplay.Keys; this.ComboBox1.SelectedIndex = this.selectedindex; this.ComboBox1.SelectionChanged += new SelectionChangedEventHandler(onSelectComboBox1); this.ComboBox2.ItemsSource = this.protocolgroupsDisplay.First().Value; this.ComboBox2.SelectedIndex = this.selectedindex2; } protected void onSelectComboBox1(object sender, EventArgs e) { this.selectedindex = this.ComboBox1.SelectedIndex; this.ComboBox2.ItemsSource = this.protocolgroupsDisplay[this.ComboBox1.SelectedItem.ToString()]; this.ComboBox2.SelectedIndex = 0; this.selectedindex2 = 0; } private void Button_Click(object sender, RoutedEventArgs e) { if (this.ComboBox2.SelectedIndex == -1) { return; } else { AddDataToDataGrid(); } } private void AddDataToDataGrid() { List<DataGridOrgans> data = new List<DataGridOrgans>() { }; List<Objective> objectiveList = this.dosimetry.GetProtocol(this.protocolgroupsFull[this.ComboBox1.SelectedItem.ToString()][this.ComboBox2.SelectedIndex]); int i = 0; foreach (Objective ob in objectiveList) { if (ob.structuretype == "Organ") { string atValue = ""; if (!Double.IsNaN(ob.at_value)) { // Conversion to Nominal dose is done automatically by Objectives.cs for at_value, // but not for than_value // Here At value is recalculated using a seperate EQD2 conversion based on the num fractions in TextBoxNumfractions // change from EQD2 to normal (nasty way of doing it) if (ob.at.Contains("cGy2")) { var oldAt = Convert.ToDouble(ob.at.Replace("cGy2", ""), System.Globalization.CultureInfo.InvariantCulture); if (ConvertTextToDouble(this.TextBoxNumFractions.Text) > 0) { ob.at_value = Eqd2ToNominal(oldAt, ob); } else { ob.at_value = 0; } } atValue = ob.at_value.ToString("0.#", CultureInfo.InvariantCulture); } string atUnit = ""; if (ob.at.Contains("cGy") || ob.at.Contains("cGy2")) { atUnit = "cGy"; } else if (ob.at.Contains("%")) { atUnit = "%"; } else if (ob.at.Contains("cm3")) { atUnit = "cm3"; } string thanValue = ""; if (!Double.IsNaN(ob.than_value)) { if (ob.than.Contains("cGy2")) { if (ConvertTextToDouble(this.TextBoxNumFractions.Text) > 0) { ob.than_value = Eqd2ToNominal(ob.than_value, ob); } else { ob.than_value = 0; } } thanValue = ob.than_value.ToString("0.#", CultureInfo.InvariantCulture); } string thanUnit = ""; if (ob.than.Contains("cGy") || ob.than.Contains("cGy2")) { thanUnit = "cGy"; } else if (ob.than.Contains("%")) { thanUnit = "%"; } else if (ob.than.Contains("cm3")) { thanUnit = "cm3"; } Structure structure = ob.FindStructure(this.dosimetry.structureset, objectiveList); string structureName = ""; if (structure != (Structure)null) { structureName = structure.Id; } DataGridOrgans item = new DataGridOrgans() { id = i, Include = true, Organ = ob.fullstructurename, Structure = structureName, ObjectiveType = ob.type, AtValue = atValue, AtUnit = atUnit, ObjectiveExp = ob.exp == "less" ? "<" : ">", ThanValue = thanValue, ThanUnit = thanUnit, Comment = ob.comment }; data.Add(item); i++; } } List<string> structureList = this.dosimetryPanel.CollectStructures(); structureList.Insert(0, ""); this.DataGridStructure.ItemsSource = structureList; this.DataGridOrgansList = data; ListCollectionView collectionView = new ListCollectionView(this.DataGridOrgansList); collectionView.GroupDescriptions.Add(new PropertyGroupDescription("Organ")); this.DataGridOrgansCollection = collectionView; this.DataGrid1.ItemsSource = this.DataGridOrgansCollection; } private void DataGrid_SourceUpdated(object sender, DataTransferEventArgs e) { } private void Button_Click_1(object sender, RoutedEventArgs e) { if (this.DataGrid1.SelectedItems.Count > 0) { var selectedItems = this.DataGrid1.SelectedItems; List<DataGridOrgans> items = selectedItems.Cast<DataGridOrgans>().ToList(); List<int> rowNumbers = new List<int>() { }; foreach (var item in items) { rowNumbers.Add(item.id); } ChangeIncludeCheckBox(rowNumbers); List<DataGridOrgans> allItems = this.DataGrid1.Items.Cast<DataGridOrgans>().ToList(); for (int i = 0; i < this.DataGrid1.Items.Count; i++) { if (rowNumbers.Contains(allItems[i].id)) { DataGridRow visualItem = (DataGridRow)this.DataGrid1.ItemContainerGenerator.ContainerFromItem(this.DataGrid1.Items[i]); if (visualItem == null) break; visualItem.IsSelected = true; visualItem.MoveFocus(new TraversalRequest(FocusNavigationDirection.Next)); } } } } private void ChangeIncludeCheckBox(List<int> rowNumbers) { foreach (var row in rowNumbers) { this.DataGridOrgansList.ElementAt(row).Include = this.checkBoxInclude; } this.checkBoxInclude = !this.checkBoxInclude; this.DataGridOrgansCollection.Refresh(); this.DataGrid1.UpdateLayout(); } private void Button_Click_2(object sender, RoutedEventArgs e) { var selectedItems = this.DataGrid1.SelectedItems; List<DataGridOrgans> items = selectedItems.Cast<DataGridOrgans>().ToList(); List<int> rowNumbers = new List<int>() { }; foreach (var item in items) { rowNumbers.Add(item.id); } if (items.Count != 1) { return; } else { string organ = this.DataGridOrgansList.ElementAt(items.First().id).Organ; string structure = this.DataGridOrgansList.ElementAt(items.First().id).Structure; ChangeStructuresComboBox(organ, structure); List<DataGridOrgans> allItems = this.DataGrid1.Items.Cast<DataGridOrgans>().ToList(); for (int i = 0; i < this.DataGrid1.Items.Count; i++) { if (rowNumbers.Contains(allItems[i].id)) { DataGridRow visualItem = (DataGridRow)this.DataGrid1.ItemContainerGenerator.ContainerFromItem(this.DataGrid1.Items[i]); if (visualItem == null) break; visualItem.IsSelected = true; visualItem.MoveFocus(new TraversalRequest(FocusNavigationDirection.Next)); } } } } private void ChangeStructuresComboBox(string organ, string structure) { foreach (var row in this.DataGridOrgansList) { if (row.Organ == organ) { row.Structure = structure; } } this.DataGridOrgansCollection.Refresh(); this.DataGrid1.UpdateLayout(); } private void Button_Click_3(object sender, RoutedEventArgs e) { this.DataGridOrgansListDialogResult = this.DataGridOrgansList; this.Close(); } private double ConvertTextToDouble(string text) { if (Double.TryParse(text, out double result)) { return result; } else { return Double.NaN; } } public double Eqd2ToNominal(double EQD, Objective ob) { // convert EQD to nominal dose double result; double n = ConvertTextToDouble(this.TextBoxNumFractions.Text); if (n > 0 && !Double.IsNaN(n)) { double ab = this.dosimetry.StructureAlphaBeta[ob.structure]; result = -n * ab / 2.0 + Math.Sqrt((n * ab / 2.0) * (n * ab / 2.0) + n * (EQD / 100.0) * (ab + 2.0)); result *= 100.0; } else { result = EQD; } return result; } private void Button_Click_5(object sender, RoutedEventArgs e) { string protocol = this.protocolgroupsFull[this.ComboBox1.SelectedItem.ToString()][this.ComboBox2.SelectedIndex]; string protocolName = this.ComboBox1.SelectedItem.ToString() + ": " + this.ComboBox2.SelectedItem.ToString(); var dataGridProtocolViews = this.dosimetryPanel.ReadFromProtocol(protocol); ProtocolView protocolview = new ProtocolView(dataGridProtocolViews, protocolName); protocolview.Owner = this; protocolview.Show(); } private void Button_Click_6(object sender, RoutedEventArgs e) { try { EQDCalculator eqdcalc = new EQDCalculator(); eqdcalc.Owner = this; eqdcalc.Show(); } catch (Exception g) { MessageBox.Show("Something went wrong. \n" + g.ToString(), "Error"); return; } } } }
37.374677
166
0.513343
[ "MIT" ]
brjdenis/Dosimetry
Dosimetry/ImportFromProtocol.xaml.cs
14,466
C#
// <copyright file="InterfaceExtensions.cs" company="RedHead"> // Copyright (c) RedHead. All rights reserved. // </copyright> namespace LibRibbonPlus; /// <summary> /// Provides extension methods for interfaces. /// </summary> public static class InterfaceExtensions { /// <summary> /// Converts an <see cref="IConvertible"/> to a <see cref="string"/> with <see cref="CultureInfo.InvariantCulture"/>. /// </summary> /// <param name="convertible">The value to get a <see cref="string"/> representation of.</param> /// <returns>A culture-invariant <see cref="string"/> representation of <paramref name="convertible"/>.</returns> public static string ToStringInvariant(this IConvertible convertible) => convertible.ToString(CultureInfo.InvariantCulture); }
39.45
121
0.704689
[ "CC0-1.0" ]
Chris2918/VibRibbonPlusAlphaPublic
LibRibbonPlus/LibRibbonPlus.Core/Source/Extensions/InterfaceExtensions.cs
791
C#
using System; using System.Threading.Tasks; namespace Bloggy.Data.Seeding { public interface ISeeder { Task SeedAsync(ApplicationDbContext dbContext, IServiceProvider serviceProvider); } }
19.181818
89
0.744076
[ "MIT" ]
georgidelchev/Bloggy
Data/Bloggy.Data/Seeding/ISeeder.cs
213
C#
using UnityEditor; namespace NaughtyAttributes.Editor { public class RequiredPropertyValidator : PropertyValidatorBase { public override void ValidateProperty(SerializedProperty property) { RequiredAttribute requiredAttribute = PropertyUtility.GetAttribute<RequiredAttribute>(property); if (property.propertyType == SerializedPropertyType.ObjectReference) { if (property.objectReferenceValue == null) { string errorMessage = property.name + " is required"; if (!string.IsNullOrEmpty(requiredAttribute.Message)) { errorMessage = requiredAttribute.Message; } NaughtyEditorGUI.HelpBox_Layout(errorMessage, MessageType.Error, context: property.serializedObject.targetObject); } } else { string warning = requiredAttribute.GetType().Name + " works only on reference types"; NaughtyEditorGUI.HelpBox_Layout(warning, MessageType.Warning, context: property.serializedObject.targetObject); } } } }
39
135
0.588141
[ "MIT" ]
Mu-L/NaughtyAttributes
Assets/NaughtyAttributes/Scripts/Editor/PropertyValidators/RequiredPropertyValidator.cs
1,250
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using LocantaApp.Data; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.HttpsPolicy; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.FileProviders; using System.IO; using Microsoft.AspNetCore.Http; namespace LocantaApp { public class Startup { public Startup(IConfiguration configuration, IWebHostEnvironment env) { Configuration = configuration; _env = env; } public IConfiguration Configuration { get; } private readonly IWebHostEnvironment _env; // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddDbContextPool<LocantaAppDbContext>(options => { if (_env.IsDevelopment()) { options.UseMySQL("server=localhost;database=locantaappdb;user=appuser;password=Apppasswd123."); //or options.UseMySQL(Configuration.GetConnectionString("LocantaAppDb")); } else { options.UseSqlite(Configuration.GetConnectionString("LocantaAppDb")); } }); // services.AddSingleton<IRestaurantData, InMemmoryRestaturantData>(); services.AddScoped<IRestaurantData, SqlRestaurantData>(); services.AddControllers(); services.AddRazorPages(); } // 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.UseStaticFiles(new StaticFileOptions() { FileProvider = new PhysicalFileProvider( Path.Combine(Directory.GetCurrentDirectory(), @"node_modules")), RequestPath = new PathString("/node_modules") }); app.UseRouting(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapRazorPages(); endpoints.MapControllers(); }); app.Use(SayHelloMiddleware); } private RequestDelegate SayHelloMiddleware(RequestDelegate nextMiddleware) { return async ctx => { if (ctx.Request.Path.StartsWithSegments("/hello")) { await ctx.Response.WriteAsync("Hello, World!"); } else { await nextMiddleware(ctx); // ctx.Response.StatusCode = 200; we can manipulate after other middlewares completed their processing } }; } } }
32.727273
143
0.581111
[ "MIT" ]
harunergul/LocantaApp
LocantaApp/Startup.cs
3,600
C#
// Project: Daggerfall Tools For Unity // Copyright: Copyright (C) 2009-2020 Daggerfall Workshop // Web Site: http://www.dfworkshop.net // License: MIT License (http://www.opensource.org/licenses/mit-license.php) // Source Code: https://github.com/Interkarma/daggerfall-unity // Original Author: Gavin Clayton (interkarma@dfworkshop.net) // Contributors: jefetienne // // Notes: // using UnityEngine; using System; using System.IO; using System.Collections; using System.Collections.Generic; using System.Linq; using DaggerfallConnect; using DaggerfallWorkshop.Game.Entity; using DaggerfallWorkshop.Game.Items; using DaggerfallWorkshop.Game.UserInterfaceWindows; using DaggerfallWorkshop.Game.Formulas; using DaggerfallWorkshop.Game.MagicAndEffects; using DaggerfallWorkshop.Game.MagicAndEffects.MagicEffects; using DaggerfallWorkshop.Game.Utility; using DaggerfallWorkshop.Utility; namespace DaggerfallWorkshop.Game.Serialization { public class PrintScreenManager : MonoBehaviour { #region Fields const string rootScreenshotsFolder = "Screenshots"; const string fileExtension = ".jpg"; private string unityScreenshotsPath; private KeyCode prtscrBinding = KeyCode.None; WaitForEndOfFrame endOfFrame = new WaitForEndOfFrame(); #endregion #region Properties public string UnityScreenshotsPath { get { return GetUnityScreenshotsPath(); } } #endregion #region Unity void Start () { DaggerfallWorkshop.Game.InputManager.OnSavedKeyBinds += GetPrintScreenKeyBind; GetPrintScreenKeyBind(); } void Update () { if (!DaggerfallUI.Instance.HotkeySequenceProcessed) { if (InputManager.Instance.GetKeyUp(prtscrBinding)) StartCoroutine(TakeScreenshot()); } } #endregion #region Private Methods void GetPrintScreenKeyBind() { prtscrBinding = InputManager.Instance.GetBinding(InputManager.Actions.PrintScreen); } IEnumerator TakeScreenshot() { string name = DateTime.Now.ToString("yyyy_MM_dd_hh_mm_ss"); int inc = 1; if (File.Exists(Path.Combine(UnityScreenshotsPath, name + fileExtension))) { while (File.Exists(Path.Combine(UnityScreenshotsPath, name + "_" + inc + fileExtension))) inc++; name += "_" + inc; } yield return endOfFrame; string path = Path.Combine(UnityScreenshotsPath, name + fileExtension); Texture2D pic = new Texture2D(Screen.width, Screen.height); pic.ReadPixels(new Rect(0, 0, Screen.width, Screen.height), 0, 0); pic.Apply(); byte[] bytes = pic.EncodeToJPG(); // Save file System.IO.File.WriteAllBytes(path, bytes); // Prevent the HUD text below from appearing on the screenshot while (!File.Exists(path)) yield return new WaitForSeconds(0.1f); DaggerfallUI.AddHUDText("Screenshot captured as '" + name + fileExtension + "'"); } string GetUnityScreenshotsPath() { if (!string.IsNullOrEmpty(unityScreenshotsPath)) return unityScreenshotsPath; string result = string.Empty; // Try settings result = DaggerfallUnity.Settings.MyDaggerfallUnityScreenshotsPath; if (string.IsNullOrEmpty(result) || !Directory.Exists(result)) { // Default to dataPath result = Path.Combine(DaggerfallUnity.Settings.PersistentDataPath, rootScreenshotsFolder); if (!Directory.Exists(result)) { // Attempt to create path Directory.CreateDirectory(result); } } // Test result is a valid path if (!Directory.Exists(result)) throw new Exception("Could not locate valid path for Unity screenshot files. Check 'MyDaggerfallUnitysScreenshotsPath' in settings.ini."); // Log result and save path DaggerfallUnity.LogMessage(string.Format("Using path '{0}' for Unity screenshots.", result), true); unityScreenshotsPath = result; return result; } #endregion } }
31.157534
154
0.61552
[ "MIT" ]
Aelthien/daggerfall-unity
Assets/Scripts/Game/Serialization/PrintScreenManager.cs
4,551
C#
/* Copyright (c) 2006 - 2008 The Open Toolkit library. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ using System; using System.Diagnostics.CodeAnalysis; using System.Diagnostics.Contracts; using System.Runtime.InteropServices; namespace OpenTK.Mathematics { /// <summary> /// Represents a 3x3 matrix containing 3D rotation and scale with double-precision components. /// </summary> [Serializable] [StructLayout(LayoutKind.Sequential)] public struct Matrix3d : IEquatable<Matrix3d> { /// <summary> /// First row of the matrix. /// </summary> public Vector3d Row0; /// <summary> /// Second row of the matrix. /// </summary> public Vector3d Row1; /// <summary> /// Third row of the matrix. /// </summary> public Vector3d Row2; /// <summary> /// The identity matrix. /// </summary> public static Matrix3d Identity = new Matrix3d(Vector3d.UnitX, Vector3d.UnitY, Vector3d.UnitZ); /// <summary> /// Initializes a new instance of the <see cref="Matrix3d"/> struct. /// </summary> /// <param name="row0">Top row of the matrix.</param> /// <param name="row1">Second row of the matrix.</param> /// <param name="row2">Bottom row of the matrix.</param> public Matrix3d(Vector3d row0, Vector3d row1, Vector3d row2) { Row0 = row0; Row1 = row1; Row2 = row2; } /// <summary> /// Initializes a new instance of the <see cref="Matrix3d"/> struct. /// </summary> /// <param name="m00">First item of the first row of the matrix.</param> /// <param name="m01">Second item of the first row of the matrix.</param> /// <param name="m02">Third item of the first row of the matrix.</param> /// <param name="m10">First item of the second row of the matrix.</param> /// <param name="m11">Second item of the second row of the matrix.</param> /// <param name="m12">Third item of the second row of the matrix.</param> /// <param name="m20">First item of the third row of the matrix.</param> /// <param name="m21">Second item of the third row of the matrix.</param> /// <param name="m22">Third item of the third row of the matrix.</param> [SuppressMessage("ReSharper", "SA1117", Justification = "For better readability of Matrix struct.")] public Matrix3d ( double m00, double m01, double m02, double m10, double m11, double m12, double m20, double m21, double m22 ) { Row0 = new Vector3d(m00, m01, m02); Row1 = new Vector3d(m10, m11, m12); Row2 = new Vector3d(m20, m21, m22); } /// <summary> /// Initializes a new instance of the <see cref="Matrix3d"/> struct. /// </summary> /// <param name="matrix">A Matrix4d to take the upper-left 3x3 from.</param> public Matrix3d(Matrix4d matrix) { Row0 = matrix.Row0.Xyz; Row1 = matrix.Row1.Xyz; Row2 = matrix.Row2.Xyz; } /// <summary> /// Gets the determinant of this matrix. /// </summary> public double Determinant { get { double m11 = Row0.X; double m12 = Row0.Y; double m13 = Row0.Z; double m21 = Row1.X; double m22 = Row1.Y; double m23 = Row1.Z; double m31 = Row2.X; double m32 = Row2.Y; double m33 = Row2.Z; return (m11 * m22 * m33) + (m12 * m23 * m31) + (m13 * m21 * m32) - (m13 * m22 * m31) - (m11 * m23 * m32) - (m12 * m21 * m33); } } /// <summary> /// Gets the first column of this matrix. /// </summary> public Vector3d Column0 => new Vector3d(Row0.X, Row1.X, Row2.X); /// <summary> /// Gets the second column of this matrix. /// </summary> public Vector3d Column1 => new Vector3d(Row0.Y, Row1.Y, Row2.Y); /// <summary> /// Gets the third column of this matrix. /// </summary> public Vector3d Column2 => new Vector3d(Row0.Z, Row1.Z, Row2.Z); /// <summary> /// Gets or sets the value at row 1, column 1 of this instance. /// </summary> public double M11 { get => Row0.X; set => Row0.X = value; } /// <summary> /// Gets or sets the value at row 1, column 2 of this instance. /// </summary> public double M12 { get => Row0.Y; set => Row0.Y = value; } /// <summary> /// Gets or sets the value at row 1, column 3 of this instance. /// </summary> public double M13 { get => Row0.Z; set => Row0.Z = value; } /// <summary> /// Gets or sets the value at row 2, column 1 of this instance. /// </summary> public double M21 { get => Row1.X; set => Row1.X = value; } /// <summary> /// Gets or sets the value at row 2, column 2 of this instance. /// </summary> public double M22 { get => Row1.Y; set => Row1.Y = value; } /// <summary> /// Gets or sets the value at row 2, column 3 of this instance. /// </summary> public double M23 { get => Row1.Z; set => Row1.Z = value; } /// <summary> /// Gets or sets the value at row 3, column 1 of this instance. /// </summary> public double M31 { get => Row2.X; set => Row2.X = value; } /// <summary> /// Gets or sets the value at row 3, column 2 of this instance. /// </summary> public double M32 { get => Row2.Y; set => Row2.Y = value; } /// <summary> /// Gets or sets the value at row 3, column 3 of this instance. /// </summary> public double M33 { get => Row2.Z; set => Row2.Z = value; } /// <summary> /// Gets or sets the values along the main diagonal of the matrix. /// </summary> public Vector3d Diagonal { get => new Vector3d(Row0.X, Row1.Y, Row2.Z); set { Row0.X = value.X; Row1.Y = value.Y; Row2.Z = value.Z; } } /// <summary> /// Gets the trace of the matrix, the sum of the values along the diagonal. /// </summary> public double Trace => Row0.X + Row1.Y + Row2.Z; /// <summary> /// Gets or sets the value at a specified row and column. /// </summary> /// <param name="rowIndex">The index of the row.</param> /// <param name="columnIndex">The index of the column.</param> public double this[int rowIndex, int columnIndex] { get { if (rowIndex == 0) { return Row0[columnIndex]; } if (rowIndex == 1) { return Row1[columnIndex]; } if (rowIndex == 2) { return Row2[columnIndex]; } throw new IndexOutOfRangeException("You tried to access this matrix at: (" + rowIndex + ", " + columnIndex + ")"); } set { if (rowIndex == 0) { Row0[columnIndex] = value; } else if (rowIndex == 1) { Row1[columnIndex] = value; } else if (rowIndex == 2) { Row2[columnIndex] = value; } else { throw new IndexOutOfRangeException("You tried to set this matrix at: (" + rowIndex + ", " + columnIndex + ")"); } } } /// <summary> /// Converts this instance into its inverse. /// </summary> public void Invert() { this = Invert(this); } /// <summary> /// Converts this instance into its transpose. /// </summary> public void Transpose() { this = Transpose(this); } /// <summary> /// Returns a normalized copy of this instance. /// </summary> /// <returns>The normalized copy.</returns> public Matrix3d Normalized() { var m = this; m.Normalize(); return m; } /// <summary> /// Divides each element in the Matrix by the <see cref="Determinant"/>. /// </summary> public void Normalize() { var determinant = Determinant; Row0 /= determinant; Row1 /= determinant; Row2 /= determinant; } /// <summary> /// Returns an inverted copy of this instance. /// </summary> /// <returns>The inverted copy.</returns> public Matrix3d Inverted() { var m = this; if (m.Determinant != 0) { m.Invert(); } return m; } /// <summary> /// Returns a copy of this Matrix3 without scale. /// </summary> /// <returns>The matrix without scaling.</returns> public Matrix3d ClearScale() { var m = this; m.Row0 = m.Row0.Normalized(); m.Row1 = m.Row1.Normalized(); m.Row2 = m.Row2.Normalized(); return m; } /// <summary> /// Returns a copy of this Matrix3 without rotation. /// </summary> /// <returns>The matrix without rotation.</returns> public Matrix3d ClearRotation() { var m = this; m.Row0 = new Vector3d(m.Row0.Length, 0, 0); m.Row1 = new Vector3d(0, m.Row1.Length, 0); m.Row2 = new Vector3d(0, 0, m.Row2.Length); return m; } /// <summary> /// Returns the scale component of this instance. /// </summary> /// <returns>The scale components.</returns> public Vector3d ExtractScale() { return new Vector3d(Row0.Length, Row1.Length, Row2.Length); } /// <summary> /// Returns the rotation component of this instance. Quite slow. /// </summary> /// <param name="rowNormalize"> /// Whether the method should row-normalize (i.e. remove scale from) the Matrix. Pass false if /// you know it's already normalized. /// </param> /// <returns>The rotation.</returns> [Pure] public Quaterniond ExtractRotation(bool rowNormalize = true) { var row0 = Row0; var row1 = Row1; var row2 = Row2; if (rowNormalize) { row0 = row0.Normalized(); row1 = row1.Normalized(); row2 = row2.Normalized(); } // code below adapted from Blender var q = default(Quaterniond); var trace = 0.25 * (row0[0] + row1[1] + row2[2] + 1.0); if (trace > 0) { var sq = Math.Sqrt(trace); q.W = sq; sq = 1.0 / (4.0 * sq); q.X = (row1[2] - row2[1]) * sq; q.Y = (row2[0] - row0[2]) * sq; q.Z = (row0[1] - row1[0]) * sq; } else if (row0[0] > row1[1] && row0[0] > row2[2]) { var sq = 2.0 * Math.Sqrt(1.0 + row0[0] - row1[1] - row2[2]); q.X = 0.25 * sq; sq = 1.0 / sq; q.W = (row2[1] - row1[2]) * sq; q.Y = (row1[0] + row0[1]) * sq; q.Z = (row2[0] + row0[2]) * sq; } else if (row1[1] > row2[2]) { var sq = 2.0 * Math.Sqrt(1.0 + row1[1] - row0[0] - row2[2]); q.Y = 0.25 * sq; sq = 1.0 / sq; q.W = (row2[0] - row0[2]) * sq; q.X = (row1[0] + row0[1]) * sq; q.Z = (row2[1] + row1[2]) * sq; } else { var sq = 2.0 * Math.Sqrt(1.0 + row2[2] - row0[0] - row1[1]); q.Z = 0.25 * sq; sq = 1.0 / sq; q.W = (row1[0] - row0[1]) * sq; q.X = (row2[0] + row0[2]) * sq; q.Y = (row2[1] + row1[2]) * sq; } q.Normalize(); return q; } /// <summary> /// Build a rotation matrix from the specified axis/angle rotation. /// </summary> /// <param name="axis">The axis to rotate about.</param> /// <param name="angle">Angle in radians to rotate counter-clockwise (looking in the direction of the given axis).</param> /// <param name="result">A matrix instance.</param> public static void CreateFromAxisAngle(Vector3d axis, double angle, out Matrix3d result) { // normalize and create a local copy of the vector. axis.Normalize(); double axisX = axis.X, axisY = axis.Y, axisZ = axis.Z; // calculate angles var cos = Math.Cos(-angle); var sin = Math.Sin(-angle); var t = 1.0f - cos; // do the conversion math once double tXX = t * axisX * axisX; double tXY = t * axisX * axisY; double tXZ = t * axisX * axisZ; double tYY = t * axisY * axisY; double tYZ = t * axisY * axisZ; double tZZ = t * axisZ * axisZ; double sinX = sin * axisX; double sinY = sin * axisY; double sinZ = sin * axisZ; result.Row0.X = tXX + cos; result.Row0.Y = tXY - sinZ; result.Row0.Z = tXZ + sinY; result.Row1.X = tXY + sinZ; result.Row1.Y = tYY + cos; result.Row1.Z = tYZ - sinX; result.Row2.X = tXZ - sinY; result.Row2.Y = tYZ + sinX; result.Row2.Z = tZZ + cos; } /// <summary> /// Build a rotation matrix from the specified axis/angle rotation. /// </summary> /// <param name="axis">The axis to rotate about.</param> /// <param name="angle">Angle in radians to rotate counter-clockwise (looking in the direction of the given axis).</param> /// <returns>A matrix instance.</returns> [Pure] public static Matrix3d CreateFromAxisAngle(Vector3d axis, double angle) { CreateFromAxisAngle(axis, angle, out Matrix3d result); return result; } /// <summary> /// Build a rotation matrix from the specified quaternion. /// </summary> /// <param name="q">Quaternion to translate.</param> /// <param name="result">Matrix result.</param> public static void CreateFromQuaternion(in Quaterniond q, out Matrix3d result) { // Adapted from https://en.wikipedia.org/wiki/Quaternions_and_spatial_rotation#Quaternion-derived_rotation_matrix // with the caviat that opentk uses row-major matrices so the matrix we create is transposed double sqx = q.X * q.X; double sqy = q.Y * q.Y; double sqz = q.Z * q.Z; double sqw = q.W * q.W; double xy = q.X * q.Y; double xz = q.X * q.Z; double xw = q.X * q.W; double yz = q.Y * q.Z; double yw = q.Y * q.W; double zw = q.Z * q.W; double s2 = 2d / (sqx + sqy + sqz + sqw); result.Row0.X = 1d - (s2 * (sqy + sqz)); result.Row1.Y = 1d - (s2 * (sqx + sqz)); result.Row2.Z = 1d - (s2 * (sqx + sqy)); result.Row0.Y = s2 * (xy + zw); result.Row1.X = s2 * (xy - zw); result.Row2.X = s2 * (xz + yw); result.Row0.Z = s2 * (xz - yw); result.Row2.Y = s2 * (yz - xw); result.Row1.Z = s2 * (yz + xw); } /// <summary> /// Build a rotation matrix from the specified quaternion. /// </summary> /// <param name="q">Quaternion to translate.</param> /// <returns>A matrix instance.</returns> [Pure] public static Matrix3d CreateFromQuaternion(Quaterniond q) { CreateFromQuaternion(in q, out Matrix3d result); return result; } /// <summary> /// Builds a rotation matrix for a rotation around the x-axis. /// </summary> /// <param name="angle">The counter-clockwise angle in radians.</param> /// <param name="result">The resulting Matrix3d instance.</param> public static void CreateRotationX(double angle, out Matrix3d result) { var cos = Math.Cos(angle); var sin = Math.Sin(angle); result = Identity; result.Row1.Y = cos; result.Row1.Z = sin; result.Row2.Y = -sin; result.Row2.Z = cos; } /// <summary> /// Builds a rotation matrix for a rotation around the x-axis. /// </summary> /// <param name="angle">The counter-clockwise angle in radians.</param> /// <returns>The resulting Matrix3d instance.</returns> [Pure] public static Matrix3d CreateRotationX(double angle) { CreateRotationX(angle, out Matrix3d result); return result; } /// <summary> /// Builds a rotation matrix for a rotation around the y-axis. /// </summary> /// <param name="angle">The counter-clockwise angle in radians.</param> /// <param name="result">The resulting Matrix3d instance.</param> public static void CreateRotationY(double angle, out Matrix3d result) { var cos = Math.Cos(angle); var sin = Math.Sin(angle); result = Identity; result.Row0.X = cos; result.Row0.Z = -sin; result.Row2.X = sin; result.Row2.Z = cos; } /// <summary> /// Builds a rotation matrix for a rotation around the y-axis. /// </summary> /// <param name="angle">The counter-clockwise angle in radians.</param> /// <returns>The resulting Matrix3d instance.</returns> [Pure] public static Matrix3d CreateRotationY(double angle) { CreateRotationY(angle, out Matrix3d result); return result; } /// <summary> /// Builds a rotation matrix for a rotation around the z-axis. /// </summary> /// <param name="angle">The counter-clockwise angle in radians.</param> /// <param name="result">The resulting Matrix3d instance.</param> public static void CreateRotationZ(double angle, out Matrix3d result) { var cos = Math.Cos(angle); var sin = Math.Sin(angle); result = Identity; result.Row0.X = cos; result.Row0.Y = sin; result.Row1.X = -sin; result.Row1.Y = cos; } /// <summary> /// Builds a rotation matrix for a rotation around the z-axis. /// </summary> /// <param name="angle">The counter-clockwise angle in radians.</param> /// <returns>The resulting Matrix3d instance.</returns> [Pure] public static Matrix3d CreateRotationZ(double angle) { CreateRotationZ(angle, out Matrix3d result); return result; } /// <summary> /// Creates a scale matrix. /// </summary> /// <param name="scale">Single scale factor for the x, y, and z axes.</param> /// <returns>A scale matrix.</returns> [Pure] public static Matrix3d CreateScale(double scale) { CreateScale(scale, out Matrix3d result); return result; } /// <summary> /// Creates a scale matrix. /// </summary> /// <param name="scale">Scale factors for the x, y, and z axes.</param> /// <returns>A scale matrix.</returns> [Pure] public static Matrix3d CreateScale(Vector3d scale) { CreateScale(in scale, out Matrix3d result); return result; } /// <summary> /// Creates a scale matrix. /// </summary> /// <param name="x">Scale factor for the x axis.</param> /// <param name="y">Scale factor for the y axis.</param> /// <param name="z">Scale factor for the z axis.</param> /// <returns>A scale matrix.</returns> [Pure] public static Matrix3d CreateScale(double x, double y, double z) { CreateScale(x, y, z, out Matrix3d result); return result; } /// <summary> /// Creates a scale matrix. /// </summary> /// <param name="scale">Single scale factor for the x, y, and z axes.</param> /// <param name="result">A scale matrix.</param> public static void CreateScale(double scale, out Matrix3d result) { result = Identity; result.Row0.X = scale; result.Row1.Y = scale; result.Row2.Z = scale; } /// <summary> /// Creates a scale matrix. /// </summary> /// <param name="scale">Scale factors for the x, y, and z axes.</param> /// <param name="result">A scale matrix.</param> public static void CreateScale(in Vector3d scale, out Matrix3d result) { result = Identity; result.Row0.X = scale.X; result.Row1.Y = scale.Y; result.Row2.Z = scale.Z; } /// <summary> /// Creates a scale matrix. /// </summary> /// <param name="x">Scale factor for the x axis.</param> /// <param name="y">Scale factor for the y axis.</param> /// <param name="z">Scale factor for the z axis.</param> /// <param name="result">A scale matrix.</param> public static void CreateScale(double x, double y, double z, out Matrix3d result) { result = Identity; result.Row0.X = x; result.Row1.Y = y; result.Row2.Z = z; } /// <summary> /// Adds two instances. /// </summary> /// <param name="left">The left operand of the addition.</param> /// <param name="right">The right operand of the addition.</param> /// <returns>A new instance that is the result of the addition.</returns> [Pure] public static Matrix3d Add(Matrix3d left, Matrix3d right) { Add(in left, in right, out Matrix3d result); return result; } /// <summary> /// Adds two instances. /// </summary> /// <param name="left">The left operand of the addition.</param> /// <param name="right">The right operand of the addition.</param> /// <param name="result">A new instance that is the result of the addition.</param> public static void Add(in Matrix3d left, in Matrix3d right, out Matrix3d result) { Vector3d.Add(in left.Row0, in right.Row0, out result.Row0); Vector3d.Add(in left.Row1, in right.Row1, out result.Row1); Vector3d.Add(in left.Row2, in right.Row2, out result.Row2); } /// <summary> /// Multiplies two instances. /// </summary> /// <param name="left">The left operand of the multiplication.</param> /// <param name="right">The right operand of the multiplication.</param> /// <returns>A new instance that is the result of the multiplication.</returns> [Pure] public static Matrix3d Mult(Matrix3d left, Matrix3d right) { Mult(in left, in right, out Matrix3d result); return result; } /// <summary> /// Multiplies two instances. /// </summary> /// <param name="left">The left operand of the multiplication.</param> /// <param name="right">The right operand of the multiplication.</param> /// <param name="result">A new instance that is the result of the multiplication.</param> public static void Mult(in Matrix3d left, in Matrix3d right, out Matrix3d result) { double leftM11 = left.Row0.X; double leftM12 = left.Row0.Y; double leftM13 = left.Row0.Z; double leftM21 = left.Row1.X; double leftM22 = left.Row1.Y; double leftM23 = left.Row1.Z; double leftM31 = left.Row2.X; double leftM32 = left.Row2.Y; double leftM33 = left.Row2.Z; double rightM11 = right.Row0.X; double rightM12 = right.Row0.Y; double rightM13 = right.Row0.Z; double rightM21 = right.Row1.X; double rightM22 = right.Row1.Y; double rightM23 = right.Row1.Z; double rightM31 = right.Row2.X; double rightM32 = right.Row2.Y; double rightM33 = right.Row2.Z; result.Row0.X = (leftM11 * rightM11) + (leftM12 * rightM21) + (leftM13 * rightM31); result.Row0.Y = (leftM11 * rightM12) + (leftM12 * rightM22) + (leftM13 * rightM32); result.Row0.Z = (leftM11 * rightM13) + (leftM12 * rightM23) + (leftM13 * rightM33); result.Row1.X = (leftM21 * rightM11) + (leftM22 * rightM21) + (leftM23 * rightM31); result.Row1.Y = (leftM21 * rightM12) + (leftM22 * rightM22) + (leftM23 * rightM32); result.Row1.Z = (leftM21 * rightM13) + (leftM22 * rightM23) + (leftM23 * rightM33); result.Row2.X = (leftM31 * rightM11) + (leftM32 * rightM21) + (leftM33 * rightM31); result.Row2.Y = (leftM31 * rightM12) + (leftM32 * rightM22) + (leftM33 * rightM32); result.Row2.Z = (leftM31 * rightM13) + (leftM32 * rightM23) + (leftM33 * rightM33); } /// <summary> /// Calculate the inverse of the given matrix. /// </summary> /// <param name="mat">The matrix to invert.</param> /// <param name="result">The inverse of the given matrix if it has one, or the input if it is singular.</param> /// <exception cref="InvalidOperationException">Thrown if the Matrix3d is singular.</exception> public static void Invert(in Matrix3d mat, out Matrix3d result) { int[] colIdx = { 0, 0, 0 }; int[] rowIdx = { 0, 0, 0 }; int[] pivotIdx = { -1, -1, -1 }; double[,] inverse = { { mat.Row0.X, mat.Row0.Y, mat.Row0.Z }, { mat.Row1.X, mat.Row1.Y, mat.Row1.Z }, { mat.Row2.X, mat.Row2.Y, mat.Row2.Z } }; var icol = 0; var irow = 0; for (var i = 0; i < 3; i++) { var maxPivot = 0.0; for (var j = 0; j < 3; j++) { if (pivotIdx[j] != 0) { for (var k = 0; k < 3; ++k) { if (pivotIdx[k] == -1) { var absVal = Math.Abs(inverse[j, k]); if (absVal > maxPivot) { maxPivot = absVal; irow = j; icol = k; } } else if (pivotIdx[k] > 0) { result = mat; return; } } } } ++pivotIdx[icol]; if (irow != icol) { for (var k = 0; k < 3; ++k) { var f = inverse[irow, k]; inverse[irow, k] = inverse[icol, k]; inverse[icol, k] = f; } } rowIdx[i] = irow; colIdx[i] = icol; var pivot = inverse[icol, icol]; if (pivot == 0.0) { throw new InvalidOperationException("Matrix is singular and cannot be inverted."); } var oneOverPivot = 1.0 / pivot; inverse[icol, icol] = 1.0; for (var k = 0; k < 3; ++k) { inverse[icol, k] *= oneOverPivot; } for (var j = 0; j < 3; ++j) { if (icol != j) { var f = inverse[j, icol]; inverse[j, icol] = 0.0; for (var k = 0; k < 3; ++k) { inverse[j, k] -= inverse[icol, k] * f; } } } } for (var j = 2; j >= 0; --j) { var ir = rowIdx[j]; var ic = colIdx[j]; for (var k = 0; k < 3; ++k) { var f = inverse[k, ir]; inverse[k, ir] = inverse[k, ic]; inverse[k, ic] = f; } } result.Row0.X = inverse[0, 0]; result.Row0.Y = inverse[0, 1]; result.Row0.Z = inverse[0, 2]; result.Row1.X = inverse[1, 0]; result.Row1.Y = inverse[1, 1]; result.Row1.Z = inverse[1, 2]; result.Row2.X = inverse[2, 0]; result.Row2.Y = inverse[2, 1]; result.Row2.Z = inverse[2, 2]; } /// <summary> /// Calculate the inverse of the given matrix. /// </summary> /// <param name="mat">The matrix to invert.</param> /// <returns>The inverse of the given matrix.</returns> /// <exception cref="InvalidOperationException">Thrown if the Matrix4 is singular.</exception> [Pure] public static Matrix3d Invert(Matrix3d mat) { Invert(in mat, out Matrix3d result); return result; } /// <summary> /// Calculate the transpose of the given matrix. /// </summary> /// <param name="mat">The matrix to transpose.</param> /// <returns>The transpose of the given matrix.</returns> [Pure] public static Matrix3d Transpose(Matrix3d mat) { return new Matrix3d(mat.Column0, mat.Column1, mat.Column2); } /// <summary> /// Calculate the transpose of the given matrix. /// </summary> /// <param name="mat">The matrix to transpose.</param> /// <param name="result">The result of the calculation.</param> public static void Transpose(in Matrix3d mat, out Matrix3d result) { result.Row0 = mat.Column0; result.Row1 = mat.Column1; result.Row2 = mat.Column2; } /// <summary> /// Matrix multiplication. /// </summary> /// <param name="left">left-hand operand.</param> /// <param name="right">right-hand operand.</param> /// <returns>A new Matrix3d which holds the result of the multiplication.</returns> [Pure] public static Matrix3d operator *(Matrix3d left, Matrix3d right) { return Mult(left, right); } /// <summary> /// Compares two instances for equality. /// </summary> /// <param name="left">The first instance.</param> /// <param name="right">The second instance.</param> /// <returns>True, if left equals right; false otherwise.</returns> [Pure] public static bool operator ==(Matrix3d left, Matrix3d right) { return left.Equals(right); } /// <summary> /// Compares two instances for inequality. /// </summary> /// <param name="left">The first instance.</param> /// <param name="right">The second instance.</param> /// <returns>True, if left does not equal right; false otherwise.</returns> [Pure] public static bool operator !=(Matrix3d left, Matrix3d right) { return !left.Equals(right); } /// <summary> /// Returns a System.String that represents the current Matrix3d. /// </summary> /// <returns>The string representation of the matrix.</returns> public override string ToString() { return $"{Row0}\n{Row1}\n{Row2}"; } /// <summary> /// Returns the hashcode for this instance. /// </summary> /// <returns>A System.Int32 containing the unique hashcode for this instance.</returns> public override int GetHashCode() { return HashCode.Combine(Row0, Row1, Row2); } /// <summary> /// Indicates whether this instance and a specified object are equal. /// </summary> /// <param name="obj">The object to compare to.</param> /// <returns>True if the instances are equal; false otherwise.</returns> [Pure] public override bool Equals(object obj) { return obj is Matrix3d && Equals((Matrix3d)obj); } /// <summary> /// Indicates whether the current matrix is equal to another matrix. /// </summary> /// <param name="other">A matrix to compare with this matrix.</param> /// <returns>true if the current matrix is equal to the matrix parameter; otherwise, false.</returns> [Pure] public bool Equals(Matrix3d other) { return Row0 == other.Row0 && Row1 == other.Row1 && Row2 == other.Row2; } } }
35.076625
130
0.491124
[ "MIT" ]
ASPePeX/opentk
src/OpenTK.Mathematics/Matrix/Matrix3d.cs
36,164
C#
using Application; using Infrastructure; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.HttpsPolicy; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using Microsoft.OpenApi.Models; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace API { 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. public void ConfigureServices(IServiceCollection services) { services.AddInfrastructure(); services.AddApplication(); services.AddControllers(); services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo { Title = "API", Version = "v1" }); }); } // 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(); app.UseSwagger(); app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "API v1")); } app.UseHttpsRedirection(); app.UseRouting(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); } } }
28.84375
106
0.627302
[ "MIT" ]
mlatchmansingh/DDDWithMediatr
src/API/Startup.cs
1,846
C#
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Threading; using System.Windows.Forms; using AutoVscJava.Classes; using AutoVscJava.Properties; namespace AutoVscJava { public partial class Form_EnvCheck : Form { private static int jdkEnv = 0; private static int vscEnv = 0; public Form_EnvCheck() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { CheckForIllegalCrossThreadCalls = false; //检查jdk Task checkJdkTask = new Task(() => { if (EnvChecker.CheckJavaSE()) { jdkEnv = 1; Label_jdk_status.Text = "已安装"; Label_jdk_status.ForeColor = Color.Green; PictureBox_jdk_status.Image = Resources.complete; InstallCompleted(); } else { Label_jdk_status.Text = "未安装"; Label_jdk_status.ForeColor = Color.Red; PictureBox_jdk_status.Image = Resources.error; Button_jdk_install.Show(); } }); checkJdkTask.Start(); //检查VScode Task checkVscTask = new Task(() => { if(EnvChecker.CheckVscode()) { Label_vsc_status.Text = "正在检查插件"; if(EnvChecker.CheckVscExtension()) { vscEnv = 1; Label_vsc_status.Text = "已完成"; Label_vsc_status.ForeColor = Color.Green; PictureBox_vsc_status.Image = Resources.complete; } else { Label_vsc_status.Text = "未安装插件"; Label_vsc_status.ForeColor = Color.Red; PictureBox_vsc_status.Image = Resources.error; Button_vsc_install.Show(); } InstallCompleted(); } else { vscEnv = -1; Label_vsc_status.Text = "未安装VScode"; PictureBox_vsc_status.Image = Resources.complete; InstallCompleted(); } }); checkVscTask.Start(); } private async void Button_install_Click(object sender, EventArgs e) { //设置窗口资源 Button_jdk_install.Enabled = false; PictureBox_jdk_status.Image = Resources.loading_small; Label_jdk_status.Text = "正在安装"; Label_jdk_status.ForeColor = Color.Black; //选择安装路径 string targetPath; while (true) { FolderBrowserDialog dialog = new FolderBrowserDialog { Description = "请选择Java SE的安装文件夹" }; if (dialog.ShowDialog() == DialogResult.OK) { targetPath = dialog.SelectedPath; break; } } //异步调用安装 var r = Task.Run(() => { return JdkInstaller.Install(targetPath); }); InstallJDKCompleted(await r); } public void InstallJDKCompleted(bool result) { if (result) { jdkEnv = 1; Label_jdk_status.Text = "已安装"; Label_jdk_status.ForeColor = Color.Green; PictureBox_jdk_status.Image = Resources.complete; Button_jdk_install.Hide(); InstallCompleted(); } else { Label_jdk_status.Text = "未安装"; Label_jdk_status.ForeColor = Color.Red; PictureBox_jdk_status.Image = Resources.error; Button_jdk_install.Text = "重试"; Button_jdk_install.Enabled = true; } } private async void Button_vsc_install_Click(object sender, EventArgs e) { //设置窗口资源 Button_vsc_install.Enabled = false; PictureBox_vsc_status.Image = Resources.loading_small; Label_vsc_status.Text = "正在配置"; Label_vsc_status.ForeColor = Color.Black; //异步调用安装 var r = Task.Run(() => { return VscExtensionInstaller.Install(); }); InstallVscCompleted(await r); } private void InstallVscCompleted(bool result) { if (result) { vscEnv = 1; Label_vsc_status.Text = "已安装"; Label_vsc_status.ForeColor = Color.Green; PictureBox_vsc_status.Image = Resources.complete; Button_vsc_install.Hide(); InstallCompleted(); } else { Label_vsc_status.Text = "未安装"; Label_vsc_status.ForeColor = Color.Red; PictureBox_vsc_status.Image = Resources.error; Button_vsc_install.Text = "重试"; Button_vsc_install.Enabled = true; } } private void InstallCompleted() { if (jdkEnv != 0 && vscEnv != 0) Button_next.Enabled = true; } private void Button_next_Click(object sender, EventArgs e) { Application.Exit(); } private void Label_copyright_Click(object sender, EventArgs e) { System.Diagnostics.Process.Start("https://space.bilibili.com/12263994"); } private void Form_EnvCheck_Shown(object sender, EventArgs e) { //隐藏按钮 Button_jdk_install.Hide(); Button_vsc_install.Hide(); } } }
31.02
84
0.485654
[ "Apache-2.0" ]
SDchao/AutoVscJava
AutoVscJava/Form_EnvCheck.cs
6,394
C#
#if NETSTANDARD2_1 using System; using System.IO; using System.Threading; using System.Threading.Tasks; #nullable enable namespace Refit.Buffers { internal sealed partial class PooledBufferWriter { private sealed partial class PooledMemoryStream : Stream { /// <inheritdoc/> public override void CopyTo(Stream destination, int bufferSize) { if (pooledBuffer is null) ThrowObjectDisposedException(); var source = pooledBuffer.AsSpan(position); position += source.Length; destination.Write(source); } /// <inheritdoc/> public override ValueTask<int> ReadAsync(Memory<byte> buffer, CancellationToken cancellationToken = default) { if (cancellationToken.IsCancellationRequested) { return new ValueTask<int>(Task.FromCanceled<int>(cancellationToken)); } try { var result = Read(buffer.Span); return new ValueTask<int>(result); } catch (OperationCanceledException e) { return new ValueTask<int>(Task.FromCanceled<int>(e.CancellationToken)); } catch (Exception e) { return new ValueTask<int>(Task.FromException<int>(e)); } } /// <inheritdoc/> public override int Read(Span<byte> buffer) { if (pooledBuffer is null) ThrowObjectDisposedException(); var source = pooledBuffer.AsSpan(position); var bytesCopied = Math.Min(source.Length, buffer.Length); var destination = buffer.Slice(0, bytesCopied); source.CopyTo(destination); position += bytesCopied; return bytesCopied; } } } } #endif
27.621622
120
0.526908
[ "MIT" ]
joelweiss/refit
Refit/Buffers/PooledBufferWriter.Stream.NETStandard21.cs
2,046
C#
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Reflection; using Microsoft.AspNetCore.Mvc.ActionConstraints; using Microsoft.AspNetCore.Mvc.Filters; using Microsoft.AspNetCore.Mvc.Routing; using Microsoft.AspNetCore.Routing; using Moq; using Xunit; namespace Microsoft.AspNetCore.Mvc.ApplicationModels { public class ActionModelTest { [Fact] public void CopyConstructor_DoesDeepCopyOfOtherModels() { // Arrange var action = new ActionModel(typeof(TestController).GetMethod(nameof(TestController.Edit)), new List<object>()); var parameter = new ParameterModel(action.ActionMethod.GetParameters()[0], new List<object>()); parameter.Action = action; action.Parameters.Add(parameter); var route = new AttributeRouteModel(new HttpGetAttribute("api/Products")); action.Selectors.Add(new SelectorModel() { AttributeRouteModel = route }); var apiExplorer = action.ApiExplorer; apiExplorer.IsVisible = false; apiExplorer.GroupName = "group1"; // Act var action2 = new ActionModel(action); // Assert Assert.NotSame(action.Parameters, action2.Parameters); Assert.NotNull(action2.Parameters); Assert.Single(action2.Parameters); Assert.NotSame(parameter, action2.Parameters[0]); Assert.NotSame(apiExplorer, action2.ApiExplorer); Assert.NotSame(action.Selectors, action2.Selectors); Assert.NotNull(action2.Selectors); Assert.Single(action2.Selectors); Assert.NotSame(action.Selectors[0], action2.Selectors[0]); Assert.NotSame(route, action2.Selectors[0].AttributeRouteModel); Assert.NotSame(action, action2.Parameters[0].Action); Assert.Same(action2, action2.Parameters[0].Action); } [Fact] public void CopyConstructor_CopiesAllProperties() { // Arrange var action = new ActionModel( typeof(TestController).GetMethod("Edit"), new List<object>() { new HttpGetAttribute(), new MyFilterAttribute(), }); var selectorModel = new SelectorModel(); selectorModel.ActionConstraints.Add(new HttpMethodActionConstraint(new string[] { "GET" })); action.Selectors.Add(selectorModel); action.ActionName = "Edit"; action.Controller = new ControllerModel (typeof(TestController).GetTypeInfo(), new List<object>()); action.Filters.Add(new MyFilterAttribute()); action.RouteParameterTransformer = Mock.Of<IOutboundParameterTransformer>(); action.RouteValues.Add("key", "value"); action.Properties.Add(new KeyValuePair<object, object>("test key", "test value")); // Act var action2 = new ActionModel(action); // Assert foreach (var property in typeof(ActionModel).GetProperties()) { // Reflection is used to make sure the test fails when a new property is added. if (property.Name.Equals("ApiExplorer") || property.Name.Equals("Selectors") || property.Name.Equals("Parameters")) { // This test excludes other ApplicationModel objects on purpose because we deep copy them. continue; } var value1 = property.GetValue(action); var value2 = property.GetValue(action2); if (typeof(IEnumerable<object>).IsAssignableFrom(property.PropertyType)) { Assert.Equal<object>((IEnumerable<object>)value1, (IEnumerable<object>)value2); // Ensure non-default value Assert.NotEmpty((IEnumerable<object>)value1); } else if (typeof(IDictionary<string, string>).IsAssignableFrom(property.PropertyType)) { Assert.Equal(value1, value2); // Ensure non-default value Assert.NotEmpty((IDictionary<string, string>)value1); } else if (typeof(IDictionary<object, object>).IsAssignableFrom(property.PropertyType)) { Assert.Equal(value1, value2); // Ensure non-default value Assert.NotEmpty((IDictionary<object, object>)value1); } else if (property.PropertyType.IsValueType || Nullable.GetUnderlyingType(property.PropertyType) != null) { Assert.Equal(value1, value2); // Ensure non-default value Assert.NotEqual(value1, Activator.CreateInstance(property.PropertyType)); } else if (property.Name.Equals(nameof(ActionModel.DisplayName))) { // DisplayName is re-calculated, hence reference equality wouldn't work. Assert.Equal(value1, value2); } else { Assert.Same(value1, value2); // Ensure non-default value Assert.NotNull(value1); } } } private class TestController { public void Edit(int id) { } } private class MyFilterAttribute : Attribute, IFilterMetadata { } private class MyRouteValueAttribute : Attribute, IRouteValueProvider { public string RouteKey { get; set; } public string RouteValue { get; set; } } } }
37.927273
111
0.556727
[ "Apache-2.0" ]
1175169074/aspnetcore
src/Mvc/Mvc.Core/test/ApplicationModels/ActionModelTest.cs
6,258
C#
using QBicSamples.SiteSpecific; using WebsiteTemplate.Data; using WebsiteTemplate.Backend.Services; using WebsiteTemplate.Menus.BaseItems; namespace QBicSamples.Samples.UserSpecificData.Patients { public class AddPatient : ModifyPatient { public AddPatient(DataService dataService, UserContext userContext) : base(dataService, true, userContext) { } public override EventNumber GetId() { return MenuNumber.AddPatient; } } }
26.210526
114
0.706827
[ "MIT" ]
quintonn/QBicSamples
QBicSamples/Samples/UserSpecificData/Patients/AddPatient.cs
500
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace UnderTheCursorTranslatorLibrary { class WordTranslation : IComparable<WordTranslation>, IComparable { public WordTranslation(string word, string translation, string transcription) { Word = word; Translation = translation; Transcription = transcription; } public int Number { get; set; } public string Word { get; set; } public string Transcription { get; set; } public string Translation { get; set; } public int CompareTo(WordTranslation other) { return Word.CompareTo(other.Word); } public int CompareTo(object obj) { return Word.CompareTo((obj as WordTranslation).Word); } } }
14.769231
79
0.688802
[ "Apache-2.0" ]
KvanTTT/Draft-Projects
UnderTheCursorTranslator/UnderTheCursorTranslatorLibrary/WordTranslation.cs
770
C#
// ------------------------------------------------------------------------------ // Copyright (c) 2015 Microsoft Corporation // // 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. // ------------------------------------------------------------------------------ namespace Microsoft.OneDrive.Sdk { using System.Collections.Generic; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Threading.Tasks; /// <summary> /// An <see cref="IAuthenticationProvider"/> implementation using the Live SDK. /// </summary> public abstract class AuthenticationProvider : IAuthenticationProvider { /// <summary> /// Constructs an <see cref="AuthenticationProvider"/>. /// </summary> protected AuthenticationProvider(ServiceInfo serviceInfo) { this.ServiceInfo = serviceInfo; } public AccountSession CurrentAccountSession { get; set; } public ServiceInfo ServiceInfo { get; private set; } /// <summary> /// Appends the authentication header to the specified web request. /// </summary> /// <param name="request">The <see cref="HttpRequestMessage"/> to authenticate.</param> /// <returns>The task to await.</returns> public virtual async Task AppendAuthHeaderAsync(HttpRequestMessage request) { if (this.CurrentAccountSession == null) { await this.AuthenticateAsync(); } if (this.CurrentAccountSession != null && !string.IsNullOrEmpty(this.CurrentAccountSession.AccessToken)) { request.Headers.Authorization = new AuthenticationHeaderValue(Constants.Headers.Bearer, this.CurrentAccountSession.AccessToken); } } /// <summary> /// Retrieves the authentication token. /// </summary> /// <returns>The authentication token.</returns> public virtual async Task<AccountSession> AuthenticateAsync() { var authResult = await this.ProcessCachedAccountSessionAsync(this.CurrentAccountSession); if (authResult != null) { return authResult; } var cachedResult = this.GetAuthenticationResultFromCache(); authResult = await this.ProcessCachedAccountSessionAsync(cachedResult); if (authResult != null) { this.CacheAuthResult(authResult); return authResult; } if (cachedResult != null) { // If we haven't retrieved a valid auth result using cached values, delete the credentials from the cache. this.DeleteUserCredentialsFromCache(cachedResult); } authResult = await this.GetAuthenticationResultAsync(); if (authResult != null) { this.CacheAuthResult(authResult); } return authResult; } /// <summary> /// Signs the current user out. /// </summary> public abstract Task SignOutAsync(); protected void CacheAuthResult(AccountSession accountSession) { this.CurrentAccountSession = accountSession; if (this.ServiceInfo.CredentialCache != null) { this.ServiceInfo.CredentialCache.AddToCache(accountSession); } } protected void DeleteUserCredentialsFromCache(AccountSession accountSession) { if (this.ServiceInfo.CredentialCache != null) { this.ServiceInfo.CredentialCache.DeleteFromCache(accountSession); } } protected abstract Task<AccountSession> GetAuthenticationResultAsync(); protected AccountSession GetAuthenticationResultFromCache() { if (this.ServiceInfo.CredentialCache != null) { var cacheResult = this.ServiceInfo.CredentialCache.GetResultFromCache( this.ServiceInfo.AccountType, this.ServiceInfo.AppId, this.ServiceInfo.UserId); return cacheResult; } return null; } protected virtual Task<AccountSession> RefreshAccessTokenAsync(string refreshToken) { return this.SendTokenRequestAsync(this.GetRefreshTokenRequestBody(refreshToken)); } internal string GetRefreshTokenRequestBody(string refreshToken) { var requestBodyStringBuilder = new StringBuilder(); requestBodyStringBuilder.AppendFormat("{0}={1}", Constants.Authentication.RedirectUriKeyName, this.ServiceInfo.ReturnUrl); requestBodyStringBuilder.AppendFormat("&{0}={1}", Constants.Authentication.ClientIdKeyName, this.ServiceInfo.AppId); requestBodyStringBuilder.AppendFormat("&{0}={1}", Constants.Authentication.ScopeKeyName, string.Join("%20", this.ServiceInfo.Scopes)); requestBodyStringBuilder.AppendFormat("&{0}={1}", Constants.Authentication.RefreshTokenKeyName, refreshToken); requestBodyStringBuilder.AppendFormat("&{0}={1}", Constants.Authentication.GrantTypeKeyName, Constants.Authentication.RefreshTokenKeyName); if (!string.IsNullOrEmpty(this.ServiceInfo.ClientSecret)) { requestBodyStringBuilder.AppendFormat("&{0}={1}", Constants.Authentication.ClientSecretKeyName, this.ServiceInfo.ClientSecret); } return requestBodyStringBuilder.ToString(); } internal async Task<AccountSession> ProcessCachedAccountSessionAsync(AccountSession accountSession) { if (accountSession != null) { // If we have cached credentials and they're not expiring, return them. if (!string.IsNullOrEmpty(accountSession.AccessToken) && !accountSession.IsExpiring()) { return accountSession; } // If we don't have an access token or it's expiring, see if we can refresh the access token. if (!string.IsNullOrEmpty(accountSession.RefreshToken)) { accountSession = await this.RefreshAccessTokenAsync(accountSession.RefreshToken); if (accountSession != null && !string.IsNullOrEmpty(accountSession.AccessToken)) { this.CacheAuthResult(accountSession); return accountSession; } } } return null; } internal async Task<AccountSession> SendTokenRequestAsync(string requestBodyString) { var httpRequestMessage = new HttpRequestMessage(HttpMethod.Post, this.ServiceInfo.TokenServiceUrl); httpRequestMessage.Content = new StringContent(requestBodyString, Encoding.UTF8, Constants.Headers.FormUrlEncodedContentType); using (var authResponse = await this.ServiceInfo.HttpProvider.SendAsync(httpRequestMessage)) using (var responseStream = await authResponse.Content.ReadAsStreamAsync()) { var responseValues = this.ServiceInfo.HttpProvider.Serializer.DeserializeObject<IDictionary<string, string>>( responseStream); if (responseValues != null) { OAuthErrorHandler.ThrowIfError(responseValues); return new AccountSession(responseValues, this.ServiceInfo.AppId, AccountType.MicrosoftAccount); } throw new OneDriveException( new Error { Code = OneDriveErrorCode.AuthenticationFailure.ToString(), Message = "Authentication failed. No response values returned from authentication flow." }); } } } }
41.38009
151
0.612575
[ "MIT" ]
jbatonnet/SmartSync
SmartSync.OneDrive/OneDriveSdk/Authentication/AuthenticationProvider.cs
9,147
C#
namespace ReactNativeCmdEase { partial class Form1 { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); System.Windows.Forms.ColumnHeader columnHeader1; System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(Form1)); this.label1 = new System.Windows.Forms.Label(); this.textBox1 = new System.Windows.Forms.TextBox(); this.button1 = new System.Windows.Forms.Button(); this.label2 = new System.Windows.Forms.Label(); this.label3 = new System.Windows.Forms.Label(); this.pictureBox1 = new System.Windows.Forms.PictureBox(); this.folderBrowserDialog1 = new System.Windows.Forms.FolderBrowserDialog(); this.label4 = new System.Windows.Forms.Label(); this.label7 = new System.Windows.Forms.Label(); this.textBox2 = new System.Windows.Forms.TextBox(); this.textBox3 = new System.Windows.Forms.TextBox(); this.button2 = new System.Windows.Forms.Button(); this.textBox4 = new System.Windows.Forms.TextBox(); this.label15 = new System.Windows.Forms.Label(); this.textBox5 = new System.Windows.Forms.TextBox(); this.label16 = new System.Windows.Forms.Label(); this.label17 = new System.Windows.Forms.Label(); this.button3 = new System.Windows.Forms.Button(); this.button4 = new System.Windows.Forms.Button(); this.button5 = new System.Windows.Forms.Button(); this.button6 = new System.Windows.Forms.Button(); this.textBox6 = new System.Windows.Forms.TextBox(); this.label18 = new System.Windows.Forms.Label(); this.button7 = new System.Windows.Forms.Button(); this.label19 = new System.Windows.Forms.Label(); this.button8 = new System.Windows.Forms.Button(); this.button9 = new System.Windows.Forms.Button(); this.label20 = new System.Windows.Forms.Label(); this.button10 = new System.Windows.Forms.Button(); this.comboBox1 = new System.Windows.Forms.ComboBox(); this.button11 = new System.Windows.Forms.Button(); this.button12 = new System.Windows.Forms.Button(); this.timer2 = new System.Windows.Forms.Timer(this.components); this.button13 = new System.Windows.Forms.Button(); this.button14 = new System.Windows.Forms.Button(); this.button15 = new System.Windows.Forms.Button(); this.textBox7 = new System.Windows.Forms.TextBox(); this.label21 = new System.Windows.Forms.Label(); this.button16 = new System.Windows.Forms.Button(); this.button17 = new System.Windows.Forms.Button(); this.label26 = new System.Windows.Forms.Label(); this.button18 = new System.Windows.Forms.Button(); this.button19 = new System.Windows.Forms.Button(); this.button20 = new System.Windows.Forms.Button(); this.button21 = new System.Windows.Forms.Button(); this.comboBox3 = new System.Windows.Forms.ComboBox(); this.label29 = new System.Windows.Forms.Label(); this.button22 = new System.Windows.Forms.Button(); this.button23 = new System.Windows.Forms.Button(); this.label27 = new System.Windows.Forms.Label(); this.label28 = new System.Windows.Forms.Label(); this.label30 = new System.Windows.Forms.Label(); this.label31 = new System.Windows.Forms.Label(); this.label32 = new System.Windows.Forms.Label(); this.label33 = new System.Windows.Forms.Label(); this.label34 = new System.Windows.Forms.Label(); this.label35 = new System.Windows.Forms.Label(); this.timer3 = new System.Windows.Forms.Timer(this.components); this.button26 = new System.Windows.Forms.Button(); this.button25 = new System.Windows.Forms.Button(); this.textBox8 = new System.Windows.Forms.TextBox(); this.label36 = new System.Windows.Forms.Label(); this.button27 = new System.Windows.Forms.Button(); this.label37 = new System.Windows.Forms.Label(); this.listView1 = new System.Windows.Forms.ListView(); this.label38 = new System.Windows.Forms.Label(); this.label39 = new System.Windows.Forms.Label(); this.radioButton1 = new System.Windows.Forms.RadioButton(); this.radioButton2 = new System.Windows.Forms.RadioButton(); this.label40 = new System.Windows.Forms.Label(); this.checkBox1 = new System.Windows.Forms.CheckBox(); this.button28 = new System.Windows.Forms.Button(); this.checkBox2 = new System.Windows.Forms.CheckBox(); this.label8 = new System.Windows.Forms.Label(); this.timer6 = new System.Windows.Forms.Timer(this.components); columnHeader1 = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader())); ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).BeginInit(); this.SuspendLayout(); // // columnHeader1 // columnHeader1.Text = "Output"; columnHeader1.Width = 450; // // label1 // this.label1.AutoSize = true; this.label1.Font = new System.Drawing.Font("Verdana", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label1.Location = new System.Drawing.Point(16, 211); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(126, 16); this.label1.TabIndex = 0; this.label1.Text = "Project Directory:"; // // textBox1 // this.textBox1.BackColor = System.Drawing.SystemColors.ActiveCaptionText; this.textBox1.Enabled = false; this.textBox1.Font = new System.Drawing.Font("Verdana", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.textBox1.ForeColor = System.Drawing.SystemColors.Window; this.textBox1.Location = new System.Drawing.Point(47, 227); this.textBox1.Name = "textBox1"; this.textBox1.Size = new System.Drawing.Size(309, 23); this.textBox1.TabIndex = 1; this.textBox1.TextChanged += new System.EventHandler(this.TextBox1_TextChanged); // // button1 // this.button1.BackColor = System.Drawing.SystemColors.ActiveCaptionText; this.button1.Font = new System.Drawing.Font("Verdana", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.button1.Location = new System.Drawing.Point(366, 227); this.button1.Name = "button1"; this.button1.Size = new System.Drawing.Size(142, 23); this.button1.TabIndex = 2; this.button1.Text = "Select folder.."; this.button1.UseVisualStyleBackColor = false; this.button1.Click += new System.EventHandler(this.Button1_Click); // // label2 // this.label2.AutoSize = true; this.label2.Font = new System.Drawing.Font("Verdana", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label2.Location = new System.Drawing.Point(18, 266); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(145, 16); this.label2.TabIndex = 3; this.label2.Text = "Project Initialization:"; // // label3 // this.label3.AutoSize = true; this.label3.Font = new System.Drawing.Font("Verdana", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label3.Location = new System.Drawing.Point(76, 288); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(76, 16); this.label3.TabIndex = 4; this.label3.Text = "Not Found"; // // pictureBox1 // this.pictureBox1.BackColor = System.Drawing.Color.Red; this.pictureBox1.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.pictureBox1.Location = new System.Drawing.Point(47, 282); this.pictureBox1.Name = "pictureBox1"; this.pictureBox1.Size = new System.Drawing.Size(23, 23); this.pictureBox1.TabIndex = 5; this.pictureBox1.TabStop = false; this.pictureBox1.Click += new System.EventHandler(this.PictureBox1_Click); // // label4 // this.label4.AutoSize = true; this.label4.Font = new System.Drawing.Font("Verdana", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label4.Location = new System.Drawing.Point(179, 266); this.label4.Name = "label4"; this.label4.Size = new System.Drawing.Size(102, 16); this.label4.TabIndex = 6; this.label4.Text = "Project Name:"; // // label7 // this.label7.AutoSize = true; this.label7.Font = new System.Drawing.Font("Verdana", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label7.Location = new System.Drawing.Point(315, 266); this.label7.Name = "label7"; this.label7.Size = new System.Drawing.Size(83, 16); this.label7.TabIndex = 8; this.label7.Text = "RN Version:"; // // textBox2 // this.textBox2.BackColor = System.Drawing.SystemColors.ActiveCaptionText; this.textBox2.Enabled = false; this.textBox2.Font = new System.Drawing.Font("Verdana", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.textBox2.ForeColor = System.Drawing.SystemColors.Info; this.textBox2.Location = new System.Drawing.Point(182, 285); this.textBox2.Name = "textBox2"; this.textBox2.Size = new System.Drawing.Size(130, 23); this.textBox2.TabIndex = 10; // // textBox3 // this.textBox3.BackColor = System.Drawing.SystemColors.ActiveCaptionText; this.textBox3.Enabled = false; this.textBox3.Font = new System.Drawing.Font("Verdana", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.textBox3.ForeColor = System.Drawing.SystemColors.Info; this.textBox3.Location = new System.Drawing.Point(318, 285); this.textBox3.Name = "textBox3"; this.textBox3.Size = new System.Drawing.Size(83, 23); this.textBox3.TabIndex = 11; // // button2 // this.button2.BackColor = System.Drawing.SystemColors.ActiveCaptionText; this.button2.Enabled = false; this.button2.Font = new System.Drawing.Font("Verdana", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.button2.ForeColor = System.Drawing.SystemColors.Info; this.button2.Location = new System.Drawing.Point(685, 283); this.button2.Name = "button2"; this.button2.Size = new System.Drawing.Size(109, 26); this.button2.TabIndex = 12; this.button2.Text = "Init"; this.button2.UseVisualStyleBackColor = false; this.button2.Click += new System.EventHandler(this.Button2_Click); // // textBox4 // this.textBox4.BackColor = System.Drawing.SystemColors.ActiveCaptionText; this.textBox4.Font = new System.Drawing.Font("Verdana", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.textBox4.ForeColor = System.Drawing.SystemColors.Info; this.textBox4.Location = new System.Drawing.Point(47, 28); this.textBox4.Name = "textBox4"; this.textBox4.Size = new System.Drawing.Size(747, 23); this.textBox4.TabIndex = 23; this.textBox4.TextChanged += new System.EventHandler(this.textBox4_TextChanged); // // label15 // this.label15.AutoSize = true; this.label15.Font = new System.Drawing.Font("Verdana", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label15.Location = new System.Drawing.Point(16, 9); this.label15.Name = "label15"; this.label15.Size = new System.Drawing.Size(235, 16); this.label15.TabIndex = 22; this.label15.Text = "JAVA_HOME environment variable:"; // // textBox5 // this.textBox5.BackColor = System.Drawing.SystemColors.ActiveCaptionText; this.textBox5.Font = new System.Drawing.Font("Verdana", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.textBox5.ForeColor = System.Drawing.SystemColors.Info; this.textBox5.Location = new System.Drawing.Point(47, 74); this.textBox5.Name = "textBox5"; this.textBox5.Size = new System.Drawing.Size(746, 23); this.textBox5.TabIndex = 25; this.textBox5.TextChanged += new System.EventHandler(this.textBox5_TextChanged); // // label16 // this.label16.AutoSize = true; this.label16.Font = new System.Drawing.Font("Verdana", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label16.Location = new System.Drawing.Point(16, 55); this.label16.Name = "label16"; this.label16.Size = new System.Drawing.Size(261, 16); this.label16.TabIndex = 24; this.label16.Text = "ANDROID_HOME environment variable:"; // // label17 // this.label17.AutoSize = true; this.label17.Font = new System.Drawing.Font("Verdana", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label17.Location = new System.Drawing.Point(16, 319); this.label17.Name = "label17"; this.label17.Size = new System.Drawing.Size(135, 16); this.label17.TabIndex = 26; this.label17.Text = "Project commands:"; // // button3 // this.button3.BackColor = System.Drawing.SystemColors.ActiveCaptionText; this.button3.Enabled = false; this.button3.Font = new System.Drawing.Font("Verdana", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.button3.ForeColor = System.Drawing.SystemColors.Control; this.button3.Location = new System.Drawing.Point(310, 464); this.button3.Name = "button3"; this.button3.Size = new System.Drawing.Size(118, 26); this.button3.TabIndex = 27; this.button3.Text = "npm install"; this.button3.UseVisualStyleBackColor = false; this.button3.Click += new System.EventHandler(this.Button3_Click); // // button4 // this.button4.BackColor = System.Drawing.SystemColors.ActiveCaptionText; this.button4.Enabled = false; this.button4.Font = new System.Drawing.Font("Verdana", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.button4.ForeColor = System.Drawing.SystemColors.Control; this.button4.Location = new System.Drawing.Point(434, 464); this.button4.Name = "button4"; this.button4.Size = new System.Drawing.Size(123, 26); this.button4.TabIndex = 28; this.button4.Text = "npm update"; this.button4.UseVisualStyleBackColor = false; this.button4.Click += new System.EventHandler(this.Button4_Click); // // button5 // this.button5.BackColor = System.Drawing.SystemColors.ActiveCaptionText; this.button5.Enabled = false; this.button5.Font = new System.Drawing.Font("Verdana", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.button5.ForeColor = System.Drawing.SystemColors.Control; this.button5.Location = new System.Drawing.Point(43, 464); this.button5.Name = "button5"; this.button5.Size = new System.Drawing.Size(163, 26); this.button5.TabIndex = 29; this.button5.Text = "Delete node_modules"; this.button5.UseVisualStyleBackColor = false; this.button5.Click += new System.EventHandler(this.Button5_Click); // // button6 // this.button6.BackColor = System.Drawing.SystemColors.ActiveCaptionText; this.button6.Enabled = false; this.button6.Font = new System.Drawing.Font("Verdana", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.button6.ForeColor = System.Drawing.SystemColors.Control; this.button6.Location = new System.Drawing.Point(212, 464); this.button6.Name = "button6"; this.button6.Size = new System.Drawing.Size(92, 26); this.button6.TabIndex = 30; this.button6.Text = "npm clean"; this.button6.UseVisualStyleBackColor = false; this.button6.Click += new System.EventHandler(this.Button6_Click_1); // // textBox6 // this.textBox6.BackColor = System.Drawing.SystemColors.ActiveCaptionText; this.textBox6.Enabled = false; this.textBox6.Font = new System.Drawing.Font("Verdana", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.textBox6.ForeColor = System.Drawing.SystemColors.Info; this.textBox6.Location = new System.Drawing.Point(565, 285); this.textBox6.Name = "textBox6"; this.textBox6.Size = new System.Drawing.Size(112, 23); this.textBox6.TabIndex = 32; // // label18 // this.label18.AutoSize = true; this.label18.Font = new System.Drawing.Font("Verdana", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label18.Location = new System.Drawing.Point(562, 266); this.label18.Name = "label18"; this.label18.Size = new System.Drawing.Size(67, 16); this.label18.TabIndex = 31; this.label18.Text = "Installer:"; // // button7 // this.button7.BackColor = System.Drawing.SystemColors.ActiveCaptionText; this.button7.Enabled = false; this.button7.Font = new System.Drawing.Font("Verdana", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.button7.ForeColor = System.Drawing.SystemColors.Control; this.button7.Location = new System.Drawing.Point(563, 464); this.button7.Name = "button7"; this.button7.Size = new System.Drawing.Size(112, 26); this.button7.TabIndex = 33; this.button7.Text = "yarn install++"; this.button7.UseVisualStyleBackColor = false; this.button7.Click += new System.EventHandler(this.Button7_Click); // // label19 // this.label19.AutoSize = true; this.label19.Font = new System.Drawing.Font("Verdana", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label19.Location = new System.Drawing.Point(12, 565); this.label19.Name = "label19"; this.label19.Size = new System.Drawing.Size(137, 16); this.label19.TabIndex = 34; this.label19.Text = "Android commands:"; // // button8 // this.button8.BackColor = System.Drawing.SystemColors.ActiveCaptionText; this.button8.Enabled = false; this.button8.Font = new System.Drawing.Font("Verdana", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.button8.ForeColor = System.Drawing.SystemColors.Control; this.button8.Location = new System.Drawing.Point(43, 613); this.button8.Name = "button8"; this.button8.Size = new System.Drawing.Size(97, 26); this.button8.TabIndex = 35; this.button8.Text = "Clean build"; this.button8.UseVisualStyleBackColor = false; this.button8.Click += new System.EventHandler(this.Button8_Click); // // button9 // this.button9.BackColor = System.Drawing.SystemColors.ActiveCaptionText; this.button9.Enabled = false; this.button9.Font = new System.Drawing.Font("Verdana", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.button9.ForeColor = System.Drawing.SystemColors.Control; this.button9.Location = new System.Drawing.Point(45, 523); this.button9.Name = "button9"; this.button9.Size = new System.Drawing.Size(95, 26); this.button9.TabIndex = 36; this.button9.Text = "Kill adbs"; this.button9.UseVisualStyleBackColor = false; this.button9.Click += new System.EventHandler(this.Button9_Click); // // label20 // this.label20.AutoSize = true; this.label20.Font = new System.Drawing.Font("Verdana", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label20.Location = new System.Drawing.Point(14, 503); this.label20.Name = "label20"; this.label20.Size = new System.Drawing.Size(132, 16); this.label20.TabIndex = 37; this.label20.Text = "Android emulators:"; // // button10 // this.button10.BackColor = System.Drawing.SystemColors.ActiveCaptionText; this.button10.Font = new System.Drawing.Font("Verdana", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.button10.ForeColor = System.Drawing.SystemColors.Control; this.button10.Location = new System.Drawing.Point(146, 523); this.button10.Name = "button10"; this.button10.Size = new System.Drawing.Size(112, 26); this.button10.TabIndex = 38; this.button10.Text = "Update list >>"; this.button10.UseVisualStyleBackColor = false; this.button10.Click += new System.EventHandler(this.Button10_Click); // // comboBox1 // this.comboBox1.BackColor = System.Drawing.SystemColors.ActiveCaptionText; this.comboBox1.Font = new System.Drawing.Font("Verdana", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.comboBox1.ForeColor = System.Drawing.SystemColors.Control; this.comboBox1.FormattingEnabled = true; this.comboBox1.Location = new System.Drawing.Point(264, 525); this.comboBox1.Name = "comboBox1"; this.comboBox1.Size = new System.Drawing.Size(164, 24); this.comboBox1.TabIndex = 39; this.comboBox1.SelectedIndexChanged += new System.EventHandler(this.ComboBox1_SelectedIndexChanged); // // button11 // this.button11.BackColor = System.Drawing.SystemColors.ActiveCaptionText; this.button11.Enabled = false; this.button11.Font = new System.Drawing.Font("Verdana", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.button11.ForeColor = System.Drawing.SystemColors.Control; this.button11.Location = new System.Drawing.Point(434, 523); this.button11.Name = "button11"; this.button11.Size = new System.Drawing.Size(123, 26); this.button11.TabIndex = 40; this.button11.Text = "Start Emulator"; this.button11.UseVisualStyleBackColor = false; this.button11.Click += new System.EventHandler(this.Button11_Click); // // button12 // this.button12.BackColor = System.Drawing.SystemColors.ActiveCaptionText; this.button12.Enabled = false; this.button12.Font = new System.Drawing.Font("Verdana", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.button12.ForeColor = System.Drawing.SystemColors.Control; this.button12.Location = new System.Drawing.Point(563, 523); this.button12.Name = "button12"; this.button12.Size = new System.Drawing.Size(230, 26); this.button12.TabIndex = 41; this.button12.Text = "Wipe Data + Start Emulator"; this.button12.UseVisualStyleBackColor = false; this.button12.Click += new System.EventHandler(this.Button12_Click); // // timer2 // this.timer2.Enabled = true; this.timer2.Interval = 1000; this.timer2.Tick += new System.EventHandler(this.Timer2_Tick); // // button13 // this.button13.BackColor = System.Drawing.SystemColors.ActiveCaptionText; this.button13.Enabled = false; this.button13.Font = new System.Drawing.Font("Verdana", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.button13.ForeColor = System.Drawing.SystemColors.Control; this.button13.Location = new System.Drawing.Point(264, 613); this.button13.Name = "button13"; this.button13.Size = new System.Drawing.Size(145, 26); this.button13.TabIndex = 42; this.button13.Text = "Run debug"; this.button13.UseVisualStyleBackColor = false; this.button13.Click += new System.EventHandler(this.Button13_Click); // // button14 // this.button14.BackColor = System.Drawing.SystemColors.ActiveCaptionText; this.button14.Enabled = false; this.button14.Font = new System.Drawing.Font("Verdana", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.button14.ForeColor = System.Drawing.SystemColors.Control; this.button14.Location = new System.Drawing.Point(415, 613); this.button14.Name = "button14"; this.button14.Size = new System.Drawing.Size(142, 26); this.button14.TabIndex = 43; this.button14.Text = "Run release"; this.button14.UseVisualStyleBackColor = false; this.button14.Click += new System.EventHandler(this.Button14_Click); // // button15 // this.button15.BackColor = System.Drawing.SystemColors.ActiveCaptionText; this.button15.Enabled = false; this.button15.Font = new System.Drawing.Font("Verdana", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.button15.ForeColor = System.Drawing.SystemColors.Control; this.button15.Location = new System.Drawing.Point(563, 613); this.button15.Name = "button15"; this.button15.Size = new System.Drawing.Size(230, 26); this.button15.TabIndex = 44; this.button15.Text = "Build release (app bundles)"; this.button15.UseVisualStyleBackColor = false; this.button15.Click += new System.EventHandler(this.Button15_Click); // // textBox7 // this.textBox7.BackColor = System.Drawing.SystemColors.ActiveCaptionText; this.textBox7.Font = new System.Drawing.Font("Verdana", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.textBox7.ForeColor = System.Drawing.SystemColors.Info; this.textBox7.Location = new System.Drawing.Point(47, 119); this.textBox7.Name = "textBox7"; this.textBox7.Size = new System.Drawing.Size(746, 23); this.textBox7.TabIndex = 46; this.textBox7.TextChanged += new System.EventHandler(this.textBox7_TextChanged); // // label21 // this.label21.AutoSize = true; this.label21.Font = new System.Drawing.Font("Verdana", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label21.Location = new System.Drawing.Point(16, 100); this.label21.Name = "label21"; this.label21.Size = new System.Drawing.Size(377, 16); this.label21.TabIndex = 45; this.label21.Text = "Android Platform tools dir in PATH environment variable:"; // // button16 // this.button16.BackColor = System.Drawing.SystemColors.ActiveCaptionText; this.button16.Enabled = false; this.button16.Font = new System.Drawing.Font("Verdana", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.button16.ForeColor = System.Drawing.SystemColors.Control; this.button16.Location = new System.Drawing.Point(563, 584); this.button16.Name = "button16"; this.button16.Size = new System.Drawing.Size(229, 26); this.button16.TabIndex = 51; this.button16.Text = "Open build folder.."; this.button16.UseVisualStyleBackColor = false; this.button16.Click += new System.EventHandler(this.Button16_Click); // // button17 // this.button17.BackColor = System.Drawing.SystemColors.ActiveCaptionText; this.button17.Enabled = false; this.button17.Font = new System.Drawing.Font("Verdana", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.button17.Location = new System.Drawing.Point(514, 225); this.button17.Name = "button17"; this.button17.Size = new System.Drawing.Size(125, 26); this.button17.TabIndex = 52; this.button17.Text = "Open folder.."; this.button17.UseVisualStyleBackColor = false; this.button17.Click += new System.EventHandler(this.Button17_Click); // // label26 // this.label26.AutoSize = true; this.label26.Font = new System.Drawing.Font("Verdana", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label26.Location = new System.Drawing.Point(42, 345); this.label26.Name = "label26"; this.label26.Size = new System.Drawing.Size(181, 16); this.label26.TabIndex = 54; this.label26.Text = "Enter npm package name:"; // // button18 // this.button18.BackColor = System.Drawing.SystemColors.ActiveCaptionText; this.button18.Enabled = false; this.button18.Font = new System.Drawing.Font("Verdana", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.button18.ForeColor = System.Drawing.SystemColors.Control; this.button18.Location = new System.Drawing.Point(264, 432); this.button18.Name = "button18"; this.button18.Size = new System.Drawing.Size(164, 26); this.button18.TabIndex = 55; this.button18.Text = "Yarn upgrade"; this.button18.UseVisualStyleBackColor = false; this.button18.Click += new System.EventHandler(this.Button18_Click); // // button19 // this.button19.BackColor = System.Drawing.SystemColors.ActiveCaptionText; this.button19.Enabled = false; this.button19.Font = new System.Drawing.Font("Verdana", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.button19.ForeColor = System.Drawing.SystemColors.Control; this.button19.Location = new System.Drawing.Point(434, 432); this.button19.Name = "button19"; this.button19.Size = new System.Drawing.Size(123, 26); this.button19.TabIndex = 56; this.button19.Text = "Npm update"; this.button19.UseVisualStyleBackColor = false; this.button19.Click += new System.EventHandler(this.Button19_Click); // // button20 // this.button20.BackColor = System.Drawing.SystemColors.ActiveCaptionText; this.button20.Enabled = false; this.button20.Font = new System.Drawing.Font("Verdana", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.button20.ForeColor = System.Drawing.SystemColors.Control; this.button20.Location = new System.Drawing.Point(684, 432); this.button20.Name = "button20"; this.button20.Size = new System.Drawing.Size(108, 26); this.button20.TabIndex = 60; this.button20.Text = "Npm uninstall"; this.button20.UseVisualStyleBackColor = false; this.button20.Click += new System.EventHandler(this.Button20_Click); // // button21 // this.button21.BackColor = System.Drawing.SystemColors.ActiveCaptionText; this.button21.Enabled = false; this.button21.Font = new System.Drawing.Font("Verdana", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.button21.ForeColor = System.Drawing.SystemColors.Control; this.button21.Location = new System.Drawing.Point(563, 432); this.button21.Name = "button21"; this.button21.Size = new System.Drawing.Size(112, 26); this.button21.TabIndex = 59; this.button21.Text = "Yarn remove"; this.button21.UseVisualStyleBackColor = false; this.button21.Click += new System.EventHandler(this.Button21_Click); // // comboBox3 // this.comboBox3.BackColor = System.Drawing.SystemColors.InfoText; this.comboBox3.Enabled = false; this.comboBox3.Font = new System.Drawing.Font("Verdana", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.comboBox3.ForeColor = System.Drawing.SystemColors.Info; this.comboBox3.FormattingEnabled = true; this.comboBox3.Location = new System.Drawing.Point(264, 342); this.comboBox3.Name = "comboBox3"; this.comboBox3.Size = new System.Drawing.Size(411, 24); this.comboBox3.TabIndex = 57; this.comboBox3.SelectedIndexChanged += new System.EventHandler(this.ComboBox3_SelectedIndexChanged); this.comboBox3.TextChanged += new System.EventHandler(this.ComboBox3_TextChanged); // // label29 // this.label29.Anchor = System.Windows.Forms.AnchorStyles.Left; this.label29.Font = new System.Drawing.Font("Verdana", 9.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label29.Location = new System.Drawing.Point(679, 342); this.label29.Name = "label29"; this.label29.RightToLeft = System.Windows.Forms.RightToLeft.Yes; this.label29.Size = new System.Drawing.Size(112, 24); this.label29.TabIndex = 62; this.label29.Text = "[not selected]"; this.label29.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; this.label29.Click += new System.EventHandler(this.label29_Click); // // button22 // this.button22.BackColor = System.Drawing.SystemColors.ActiveCaptionText; this.button22.Enabled = false; this.button22.Font = new System.Drawing.Font("Verdana", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.button22.ForeColor = System.Drawing.SystemColors.Control; this.button22.Location = new System.Drawing.Point(146, 432); this.button22.Name = "button22"; this.button22.Size = new System.Drawing.Size(112, 26); this.button22.TabIndex = 64; this.button22.Text = "Npm install"; this.button22.UseVisualStyleBackColor = false; this.button22.Click += new System.EventHandler(this.Button22_Click); // // button23 // this.button23.BackColor = System.Drawing.SystemColors.ActiveCaptionText; this.button23.Enabled = false; this.button23.Font = new System.Drawing.Font("Verdana", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.button23.ForeColor = System.Drawing.SystemColors.Control; this.button23.Location = new System.Drawing.Point(43, 432); this.button23.Name = "button23"; this.button23.Size = new System.Drawing.Size(97, 26); this.button23.TabIndex = 63; this.button23.Text = "Yarn add"; this.button23.UseVisualStyleBackColor = false; this.button23.Click += new System.EventHandler(this.Button23_Click); // // label27 // this.label27.AutoSize = true; this.label27.Font = new System.Drawing.Font("Verdana", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label27.Location = new System.Drawing.Point(40, 378); this.label27.Name = "label27"; this.label27.Size = new System.Drawing.Size(138, 16); this.label27.TabIndex = 65; this.label27.Text = "Package details url:"; // // label28 // this.label28.Anchor = System.Windows.Forms.AnchorStyles.Left; this.label28.Font = new System.Drawing.Font("Verdana", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label28.Location = new System.Drawing.Point(185, 378); this.label28.Name = "label28"; this.label28.RightToLeft = System.Windows.Forms.RightToLeft.No; this.label28.Size = new System.Drawing.Size(606, 16); this.label28.TabIndex = 66; this.label28.Text = " N/A "; this.label28.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; this.label28.Click += new System.EventHandler(this.Label28_Click); // // label30 // this.label30.Anchor = System.Windows.Forms.AnchorStyles.Left; this.label30.Font = new System.Drawing.Font("Verdana", 9F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label30.Location = new System.Drawing.Point(680, 404); this.label30.Name = "label30"; this.label30.RightToLeft = System.Windows.Forms.RightToLeft.Yes; this.label30.Size = new System.Drawing.Size(108, 16); this.label30.TabIndex = 68; this.label30.Text = " N/A "; this.label30.TextAlign = System.Drawing.ContentAlignment.MiddleRight; this.label30.Click += new System.EventHandler(this.label30_Click); // // label31 // this.label31.AutoSize = true; this.label31.Font = new System.Drawing.Font("Verdana", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label31.Location = new System.Drawing.Point(570, 404); this.label31.Name = "label31"; this.label31.Size = new System.Drawing.Size(108, 16); this.label31.TabIndex = 67; this.label31.Text = "Latest version:"; // // label32 // this.label32.Anchor = System.Windows.Forms.AnchorStyles.Left; this.label32.Font = new System.Drawing.Font("Verdana", 9F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label32.Location = new System.Drawing.Point(430, 404); this.label32.Name = "label32"; this.label32.RightToLeft = System.Windows.Forms.RightToLeft.Yes; this.label32.Size = new System.Drawing.Size(110, 16); this.label32.TabIndex = 70; this.label32.Text = " N/A "; this.label32.TextAlign = System.Drawing.ContentAlignment.MiddleRight; this.label32.Click += new System.EventHandler(this.label32_Click); // // label33 // this.label33.AutoSize = true; this.label33.Font = new System.Drawing.Font("Verdana", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label33.Location = new System.Drawing.Point(313, 404); this.label33.Name = "label33"; this.label33.Size = new System.Drawing.Size(115, 16); this.label33.TabIndex = 69; this.label33.Text = "Current version:"; // // label34 // this.label34.Anchor = System.Windows.Forms.AnchorStyles.Left; this.label34.Font = new System.Drawing.Font("Verdana", 9F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label34.Location = new System.Drawing.Point(147, 404); this.label34.Name = "label34"; this.label34.RightToLeft = System.Windows.Forms.RightToLeft.Yes; this.label34.Size = new System.Drawing.Size(110, 16); this.label34.TabIndex = 72; this.label34.Text = " N/A "; this.label34.TextAlign = System.Drawing.ContentAlignment.MiddleRight; // // label35 // this.label35.AutoSize = true; this.label35.Font = new System.Drawing.Font("Verdana", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label35.Location = new System.Drawing.Point(92, 404); this.label35.Name = "label35"; this.label35.Size = new System.Drawing.Size(58, 16); this.label35.TabIndex = 71; this.label35.Text = "Status:"; // // timer3 // this.timer3.Interval = 500; this.timer3.Tick += new System.EventHandler(this.Timer3_Tick); // // button26 // this.button26.BackColor = System.Drawing.SystemColors.ActiveCaptionText; this.button26.Enabled = false; this.button26.Font = new System.Drawing.Font("Verdana", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.button26.ForeColor = System.Drawing.SystemColors.Control; this.button26.Location = new System.Drawing.Point(43, 584); this.button26.Name = "button26"; this.button26.Size = new System.Drawing.Size(215, 26); this.button26.TabIndex = 75; this.button26.Text = "Generate release keystore.."; this.button26.UseVisualStyleBackColor = false; this.button26.Click += new System.EventHandler(this.Button26_Click); // // button25 // this.button25.BackColor = System.Drawing.SystemColors.ActiveCaptionText; this.button25.Enabled = false; this.button25.Font = new System.Drawing.Font("Verdana", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.button25.ForeColor = System.Drawing.SystemColors.Control; this.button25.Location = new System.Drawing.Point(683, 464); this.button25.Name = "button25"; this.button25.Size = new System.Drawing.Size(108, 26); this.button25.TabIndex = 77; this.button25.Text = "Start Metro"; this.button25.UseVisualStyleBackColor = false; this.button25.Click += new System.EventHandler(this.button25_Click_1); // // textBox8 // this.textBox8.BackColor = System.Drawing.SystemColors.ActiveCaptionText; this.textBox8.Enabled = false; this.textBox8.Font = new System.Drawing.Font("Verdana", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.textBox8.ForeColor = System.Drawing.SystemColors.Info; this.textBox8.Location = new System.Drawing.Point(407, 285); this.textBox8.Name = "textBox8"; this.textBox8.Size = new System.Drawing.Size(152, 23); this.textBox8.TabIndex = 79; this.textBox8.Text = "@ui-kitten/template-js"; // // label36 // this.label36.AutoSize = true; this.label36.Font = new System.Drawing.Font("Verdana", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label36.Location = new System.Drawing.Point(404, 266); this.label36.Name = "label36"; this.label36.Size = new System.Drawing.Size(94, 16); this.label36.TabIndex = 78; this.label36.Text = "RN template:"; // // button27 // this.button27.BackColor = System.Drawing.SystemColors.ActiveCaptionText; this.button27.Enabled = false; this.button27.Font = new System.Drawing.Font("Verdana", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.button27.Location = new System.Drawing.Point(645, 225); this.button27.Name = "button27"; this.button27.Size = new System.Drawing.Size(149, 26); this.button27.TabIndex = 80; this.button27.Text = "Open with Atom"; this.button27.UseVisualStyleBackColor = false; this.button27.Click += new System.EventHandler(this.button27_Click_1); // // label37 // this.label37.AutoSize = true; this.label37.Font = new System.Drawing.Font("Verdana", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label37.Location = new System.Drawing.Point(807, 9); this.label37.Name = "label37"; this.label37.Size = new System.Drawing.Size(65, 16); this.label37.TabIndex = 81; this.label37.Text = "Console:"; this.label37.Click += new System.EventHandler(this.label37_Click); // // listView1 // this.listView1.BackColor = System.Drawing.SystemColors.MenuText; this.listView1.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] { columnHeader1}); this.listView1.Font = new System.Drawing.Font("Verdana", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.listView1.ForeColor = System.Drawing.SystemColors.Menu; this.listView1.FullRowSelect = true; this.listView1.GridLines = true; this.listView1.HideSelection = false; this.listView1.Location = new System.Drawing.Point(810, 28); this.listView1.MultiSelect = false; this.listView1.Name = "listView1"; this.listView1.Size = new System.Drawing.Size(484, 611); this.listView1.TabIndex = 82; this.listView1.UseCompatibleStateImageBehavior = false; this.listView1.View = System.Windows.Forms.View.Details; this.listView1.SelectedIndexChanged += new System.EventHandler(this.listView1_SelectedIndexChanged); this.listView1.MouseDown += new System.Windows.Forms.MouseEventHandler(this.listView1_MouseDown); // // label38 // this.label38.AutoSize = true; this.label38.Font = new System.Drawing.Font("Verdana", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label38.Location = new System.Drawing.Point(1094, 9); this.label38.Name = "label38"; this.label38.RightToLeft = System.Windows.Forms.RightToLeft.No; this.label38.Size = new System.Drawing.Size(0, 16); this.label38.TabIndex = 83; this.label38.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; // // label39 // this.label39.AutoSize = true; this.label39.Font = new System.Drawing.Font("Verdana", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label39.Location = new System.Drawing.Point(16, 153); this.label39.Name = "label39"; this.label39.Size = new System.Drawing.Size(146, 16); this.label39.TabIndex = 84; this.label39.Text = "Application Settings:"; // // radioButton1 // this.radioButton1.AutoSize = true; this.radioButton1.Checked = true; this.radioButton1.Font = new System.Drawing.Font("Verdana", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.radioButton1.Location = new System.Drawing.Point(61, 172); this.radioButton1.Name = "radioButton1"; this.radioButton1.Size = new System.Drawing.Size(98, 20); this.radioButton1.TabIndex = 85; this.radioButton1.TabStop = true; this.radioButton1.Text = "Light Mood"; this.radioButton1.UseVisualStyleBackColor = true; this.radioButton1.CheckedChanged += new System.EventHandler(this.radioButton1_CheckedChanged); // // radioButton2 // this.radioButton2.AutoSize = true; this.radioButton2.Font = new System.Drawing.Font("Verdana", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.radioButton2.Location = new System.Drawing.Point(163, 173); this.radioButton2.Name = "radioButton2"; this.radioButton2.Size = new System.Drawing.Size(95, 20); this.radioButton2.TabIndex = 86; this.radioButton2.Text = "Dark Mood"; this.radioButton2.UseVisualStyleBackColor = true; this.radioButton2.CheckedChanged += new System.EventHandler(this.radioButton2_CheckedChanged); // // label40 // this.label40.AutoSize = true; this.label40.Font = new System.Drawing.Font("Verdana", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label40.Location = new System.Drawing.Point(420, 153); this.label40.Name = "label40"; this.label40.Size = new System.Drawing.Size(137, 16); this.label40.TabIndex = 87; this.label40.Text = "Command Settings:"; // // checkBox1 // this.checkBox1.AutoSize = true; this.checkBox1.Checked = true; this.checkBox1.CheckState = System.Windows.Forms.CheckState.Checked; this.checkBox1.Font = new System.Drawing.Font("Verdana", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.checkBox1.Location = new System.Drawing.Point(469, 174); this.checkBox1.Name = "checkBox1"; this.checkBox1.Size = new System.Drawing.Size(160, 20); this.checkBox1.TabIndex = 88; this.checkBox1.Text = "RNCMDEase Console"; this.checkBox1.UseVisualStyleBackColor = true; this.checkBox1.CheckedChanged += new System.EventHandler(this.checkBox1_CheckedChanged); // // button28 // this.button28.BackColor = System.Drawing.SystemColors.ActiveCaptionText; this.button28.Enabled = false; this.button28.Font = new System.Drawing.Font("Verdana", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.button28.ForeColor = System.Drawing.SystemColors.Control; this.button28.Location = new System.Drawing.Point(146, 613); this.button28.Name = "button28"; this.button28.Size = new System.Drawing.Size(112, 26); this.button28.TabIndex = 89; this.button28.Text = "Clean Proc"; this.button28.UseVisualStyleBackColor = false; this.button28.Click += new System.EventHandler(this.button28_Click); // // checkBox2 // this.checkBox2.AutoSize = true; this.checkBox2.Font = new System.Drawing.Font("Verdana", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.checkBox2.Location = new System.Drawing.Point(645, 174); this.checkBox2.Name = "checkBox2"; this.checkBox2.Size = new System.Drawing.Size(151, 20); this.checkBox2.TabIndex = 90; this.checkBox2.Text = "FullScreen Console"; this.checkBox2.UseVisualStyleBackColor = true; this.checkBox2.CheckedChanged += new System.EventHandler(this.checkBox2_CheckedChanged); // // label8 // this.label8.AutoSize = true; this.label8.Font = new System.Drawing.Font("Verdana", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label8.Location = new System.Drawing.Point(436, 9); this.label8.Name = "label8"; this.label8.Size = new System.Drawing.Size(0, 16); this.label8.TabIndex = 93; this.label8.Visible = false; // // timer6 // this.timer6.Enabled = true; this.timer6.Interval = 500; this.timer6.Tick += new System.EventHandler(this.timer6_Tick); // // Form1 // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.BackColor = System.Drawing.SystemColors.ActiveCaptionText; this.ClientSize = new System.Drawing.Size(1306, 655); this.Controls.Add(this.label8); this.Controls.Add(this.checkBox2); this.Controls.Add(this.button28); this.Controls.Add(this.checkBox1); this.Controls.Add(this.label40); this.Controls.Add(this.radioButton2); this.Controls.Add(this.radioButton1); this.Controls.Add(this.label39); this.Controls.Add(this.label38); this.Controls.Add(this.listView1); this.Controls.Add(this.label37); this.Controls.Add(this.button27); this.Controls.Add(this.textBox8); this.Controls.Add(this.label36); this.Controls.Add(this.button25); this.Controls.Add(this.button26); this.Controls.Add(this.label34); this.Controls.Add(this.label35); this.Controls.Add(this.label32); this.Controls.Add(this.label33); this.Controls.Add(this.label30); this.Controls.Add(this.label31); this.Controls.Add(this.label28); this.Controls.Add(this.label27); this.Controls.Add(this.button22); this.Controls.Add(this.button23); this.Controls.Add(this.label29); this.Controls.Add(this.button20); this.Controls.Add(this.button21); this.Controls.Add(this.comboBox3); this.Controls.Add(this.button19); this.Controls.Add(this.button18); this.Controls.Add(this.label26); this.Controls.Add(this.button17); this.Controls.Add(this.button16); this.Controls.Add(this.textBox7); this.Controls.Add(this.label21); this.Controls.Add(this.button15); this.Controls.Add(this.button14); this.Controls.Add(this.button13); this.Controls.Add(this.button12); this.Controls.Add(this.button11); this.Controls.Add(this.comboBox1); this.Controls.Add(this.button10); this.Controls.Add(this.label20); this.Controls.Add(this.button9); this.Controls.Add(this.button8); this.Controls.Add(this.label19); this.Controls.Add(this.button7); this.Controls.Add(this.textBox6); this.Controls.Add(this.label18); this.Controls.Add(this.button6); this.Controls.Add(this.button5); this.Controls.Add(this.button4); this.Controls.Add(this.button3); this.Controls.Add(this.label17); this.Controls.Add(this.textBox5); this.Controls.Add(this.label16); this.Controls.Add(this.textBox4); this.Controls.Add(this.label15); this.Controls.Add(this.button2); this.Controls.Add(this.textBox3); this.Controls.Add(this.textBox2); this.Controls.Add(this.label7); this.Controls.Add(this.label4); this.Controls.Add(this.pictureBox1); this.Controls.Add(this.label3); this.Controls.Add(this.label2); this.Controls.Add(this.button1); this.Controls.Add(this.textBox1); this.Controls.Add(this.label1); this.ForeColor = System.Drawing.SystemColors.ButtonHighlight; this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog; this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); this.MaximizeBox = false; this.MinimizeBox = false; this.Name = "Form1"; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; this.Text = "ReactNativeCmdEase v8 by Sashitha"; this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.Form1_FormClosing); this.Load += new System.EventHandler(this.Form1_Load); ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).EndInit(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.Label label1; private System.Windows.Forms.TextBox textBox1; private System.Windows.Forms.Button button1; private System.Windows.Forms.Label label2; private System.Windows.Forms.Label label3; private System.Windows.Forms.PictureBox pictureBox1; private System.Windows.Forms.FolderBrowserDialog folderBrowserDialog1; private System.Windows.Forms.Label label4; private System.Windows.Forms.Label label7; private System.Windows.Forms.TextBox textBox2; private System.Windows.Forms.TextBox textBox3; private System.Windows.Forms.Button button2; private System.Windows.Forms.TextBox textBox4; private System.Windows.Forms.Label label15; private System.Windows.Forms.TextBox textBox5; private System.Windows.Forms.Label label16; private System.Windows.Forms.Label label17; private System.Windows.Forms.Button button3; private System.Windows.Forms.Button button4; private System.Windows.Forms.Button button5; private System.Windows.Forms.Button button6; private System.Windows.Forms.TextBox textBox6; private System.Windows.Forms.Label label18; private System.Windows.Forms.Button button7; private System.Windows.Forms.Label label19; private System.Windows.Forms.Button button8; private System.Windows.Forms.Button button9; private System.Windows.Forms.Label label20; private System.Windows.Forms.Button button10; private System.Windows.Forms.ComboBox comboBox1; private System.Windows.Forms.Button button11; private System.Windows.Forms.Button button12; private System.Windows.Forms.Timer timer2; private System.Windows.Forms.Button button13; private System.Windows.Forms.Button button14; private System.Windows.Forms.Button button15; private System.Windows.Forms.TextBox textBox7; private System.Windows.Forms.Label label21; private System.Windows.Forms.Button button16; private System.Windows.Forms.Button button17; private System.Windows.Forms.Label label26; private System.Windows.Forms.Button button18; private System.Windows.Forms.Button button19; private System.Windows.Forms.Button button20; private System.Windows.Forms.Button button21; private System.Windows.Forms.ComboBox comboBox3; private System.Windows.Forms.Label label29; private System.Windows.Forms.Button button22; private System.Windows.Forms.Button button23; private System.Windows.Forms.Label label27; private System.Windows.Forms.Label label28; private System.Windows.Forms.Label label30; private System.Windows.Forms.Label label31; private System.Windows.Forms.Label label32; private System.Windows.Forms.Label label33; private System.Windows.Forms.Label label34; private System.Windows.Forms.Label label35; private System.Windows.Forms.Timer timer3; private System.Windows.Forms.Button button26; private System.Windows.Forms.Button button25; private System.Windows.Forms.TextBox textBox8; private System.Windows.Forms.Label label36; private System.Windows.Forms.Button button27; private System.Windows.Forms.Label label37; private System.Windows.Forms.Label label38; private System.Windows.Forms.ListView listView1; private System.Windows.Forms.Label label39; private System.Windows.Forms.RadioButton radioButton1; private System.Windows.Forms.RadioButton radioButton2; private System.Windows.Forms.Label label40; private System.Windows.Forms.CheckBox checkBox1; private System.Windows.Forms.Button button28; private System.Windows.Forms.CheckBox checkBox2; private System.Windows.Forms.Label label8; private System.Windows.Forms.Timer timer6; } }
56.791667
162
0.60136
[ "MIT" ]
sashithacj/ReactNativeCmdEase
ReactNativeCmdEase/ReactNativeCmdEase/Form1.Designer.cs
66,789
C#
using Avalonia; using Avalonia.Controls; using Avalonia.Media; namespace Material.Styles.Assists { public static class ToggleSwitchAssist { public static AvaloniaProperty<IBrush> SwitchTrackOnBackgroundProperty = AvaloniaProperty.RegisterAttached<ToggleSwitch, IBrush>( "SwitchTrackOnBackground", typeof(ToggleSwitchAssist)); public static AvaloniaProperty<IBrush> SwitchTrackOffBackgroundProperty = AvaloniaProperty.RegisterAttached<ToggleSwitch, IBrush>( "SwitchTrackOffBackground", typeof(ToggleSwitchAssist)); public static void SetSwitchTrackOnBackground(AvaloniaObject element, IBrush value) { element.SetValue(SwitchTrackOnBackgroundProperty, value); } public static IBrush GetSwitchTrackOnBackground(AvaloniaObject element) { return (IBrush) element.GetValue(SwitchTrackOnBackgroundProperty); } public static void SetSwitchTrackOffBackground(AvaloniaObject element, IBrush value) { element.SetValue(SwitchTrackOffBackgroundProperty, value); } public static IBrush GetSwitchTrackOffBackground(AvaloniaObject element) { return (IBrush) element.GetValue(SwitchTrackOffBackgroundProperty); } } }
43.655172
138
0.744866
[ "MIT" ]
Al-Dyachkov/Material.Avalonia
Material.Styles/Assists/ToggleSwitchAssist.cs
1,268
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class WaypointController : MonoBehaviour { public List<Transform> waypoints = new List<Transform>(); private Transform targetWaypoint; private int targetWaypointIndex = 0; private float minDistance = 0.1f; //If the distance between the enemy and the waypoint is less than this, then it has reacehd the waypoint private int lastWaypointIndex; private float rotationSpeed = 5.0f; public ParticleSystem smoke; // Settings public float movementSpeed = 5; public float maxSpeed = 10; public float SteerSpeed = 180; public float BodySpeed = 5; public int Gap = 10; // References public GameObject BodyPrefab; // Lists public List<GameObject> BodyParts = new List<GameObject>(); private List<int> PositionsHistory = new List<int>(); private List<Transform> targetWaypointS = new List<Transform>(); public bool isMoving = false; // Use this for initialization AudioSource audioSource; void Start () { audioSource = GetComponent<AudioSource>(); lastWaypointIndex = waypoints.Count - 1; targetWaypoint = waypoints[targetWaypointIndex]; foreach (var body in BodyParts) { PositionsHistory.Add(0); Transform newone = waypoints[targetWaypointIndex]; targetWaypointS.Add(newone); } } public void SwitchMoving() { isMoving = !isMoving; audioSource.Play(); if (isMoving) smoke.Play(true); else smoke.Stop(true, ParticleSystemStopBehavior.StopEmitting); } // Update is called once per frame void Update () { if (isMoving == true) { float movementStep = movementSpeed * Time.deltaTime; float rotationStep = rotationSpeed * Time.deltaTime; Vector3 directionToTarget = targetWaypoint.position - transform.position; Quaternion rotationToTarget = Quaternion.LookRotation(directionToTarget); transform.rotation = Quaternion.Slerp(transform.rotation, rotationToTarget, rotationStep); float distance = Vector3.Distance(transform.position, targetWaypoint.position); CheckDistanceToWaypoint(distance); transform.position = Vector3.MoveTowards(transform.position, targetWaypoint.position, movementStep); // Move body parts int index = 0; foreach (var body in BodyParts) { float movementStepC = movementSpeed * Time.deltaTime; float rotationStepC = rotationSpeed * Time.deltaTime; Vector3 directionToTargetC = targetWaypointS[index].position - body.transform.position; Quaternion rotationToTargetC = Quaternion.LookRotation(directionToTargetC); body.transform.rotation = Quaternion.Slerp(body.transform.rotation, rotationToTargetC, rotationStep); float distancec = Vector3.Distance(body.transform.position, targetWaypointS[index].position); CheckDistanceToWaypointc(distancec,index); body.transform.position = Vector3.MoveTowards(body.transform.position, targetWaypointS[index].position, movementStep); index++; } } } /// <summary> /// Checks to see if the enemy is within distance of the waypoint. If it is, it called the UpdateTargetWaypoint function /// </summary> /// <param name="currentDistance">The enemys current distance from the waypoint</param> void CheckDistanceToWaypoint(float currentDistance) { if(currentDistance <= minDistance) { targetWaypointIndex++; UpdateTargetWaypoint(); } } void CheckDistanceToWaypointc(float currentDistance,int index) { if (currentDistance <= minDistance) { PositionsHistory[index]++; UpdateTargetWaypoints(index); } } /// <summary> /// Increaes the index of the target waypoint. If the enemy has reached the last waypoint in the waypoints list, it resets the targetWaypointIndex to the first waypoint in the list (causes the enemy to loop) /// </summary> void UpdateTargetWaypoint() { if(targetWaypointIndex > lastWaypointIndex) { // targetWaypointIndex = waypoints.FindLast(); isMoving = !isMoving; } targetWaypoint = waypoints[targetWaypointIndex]; } void UpdateTargetWaypoints(int index) { if (PositionsHistory[index] > lastWaypointIndex) { // PositionsHistory[index] = 0; isMoving = !isMoving; } targetWaypointS[index] = waypoints[PositionsHistory[index]]; } private void GrowSnake() { // Instantiate body instance and // add it to the list GameObject body = Instantiate(BodyPrefab); body.transform.position = this.transform.position; BodyParts.Add(body); } }
32.29375
211
0.638862
[ "Apache-2.0" ]
MasterKiller1239/MyCV
Assets/Scenes/WaypointController.cs
5,169
C#
using System.Collections.Generic; using Payabbhi; using Xunit; namespace UnitTesting.Payabbhi.Tests { public class TestRefund { const string ACCESSID = "access_id"; const string SECRETKEY = "secret_key"; const string REFUNDID = "dummy_refund_id"; const string PAYMENTID = "dummy_payment_id"; string paymentUrl = "api/v1/payments"; string refundUrl = "api/v1/refunds"; [Fact] public void TestGetAllRefunds () { string filepath = "dummy_refund_collection.json"; Client client = new Client (ACCESSID, SECRETKEY, Helper.GetMockRequestFactory (filepath, refundUrl)); var result = client.Refund.All (); Assert.NotSame (null, result); } [Fact] public void TestGetAllRefundsWithFilters () { string filepath = "dummy_refund_collection_filters.json"; Dictionary<string, object> options = new Dictionary<string, object> (); options.Add ("count", 5); options.Add ("skip", 2); string url = string.Format ("{0}?count={1}&skip={2}", refundUrl, options["count"], options["skip"]); Client client = new Client (ACCESSID, SECRETKEY, Helper.GetMockRequestFactory (filepath, url)); var result = client.Refund.All (options); string expectedJsonString = Helper.GetJsonString (filepath); Helper.AssertEntity (result, expectedJsonString); } [Fact] public void TestRetrieveRefund () { string filepath = "dummy_refund.json"; string url = string.Format ("{0}/{1}", refundUrl, REFUNDID); Client client = new Client (ACCESSID, SECRETKEY, Helper.GetMockRequestFactory (filepath, url)); Refund refund = client.Refund.Retrieve (REFUNDID); Assert.NotSame (null, refund); string expectedJsonString = Helper.GetJsonString (filepath); Helper.AssertEntity (refund, expectedJsonString); } [Fact] public void TestCreateRefund () { string filepath = "dummy_refund_create.json"; IDictionary<string, object> attributes = new Dictionary<string, object> (); attributes.Add ("amount", 100); string url = string.Format ("{0}/{1}/refunds", paymentUrl, PAYMENTID); Client client = new Client (ACCESSID, SECRETKEY, Helper.GetMockRequestFactory (filepath, url)); Refund refund = client.Refund.Create (PAYMENTID); string expectedJsonString = Helper.GetJsonString (filepath); Helper.AssertEntity (refund, expectedJsonString); } } }
46.051724
113
0.625234
[ "MIT" ]
payabbhi/payabbhi-dotnet
test/TestRefund.cs
2,671
C#