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
// <auto-generated/> // Contents of: hl7.fhir.r5.core version: 4.4.0 using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using Hl7.Fhir.Introspection; using Hl7.Fhir.Serialization; using Hl7.Fhir.Specification; using Hl7.Fhir.Utility; using Hl7.Fhir.Validation; /* Copyright (c) 2011+, HL7, Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of HL7 nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ namespace Hl7.Fhir.Model { /// <summary> /// Primitive Type positiveInt /// An integer with a value that is positive (e.g. &gt;0) /// </summary> [FhirType("positiveInt")] [DataContract] public partial class PositiveInt : Hl7.Fhir.Model.Primitive<int?>, System.ComponentModel.INotifyPropertyChanged { /// <summary> /// FHIR Type Name /// </summary> [NotMapped] public override string TypeName { get { return "positiveInt"; } } /// Must conform to the pattern "[1-9][0-9]*" public const string PATTERN = @"[1-9][0-9]*"; public PositiveInt(int? value) { Value = value; } public PositiveInt(): this((int?)null) {} /// <summary> /// Primitive value of the element /// </summary> [FhirElement("value", IsPrimitiveValue=true, XmlSerialization=XmlRepresentation.XmlAttr, InSummary=true, Order=30)] [DataMember] public int? Value { get { return (int?)ObjectValue; } set { ObjectValue = value; OnPropertyChanged("Value"); } } } } // end of file
33.597701
119
0.716387
[ "MIT" ]
Vermonster/fhir-codegen
generated/CSharpFirely1_R5/Generated/PositiveInt.cs
2,923
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("adalMVC")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("adalMVC")] [assembly: AssemblyCopyright("Copyright © 2014")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("3a726806-d831-46ae-8dcc-6d994e2fde7f")] // 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 Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
37.277778
84
0.749627
[ "Apache-2.0" ]
kaevans/adal-angular-mvc
adalMVC/Properties/AssemblyInfo.cs
1,345
C#
// Copyright (c) 2014-2015 Robert Rouhani <robert.rouhani@gmail.com> and other contributors (see CONTRIBUTORS file). // Licensed under the MIT License - https://raw.github.com/Robmaister/SharpNav/master/LICENSE using System; using NUnit.Framework; using SharpNav; using SharpNav.Geometry; #if MONOGAME using Vector3 = Microsoft.Xna.Framework.Vector3; #elif OPENTK using Vector3 = OpenTK.Vector3; #elif SHARPDX using Vector3 = SharpDX.Vector3; #endif namespace SharpNav.Tests.Geometry { [TestFixture] public class IntersectionTests { [Test] public void SegmentSegment2D_without_float_success() { //the Segment 1 Vector3 a = new Vector3(0, 0, 0); Vector3 b = new Vector3(1, 0, 1); //the segment 2 Vector3 p = new Vector3(0, 0, 1); Vector3 q = new Vector3(1, 0, 0); bool f = Intersection.SegmentSegment2D(ref a, ref b, ref p, ref q); Assert.IsTrue(f); } [Test] public void SegmentSegment2D_without_float_false() { //the Segment 1 Vector3 a = new Vector3(0, 0, 0); Vector3 b = new Vector3(1, 0, 1); //the segment 2 Vector3 p = new Vector3(1, 0, 0); Vector3 q = new Vector3(2, 0, 1); bool f = Intersection.SegmentSegment2D(ref a, ref b, ref p, ref q); Assert.IsFalse(f); } [Test] public void SegmentSegment2D_with_float_success() { //the Segment 1 Vector3 a = new Vector3(0, 0, 0); Vector3 b = new Vector3(1, 0, 1); //the segment 2 Vector3 p = new Vector3(0, 0, 1); Vector3 q = new Vector3(1, 0, 0); float m; float n; bool f = Intersection.SegmentSegment2D(ref a, ref b, ref p, ref q, out m, out n); Assert.IsTrue(f); } [Test] public void SegmentSegment2D_with_float_false() { //the Segment 1 Vector3 a = new Vector3(0, 0, 0); Vector3 b = new Vector3(1, 0, 1); //the segment 2 Vector3 p = new Vector3(1, 0, 0); Vector3 q = new Vector3(2, 0, 1); float m; float n; bool f = Intersection.SegmentSegment2D(ref a, ref b, ref p, ref q, out m, out n); Assert.IsFalse(f); } } }
23
116
0.660573
[ "MIT" ]
AngelKyriako/SharpNav
Source/SharpNav.Tests/Geometry/IntersectionTests.cs
2,024
C#
using System; using System.Collections.Generic; using System.Linq; using System.Web.Http; namespace PuntoDeVenta { public static class WebApiConfig { public static void Register(HttpConfiguration config) { // Configuración y servicios de API web // Rutas de API web config.MapHttpAttributeRoutes(); config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } ); } } }
23.64
62
0.580372
[ "MIT" ]
DesarrolloProsis/PuntoDeVenta
PuntoDeVenta/App_Start/WebApiConfig.cs
594
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Xamarin.Forms; using Xamarin.Forms.Xaml; // TODO #12 : add XamlCompilation attribute [assembly: XamlCompilation(XamlCompilationOptions.Compile)] namespace Calculator { public class App : Application { public App() { // The root page of your application // TODO #5 MainPage = new MainPage(); } protected override void OnStart() { // Handle when your app starts } protected override void OnSleep() { // Handle when your app sleeps } protected override void OnResume() { // Handle when your app resumes } } }
20.128205
59
0.57707
[ "MIT" ]
Loryleen/Xamarin-University
Xamarin.Forms/XAM130-XAML/Exercise1/Calculator/Calculator/App.cs
787
C#
using System; namespace Lykke.Service.OperationsCache.Client { public class OperationsCacheServiceClientSettings { public string ServiceUrl {get; set;} } }
19.777778
54
0.719101
[ "MIT" ]
LykkeCity/Lykke.Service.OperationsCache
client/Lykke.Service.OperationsCache.Client/OperationsCacheServiceClientSettings.cs
178
C#
using AReport.Support.Entity; using AReport.Support.Interface; using System.Collections.ObjectModel; using AReport.DAL.Reader; using AReport.DAL.Writer; using System; namespace AReport.DAL.Data { public class UsuarioData : ICollectionRead<Usuario>, ICollectionWrite<Usuario> { public Collection<Usuario> QueryCollection() { UsuarioCollectionRead colRead = new UsuarioCollectionRead(); return colRead.QueryCollection(); } public bool WriteCollection(Collection<Usuario> collection) { UsuarioCollectionWrite colWrite = new UsuarioCollectionWrite(); return colWrite.WriteCollection(collection); } } class UsuarioCollectionRead : CollectionReadBase<Usuario>, ICollectionRead<Usuario> { public Collection<Usuario> QueryCollection() { return Collection(); } protected override ObjectReaderBase<Usuario> GetReader() { return new UsuarioReader(); } } class UsuarioCollectionWrite : CollectionWriteBase<Usuario>, ICollectionWrite<Usuario> { public bool WriteCollection(Collection<Usuario> collection) { return Write(collection); } protected override ObjectWriterBase<Usuario> GetWriter() { return new UsuarioWriter(); } } }
27.396226
91
0.62741
[ "MIT" ]
aamartin2k/AReporte
ARDAL/Data/UsuarioData.cs
1,454
C#
using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; using Xamarin.Forms.Xaml; using MyXamarinApp.Models; using MyXamarinApp.Views; using MyXamarinApp.ViewModels; namespace MyXamarinApp.Views { // Learn more about making custom code visible in the Xamarin.Forms previewer // by visiting https://aka.ms/xamarinforms-previewer [DesignTimeVisible(false)] public partial class ItemsPage : ContentPage { ItemsViewModel viewModel; public ItemsPage() { InitializeComponent(); BindingContext = viewModel = new ItemsViewModel(); } async void OnItemSelected(object sender, SelectedItemChangedEventArgs args) { var item = args.SelectedItem as Item; if (item == null) return; await Navigation.PushAsync(new ItemDetailPage(new ItemDetailViewModel(item))); // Manually deselect item. ItemsListView.SelectedItem = null; } async void AddItem_Clicked(object sender, EventArgs e) { await Navigation.PushModalAsync(new NavigationPage(new NewItemPage())); } protected override void OnAppearing() { base.OnAppearing(); if (viewModel.Items.Count == 0) viewModel.LoadItemsCommand.Execute(null); } } }
26.927273
90
0.64551
[ "MIT" ]
CNILearn/xamarinworkshopoct2019
day2/MyXamarinApp/MyXamarinApp/MyXamarinApp/Views/ItemsPage.xaml.cs
1,483
C#
namespace Atata.Tests { using _ = DragAndDropPage; [Url("DragAndDrop.html")] public class DragAndDropPage : Page<_> { [FindById] public ItemsControl<DragItem, _> DropContainer { get; private set; } [FindById] public ItemsControl<DragItem, _> DragItems { get; private set; } [ControlDefinition("span", ContainingClass = "drag-item")] [DragAndDropUsingDomEvents] public class DragItem : Control<_> { } } }
24.714286
77
0.583815
[ "Apache-2.0" ]
Artemyj/atata
src/Atata.Tests/Components/DragAndDropPage.cs
521
C#
namespace TcecEvaluationBot.ConsoleUI.Services { using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Net.Sockets; using System.Text; using System.Threading; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using TcecEvaluationBot.ConsoleUI.Services.Models.ChessPosDbQuery; public class DatabaseImportStats { public DatabaseImportStats(JObject json) { this.StatsByLevel = new Dictionary<GameLevel, DatabaseSingleLevelImportStats> { { GameLevel.Engine, new DatabaseSingleLevelImportStats(json["engine"].Value<JObject>()) }, { GameLevel.Human, new DatabaseSingleLevelImportStats(json["human"].Value<JObject>()) }, { GameLevel.Server, new DatabaseSingleLevelImportStats(json["server"].Value<JObject>()) }, }; } public Dictionary<GameLevel, DatabaseSingleLevelImportStats> StatsByLevel { get; private set; } public DatabaseSingleLevelImportStats GetTotal() { DatabaseSingleLevelImportStats total = new DatabaseSingleLevelImportStats(this.StatsByLevel[GameLevel.Engine]); total.Add(this.StatsByLevel[GameLevel.Human]); total.Add(this.StatsByLevel[GameLevel.Server]); return total; } } }
36.315789
123
0.673188
[ "MIT" ]
NikolayIT/TcecEvaluationBot
src/TcecEvaluationBot.ConsoleUI/Services/Models/ChessPosDb/DatabaseImportStats.cs
1,382
C#
namespace Grasews.Infra.Data.EF.SqlServer.Contexts { using System; using System.Data.Entity; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; public partial class Model1 : DbContext { public Model1() : base("name=Model1") { } public virtual DbSet<Issue> Issues { get; set; } public virtual DbSet<ServiceDescription> ServiceDescriptions { get; set; } public virtual DbSet<WsdlInFault> WsdlInFaults { get; set; } public virtual DbSet<WsdlInput> WsdlInputs { get; set; } public virtual DbSet<WsdlInterface> WsdlInterfaces { get; set; } public virtual DbSet<WsdlOperation> WsdlOperations { get; set; } public virtual DbSet<WsdlOutFault> WsdlOutFaults { get; set; } public virtual DbSet<WsdlOutput> WsdlOutputs { get; set; } public virtual DbSet<XsdComplexElement> XsdComplexElements { get; set; } public virtual DbSet<XsdDocument> XsdDocuments { get; set; } public virtual DbSet<XsdElement> XsdElements { get; set; } public virtual DbSet<XsdSimpleElement> XsdSimpleElements { get; set; } protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.Entity<Issue>() .Property(e => e.Description) .IsUnicode(false); modelBuilder.Entity<ServiceDescription>() .Property(e => e.GraphJson) .IsUnicode(false); modelBuilder.Entity<ServiceDescription>() .Property(e => e.Xml) .IsUnicode(false); modelBuilder.Entity<ServiceDescription>() .HasMany(e => e.Issues) .WithRequired(e => e.ServiceDescription) .HasForeignKey(e => e.IdServiceDescription); modelBuilder.Entity<ServiceDescription>() .HasMany(e => e.WsdlInterfaces) .WithRequired(e => e.ServiceDescription) .HasForeignKey(e => e.IdServiceDescription) .WillCascadeOnDelete(false); modelBuilder.Entity<ServiceDescription>() .HasOptional(e => e.XsdDocument) .WithRequired(e => e.ServiceDescription); modelBuilder.Entity<WsdlInFault>() .HasMany(e => e.Issues) .WithOptional(e => e.WsdlInFault) .HasForeignKey(e => e.IdWsdlInFault); modelBuilder.Entity<WsdlInFault>() .HasMany(e => e.XsdComplexElements) .WithOptional(e => e.WsdlInFault) .HasForeignKey(e => e.IdWsdlInFault); modelBuilder.Entity<WsdlInFault>() .HasMany(e => e.XsdSimpleElements) .WithOptional(e => e.WsdlInFault) .HasForeignKey(e => e.IdWsdlInFault); modelBuilder.Entity<WsdlInput>() .HasMany(e => e.Issues) .WithOptional(e => e.WsdlInput) .HasForeignKey(e => e.IdWsdlInput); modelBuilder.Entity<WsdlInput>() .HasMany(e => e.XsdComplexElements) .WithOptional(e => e.WsdlInput) .HasForeignKey(e => e.IdWsdlInput); modelBuilder.Entity<WsdlInput>() .HasMany(e => e.XsdSimpleElements) .WithOptional(e => e.WsdlInput) .HasForeignKey(e => e.IdWsdlInput); modelBuilder.Entity<WsdlInterface>() .HasMany(e => e.Issues) .WithOptional(e => e.WsdlInterface) .HasForeignKey(e => e.IdWsdlInterface); modelBuilder.Entity<WsdlInterface>() .HasMany(e => e.WsdlOperations) .WithRequired(e => e.WsdlInterface) .HasForeignKey(e => e.IdWsdlInterface) .WillCascadeOnDelete(false); modelBuilder.Entity<WsdlOperation>() .HasMany(e => e.Issues) .WithOptional(e => e.WsdlOperation) .HasForeignKey(e => e.IdWsdlOperation); modelBuilder.Entity<WsdlOperation>() .HasMany(e => e.WsdlInFaults) .WithRequired(e => e.WsdlOperation) .HasForeignKey(e => e.IdWsdlOperation) .WillCascadeOnDelete(false); modelBuilder.Entity<WsdlOperation>() .HasMany(e => e.WsdlInputs) .WithRequired(e => e.WsdlOperation) .HasForeignKey(e => e.IdWsdlOperation) .WillCascadeOnDelete(false); modelBuilder.Entity<WsdlOperation>() .HasMany(e => e.WsdlOutFaults) .WithRequired(e => e.WsdlOperation) .HasForeignKey(e => e.IdWsdlOperation) .WillCascadeOnDelete(false); modelBuilder.Entity<WsdlOperation>() .HasMany(e => e.WsdlOutputs) .WithRequired(e => e.WsdlOperation) .HasForeignKey(e => e.IdWsdlOperation) .WillCascadeOnDelete(false); modelBuilder.Entity<WsdlOutFault>() .HasMany(e => e.Issues) .WithOptional(e => e.WsdlOutFault) .HasForeignKey(e => e.IdWsdlOutFault); modelBuilder.Entity<WsdlOutFault>() .HasMany(e => e.XsdComplexElements) .WithOptional(e => e.WsdlOutFault) .HasForeignKey(e => e.IdWsdlOutFault); modelBuilder.Entity<WsdlOutFault>() .HasMany(e => e.XsdSimpleElements) .WithOptional(e => e.WsdlOutFault) .HasForeignKey(e => e.IdWsdlOutFault); modelBuilder.Entity<WsdlOutput>() .HasMany(e => e.Issues) .WithOptional(e => e.WsdlOutput) .HasForeignKey(e => e.IdWsdlOutput); modelBuilder.Entity<WsdlOutput>() .HasMany(e => e.XsdComplexElements) .WithOptional(e => e.WsdlOutput) .HasForeignKey(e => e.IdWsdlOutput); modelBuilder.Entity<WsdlOutput>() .HasMany(e => e.XsdSimpleElements) .WithOptional(e => e.WsdlOutput) .HasForeignKey(e => e.IdWsdlOutput); modelBuilder.Entity<XsdComplexElement>() .HasMany(e => e.Issues) .WithOptional(e => e.XsdComplexElement) .HasForeignKey(e => e.IdXsdComplexElement); modelBuilder.Entity<XsdComplexElement>() .HasMany(e => e.XsdElements) .WithRequired(e => e.XsdComplexElement) .HasForeignKey(e => e.IdXsdComplexElement) .WillCascadeOnDelete(false); modelBuilder.Entity<XsdDocument>() .HasMany(e => e.XsdComplexElements) .WithRequired(e => e.XsdDocument) .HasForeignKey(e => e.IdXsdDocument) .WillCascadeOnDelete(false); modelBuilder.Entity<XsdDocument>() .HasMany(e => e.XsdSimpleElements) .WithRequired(e => e.XsdDocument) .HasForeignKey(e => e.IdXsdDocument) .WillCascadeOnDelete(false); modelBuilder.Entity<XsdElement>() .HasMany(e => e.Issues) .WithOptional(e => e.XsdElement) .HasForeignKey(e => e.IdXsdElement); modelBuilder.Entity<XsdSimpleElement>() .HasMany(e => e.Issues) .WithOptional(e => e.XsdSimpleElement) .HasForeignKey(e => e.IdXsdSimpleElement); } } }
39.9375
82
0.552556
[ "MIT" ]
mlcalache/grasews
Grasews.Infra.Data.EF.SqlServer/Contexts/Model1.cs
7,668
C#
// ███╗ ██╗ ██████╗ ████████╗██╗ ██████╗███████╗ // ████╗ ██║██╔═══██╗╚══██╔══╝██║██╔════╝██╔════╝ // ██╔██╗ ██║██║ ██║ ██║ ██║██║ █████╗ // ██║╚██╗██║██║ ██║ ██║ ██║██║ ██╔══╝ // ██║ ╚████║╚██████╔╝ ██║ ██║╚██████╗███████╗ // ╚═╝ ╚═══╝ ╚═════╝ ╚═╝ ╚═╝ ╚═════╝╚══════╝ // ----------------------------------------------- // // This file is automatically generated // Please do not edit these files manually // Run the following in the root of the repos: // // *NIX : ./build.sh codegen // Windows : build.bat codegen // // ----------------------------------------------- // ReSharper disable RedundantUsingDirective using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Linq.Expressions; // ReSharper disable once CheckNamespace namespace Elasticsearch.Net.Specification.SqlApi { ///<summary>Request options for ClearCursor <para>Clear SQL cursor</para></summary> public class ClearSqlCursorRequestParameters : RequestParameters<ClearSqlCursorRequestParameters> { public override HttpMethod DefaultHttpMethod => HttpMethod.POST; public override bool SupportsBody => true; } ///<summary>Request options for Query <para>Execute SQL</para></summary> public class QuerySqlRequestParameters : RequestParameters<QuerySqlRequestParameters> { public override HttpMethod DefaultHttpMethod => HttpMethod.POST; public override bool SupportsBody => true; ///<summary>a short version of the Accept header, e.g. json, yaml</summary> public string Format { get => Q<string>("format"); set => Q("format", value); } } ///<summary>Request options for Translate <para>Translate SQL into Elasticsearch queries</para></summary> public class TranslateSqlRequestParameters : RequestParameters<TranslateSqlRequestParameters> { public override HttpMethod DefaultHttpMethod => HttpMethod.POST; public override bool SupportsBody => true; } }
36.735849
106
0.60452
[ "Apache-2.0" ]
FrankyBoy/elasticsearch-net
src/Elasticsearch.Net/Api/RequestParameters/RequestParameters.Sql.cs
2,393
C#
namespace ml_abp { static class Utils { public static float QuadraticEaseOut(float p_value) { return (1f - UnityEngine.Mathf.Pow(1f - p_value, 2f)); } // VRChat related static VRC.UI.Elements.QuickMenu ms_quickMenu = null; public static VRC.Player GetPlayerQM() // Thanks, now I hate this new menu { VRC.Player l_result = null; if(ms_quickMenu == null) ms_quickMenu = UnityEngine.GameObject.Find("UserInterface").transform.Find("Canvas_QuickMenu(Clone)").GetComponent<VRC.UI.Elements.QuickMenu>(); if((ms_quickMenu != null) && (ms_quickMenu.field_Private_UIPage_1 != null) && ms_quickMenu.field_Private_UIPage_1.isActiveAndEnabled) { var l_selectedUserQM = ms_quickMenu.field_Private_UIPage_1.TryCast<VRC.UI.Elements.Menus.SelectedUserMenuQM>(); if((l_selectedUserQM != null) && (l_selectedUserQM.field_Private_IUser_0 != null)) { l_result = GetPlayerWithId(l_selectedUserQM.field_Private_IUser_0.prop_String_0); } } return l_result; } public static VRC.Player GetLocalPlayer() => VRC.Player.prop_Player_0; public static bool IsFriend(VRC.Player p_player) { bool l_result = false; if(p_player.field_Private_APIUser_0 != null) l_result = p_player.field_Private_APIUser_0.isFriend; if(p_player.field_Private_VRCPlayerApi_0 != null) l_result = (l_result && !p_player.field_Private_VRCPlayerApi_0.isLocal); return l_result; } public static Il2CppSystem.Collections.Generic.List<VRC.Player> GetPlayers() => VRC.PlayerManager.field_Private_Static_PlayerManager_0.field_Private_List_1_Player_0; public static VRC.Player GetPlayerWithId(string p_id) { return (VRC.Player)MethodsResolver.GetPlayerById?.Invoke(null, new object[] { p_id }); } public static System.Collections.Generic.List<VRC.Player> GetFriendsInInstance() { System.Collections.Generic.List<VRC.Player> l_result = new System.Collections.Generic.List<VRC.Player>(); var l_remotePlayers = GetPlayers(); if(l_remotePlayers != null) { foreach(VRC.Player l_remotePlayer in l_remotePlayers) { if((l_remotePlayer != null) && IsFriend(l_remotePlayer)) l_result.Add(l_remotePlayer); } } return l_result; } // Extensions public static void SetAvatarFloatParamEx(this AvatarPlayableController controller, int paramHash, float val, bool debug = false) { MethodsResolver.SetAvatarFloatParam?.Invoke(controller, new object[] { paramHash, val, debug }); controller.field_Private_Boolean_3 = true; // bool requiresNetworkSync; } } }
44.086957
173
0.623603
[ "MIT" ]
Natedog1423/ml_mods
ml_abp/Utils.cs
3,044
C#
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace InterviewWebApplication { public partial class SiteMaster : MasterPage { protected void Page_Load(object sender, EventArgs e) { } } }
18.882353
60
0.70405
[ "MIT" ]
lhesnadeemshaikh/InterviewWebAppDotNet
InterviewWebApplication/InterviewWebApplication/Site.Master.cs
323
C#
using System.Collections.Generic; namespace ScriptTester { public class CrawledURL { public string Url { get; set; } public bool IsChecked { get; set; } public List<string> FoundKeywords { get; private set; } public CrawledURL(string url, bool isChecked) { this.Url = url; this.IsChecked = isChecked; this.FoundKeywords = new List<string>(); } /// <summary> /// Checks if object contains keyword (if empty -->returns all items in list) /// </summary> /// <param name="keywords"></param> /// <returns></returns> public bool UrlContainsKeyword(List<string> keywords) { foreach (var kw in keywords) { if (this.FoundKeywords.Contains(kw)) return true; } return false; } } }
27
85
0.527233
[ "MIT" ]
dommyrock/ScaperSelenium
ScriptTester/ScriptTester/CrawledURL.cs
920
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("SnakeGame")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("SnakeGame")] [assembly: AssemblyCopyright("Copyright © 2016")] [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("0fbf9dc7-4218-4573-a19c-b4459bb7141d")] // 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
[ "MIT" ]
SALTx/SnakeGame
SnakeGame/Properties/AssemblyInfo.cs
1,394
C#
using System; using System.Collections.Generic; using UnityEngine; namespace Drags { public class ConnectionChecker : MonoBehaviour { //[SerializeField] private GameObject[] cylinders; [SerializeField] private GameObject cube; [SerializeField] private DragLimiter dragLimiter; private int _jointsCounter; private List<GameObject> _attached; private float _theFarest; private GameObject _theFarestCylinder; private bool _lock = false; public bool Lock { get => _lock; } private void Awake() { _attached = new List<GameObject>(); } private void Update() { _lock = _jointsCounter == 2; } public void IncreaseCounter() { _jointsCounter++; if (_jointsCounter > 2) { CheckFarest(); _lock = false; } if (_jointsCounter == 1) { dragLimiter.UpdateTimeLimit(); _lock = false; } Debug.Log("Increased Counter is " + _jointsCounter); } public void DecreaseCounter() { _jointsCounter--; if (_jointsCounter > 2) { CheckFarest(); } if (_jointsCounter == 1) { dragLimiter.UpdateTimeLimit(); } Debug.Log("Decreased counter is " + _jointsCounter); } private void CheckFarest() { if (_attached.Count == 0) return; for (int i = 0; i < _attached.Count; i++) { if (_attached[i].GetComponent<SpringJoint>() == null) continue; if (!(_theFarest < Vector3.Distance(cube.transform.position, _attached[i].transform.position))) continue; _theFarest = Vector3.Distance(cube.transform.position, _attached[i].transform.position); _theFarestCylinder = _attached[i]; } if (_theFarestCylinder.GetComponent<SpringJoint>().connectedBody != cube.GetComponent<Rigidbody>()) return; _theFarestCylinder.GetComponent<SpringJoint>().connectedBody = null; DecreaseCounter(); _attached.Remove(_theFarestCylinder); _theFarest = 0; _theFarestCylinder = null; } public void AddtoList(GameObject cylinder) { _attached.Add(cylinder); } public void RemoveFromList(GameObject cylinder) { if (_attached.Contains(cylinder)) { _attached.Remove(cylinder); } } public bool IsAvailableToConnect() => _jointsCounter != 1; public bool IsFlying() => _jointsCounter == 0; } }
26.697248
119
0.527491
[ "Unlicense" ]
ProjectS2O2O/Spring-Climber
Assets/Scripts/Drags/ConnectionChecker.cs
2,912
C#
using System.Text.Json.Serialization; namespace Horizon.Payment.Alipay.Domain { /// <summary> /// AntMerchantExpandItemOpenDeleteModel Data Structure. /// </summary> public class AntMerchantExpandItemOpenDeleteModel : AlipayObject { /// <summary> /// 商品ID /// </summary> [JsonPropertyName("item_id")] public string ItemId { get; set; } } }
23.882353
68
0.625616
[ "Apache-2.0" ]
bluexray/Horizon.Sample
Horizon.Payment.Alipay/Domain/AntMerchantExpandItemOpenDeleteModel.cs
412
C#
namespace Pulstar.Web.Models.AccountViewModels { using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Threading.Tasks; public class ResetPasswordViewModel { [Required] [EmailAddress] public string Email { get; set; } [Required] [StringLength(100, ErrorMessage = "The {0} must be at least {2} and at max {1} characters long.", MinimumLength = 6)] [DataType(DataType.Password)] public string Password { get; set; } [DataType(DataType.Password)] [Display(Name = "Confirm password")] [Compare("Password", ErrorMessage = "The password and confirmation password do not match.")] public string ConfirmPassword { get; set; } public string Code { get; set; } } }
30.678571
125
0.644936
[ "MIT" ]
Domin1k/Pulstar
src/Pulstar.Web/Models/AccountViewModels/ResetPasswordViewModel.cs
861
C#
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ using System; using Org.Apache.REEF.Utilities; using Org.Apache.REEF.Utilities.Logging; namespace Org.Apache.REEF.Common.Tasks { public class TaskMessage : IMessage { private static readonly Logger LOGGER = Logger.GetLogger(typeof(TaskMessage)); private readonly string _messageSourcId; private readonly byte[] _bytes; private TaskMessage(string messageSourceId, byte[] bytes) { _messageSourcId = messageSourceId; _bytes = bytes; } public string MessageSourceId { get { return _messageSourcId; } } public byte[] Message { get { return _bytes; } set { } } /// <summary> /// From byte[] message to a TaskMessage /// </summary> /// <param name="messageSourceId">messageSourceId The message's sourceID. This will be accessible in the Driver for routing</param> /// <param name="message">The actual content of the message, serialized into a byte[]</param> /// <returns>a new TaskMessage with the given content</returns> public static TaskMessage From(string messageSourceId, byte[] message) { if (string.IsNullOrEmpty(messageSourceId)) { Org.Apache.REEF.Utilities.Diagnostics.Exceptions.Throw(new ArgumentNullException("messageSourceId"), LOGGER); } if (message == null) { Org.Apache.REEF.Utilities.Diagnostics.Exceptions.Throw(new ArgumentNullException("bytes"), LOGGER); } return new TaskMessage(messageSourceId, message); } } }
36.217391
139
0.653061
[ "Apache-2.0" ]
Gyeongin/incubator-reef
lang/cs/Org.Apache.REEF.Common/Tasks/TaskMessage.cs
2,501
C#
/* This file is part of PacketDotNet PacketDotNet is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. PacketDotNet is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with PacketDotNet. If not, see <http://www.gnu.org/licenses/>. */ /* * Copyright 2009 Chris Morgan <chmorgan@gmail.com> */ namespace PacketDotNet { /// <summary> /// Session layer packet /// </summary> public abstract class SessionPacket : Packet { /// <summary> /// Constructor /// </summary> public SessionPacket() { } } }
27.805556
75
0.709291
[ "Apache-2.0" ]
CrypToolProject/CrypTool-2
LibSource/PacketDotNet/SessionPacket.cs
1,001
C#
namespace ApexSharpDemo.ApexCode { using Apex; using Apex.ApexSharp; using Apex.ApexSharp.ApexAttributes; using Apex.ApexSharp.Extensions; using Apex.System; using SObjects; [WithSharing] public class Collections { public List<string> StringList = new List<string>{"one", "two"}; public int[] IntegerArray = new int[]{1, 2, 3}; public void ArrayDemo() { List<string> stringListLocal = new List<string>{"one", "two"}; int[] integerArrayLocal = new int[]{1, 2, 3}; } public void ListExample() { List<int> myList = new List<int>(); myList.Add(47); int i = myList.Get(0); myList.Set(0, 1); myList.Clear(); List<SelectOption> options = new List<SelectOption>(); options.Add(new SelectOption("A","United States")); options.Add(new SelectOption("C","Canada")); options.Add(new SelectOption("A","Mexico")); System.Debug("Before sorting: "+ options); options.Sort(); System.Debug("After sorting: "+ options); } public void SetExample() { Set<int> s = new Set<int>(); s.Add(1); s.Remove(1); } public void MapExample() { Map<int, string> m = new Map<int, string>(); m.Put(1, "First entry"); m.Put(2, "Second entry"); string value = m.Get(2); } public void MapSoqlExample() { // Map<Id, Contact> m = new Map<Id, Contact>(Soql.Query<Contact>("SELECT Id FROM Jay__c")); Map<ID, Contact> m = new Map<ID, Contact>(Soql.query<Contact>(@"SELECT Id, Name FROM Contact LIMIT 10")); foreach (ID idKey in m.KeySet()) { Contact contact = m.Get(idKey); } } } }
29.969231
117
0.514374
[ "MIT" ]
apexsharp/apexparser
ApexSharp.ApexParser.Tests/ApexRoundtrip/Collections_CSharp.cs
1,948
C#
 namespace Catstagram.Server.Controllers { using Microsoft.AspNetCore.Mvc; [ApiController] [Route("api/[controller]")] public abstract class ApiBaseController : ControllerBase { } }
17.333333
60
0.692308
[ "MIT" ]
RivaIvanova/Catstagram
Catstagram.Server/Catstagram.Server/Controllers/ApiBaseController.cs
210
C#
using System; namespace _2231 { class Program { static void Main(string[] args) { int num = int.Parse(Console.ReadLine()); int sum; int part; for (int i = 1; i < num; i++) { sum = i; part = i; while (part != 0) { sum += part % 10; part /= 10; } if (num == sum) { Console.WriteLine(i); return; } } Console.WriteLine(0); return; } } }
20.484848
52
0.301775
[ "MIT" ]
VontineDev/repos
CSharp/2231/Program.cs
678
C#
using System; using Xunit; namespace BeckonedPath.Testing.Library { public class UnitTest1 { [Fact] public void Test1() { } } }
11.6
38
0.545977
[ "MIT" ]
bezp/playRepo
test/BeckonedPath.Testing.Library/UnitTest1.cs
174
C#
using CuraManager.Models; namespace CuraManager.Services; public interface ICachingService { MetadataCache LoadCache(string printsPath); void UpdateCache(MetadataCache cache); }
18.9
47
0.798942
[ "MIT" ]
MaSch0212/cura-manager
src/CuraManager/Services/_Interfaces/ICachingService.cs
191
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("u2_books.shared")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("u2_books.shared")] [assembly: AssemblyCopyright("Copyright © 2010")] [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("51a1915b-7a3f-49aa-9240-1544aecf0ec0")] // 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.918919
84
0.744833
[ "MIT" ]
baffled/bookstore
clients/u2_books_cs_u2toolkit/u2_books.shared/Properties/AssemblyInfo.cs
1,406
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. //------------------------------------------------------------------------------ using System.Collections.Generic; using System.Data.Common; using System.Diagnostics; namespace System.Data.SqlClient { internal class TdsParserSessionPool { // NOTE: This is a very simplistic, lightweight pooler. It wasn't // intended to handle huge number of items, just to keep track // of the session objects to ensure that they're cleaned up in // a timely manner, to avoid holding on to an unacceptible // amount of server-side resources in the event that consumers // let their data readers be GC'd, instead of explicitly // closing or disposing of them private const int MaxInactiveCount = 10; // pick something, preferably small... private readonly TdsParser _parser; // parser that owns us private readonly List<TdsParserStateObject> _cache; // collection of all known sessions private int _cachedCount; // lock-free _cache.Count private TdsParserStateObject[] _freeStateObjects; // collection of all sessions available for reuse private int _freeStateObjectCount; // Number of available free sessions internal TdsParserSessionPool(TdsParser parser) { _parser = parser; _cache = new List<TdsParserStateObject>(); _freeStateObjects = new TdsParserStateObject[MaxInactiveCount]; _freeStateObjectCount = 0; } private bool IsDisposed { get { return (null == _freeStateObjects); } } internal void Deactivate() { // When being deactivated, we check all the sessions in the // cache to make sure they're cleaned up and then we dispose of // sessions that are past what we want to keep around. lock (_cache) { // NOTE: The PutSession call below may choose to remove the // session from the cache, which will throw off our // enumerator. We avoid that by simply indexing backward // through the array. for (int i = _cache.Count - 1; i >= 0; i--) { TdsParserStateObject session = _cache[i]; if (null != session) { if (session.IsOrphaned) { // TODO: consider adding a performance counter for the number of sessions we reclaim PutSession(session); } } } // TODO: re-enable this assert when the connection isn't doomed. //Debug.Assert (_cachedCount < MaxInactiveCount, "non-orphaned connection past initial allocation?"); } } // This is called from a ThreadAbort - ensure that it can be run from a CER Catch internal void BestEffortCleanup() { for (int i = 0; i < _cache.Count; i++) { TdsParserStateObject session = _cache[i]; if (null != session) { var sessionHandle = session.Handle; if (sessionHandle != null) { sessionHandle.Dispose(); } } } } internal void Dispose() { lock (_cache) { // Dispose free sessions for (int i = 0; i < _freeStateObjectCount; i++) { if (_freeStateObjects[i] != null) { _freeStateObjects[i].Dispose(); } } _freeStateObjects = null; _freeStateObjectCount = 0; // Dispose orphaned sessions for (int i = 0; i < _cache.Count; i++) { if (_cache[i] != null) { if (_cache[i].IsOrphaned) { _cache[i].Dispose(); } else { // Remove the "initial" callback (this will allow the stateObj to be GC collected if need be) _cache[i].DecrementPendingCallbacks(false); } } } _cache.Clear(); _cachedCount = 0; // Any active sessions will take care of themselves // (It's too dangerous to dispose them, as this can cause AVs) } } internal TdsParserStateObject GetSession(object owner) { TdsParserStateObject session; lock (_cache) { if (IsDisposed) { throw ADP.ClosedConnectionError(); } else if (_freeStateObjectCount > 0) { // Free state object - grab it _freeStateObjectCount--; session = _freeStateObjects[_freeStateObjectCount]; _freeStateObjects[_freeStateObjectCount] = null; Debug.Assert(session != null, "There was a null session in the free session list?"); } else { // No free objects, create a new one session = _parser.CreateSession(); _cache.Add(session); _cachedCount = _cache.Count; } session.Activate(owner); } return session; } internal void PutSession(TdsParserStateObject session) { Debug.Assert(null != session, "null session?"); //Debug.Assert(null != session.Owner, "session without owner?"); bool okToReuse = session.Deactivate(); lock (_cache) { if (IsDisposed) { // We're diposed - just clean out the session Debug.Assert(_cachedCount == 0, "SessionPool is disposed, but there are still sessions in the cache?"); session.Dispose(); } else if ((okToReuse) && (_freeStateObjectCount < MaxInactiveCount)) { // Session is good to re-use and our cache has space Debug.Assert(!session._pendingData, "pending data on a pooled session?"); _freeStateObjects[_freeStateObjectCount] = session; _freeStateObjectCount++; } else { // Either the session is bad, or we have no cache space - so dispose the session and remove it bool removed = _cache.Remove(session); Debug.Assert(removed, "session not in pool?"); _cachedCount = _cache.Count; session.Dispose(); } session.RemoveOwner(); } } internal int ActiveSessionsCount { get { return _cachedCount - _freeStateObjectCount; } } } }
35.211712
123
0.481643
[ "MIT" ]
benjamin-bader/corefx
src/System.Data.SqlClient/src/System/Data/SqlClient/TdsParserSessionPool.cs
7,817
C#
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Linq; using System.Threading; using System.Windows.Data; using System.Windows.Threading; using ACT.UltraScouter.Common; using ACT.UltraScouter.Config; using ACT.UltraScouter.Models; using ACT.UltraScouter.ViewModels.Bases; using FFXIV.Framework.Common; using FFXIV.Framework.Extensions; using FFXIV.Framework.XIVHelper; using Sharlayan.Core.Enums; namespace ACT.UltraScouter.ViewModels { public class TacticalRadarViewModel : OverlayViewModelBase, IOverlayViewModel { public TacticalRadarViewModel() { this.Initialize(); } public override void Initialize() { if (this.refreshTimer != null) { this.refreshTimer.Tick += (x, y) => this.RefreshOriginAngle(); this.refreshTimer.Start(); } if (WPFHelper.IsDesignMode) { this.UpdateTargets(null); } var src = this.TacticalTargetListSource; src.Source = this.TacticalTargetList; src.IsLiveSortingRequested = true; src.SortDescriptions.Add(new SortDescription(nameof(TacticalTarget.Order), ListSortDirection.Ascending)); src.View.Refresh(); } public override void Dispose() { if (this.refreshTimer != null) { this.refreshTimer.Stop(); this.refreshTimer = null; } base.Dispose(); } public virtual Settings RootConfig => Settings.Instance; public virtual TacticalRadar Config => Settings.Instance.TacticalRadar; private readonly ObservableCollection<TacticalTarget> TacticalTargetList = new ObservableCollection<TacticalTarget>(); private readonly CollectionViewSource TacticalTargetListSource = new CollectionViewSource(); public ICollectionView TacticalTargetView => this.TacticalTargetListSource.View; public void UpdateTargets( IEnumerable<CombatantEx> combatants) { if (this.Config.IsDesignMode || WPFHelper.IsDesignMode) { combatants = DesignTimeCombatantList; } // ゴミを除去しておく combatants = combatants.Where(x => !string.IsNullOrEmpty(x.Name) && !x.Name.ContainsIgnoreCase("typeid")); using (this.TacticalTargetListSource.DeferRefresh()) { foreach (var combatant in combatants) { var clone = combatant.Clone(); var exists = this.TacticalTargetList.FirstOrDefault(x => x.ID == clone.UUID); if (exists != null) { exists.TargetActor = clone; } else { var config = this.Config.TacticalItems.FirstOrDefault(x => x.TargetName.ToLower() == clone.Name.ToLower()); exists = new TacticalTarget() { TargetActor = clone, TargetConfig = config, }; this.TacticalTargetList.Add(exists); if (exists.TargetConfig != null && exists.TargetConfig.IsNoticeEnabled && !string.IsNullOrEmpty(exists.TargetConfig.TTS)) { TTSWrapper.Speak(exists.TargetConfig.TTS); } } exists.UpdateTargetInfo(); Thread.Yield(); } var toRemoveTargets = this.TacticalTargetList .Where(x => !combatants.Any(y => y.UUID == x.ID)) .ToArray(); foreach (var item in toRemoveTargets) { this.TacticalTargetList.Remove(item); Thread.Yield(); } var ordered = ( from x in this.TacticalTargetList orderby x.TargetActor.Type descending, x.Distance ascending, x.ID ascending select x).ToArray(); var order = 1; foreach (var target in ordered) { target.Order = order++; } } this.RaisePropertyChanged(nameof(this.IsExistsTargets)); } public bool OverlayVisible => this.Config.Visible; public bool IsExistsTargets => this.TacticalTargetList.Count > 0; private double originAngle = 0; public double OriginAngle { get => this.originAngle; set => this.SetProperty(ref this.originAngle, value); } private double cameraHeading = 0; public double CameraHeading { get => this.cameraHeading; set => this.SetProperty(ref this.cameraHeading, value); } private DispatcherTimer refreshTimer = new DispatcherTimer(DispatcherPriority.Background) { Interval = TimeSpan.FromSeconds(0.02), }; private void RefreshOriginAngle() { if (!this.OverlayVisible) { return; } if (this.TacticalTargetList.Count < 1) { return; } var angle = 0d; switch (this.Config.DirectionOrigin) { case DirectionOrigin.North: angle = 0; break; case DirectionOrigin.Me: var player = CombatantsManager.Instance.Player; if (player != null) { angle = player.HeadingDegree * -1; } break; case DirectionOrigin.Camera: CameraInfo.Instance.Refresh(); angle = CameraInfo.Instance.HeadingDegree * -1; this.CameraHeading = CameraInfo.Instance.Heading; break; } // 補正角度を加算する this.OriginAngle = angle; } #region Design Time List private static readonly CombatantEx[] DesignTimeCombatantList = new[] { new CombatantEx() { Name = "ガルーダ", Type = (byte)Actor.Type.Monster, PosX = 0, PosY = 0, PosZ = 0, }, new CombatantEx() { Name = "イフリート", Type = (byte)Actor.Type.Monster, PosX = 0, PosY = 0, PosZ = 0, }, new CombatantEx() { Name = "タイタン", Type = (byte)Actor.Type.Monster, PosX = 0, PosY = 0, PosZ = 0, }, new CombatantEx() { Name = "Himechan Hanako", Type = (byte)Actor.Type.PC, Job = (int)Actor.Job.WHM, PosX = 0, PosY = 0, PosZ = 0, }, new CombatantEx() { Name = "Fairy Princess", Type = (byte)Actor.Type.PC, Job = (int)Actor.Job.WHM, PosX = 0, PosY = 0, PosZ = 0, }, }; #endregion Design Time List } }
30.660448
127
0.461239
[ "BSD-3-Clause" ]
Noisyfox/ACT.Hojoring
source/ACT.UltraScouter/ACT.UltraScouter.Core/ViewModels/TacticalRadarViewModel.cs
8,279
C#
using System; class PrintCompanyInformation { static void Main() { Console.Write("Company name: "); string companyName = Console.ReadLine(); Console.Write("Company address: "); string companyAddress = Console.ReadLine(); Console.Write("Company Phone: "); ulong companyPhone = ulong.Parse(Console.ReadLine()); Console.Write("Company Fax: "); ulong companyFax = ulong.Parse(Console.ReadLine()); Console.Write("Company Website: "); string companyWebsite = Console.ReadLine(); Console.Write("Manager name: "); string managerName = Console.ReadLine(); Console.Write("Manager last name: "); string managerLastName = Console.ReadLine(); Console.Write("Manager age: "); sbyte managerAge = sbyte.Parse(Console.ReadLine()); Console.Write("Manager phone: "); ulong managerPhone = ulong.Parse(Console.ReadLine()); Console.WriteLine("Company name - {0} \r\nCompany address - {1} " + "\r\nCompany phone - {2} \r\nCompany fax - {3} \r\nCompany website - {4}" + "\r\nManager name - {5} \r\nManager last name - {6} \r\nManager age - {7} " + "\r\nManager phone - {8}", companyName, companyAddress, companyPhone, companyFax, companyWebsite, managerName, managerLastName, managerAge, managerPhone); } }
44.96875
107
0.599722
[ "MIT" ]
beBoss/SoftUni
SoftUni-CSharp/Console Input Output Homework/2. Print Company Information/PrintCompanyInformation.cs
1,441
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class CameraController : MonoBehaviour { public Camera headViewCam; public GameObject target; public Button actionerSwapCam; private Camera topViewCam; // Start is called before the first frame update void Start() { headViewCam.enabled = true; topViewCam = GetComponent<Camera>(); topViewCam.enabled = false; if (actionerSwapCam != null) actionerSwapCam.onClick.AddListener(OnClick); } // Update is called once per frame void Update() { transform.LookAt(target.transform.position); } void OnClick(){ topViewCam.enabled = !topViewCam.enabled; headViewCam.enabled = !headViewCam.enabled; } }
21.578947
82
0.676829
[ "MIT" ]
gilcoder/AI4U
serverside/unityversion/baseline/ext/EmoBoy/Scripts/CameraController.cs
822
C#
using System; using System.Diagnostics.CodeAnalysis; using Armature; using Armature.Core; using Armature.Core.Sdk; using FluentAssertions; using NUnit.Framework; namespace Tests.Functional { public class AutowiringTest { [Test] public void should_inject_registered_values() { const string expectedText = "expected 09765"; const int expectedValue = 93979; // --arrange var target = CreateTarget(); target.Treat<string>().AsInstance(expectedText); target.Treat<int>().AsInstance(expectedValue); target.Treat<Subject>().AsIs(); // --act var actual = target.Build<Subject>()!; // --assert actual.Text.Should().Be(expectedText); actual.Value.Should().Be(expectedValue); } [Test] public void should_inject_runtime_values() { const string expectedText = "expected 09765"; const int expectedValue = 93979; // --arrange var target = CreateTarget(); target.Treat<Subject>().AsIs(); // --act var actual = target.Build<Subject>(expectedText, expectedValue)!; // --assert actual.Text.Should().Be(expectedText); actual.Value.Should().Be(expectedValue); } [Test] public void should_get_one_value_from_registration_and_another_runtime() { const string expectedText = "expected 09765"; const int expectedValue = 93979; // --arrange var target = CreateTarget(); target.Treat<string>().AsInstance(expectedText); target .Treat<Subject>() .AsIs(); // --act var actual = target.Build<Subject>(expectedValue)!; // --assert actual.Text.Should().Be(expectedText); actual.Value.Should().Be(expectedValue); } [Test] public void should_inject_null() { const int expectedValue = 93979; // --arrange var target = CreateTarget(); target.Treat<string>().AsInstance(null!); target.Treat<int>().AsInstance(expectedValue); target .Treat<Subject>() .AsIs(); // --act var actual = target.Build<Subject>()!; // --assert actual.Text.Should().BeNull(); actual.Value.Should().Be(expectedValue); } [Test] public void should_use_inject_point_id_as_tag() { const string expectedText = "expected 09765"; const int expectedValue = 93979; // --arrange var target = CreateTarget(); target.Treat<string>(Subject.TextParameterId).AsInstance(expectedText); target.Treat<int>().AsInstance(expectedValue); target .Treat<Subject>() .AsIs(); // --act var actual = target.Build<Subject>()!; // --assert actual.Text.Should().Be(expectedText); actual.Value.Should().Be(expectedValue); } [Test] public void should_fail_if_there_is_no_value_wo_tag_registered() { // --arrange var target = CreateTarget(); target .Treat<string>("tag") .AsInstance("09765"); target .Treat<Subject>() .AsIs(); // --act Action actual = () => target.Build<Subject>(); // --assert actual.Should().ThrowExactly<ArmatureException>(); } private static Builder CreateTarget() => new(BuildStage.Cache, BuildStage.Create) { new SkipAllUnits { // inject into constructor new IfFirstUnit(new IsConstructor()) .UseBuildAction( new TryInOrder { new GetConstructorByInjectPointId(), // constructor marked with [Inject] attribute has more priority new GetConstructorWithMaxParametersCount() // constructor with largest number of parameters has less priority }, BuildStage.Create), new IfFirstUnit(new IsParameterInfoList()) .UseBuildAction(new BuildMethodArgumentsInDirectOrder(), BuildStage.Create), new IfFirstUnit(new IsParameterInfo()) .UseBuildAction( new TryInOrder { Static.Of<BuildArgumentByParameterInjectPointId>(), Static.Of<BuildArgumentByParameterType>() }, BuildStage.Create) } }; private interface ISubject1 { string Text { get; } } private interface ISubject2 { string Text { get; } } [SuppressMessage("ReSharper", "ClassNeverInstantiated.Local")] private class Subject : ISubject1, ISubject2 { public const string TextParameterId = "Text"; public Subject([Inject(TextParameterId)] string text, int value) { Text = text; Value = value; } public int Value { get; } public string Text { get; } } } }
25.061224
128
0.588762
[ "Apache-2.0" ]
Ed-ward/Armature
tests/Tests/src/Functional/AutowiringTest.cs
4,914
C#
using System; using System.IO; using PRISM.Logging; using PRISM; namespace DeconTools.Backend.Utilities.IqLogger { public static class IqLogger { static IqLogger() { Log = new FileLogger { LogLevel = BaseLogger.LogLevels.INFO }; var baseName = Path.Combine(Environment.CurrentDirectory, "IqLog"); FileLogger.ChangeLogFileBaseName(baseName, false); } private static readonly FileLogger Log; public static string LogDirectory { get; set; } = string.Empty; /// <summary> /// Set to True to enable verbose logging /// </summary> public static bool VerboseLogging { get; set; } = false; /// <summary> /// Immediately write out any queued messages /// </summary> public static void FlushPendingMessages() { FileLogger.FlushPendingMessages(); } /// <summary> /// Initializes the standard IqLog file for the given dataset /// </summary> /// <param name="datasetName"></param> /// <param name="logDirectory"></param> public static void InitializeIqLog(string datasetName, string logDirectory) { if (string.IsNullOrWhiteSpace(logDirectory)) LogDirectory = string.Empty; else LogDirectory = logDirectory; ChangeLogLocation(LogDirectory, datasetName, "_IqLog.txt"); } /// <summary> /// Changes the log location / log file name of the desired appender /// </summary> /// <param name="logDirectoryPath"></param> /// <param name="logFileNamePrefix"></param> /// <param name="logFileNameSuffix"></param> private static void ChangeLogLocation(string logDirectoryPath, string logFileNamePrefix, string logFileNameSuffix) { var baseName = Path.Combine(logDirectoryPath, logFileNamePrefix + logFileNameSuffix); FileLogger.ChangeLogFileBaseName(baseName, false); } /// <summary> /// Verbose logging; not shown at the console /// </summary> /// <param name="message"></param> public static void LogTrace(string message) { if (!VerboseLogging) return; if (Log.LogLevel < BaseLogger.LogLevels.DEBUG) Log.LogLevel = BaseLogger.LogLevels.DEBUG; Log.Debug(message); } /// <summary> /// Log a debug message, level Info /// </summary> /// <param name="message"></param> public static void LogDebug(string message) { Log.Debug(message); ConsoleMsgUtils.ShowDebug(message); } /// <summary> /// Log an errr message /// </summary> /// <param name="message"></param> /// <param name="ex"></param> public static void LogError(string message, Exception ex = null) { Log.Error(message, ex); ConsoleMsgUtils.ShowError(message, ex); } /// <summary> /// Log a message, level Info /// </summary> /// <param name="message"></param> public static void LogMessage(string message) { Log.Info(message); Console.WriteLine(message); } /// <summary> /// Log a message, level warn /// </summary> /// <param name="message"></param> public static void LogWarning(string message) { Log.Warn(message); ConsoleMsgUtils.ShowWarning(message); } } }
31.628099
123
0.536713
[ "Apache-2.0" ]
PNNL-Comp-Mass-Spec/DeconTools
DeconTools.Backend/Utilities/IqLogger/IqLogger.cs
3,827
C#
namespace SharedModel.Payloads.Requests { public record CreateGroupDtoRequest(string GroupName, string? Description); }
25
79
0.808
[ "MIT" ]
returner/asp-net-core-jwt-identity
SharedModel/Payloads/Requests/CreateGroupDtoRequest.cs
127
C#
using AutoMapper; using EPlast.BLL.DTO; using EPlast.BLL.DTO.UserProfiles; using EPlast.BLL.Interfaces.AzureStorage; using EPlast.BLL.Interfaces.UserProfiles; using EPlast.BLL.Services.Interfaces; using EPlast.BLL.Services.UserProfiles; using EPlast.DataAccess.Entities; using EPlast.DataAccess.Repositories; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Identity; using Moq; using System; using System.Collections.Generic; using System.Linq.Expressions; using System.Security.Claims; using System.Threading.Tasks; using Xunit; namespace EPlast.XUnitTest.Services.UserArea { public class UserServiceTests { private Mock<IRepositoryWrapper> _repoWrapper; private Mock<IUserStore<User>> _userStoreMock; private Mock<UserManager<User>> _userManager; private Mock<IWebHostEnvironment> _hostEnv; private Mock<IMapper> _mapper; private Mock<IWorkService> _workService; private Mock<IEducationService> _educationService; private Mock<IUserBlobStorageRepository> _userBlobStorage; private Mock<IWebHostEnvironment> _env; private Mock<IUserManagerService> _userManagerService; private Mock<IConfirmedUsersService> _confirmedUserService; public UserServiceTests() { _repoWrapper = new Mock<IRepositoryWrapper>(); _userStoreMock = new Mock<IUserStore<User>>(); _userManager = new Mock<UserManager<User>>(_userStoreMock.Object, null, null, null, null, null, null, null, null); _mapper = new Mock<IMapper>(); _workService = new Mock<IWorkService>(); _educationService = new Mock<IEducationService>(); _userBlobStorage=new Mock<IUserBlobStorageRepository>(); _env=new Mock<IWebHostEnvironment>(); _userManagerService = new Mock<IUserManagerService>(); _confirmedUserService = new Mock<IConfirmedUsersService>(); } private UserService GetService() { return new UserService(_repoWrapper.Object, _userManager.Object, _mapper.Object, _workService.Object, _educationService.Object, _userBlobStorage.Object,_env.Object, _userManagerService.Object, _confirmedUserService.Object); } [Fact] public async Task GetUserProfileTest() { _repoWrapper.SetupSequence(r => r.User.GetFirstAsync(It.IsAny<Expression<Func<User, bool>>>(), null)).ReturnsAsync(new User { FirstName = "Vova", LastName = "Vermii", UserProfile = new UserProfile { Nationality = new Nationality { Name = "Українець" }, Religion = new Religion { Name = "Християнство" }, Education = new Education() { PlaceOfStudy = "ЛНУ", Speciality = "КН" }, Degree = new Degree { Name = "Бакалавр" }, Work = new Work { PlaceOfwork = "SoftServe", Position = "ProjectManager" }, Gender = new Gender { Name = "Чоловік" } } }); var service = GetService(); _mapper.Setup(x => x.Map<User, UserDTO>(It.IsAny<User>())).Returns(new UserDTO()); // Act var result = await service.GetUserAsync("1"); // Assert Assert.NotNull(result); var viewResult = Assert.IsType<UserDTO>(result); } [Fact] public void GetConfirmedUsersTest() { UserDTO user = new UserDTO { ConfirmedUsers = new List<ConfirmedUserDTO>() }; var service = GetService(); // Act var result = service.GetConfirmedUsers(user); // Assert Assert.NotNull(result); var viewResult = Assert.IsAssignableFrom<IEnumerable<ConfirmedUserDTO>>(result); } [Fact] public void GetClubAdminConfirmedUserTest() { UserDTO user = new UserDTO { ConfirmedUsers = new List<ConfirmedUserDTO>() }; var service = GetService(); // Act var result = service.GetConfirmedUsers(user); // Assert Assert.NotNull(result); var viewResult = Assert.IsAssignableFrom<IEnumerable<ConfirmedUserDTO>>(result); } [Fact] public void GetCityAdminConfirmedUserTest() { UserDTO user = new UserDTO { ConfirmedUsers = new List<ConfirmedUserDTO>() }; var service = GetService(); // Act var result = service.GetConfirmedUsers(user); // Assert Assert.NotNull(result); Assert.IsAssignableFrom<IEnumerable<ConfirmedUserDTO>>(result); } [Fact] public async Task CanApproveTest() { var conUser = new ConfirmedUserDTO { UserID = "1", ConfirmDate = DateTime.Now, isClubAdmin = false, isCityAdmin = false }; var appUser = new ApproverDTO { UserID = "3", ConfirmedUser = conUser }; conUser.Approver = appUser; UserDTO user = new UserDTO { ConfirmedUsers = new List<ConfirmedUserDTO>() }; var confUsers = new List<ConfirmedUserDTO> { conUser, conUser }; _userManager.Setup(x => x.GetUserAsync(It.IsAny<ClaimsPrincipal>())).ReturnsAsync(new User { Id = "1" }); var service = GetService(); // Act var result = await service.CanApproveAsync(confUsers, "2", It.IsAny<ClaimsPrincipal>()); // Assert var res = Assert.IsType<bool>(result); Assert.True(result); } [Fact] public async Task CanApproveTestFailure() { UserDTO user = new UserDTO { ConfirmedUsers = new List<ConfirmedUserDTO>() }; var conUser = new ConfirmedUserDTO(); var confUsers = new List<ConfirmedUserDTO> { conUser, conUser, conUser, conUser }; _userManager.Setup(x => x.GetUserAsync(It.IsAny<ClaimsPrincipal>())).ReturnsAsync(new User { Id = "1" }); var service = GetService(); // Act var result = await service.CanApproveAsync(confUsers, "1", It.IsAny<ClaimsPrincipal>()); // Assert var res = Assert.IsType<bool>(result); Assert.False(result); } [Fact] public async Task CheckOrAddPlastunRoleTest() { _userManager.Setup(x => x.FindByIdAsync(It.IsAny<string>())).ReturnsAsync(new User()); var service = GetService(); // Act var result = await service.CheckOrAddPlastunRoleAsync("1", DateTime.MinValue); // Assert var res = Assert.IsType<TimeSpan>(result); } [Fact] public async Task UpdateTest() { var userDTO = new UserDTO { FirstName = "Vova", LastName = "Vermii", UserProfile = new UserProfileDTO { Nationality = new NationalityDTO { Name = "Українець" }, NationalityId = 1, Religion = new ReligionDTO { Name = "Християнство" }, ReligionId = 1, Education = new EducationDTO() { PlaceOfStudy = "ЛНУ", Speciality = "КН" }, EducationId = 1, Degree = new DegreeDTO { Name = "Бакалавр" }, DegreeId = 1, Work = new WorkDTO { PlaceOfwork = "SoftServe", Position = "ProjectManager" }, WorkId = 1, Gender = new GenderDTO { Name = "Чоловік" }, GenderID = 1 } }; var user = new User { FirstName = "Vova", LastName = "Vermii", UserProfile = new UserProfile { Nationality = new Nationality { Name = "Українець" }, Religion = new Religion { Name = "Християнство" }, Education = new Education() { PlaceOfStudy = "ЛНУ", Speciality = "КН" }, Degree = new Degree { Name = "Бакалавр" }, Work = new Work { PlaceOfwork = "SoftServe", Position = "ProjectManager" }, Gender = new Gender { Name = "Чоловік" } } }; _repoWrapper.Setup(r => r.User.GetFirstOrDefaultAsync(It.IsAny<Expression<Func<User, bool>>>(), null)).ReturnsAsync(user); _repoWrapper.Setup(r => r.UserProfile.GetFirstOrDefaultAsync(It.IsAny<Expression<Func<UserProfile, bool>>>(), null)).ReturnsAsync(new UserProfile()); _repoWrapper.Setup(r => r.Education.GetFirstOrDefaultAsync(It.IsAny<Expression<Func<Education, bool>>>(), null)).ReturnsAsync(new Education { PlaceOfStudy = "place", Speciality = "spec", }); _repoWrapper.Setup(r => r.Work.GetFirstOrDefaultAsync(It.IsAny<Expression<Func<Work, bool>>>(), null)).ReturnsAsync(new Work { PlaceOfwork = "place", Position = "position", }); _mapper.Setup(x => x.Map<UserDTO, User>(It.IsAny<UserDTO>())).Returns(user); var mockFile = new Mock<IFormFile>(); var service = GetService(); // Act await service.UpdateAsync(userDTO, mockFile.Object, 1, 1, 1, 1); // Assert _repoWrapper.Verify(r => r.User.Update(It.IsAny<User>()), Times.Once()); _repoWrapper.Verify(r => r.UserProfile.Update(It.IsAny<UserProfile>()), Times.Once()); _repoWrapper.Verify(r => r.SaveAsync(), Times.Once()); } } }
45.67907
235
0.576112
[ "MIT" ]
gatalyak/EPlast
EPlast/EPlast.XUnitTest/Services/UserArea/UserServiceTests.cs
9,946
C#
using System; using System.IO; namespace KugelmatikLibrary.Protocol { public struct PacketStepper : IPacket { public PacketType Type { get { return PacketType.Stepper; } } public StepperPosition Position; public ushort Height; public byte WaitTime; public PacketStepper(StepperPosition position, ushort height, byte waitTime) { this.Position = position; this.Height = height; this.WaitTime = waitTime; } public void Read(BinaryReader reader) { if (reader == null) throw new ArgumentNullException("reader"); this.Position = new StepperPosition(reader); this.Height = reader.ReadUInt16(); this.WaitTime = reader.ReadByte(); } public void Write(BinaryWriter writer) { if(writer == null) throw new ArgumentNullException("writer"); writer.Write(Position.Value); writer.Write(Height); writer.Write(WaitTime); } } }
25
84
0.56
[ "MIT" ]
henrik1235/Kugelmatik
KugelmatikLibrary/Protocol/PacketStepper.cs
1,127
C#
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using NUnit.Framework; using UnityEngine; namespace Unity.Entities.Tests { class ComponentDataWrapper_UnitTests { static bool IsSubclassOfOpenGenericType(Type type, Type genericType) { if (type.IsSubclassOf(genericType)) return true; while (type != null && type != typeof(object)) { var cur = type.IsGenericType ? type.GetGenericTypeDefinition() : type; if (genericType == cur) return true; type = type.BaseType; } return false; } static IEnumerable<Type> GetAllSubTypes(Type genericType, params Type[] ignoreTypes) { var result = new List<Type>(); foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies()) { try { result.AddRange( assembly.GetTypes() .Where(t => !t.IsAbstract && !t.IsGenericType && !ignoreTypes.Contains(t) && IsSubclassOfOpenGenericType(t, genericType) ) ); } // ignore if error loading some type from a dll catch (TypeLoadException) { } } return result; } static readonly IEnumerable k_AllComponentDataWrapperTypes = GetAllSubTypes(typeof(ComponentDataWrapper<>)).Select(t => new TestCaseData(t).SetName(t.FullName)); [TestCaseSource(nameof(k_AllComponentDataWrapperTypes))] public void AllComponentDataWrappers_DisallowMultipleComponent(Type type) { Assert.That(Attribute.IsDefined(type, typeof(DisallowMultipleComponent)), Is.True); } static readonly IEnumerable k_AllSharedComponentDataWrapperTypes = GetAllSubTypes( typeof(SharedComponentDataWrapper<>), ignoreTypes: typeof(MockSharedDisallowMultipleComponent) ).Select(t => new TestCaseData(t).SetName(t.FullName)); // currently enforced due to implementation of SerializeUtilityHybrid // ideally all types should ultimately have DisallowMultipleComponent [TestCaseSource(nameof(k_AllSharedComponentDataWrapperTypes))] public void NoSharedComponentDataWrappers_DisallowMultipleComponent(Type type) { Assert.That(Attribute.IsDefined(type, typeof(DisallowMultipleComponent)), Is.False); } } }
38.295775
112
0.58367
[ "MIT" ]
1978mountain/UnityMMO
Packages/com.unity.entities/Unity.Entities.Hybrid.Tests/ComponentDataWrapper_UnitTests.cs
2,721
C#
namespace LearningSystem.Web.Controllers { using LearningSystem.Data.Models; using LearningSystem.Services; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Mvc; using System.Threading.Tasks; [Authorize] public class UsersController : Controller { private readonly IUserService users; private readonly UserManager<User> userManager; public UsersController(IUserService users, UserManager<User> userManager) { this.users = users; this.userManager = userManager; } public async Task<IActionResult> Profile() { var userId = this.userManager.GetUserId(User); if (userId == null) { return NotFound(); } var profile = await this.users.ProfileAsync(userId); return View(profile); } } }
26.611111
81
0.618998
[ "MIT" ]
ivanrk/Learning-System
LearningSystem.Web/Controllers/UsersController.cs
960
C#
using System; using System.Linq; using Common.Commands; using Common.Constants; using Common.Extensions; using Common.Interfaces; using Common.Interfaces.Handlers; using Common.Structs; namespace Beta_3592.Handlers { public class CharHandler : ICharHandler { public void HandleCharCreate(ref IPacketReader packet, ref IWorldManager manager) { string name = packet.ReadString(); Character cha = new Character() { Name = name.ToUpperFirst(), Race = packet.ReadByte(), Class = packet.ReadByte(), Gender = packet.ReadByte(), Skin = packet.ReadByte(), Face = packet.ReadByte(), HairStyle = packet.ReadByte(), HairColor = packet.ReadByte(), FacialHair = packet.ReadByte() }; var result = manager.Account.Characters.Where(x => x.Build == Sandbox.Instance.Build); PacketWriter writer = new PacketWriter(Sandbox.Instance.Opcodes[global::Opcodes.SMSG_CHAR_CREATE], "SMSG_CHAR_CREATE"); if (result.Any(x => x.Name.Equals(cha.Name, StringComparison.CurrentCultureIgnoreCase))) { writer.WriteUInt8(0x2B); // Duplicate name manager.Send(writer); return; } cha.Guid = (ulong)(manager.Account.Characters.Count + 1); cha.Location = new Location(-8949.95f, -132.493f, 83.5312f, 0, 0); cha.RestedState = (byte)new Random().Next(1, 5); cha.SetDefaultValues(); manager.Account.Characters.Add(cha); manager.Account.Save(); // Success writer.WriteUInt8(0x28); manager.Send(writer); } public void HandleCharDelete(ref IPacketReader packet, ref IWorldManager manager) { ulong guid = packet.ReadUInt64(); var character = manager.Account.GetCharacter(guid, Sandbox.Instance.Build); PacketWriter writer = new PacketWriter(Sandbox.Instance.Opcodes[global::Opcodes.SMSG_CHAR_DELETE], "SMSG_CHAR_DELETE"); writer.WriteUInt8(0x2C); manager.Send(writer); if (character != null) { manager.Account.Characters.Remove(character); manager.Account.Save(); } } public void HandleCharEnum(ref IPacketReader packet, ref IWorldManager manager) { var account = manager.Account; var result = account.Characters.Where(x => x.Build == Sandbox.Instance.Build); PacketWriter writer = new PacketWriter(Sandbox.Instance.Opcodes[global::Opcodes.SMSG_CHAR_ENUM], "SMSG_CHAR_ENUM"); writer.WriteUInt8((byte)result.Count()); foreach (Character c in result) { writer.WriteUInt64(c.Guid); writer.WriteString(c.Name); writer.WriteUInt8(c.Race); writer.WriteUInt8(c.Class); writer.WriteUInt8(c.Gender); writer.WriteUInt8(c.Skin); writer.WriteUInt8(c.Face); writer.WriteUInt8(c.HairStyle); writer.WriteUInt8(c.HairColor); writer.WriteUInt8(c.FacialHair); writer.WriteUInt8((byte)c.Level); writer.WriteUInt32(c.Zone); writer.WriteUInt32(c.Location.Map); writer.WriteFloat(c.Location.X); writer.WriteFloat(c.Location.Y); writer.WriteFloat(c.Location.Z); writer.WriteUInt32(0); writer.WriteUInt32(0); writer.WriteUInt8(c.RestedState); writer.WriteUInt32(0); writer.WriteUInt32(0); writer.WriteUInt32(0); // Items for (int j = 0; j < 0x14; j++) { writer.WriteUInt32(0); // DisplayId writer.WriteUInt8(0); // InventoryType } } manager.Send(writer); } public void HandleMessageChat(ref IPacketReader packet, ref IWorldManager manager) { var character = manager.Account.ActiveCharacter; PacketWriter writer = new PacketWriter(Sandbox.Instance.Opcodes[global::Opcodes.SMSG_MESSAGECHAT], "SMSG_MESSAGECHAT"); writer.WriteUInt8((byte)packet.ReadInt32()); // System Message packet.ReadUInt32(); writer.WriteUInt32(0); // Language: General writer.WriteUInt64(character.Guid); string message = packet.ReadString(); writer.WriteString(message); writer.WriteUInt8(0); if (!CommandManager.InvokeHandler(message, manager)) manager.Send(writer); } public void HandleMovementStatus(ref IPacketReader packet, ref IWorldManager manager) { if (manager.Account.ActiveCharacter.IsTeleporting) return; uint Flags = packet.ReadUInt32(); manager.Account.ActiveCharacter.Location.Update(packet, true); } public void HandleNameCache(ref IPacketReader packet, ref IWorldManager manager) { ulong guid = packet.ReadUInt64(); var character = manager.Account.GetCharacter(guid, Sandbox.Instance.Build); PacketWriter nameCache = new PacketWriter(Sandbox.Instance.Opcodes[global::Opcodes.SMSG_NAME_QUERY_RESPONSE], "SMSG_NAME_QUERY_RESPONSE"); nameCache.WriteUInt64(guid); nameCache.WriteString(character.Name); nameCache.WriteUInt32(character.Race); nameCache.WriteUInt32(character.Gender); nameCache.WriteUInt32(character.Class); manager.Send(nameCache); } public void HandleStandState(ref IPacketReader packet, ref IWorldManager manager) { manager.Account.ActiveCharacter.StandState = (StandState)packet.ReadUInt32(); manager.Send(manager.Account.ActiveCharacter.BuildUpdate()); } public void HandleTextEmote(ref IPacketReader packet, ref IWorldManager manager) { uint emote = packet.ReadUInt32(); ulong guid = packet.ReadUInt64(); uint emoteId = Emotes.Get((TextEmotes)emote); Character character = (Character)manager.Account.ActiveCharacter; PacketWriter pw = new PacketWriter(Sandbox.Instance.Opcodes[global::Opcodes.SMSG_TEXT_EMOTE], "SMSG_TEXT_EMOTE"); pw.Write(character.Guid); pw.Write(emote); if (guid == character.Guid) pw.WriteString(character.Name); else pw.WriteUInt8(0); manager.Send(pw); switch ((TextEmotes)emote) { case TextEmotes.EMOTE_SIT: character.StandState = StandState.SITTING; manager.Send(character.BuildUpdate()); return; case TextEmotes.EMOTE_STAND: character.StandState = StandState.STANDING; manager.Send(character.BuildUpdate()); return; case TextEmotes.EMOTE_SLEEP: character.StandState = StandState.SLEEPING; manager.Send(character.BuildUpdate()); return; case TextEmotes.EMOTE_KNEEL: character.StandState = StandState.KNEEL; manager.Send(character.BuildUpdate()); return; } if (emoteId > 0) { pw = new PacketWriter(Sandbox.Instance.Opcodes[global::Opcodes.SMSG_EMOTE], "SMSG_EMOTE"); pw.WriteUInt32(emoteId); pw.WriteUInt64(character.Guid); manager.Send(pw); } } } }
37.296296
150
0.569265
[ "MIT" ]
Ghaster/AIO-Sandbox
Plugins/Beta_3592/Handlers/CharHandler.cs
8,058
C#
using RateIt.Model; using RateIt.Repositories.Interfaces; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace RateIt.Repositories.Repositories { public class UserRatingsRepository : BaseRepository, IRepository<UserRating> { public UserRatingsRepository(MoralityNetworkEntities entities) : base(entities) { } public UserRating Add(UserRating item) { _entities.UserRatings.Add(item); return item; } public IEnumerable<UserRating> GetAll() { return _entities.UserRatings; } public UserRating Remove(UserRating item) { _entities.UserRatings.Remove(item); return item; } public IList<UserRating> RemoveList(IList<UserRating> items) { _entities.UserRatings.RemoveRange(items); return items; } public UserRating Update(UserRating item) { _entities.Entry(item).State = System.Data.Entity.EntityState.Modified; return item; } } }
24.659574
87
0.627265
[ "MIT" ]
morality-admin/morality.network
Back end Prototype/RateIt.Repositories/Repositories/UserRatingsRepository.cs
1,161
C#
using Microsoft.AspNetCore.Components; using Microsoft.AspNetCore.Components.Forms; using Microsoft.AspNetCore.Components.Web; using Microsoft.JSInterop; using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Threading.Tasks; using System.Timers; namespace Blazored.Typeahead { public partial class BlazoredTypeahead<TItem, TValue> : ComponentBase, IDisposable { private EditContext _editContext; private FieldIdentifier _fieldIdentifier; private Timer _debounceTimer; private string _searchText = string.Empty; private bool _eventsHookedUp = false; private ElementReference _searchInput; private ElementReference _mask; [Inject] private IJSRuntime JSRuntime { get; set; } [CascadingParameter] private EditContext CascadedEditContext { get; set; } [Parameter] public TValue Value { get; set; } [Parameter] public EventCallback<TValue> ValueChanged { get; set; } [Parameter] public Expression<Func<TValue>> ValueExpression { get; set; } [Parameter] public IList<TValue> Values { get; set; } [Parameter] public EventCallback<IList<TValue>> ValuesChanged { get; set; } [Parameter] public Expression<Func<IList<TValue>>> ValuesExpression { get; set; } [Parameter] public Func<string, Task<IEnumerable<TItem>>> SearchMethod { get; set; } [Parameter] public Func<TItem, TValue> ConvertMethod { get; set; } [Parameter] public RenderFragment NotFoundTemplate { get; set; } [Parameter] public RenderFragment HelpTemplate { get; set; } [Parameter] public RenderFragment<TItem> ResultTemplate { get; set; } [Parameter] public RenderFragment<TValue> SelectedTemplate { get; set; } [Parameter] public RenderFragment HeaderTemplate { get; set; } [Parameter] public RenderFragment FooterTemplate { get; set; } [Parameter(CaptureUnmatchedValues = true)] public IReadOnlyDictionary<string, object> AdditionalAttributes { get; set; } [Parameter] public int MinimumLength { get; set; } = 1; [Parameter] public int Debounce { get; set; } = 300; [Parameter] public int MaximumSuggestions { get; set; } = 10; [Parameter] public bool Disabled { get; set; } = false; [Parameter] public bool EnableDropDown { get; set; } = false; [Parameter] public bool ShowDropDownOnFocus { get; set; } = false; [Parameter] public bool StopPropagation { get; set; } = false; [Parameter] public bool PreventDefault { get; set; } = false; private bool IsSearching { get; set; } = false; private bool IsShowingSuggestions { get; set; } = false; private bool IsShowingMask { get; set; } = false; private TItem[] Suggestions { get; set; } = new TItem[0]; private int SelectedIndex { get; set; } private bool ShowHelpTemplate { get; set; } = false; private string SearchText { get => _searchText; set { _searchText = value; if (value.Length == 0) { _debounceTimer.Stop(); SelectedIndex = -1; } else { _debounceTimer.Stop(); _debounceTimer.Start(); } } } private string FieldCssClasses => _editContext?.FieldCssClass(_fieldIdentifier) ?? ""; private bool IsMultiselect => ValuesExpression != null; protected override void OnInitialized() { if (SearchMethod == null) { throw new InvalidOperationException($"{GetType()} requires a {nameof(SearchMethod)} parameter."); } if (ConvertMethod == null) { if (typeof(TItem) != typeof(TValue)) { throw new InvalidOperationException($"{GetType()} requires a {nameof(ConvertMethod)} parameter."); } ConvertMethod = item => item is TValue value ? value : default; } if (SelectedTemplate == null) { throw new InvalidOperationException($"{GetType()} requires a {nameof(SelectedTemplate)} parameter."); } if (ResultTemplate == null) { throw new InvalidOperationException($"{GetType()} requires a {nameof(ResultTemplate)} parameter."); } _debounceTimer = new Timer(); _debounceTimer.Interval = Debounce; _debounceTimer.AutoReset = false; _debounceTimer.Elapsed += Search; _editContext = CascadedEditContext; _fieldIdentifier = IsMultiselect ? FieldIdentifier.Create(ValuesExpression) : FieldIdentifier.Create(ValueExpression); Initialize(); } protected override async Task OnAfterRenderAsync(bool firstRender) { if ((firstRender && !Disabled) || (!_eventsHookedUp && !Disabled)) { await Interop.AddKeyDownEventListener(JSRuntime, _searchInput); _eventsHookedUp = true; } } protected override void OnParametersSet() { Initialize(); } private void Initialize() { SearchText = ""; IsShowingSuggestions = false; IsShowingMask = Value != null; } private async Task RemoveValue(TValue item) { var valueList = Values ?? new List<TValue>(); if (valueList.Contains(item)) { valueList.Remove(item); } await ValuesChanged.InvokeAsync(valueList); _editContext?.NotifyFieldChanged(_fieldIdentifier); } private async Task HandleClear() { SearchText = ""; IsShowingMask = false; if (IsMultiselect) { await ValuesChanged.InvokeAsync(new List<TValue>()); } else { await ValueChanged.InvokeAsync(default); } _editContext?.NotifyFieldChanged(_fieldIdentifier); await Task.Delay(250); // Possible race condition here. await Interop.Focus(JSRuntime, _searchInput); } private async Task HandleClickOnMask() { SearchText = ""; IsShowingMask = false; await Task.Delay(250); // Possible race condition here. await Interop.Focus(JSRuntime, _searchInput); } private async Task HandleKeyUpOnShowDropDown(KeyboardEventArgs args) { if (args.Key == "ArrowDown") { MoveSelection(1); } else if (args.Key == "ArrowUp") { MoveSelection(-1); } else if (args.Key == "Escape") { Initialize(); } else if (args.Key == "Enter" && Suggestions.Length == 1) { await SelectTheFirstAndOnlySuggestion(); } else if (args.Key == "Enter" && SelectedIndex >= 0 && SelectedIndex < Suggestions.Length) { await SelectResult(Suggestions[SelectedIndex]); } else if (args.Key == "Enter") { await ShowMaximumSuggestions(); } } private async Task HandleKeyUpOnMask(KeyboardEventArgs args) { switch (args.Key) { case "Tab": break; // Don't do anything on tab. case "Enter": case "Backspace": case "Delete": case "Escape": await HandleClear(); break; default: break; } // You can only start searching if it's not a special key (Tab, Enter, Escape, ...) if (args.Key.Length == 1) { IsShowingMask = false; await Task.Delay(250); // Possible race condition here. await Interop.Focus(JSRuntime, _searchInput); SearchText = args.Key; } } private async Task HandleKeyup(KeyboardEventArgs args) { if ((args.Key == "ArrowDown" || args.Key == "Enter") && EnableDropDown && !IsShowingSuggestions) { await ShowMaximumSuggestions(); } if (args.Key == "ArrowDown") { MoveSelection(1); } else if (args.Key == "ArrowUp") { MoveSelection(-1); } else if (args.Key == "Escape") { Initialize(); } else if (args.Key == "Enter" && Suggestions.Count() == 1) { await SelectTheFirstAndOnlySuggestion(); } else if (args.Key == "Enter" && SelectedIndex >= 0 && SelectedIndex < Suggestions.Count()) { await SelectResult(Suggestions[SelectedIndex]); } else if (IsMultiselect && !IsShowingSuggestions && args.Key == "Backspace") { if (Values.Any()) await RemoveValue(Values.Last()); } } private async Task HandleInputFocus() { if (ShowDropDownOnFocus) { await ShowMaximumSuggestions(); } } private bool _resettingControl = false; private async Task ResetControl() { if (!_resettingControl) { _resettingControl = true; await Task.Delay(5000); Initialize(); _resettingControl = false; } } private async Task ShowMaximumSuggestions() { if (_resettingControl) { while (_resettingControl) { await Task.Delay(150); } } IsShowingSuggestions = !IsShowingSuggestions; if (IsShowingSuggestions) { SearchText = ""; IsSearching = true; await InvokeAsync(StateHasChanged); Suggestions = (await SearchMethod?.Invoke(_searchText)).Take(MaximumSuggestions).ToArray(); IsSearching = false; await InvokeAsync(StateHasChanged); } } private string GetSelectedSuggestionClass(TItem item, int index) { const string resultClass = "blazored-typeahead__active-item"; TValue value = ConvertMethod(item); if (Equals(value, Value) || (Values?.Contains(value) ?? false)) { if (index == SelectedIndex) { return "blazored-typeahead__selected-item-highlighted"; } return "blazored-typeahead__selected-item"; } if (index == SelectedIndex) { return resultClass; } return Equals(value, Value) ? resultClass : string.Empty; } private async void Search(Object source, ElapsedEventArgs e) { if (_searchText.Length < MinimumLength) { ShowHelpTemplate = true; await InvokeAsync(StateHasChanged); return; } ShowHelpTemplate = false; IsSearching = true; await InvokeAsync(StateHasChanged); Suggestions = (await SearchMethod?.Invoke(_searchText)).Take(MaximumSuggestions).ToArray(); IsSearching = false; IsShowingSuggestions = true; SelectedIndex = 0; await InvokeAsync(StateHasChanged); } private async Task SelectResult(TItem item) { var value = ConvertMethod(item); if (IsMultiselect) { var valueList = Values ?? new List<TValue>(); if (valueList.Contains(value)) valueList.Remove(value); else valueList.Add(value); await ValuesChanged.InvokeAsync(valueList); } else { Value = value; await ValueChanged.InvokeAsync(value); } _editContext?.NotifyFieldChanged(_fieldIdentifier); if (IsMultiselect) { await Interop.Focus(JSRuntime, _searchInput); } else { await Task.Delay(250); await Interop.Focus(JSRuntime, _mask); } } private bool ShouldShowHelpTemplate() { return SearchText.Length > 0 && ShowHelpTemplate && HelpTemplate != null; } private bool ShouldShowSuggestions() { return IsShowingSuggestions && Suggestions.Any() && !IsSearchingOrDebouncing; } private void MoveSelection(int count) { var index = SelectedIndex + count; if (index >= Suggestions.Length) { index = 0; } if (index < 0) { index = Suggestions.Length - 1; } SelectedIndex = index; } private Task SelectTheFirstAndOnlySuggestion() { SelectedIndex = 0; return SelectResult(Suggestions[SelectedIndex]); } private bool IsSearchingOrDebouncing => IsSearching || _debounceTimer.Enabled; private bool ShowNotFound() { return IsShowingSuggestions && !IsSearchingOrDebouncing && !Suggestions.Any(); } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (disposing) { _debounceTimer.Dispose(); } } } }
31.936404
130
0.521115
[ "MIT" ]
foundation29org/Dx29.Web
src/Dx29.Web.UI/Components/Typeahead/BlazoredTypeahead.razor.cs
14,563
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using Microsoft.AspNetCore.Http.Metadata; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; namespace Microsoft.AspNetCore.Http.HttpResults; /// <summary> /// An <see cref="IResult"/> that on execution will write an object to the response /// with Ok (200) status code. /// </summary> /// <typeparam name="TValue">The type of object that will be JSON serialized to the response body.</typeparam> public sealed class Ok<TValue> : IResult, IEndpointMetadataProvider { /// <summary> /// Initializes a new instance of the <see cref="Ok"/> class with the values. /// </summary> /// <param name="value">The value to format in the entity body.</param> internal Ok(TValue? value) { Value = value; HttpResultsHelper.ApplyProblemDetailsDefaultsIfNeeded(Value, StatusCode); } /// <summary> /// Gets the object result. /// </summary> public TValue? Value { get; } /// <summary> /// Gets the HTTP status code: <see cref="StatusCodes.Status200OK"/> /// </summary> public int StatusCode => StatusCodes.Status200OK; /// <inheritdoc/> public Task ExecuteAsync(HttpContext httpContext) { ArgumentNullException.ThrowIfNull(httpContext); // Creating the logger with a string to preserve the category after the refactoring. var loggerFactory = httpContext.RequestServices.GetRequiredService<ILoggerFactory>(); var logger = loggerFactory.CreateLogger("Microsoft.AspNetCore.Http.Result.OkObjectResult"); HttpResultsHelper.Log.WritingResultAsStatusCode(logger, StatusCode); httpContext.Response.StatusCode = StatusCode; return HttpResultsHelper.WriteResultAsJsonAsync( httpContext, logger: logger, Value); } /// <inheritdoc/> static void IEndpointMetadataProvider.PopulateMetadata(EndpointMetadataContext context) { ArgumentNullException.ThrowIfNull(context); context.EndpointMetadata.Add(new ProducesResponseTypeMetadata(typeof(TValue), StatusCodes.Status200OK, "application/json")); } }
36.111111
132
0.70022
[ "MIT" ]
Akarachudra/kontur-aspnetcore-fork
src/Http/Http.Results/src/OkOfT.cs
2,275
C#
using System; using System.IO; using ClickHouse.Ado.Impl.Data; using K4os.Compression.LZ4; using K4os.Compression.LZ4.Streams; namespace ClickHouse.Ado.Impl.Compress { internal class Lz4Compressor : HashingCompressor { private static readonly byte[] Header = {0x82}; private readonly bool _useHc; public Lz4Compressor(bool useHc, ClickHouseConnectionSettings settings) : base(settings) => _useHc = useHc; public override CompressionMethod Method => _useHc ? CompressionMethod.Lz4Hc : CompressionMethod.Lz4; private LZ4Level Level => _useHc ? LZ4Level.L09_HC : LZ4Level.L00_FAST; protected override byte[] Compress(MemoryStream uncompressed) { using (var output = new MemoryStream()) using (var encoder = LZ4Stream.Encode(output, Level)) { uncompressed.CopyTo(encoder); return output.ToArray(); } } protected override byte[] Decompress(Stream compressed, out UInt128 compressedHash) { var header = new byte[9]; var read = 0; do { read += compressed.Read(header, read, header.Length - read); } while (read < header.Length); if (header[0] != Header[0]) throw new FormatException($"Invalid header value {header[0]}"); var compressedSize = BitConverter.ToInt32(header, 1); var uncompressedSize = BitConverter.ToInt32(header, 5); read = 0; compressedSize -= header.Length; var compressedBytes = new byte[compressedSize + header.Length]; Array.Copy(header, 0, compressedBytes, 0, header.Length); do { read += compressed.Read(compressedBytes, header.Length + read, compressedSize - read); } while (read < compressedSize); compressedHash = ClickHouseCityHash.CityHash128(compressedBytes); //return LZ4Codec.Decode(compressedBytes, header.Length, compressedSize, uncompressedSize); using (var output = new MemoryStream()) using (var encoder = LZ4Stream.Decode(output)) { compressed.CopyTo(encoder); return output.ToArray(); } } } }
38.366667
115
0.612511
[ "MIT" ]
ili/ClickHouse-Net
ClickHouse.Ado/Impl/Compress/Lz4Compressor.cs
2,304
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; namespace AutoRest.Core.Extensibility { /// <summary> /// In-memory representation of AutoRest.json configuration. /// </summary> public class AutoRestConfiguration { public AutoRestConfiguration() { Plugins = new Dictionary<string, AutoRestProviderConfiguration>(); Modelers = new Dictionary<string, AutoRestProviderConfiguration>(); } /// <summary> /// Gets or sets collections of Plugins. /// </summary> [SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly", Justification = "Required for JSON serialization.")] public IDictionary<string, AutoRestProviderConfiguration> Plugins { get; set; } /// <summary> /// Gets or sets collections of Modelers. /// </summary> [SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly", Justification = "Required for JSON serialization.")] public IDictionary<string, AutoRestProviderConfiguration> Modelers { get; set; } } }
40.65625
143
0.68947
[ "MIT" ]
DiogenesPolanco/autorest
src/core/AutoRest.Core/Extensibility/AutoRestConfiguration.cs
1,303
C#
/* * Swaggy Jenkins * * Jenkins API clients generated from Swagger / Open API specification * * The version of the OpenAPI document: 1.1.2-pre.0 * Contact: blah@cliffano.com * 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> /// BranchImpl /// </summary> [DataContract] public partial class BranchImpl : IEquatable<BranchImpl>, IValidatableObject { /// <summary> /// Initializes a new instance of the <see cref="BranchImpl" /> class. /// </summary> /// <param name="_class">_class.</param> /// <param name="displayName">displayName.</param> /// <param name="estimatedDurationInMillis">estimatedDurationInMillis.</param> /// <param name="fullDisplayName">fullDisplayName.</param> /// <param name="fullName">fullName.</param> /// <param name="name">name.</param> /// <param name="organization">organization.</param> /// <param name="parameters">parameters.</param> /// <param name="permissions">permissions.</param> /// <param name="weatherScore">weatherScore.</param> /// <param name="pullRequest">pullRequest.</param> /// <param name="links">links.</param> /// <param name="latestRun">latestRun.</param> public BranchImpl(string _class = default(string), string displayName = default(string), int estimatedDurationInMillis = default(int), string fullDisplayName = default(string), string fullName = default(string), string name = default(string), string organization = default(string), List<StringParameterDefinition> parameters = default(List<StringParameterDefinition>), BranchImplpermissions permissions = default(BranchImplpermissions), int weatherScore = default(int), string pullRequest = default(string), BranchImpllinks links = default(BranchImpllinks), PipelineRunImpl latestRun = default(PipelineRunImpl)) { this.Class = _class; this.DisplayName = displayName; this.EstimatedDurationInMillis = estimatedDurationInMillis; this.FullDisplayName = fullDisplayName; this.FullName = fullName; this.Name = name; this.Organization = organization; this.Parameters = parameters; this.Permissions = permissions; this.WeatherScore = weatherScore; this.PullRequest = pullRequest; this.Links = links; this.LatestRun = latestRun; } /// <summary> /// Gets or Sets Class /// </summary> [DataMember(Name="_class", EmitDefaultValue=false)] public string Class { get; set; } /// <summary> /// Gets or Sets DisplayName /// </summary> [DataMember(Name="displayName", EmitDefaultValue=false)] public string DisplayName { get; set; } /// <summary> /// Gets or Sets EstimatedDurationInMillis /// </summary> [DataMember(Name="estimatedDurationInMillis", EmitDefaultValue=false)] public int EstimatedDurationInMillis { get; set; } /// <summary> /// Gets or Sets FullDisplayName /// </summary> [DataMember(Name="fullDisplayName", EmitDefaultValue=false)] public string FullDisplayName { get; set; } /// <summary> /// Gets or Sets FullName /// </summary> [DataMember(Name="fullName", EmitDefaultValue=false)] public string FullName { get; set; } /// <summary> /// Gets or Sets Name /// </summary> [DataMember(Name="name", EmitDefaultValue=false)] public string Name { get; set; } /// <summary> /// Gets or Sets Organization /// </summary> [DataMember(Name="organization", EmitDefaultValue=false)] public string Organization { get; set; } /// <summary> /// Gets or Sets Parameters /// </summary> [DataMember(Name="parameters", EmitDefaultValue=false)] public List<StringParameterDefinition> Parameters { get; set; } /// <summary> /// Gets or Sets Permissions /// </summary> [DataMember(Name="permissions", EmitDefaultValue=false)] public BranchImplpermissions Permissions { get; set; } /// <summary> /// Gets or Sets WeatherScore /// </summary> [DataMember(Name="weatherScore", EmitDefaultValue=false)] public int WeatherScore { get; set; } /// <summary> /// Gets or Sets PullRequest /// </summary> [DataMember(Name="pullRequest", EmitDefaultValue=false)] public string PullRequest { get; set; } /// <summary> /// Gets or Sets Links /// </summary> [DataMember(Name="_links", EmitDefaultValue=false)] public BranchImpllinks Links { get; set; } /// <summary> /// Gets or Sets LatestRun /// </summary> [DataMember(Name="latestRun", EmitDefaultValue=false)] public PipelineRunImpl LatestRun { 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 BranchImpl {\n"); sb.Append(" Class: ").Append(Class).Append("\n"); sb.Append(" DisplayName: ").Append(DisplayName).Append("\n"); sb.Append(" EstimatedDurationInMillis: ").Append(EstimatedDurationInMillis).Append("\n"); sb.Append(" FullDisplayName: ").Append(FullDisplayName).Append("\n"); sb.Append(" FullName: ").Append(FullName).Append("\n"); sb.Append(" Name: ").Append(Name).Append("\n"); sb.Append(" Organization: ").Append(Organization).Append("\n"); sb.Append(" Parameters: ").Append(Parameters).Append("\n"); sb.Append(" Permissions: ").Append(Permissions).Append("\n"); sb.Append(" WeatherScore: ").Append(WeatherScore).Append("\n"); sb.Append(" PullRequest: ").Append(PullRequest).Append("\n"); sb.Append(" Links: ").Append(Links).Append("\n"); sb.Append(" LatestRun: ").Append(LatestRun).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 Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.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 BranchImpl); } /// <summary> /// Returns true if BranchImpl instances are equal /// </summary> /// <param name="input">Instance of BranchImpl to be compared</param> /// <returns>Boolean</returns> public bool Equals(BranchImpl input) { if (input == null) return false; return ( this.Class == input.Class || (this.Class != null && this.Class.Equals(input.Class)) ) && ( this.DisplayName == input.DisplayName || (this.DisplayName != null && this.DisplayName.Equals(input.DisplayName)) ) && ( this.EstimatedDurationInMillis == input.EstimatedDurationInMillis || (this.EstimatedDurationInMillis != null && this.EstimatedDurationInMillis.Equals(input.EstimatedDurationInMillis)) ) && ( this.FullDisplayName == input.FullDisplayName || (this.FullDisplayName != null && this.FullDisplayName.Equals(input.FullDisplayName)) ) && ( this.FullName == input.FullName || (this.FullName != null && this.FullName.Equals(input.FullName)) ) && ( this.Name == input.Name || (this.Name != null && this.Name.Equals(input.Name)) ) && ( this.Organization == input.Organization || (this.Organization != null && this.Organization.Equals(input.Organization)) ) && ( this.Parameters == input.Parameters || this.Parameters != null && input.Parameters != null && this.Parameters.SequenceEqual(input.Parameters) ) && ( this.Permissions == input.Permissions || (this.Permissions != null && this.Permissions.Equals(input.Permissions)) ) && ( this.WeatherScore == input.WeatherScore || (this.WeatherScore != null && this.WeatherScore.Equals(input.WeatherScore)) ) && ( this.PullRequest == input.PullRequest || (this.PullRequest != null && this.PullRequest.Equals(input.PullRequest)) ) && ( this.Links == input.Links || (this.Links != null && this.Links.Equals(input.Links)) ) && ( this.LatestRun == input.LatestRun || (this.LatestRun != null && this.LatestRun.Equals(input.LatestRun)) ); } /// <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.Class != null) hashCode = hashCode * 59 + this.Class.GetHashCode(); if (this.DisplayName != null) hashCode = hashCode * 59 + this.DisplayName.GetHashCode(); if (this.EstimatedDurationInMillis != null) hashCode = hashCode * 59 + this.EstimatedDurationInMillis.GetHashCode(); if (this.FullDisplayName != null) hashCode = hashCode * 59 + this.FullDisplayName.GetHashCode(); if (this.FullName != null) hashCode = hashCode * 59 + this.FullName.GetHashCode(); if (this.Name != null) hashCode = hashCode * 59 + this.Name.GetHashCode(); if (this.Organization != null) hashCode = hashCode * 59 + this.Organization.GetHashCode(); if (this.Parameters != null) hashCode = hashCode * 59 + this.Parameters.GetHashCode(); if (this.Permissions != null) hashCode = hashCode * 59 + this.Permissions.GetHashCode(); if (this.WeatherScore != null) hashCode = hashCode * 59 + this.WeatherScore.GetHashCode(); if (this.PullRequest != null) hashCode = hashCode * 59 + this.PullRequest.GetHashCode(); if (this.Links != null) hashCode = hashCode * 59 + this.Links.GetHashCode(); if (this.LatestRun != null) hashCode = hashCode * 59 + this.LatestRun.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; } } }
41.169811
619
0.547281
[ "MIT" ]
cliffano/jenkins-api-clients-generator
clients/csharp/generated/src/Org.OpenAPITools/Model/BranchImpl.cs
13,092
C#
using System.Diagnostics.CodeAnalysis; using System.IO; using System.Linq; using PoESkillTree.Utils; using PoESkillTree.Localization; using PoESkillTree.Model; using PoESkillTree.Model.Serialization; namespace PoESkillTree.ViewModels.Builds { /// <summary> /// Used to validate build names and to decide whether builds can be moved into a folder or whether /// a folder can have subfolders. /// </summary> public class BuildValidator { /// <summary> /// The maximum depth of folder nesting. Includes the root folder. /// </summary> private const int MaxBuildDepth = 4; private readonly Options _options; public BuildValidator(Options options) { _options = options; } /// <summary> /// Returns true iff the <paramref name="folder"/> can have subfolders. There can only be a constant number /// of folders nested into each other. /// </summary> public bool CanHaveSubfolder(IBuildFolderViewModel folder) { return GetDepthOfFolder(folder) < MaxBuildDepth; } /// <summary> /// Returns true iff <paramref name="build"/> can be moved to <paramref name="parent"/>. /// </summary> public bool CanMoveTo(IBuildViewModel build, IBuildFolderViewModel parent) { if (!IsNameUnique(build.Build.Name, build, parent)) return false; var parentPath = BasePathFor(parent); var folder = build as IBuildFolderViewModel; if (folder == null) { return CanBeChildOf(build, parentPath); } else { var parentDepth = GetDepthOfFolder(parent); return CanBeChildOf(folder, parentPath, parentDepth); } } private static bool CanBeChildOf(IBuildFolderViewModel build, string parentPath, int parentDepth) { // Check depth and name if (parentDepth >= MaxBuildDepth) return false; var name = build.Build.Name; if (!IsNameValid(name, Path.Combine(parentPath, FileNameForFolder(name)))) return false; // Check all subbuilds var nextPath = Path.Combine(parentPath, SerializationUtils.EncodeFileName(name)); var nextDepth = parentDepth + 1; foreach (var child in build.Children) { var folder = child as IBuildFolderViewModel; if (folder == null) { if (!CanBeChildOf(child, nextPath)) { return false; } } else { if (!CanBeChildOf(folder, nextPath, nextDepth)) { return false; } } } return true; } private static bool CanBeChildOf(IBuildViewModel build, string parentPath) { var name = build.Build.Name; return IsNameValid(name, Path.Combine(parentPath, FileNameForBuild(name))); } private static int GetDepthOfFolder(IBuildFolderViewModel folder) { return folder.Parent == null ? 1 : 1 + GetDepthOfFolder(folder.Parent); } /// <summary> /// Returns an string that contains an error message if it is not null or empty that describes /// why <paramref name="name"/> is not allowed as a name for <paramref name="folder"/>. /// </summary> public string? ValidateExistingFolderName(string name, IBuildViewModel folder) { return ValidateName(name, PathForFolder(name, folder.Parent!), folder, folder.Parent!); } /// <summary> /// Returns an string that contains an error message if it is not null or empty that describes /// why <paramref name="name"/> is not allowed as a name for a new subfolder of <paramref name="parent"/>. /// </summary> public string? ValidateNewFolderName(string name, IBuildFolderViewModel parent) { return ValidateName(name, PathForFolder(name, parent), null, parent); } /// <summary> /// Returns an string that contains an error message if it is not null or empty that describes /// why <paramref name="name"/> is not allowed as a name for <paramref name="build"/>. /// </summary> public string? ValidateExistingFileName(string name, IBuildViewModel build) { return ValidateName(name, PathForBuild(name, build.Parent!), build, build.Parent!); } /// <summary> /// Returns an string that contains an error message if it is not null or empty that describes /// why <paramref name="name"/> is not allowed as a name for a new build located in <paramref name="parent"/>. /// </summary> public string? ValidateNewBuildName(string name, IBuildFolderViewModel parent) { return ValidateName(name, PathForBuild(name, parent), null, parent); } private static string? ValidateName(string name, string fullPath, IBuildViewModel? build, IBuildFolderViewModel parent) { if (!IsNameUnique(name, build, parent)) { return L10n.Message("A build or folder with this name already exists."); } IsNameValid(name, fullPath, out var message); return message; } private static bool IsNameUnique(string name, IBuildViewModel? build, IBuildFolderViewModel parent) { return parent.Children.All(b => b == build || b.Build.Name != name); } private static bool IsNameValid(string name, string fullPath) { return IsNameValid(name, fullPath, out _); } private static bool IsNameValid(string name, string fullPath, [NotNullWhen(false)] out string? errorMessage) { if (string.IsNullOrWhiteSpace(name)) { errorMessage = L10n.Message("Value is required."); return false; } return PathEx.IsPathValid(fullPath, out errorMessage, mustBeFile: true); } private static string FileNameForBuild(string name) { return SerializationUtils.EncodeFileName(name) + SerializationConstants.BuildFileExtension; } private string PathForBuild(string name, IBuildViewModel parent) { return Path.Combine(BasePathFor(parent), FileNameForBuild(name)); } private static string FileNameForFolder(string name) { return Path.Combine(SerializationUtils.EncodeFileName(name), SerializationConstants.BuildFolderFileName); } private string PathForFolder(string name, IBuildViewModel parent) { return Path.Combine(BasePathFor(parent), FileNameForFolder(name)); } private string BasePathFor(IBuildViewModel build) { var fileName = SerializationUtils.EncodeFileName(build.Build.Name); return build.Parent == null ? _options.BuildsSavePath // Root folder is not directly part of the path : Path.Combine(BasePathFor(build.Parent), fileName); } } }
38.888889
119
0.575195
[ "MIT" ]
BlazesRus/PoESkillTree
WPFSKillTree/ViewModels/Builds/BuildValidator.cs
7,505
C#
// (c) Copyright HutongGames, LLC 2010-2013. All rights reserved. using UnityEngine; namespace HutongGames.PlayMaker.Actions { [ActionCategory(ActionCategory.StateMachine)] [ActionTarget(typeof(PlayMakerFSM), "gameObject,fsmName")] [Tooltip("Set the value of an Integer Variable in another FSM.")] public class SetFsmInt : FsmStateAction { [RequiredField] [Tooltip("The GameObject that owns the FSM.")] public FsmOwnerDefault gameObject; [UIHint(UIHint.FsmName)] [Tooltip("Optional name of FSM on Game Object")] public FsmString fsmName; [RequiredField] [UIHint(UIHint.FsmInt)] [Tooltip("The name of the FSM variable.")] public FsmString variableName; [RequiredField] [Tooltip("Set the value of the variable.")] public FsmInt setValue; [Tooltip("Repeat every frame. Useful if the value is changing.")] public bool everyFrame; GameObject goLastFrame; string fsmNameLastFrame; PlayMakerFSM fsm; public override void Reset() { gameObject = null; fsmName = ""; setValue = null; } public override void OnEnter() { DoSetFsmInt(); if (!everyFrame) { Finish(); } } void DoSetFsmInt() { if (setValue == null) { return; } var go = Fsm.GetOwnerDefaultTarget(gameObject); if (go == null) return; // FIX: must check as well that the fsm name is different. if (go != goLastFrame || fsmName.Value != fsmNameLastFrame) { goLastFrame = go; fsmNameLastFrame = fsmName.Value; // only get the fsm component if go or fsm name has changed fsm = ActionHelpers.GetGameObjectFsm(go, fsmName.Value); } if (fsm == null) { LogWarning("Could not find FSM: " + fsmName.Value); return; } var fsmInt = fsm.FsmVariables.GetFsmInt(variableName.Value); if (fsmInt != null) { fsmInt.Value = setValue.Value; } else { LogWarning("Could not find variable: " + variableName.Value); } } public override void OnUpdate() { DoSetFsmInt(); } } }
22.785714
78
0.603224
[ "Apache-2.0" ]
Drestat/ARfun
ARfun/Assets/PlayMaker/Actions/SetFsmInt.cs
2,233
C#
using System; using System.Diagnostics; using System.Resources; using System.Windows; using System.Windows.Markup; using System.Windows.Navigation; using Microsoft.Phone.Controls; using Microsoft.Phone.Shell; using AudioPlay.WinPhone.Resources; namespace AudioPlay.WinPhone { public partial class App : Application { /// <summary> /// Provides easy access to the root frame of the Phone Application. /// </summary> /// <returns>The root frame of the Phone Application.</returns> public static PhoneApplicationFrame RootFrame { get; private set; } /// <summary> /// Constructor for the Application object. /// </summary> public App() { // Global handler for uncaught exceptions. UnhandledException += Application_UnhandledException; // Standard XAML initialization InitializeComponent(); // Phone-specific initialization InitializePhoneApplication(); // Language display initialization InitializeLanguage(); // Show graphics profiling information while debugging. if (Debugger.IsAttached) { // Display the current frame rate counters. Application.Current.Host.Settings.EnableFrameRateCounter = true; // Show the areas of the app that are being redrawn in each frame. //Application.Current.Host.Settings.EnableRedrawRegions = true; // Enable non-production analysis visualization mode, // which shows areas of a page that are handed off to GPU with a colored overlay. //Application.Current.Host.Settings.EnableCacheVisualization = true; // Prevent the screen from turning off while under the debugger by disabling // the application's idle detection. // Caution:- Use this under debug mode only. Application that disables user idle detection will continue to run // and consume battery power when the user is not using the phone. PhoneApplicationService.Current.UserIdleDetectionMode = IdleDetectionMode.Disabled; } } // Code to execute when the application is launching (eg, from Start) // This code will not execute when the application is reactivated private void Application_Launching(object sender, LaunchingEventArgs e) { } // Code to execute when the application is activated (brought to foreground) // This code will not execute when the application is first launched private void Application_Activated(object sender, ActivatedEventArgs e) { } // Code to execute when the application is deactivated (sent to background) // This code will not execute when the application is closing private void Application_Deactivated(object sender, DeactivatedEventArgs e) { } // Code to execute when the application is closing (eg, user hit Back) // This code will not execute when the application is deactivated private void Application_Closing(object sender, ClosingEventArgs e) { } // Code to execute if a navigation fails private void RootFrame_NavigationFailed(object sender, NavigationFailedEventArgs e) { if (Debugger.IsAttached) { // A navigation has failed; break into the debugger Debugger.Break(); } } // Code to execute on Unhandled Exceptions private void Application_UnhandledException(object sender, ApplicationUnhandledExceptionEventArgs e) { if (Debugger.IsAttached) { // An unhandled exception has occurred; break into the debugger Debugger.Break(); } } #region Phone application initialization // Avoid double-initialization private bool phoneApplicationInitialized = false; // Do not add any additional code to this method private void InitializePhoneApplication() { if (phoneApplicationInitialized) return; // Create the frame but don't set it as RootVisual yet; this allows the splash // screen to remain active until the application is ready to render. RootFrame = new PhoneApplicationFrame(); RootFrame.Navigated += CompleteInitializePhoneApplication; // Handle navigation failures RootFrame.NavigationFailed += RootFrame_NavigationFailed; // Handle reset requests for clearing the backstack RootFrame.Navigated += CheckForResetNavigation; // Ensure we don't initialize again phoneApplicationInitialized = true; } // Do not add any additional code to this method private void CompleteInitializePhoneApplication(object sender, NavigationEventArgs e) { // Set the root visual to allow the application to render if (RootVisual != RootFrame) RootVisual = RootFrame; // Remove this handler since it is no longer needed RootFrame.Navigated -= CompleteInitializePhoneApplication; } private void CheckForResetNavigation(object sender, NavigationEventArgs e) { // If the app has received a 'reset' navigation, then we need to check // on the next navigation to see if the page stack should be reset if (e.NavigationMode == NavigationMode.Reset) RootFrame.Navigated += ClearBackStackAfterReset; } private void ClearBackStackAfterReset(object sender, NavigationEventArgs e) { // Unregister the event so it doesn't get called again RootFrame.Navigated -= ClearBackStackAfterReset; // Only clear the stack for 'new' (forward) and 'refresh' navigations if (e.NavigationMode != NavigationMode.New && e.NavigationMode != NavigationMode.Refresh) return; // For UI consistency, clear the entire page stack while (RootFrame.RemoveBackEntry() != null) { ; // do nothing } } #endregion // Initialize the app's font and flow direction as defined in its localized resource strings. // // To ensure that the font of your application is aligned with its supported languages and that the // FlowDirection for each of those languages follows its traditional direction, ResourceLanguage // and ResourceFlowDirection should be initialized in each resx file to match these values with that // file's culture. For example: // // AppResources.es-ES.resx // ResourceLanguage's value should be "es-ES" // ResourceFlowDirection's value should be "LeftToRight" // // AppResources.ar-SA.resx // ResourceLanguage's value should be "ar-SA" // ResourceFlowDirection's value should be "RightToLeft" // // For more info on localizing Windows Phone apps see http://go.microsoft.com/fwlink/?LinkId=262072. // private void InitializeLanguage() { try { // Set the font to match the display language defined by the // ResourceLanguage resource string for each supported language. // // Fall back to the font of the neutral language if the Display // language of the phone is not supported. // // If a compiler error is hit then ResourceLanguage is missing from // the resource file. RootFrame.Language = XmlLanguage.GetLanguage(AppResources.ResourceLanguage); // Set the FlowDirection of all elements under the root frame based // on the ResourceFlowDirection resource string for each // supported language. // // If a compiler error is hit then ResourceFlowDirection is missing from // the resource file. FlowDirection flow = (FlowDirection)Enum.Parse(typeof(FlowDirection), AppResources.ResourceFlowDirection); RootFrame.FlowDirection = flow; } catch { // If an exception is caught here it is most likely due to either // ResourceLangauge not being correctly set to a supported language // code or ResourceFlowDirection is set to a value other than LeftToRight // or RightToLeft. if (Debugger.IsAttached) { Debugger.Break(); } throw; } } } }
33.741071
115
0.73538
[ "MIT" ]
Samples-Playgrounds/Samples.Xamarin.Forms
samples/tutorial/Expert-01-PlatformSpecific/DependencyService/Audio/AudioPlayer/AudioPlayer.WinPhone/App.xaml.cs
7,560
C#
using System; namespace Chap02.Models { public class ErrorViewModel { public string RequestId { get; set; } public bool ShowRequestId => !string.IsNullOrEmpty(RequestId); } }
17.083333
70
0.658537
[ "MIT" ]
wagnerhsu/Mastering-Bootstrap-4-Second-Edition
MyCode/02/Chap02/Models/ErrorViewModel.cs
205
C#
using System; using System.Collections; using System.Collections.Generic; using Legacy.Core.Api; using Legacy.Core.Entities.Items; using Legacy.Core.PartyManagement; using Legacy.Core.StaticData; using Legacy.Core.StaticData.Items; using Legacy.Game.MMGUI; using UnityEngine; using Object = System.Object; namespace Legacy.Game.Cheats { [AddComponentMenu("MM Legacy/Cheats/CheatsItems")] public class CheatsItems : MonoBehaviour { private const String DATA_ARMOR = "Armor"; private const String DATA_JEWELRY = "Jewelry"; private const String DATA_SHIELDS = "Shields"; private const String DATA_MELEE_WEAPON = "Melee Weapons"; private const String DATA_MAGIC_FOCUS = "Magic Focus"; private const String DATA_RANGED_WEAPONS = "Ranged Weapons"; private const String DATA_POTIONS = "Potions"; private const String DATA_SCROLLS = "Scrolls"; [SerializeField] private UIPopupList m_categoryList; [SerializeField] private UIPopupList m_itemList; [SerializeField] private UIPopupList m_prefixList; [SerializeField] private SelectionList m_suffixList; [SerializeField] private UICheckbox m_checkboxBroken; [SerializeField] private UICheckbox m_checkboxUnidentified; private List<Int32> m_staticIdList; private EDataType m_currentDataType; private Boolean m_isEquipment; private void OnEnable() { if (m_categoryList != null) { m_categoryList.items.Clear(); m_staticIdList = new List<Int32>(); m_categoryList.items.Add("Armor"); m_categoryList.items.Add("Jewelry"); m_categoryList.items.Add("Shields"); m_categoryList.items.Add("Melee Weapons"); m_categoryList.items.Add("Magic Focus"); m_categoryList.items.Add("Ranged Weapons"); m_categoryList.items.Add("Potions"); m_categoryList.items.Add("Scrolls"); } m_prefixList.items.Clear(); m_suffixList.Clear(); IEnumerable<PrefixStaticData> iterator = StaticDataHandler.GetIterator<PrefixStaticData>(EDataType.PREFIX); IEnumerable<SuffixStaticData> iterator2 = StaticDataHandler.GetIterator<SuffixStaticData>(EDataType.SUFFIX); m_prefixList.items.Add("0: NONE"); foreach (PrefixStaticData prefixStaticData in iterator) { m_prefixList.items.Add(prefixStaticData.StaticID + ": " + prefixStaticData.Name); } m_suffixList.AddItem("0: NONE"); foreach (SuffixStaticData suffixStaticData in iterator2) { m_suffixList.AddItemWithoutReposition(suffixStaticData.StaticID + ": " + suffixStaticData.Name); } m_suffixList.ReposItems(); SelectItemCategory("Armor"); } private void SelectItemCategory(String p_category) { m_categoryList.selection = p_category; if (m_itemList != null) { m_itemList.items.Clear(); m_staticIdList.Clear(); IEnumerable enumerable = null; switch (p_category) { case "Armor": enumerable = StaticDataHandler.GetIterator<ArmorStaticData>(EDataType.ARMOR); m_currentDataType = EDataType.ARMOR; m_isEquipment = true; break; case "Jewelry": enumerable = StaticDataHandler.GetIterator<JewelryStaticData>(EDataType.JEWELRY); m_currentDataType = EDataType.JEWELRY; m_isEquipment = true; break; case "Shields": enumerable = StaticDataHandler.GetIterator<ShieldStaticData>(EDataType.SHIELD); m_currentDataType = EDataType.SHIELD; m_isEquipment = true; break; case "Melee Weapons": enumerable = StaticDataHandler.GetIterator<MeleeWeaponStaticData>(EDataType.MELEE_WEAPON); m_currentDataType = EDataType.MELEE_WEAPON; m_isEquipment = true; break; case "Magic Focus": enumerable = StaticDataHandler.GetIterator<MagicFocusStaticData>(EDataType.MAGIC_FOCUS); m_currentDataType = EDataType.MAGIC_FOCUS; m_isEquipment = true; break; case "Ranged Weapons": enumerable = StaticDataHandler.GetIterator<RangedWeaponStaticData>(EDataType.RANGED_WEAPON); m_currentDataType = EDataType.RANGED_WEAPON; m_isEquipment = true; break; case "Potions": enumerable = StaticDataHandler.GetIterator<PotionStaticData>(EDataType.POTION); m_currentDataType = EDataType.POTION; m_isEquipment = false; break; case "Scrolls": enumerable = StaticDataHandler.GetIterator<ScrollStaticData>(EDataType.SCROLL); m_currentDataType = EDataType.SCROLL; m_isEquipment = false; break; } IEnumerator enumerator = enumerable.GetEnumerator(); try { while (enumerator.MoveNext()) { Object obj = enumerator.Current; BaseItemStaticData baseItemStaticData = (BaseItemStaticData)obj; m_itemList.items.Add(baseItemStaticData.NameKey); m_staticIdList.Add(baseItemStaticData.StaticID); } } finally { IDisposable disposable; if ((disposable = (enumerator as IDisposable)) != null) { disposable.Dispose(); } } if (m_itemList.items.Count > 0) { m_itemList.selection = m_itemList.items[0]; } else { m_itemList.selection = String.Empty; } NGUITools.SetActive(m_prefixList.gameObject, m_isEquipment); NGUITools.SetActive(m_suffixList.gameObject, m_isEquipment); } } public void OnAddToInventoryButtonClick() { BaseItem baseItem = ItemFactory.CreateItem(m_currentDataType); Int32 index = m_itemList.items.IndexOf(m_itemList.selection); baseItem.Init(m_staticIdList[index]); if (m_isEquipment) { Equipment equipment = baseItem as Equipment; if (equipment != null) { Int32 num = Int32.Parse(m_prefixList.selection.Split(new Char[] { ':' })[0]); if (num != 0) { PrefixStaticData staticData = StaticDataHandler.GetStaticData<PrefixStaticData>(EDataType.PREFIX, num); equipment.Prefixes.Add(staticData); } Int32 num2 = Int32.Parse(m_suffixList.SelectedItem.Split(new Char[] { ':' })[0]); if (num2 != 0) { SuffixStaticData staticData2 = StaticDataHandler.GetStaticData<SuffixStaticData>(EDataType.SUFFIX, num2); equipment.Suffixes.Add(staticData2); } } equipment.Broken = m_checkboxBroken.isChecked; equipment.Identified = !m_checkboxUnidentified.isChecked; } Party party = LegacyLogic.Instance.WorldManager.Party; party.Inventory.AddItem(baseItem); } } }
29.966825
111
0.71833
[ "MIT" ]
Albeoris/MMXLegacy
Legacy.Game/Game/Cheats/CheatsItems.cs
6,325
C#
using ARKBreedingStats.Library; using ARKBreedingStats.species; using ARKBreedingStats.values; using System; using System.Collections.Generic; using System.Linq; using System.Windows.Forms; namespace ARKBreedingStats.oldLibraryFormat { /// <summary> /// This class provides methods to convert old file-formats to new formats, e.g. the 8-stat-format to the 12-stat-format. /// </summary> static class FormatConverter { /// <summary> /// Convert old libraries /// </summary> /// <param name="ccOld">CreatureCollection to be converted</param> public static CreatureCollection ConvertXml2Asb(CreatureCollectionOld ccOld, string libraryFilePath) { MessageBox.Show($"The library will be converted to the new format that supports all possible ARK-stats (e.g. the crafting speed for the Gacha).\n\nThe old library file is still available at \n{libraryFilePath}\nyou can keep it as a backup.", "Library will be converted", MessageBoxButtons.OK, MessageBoxIcon.Information); CreatureCollection ccNew = new CreatureCollection() { FormatVersion = CreatureCollection.CURRENT_FORMAT_VERSION }; UpgradeFormatTo12Stats(ccOld, ccNew); TransferParameters(ccOld, ccNew); return ccNew; } /// <summary> /// Tries to converts the library from the 8-stats format to the 12-stats format and the species identification by the blueprintpath. /// </summary> public static void UpgradeFormatTo12Stats(CreatureCollectionOld ccOld, CreatureCollection ccNew) { if (ccOld == null) return; // if library has the old statMultiplier-indices, fix the order var newToOldIndices = new int[] { 0, 1, 7, 2, 3, -1, -1, 4, 5, 6, -1, -1 }; if (ccOld.multipliers != null && ccOld.multipliers.Length == 8) { /// old order was /// HP, Stam, Ox, Fo, We, Dm, Sp, To /// new order is // 0: Health // 1: Stamina / Charge Capacity // 2: Torpidity // 3: Oxygen / Charge Regeneration // 4: Food // 5: Water // 6: Temperature // 7: Weight // 8: MeleeDamageMultiplier / Charge Emission Range // 9: SpeedMultiplier // 10: TemperatureFortitude // 11: CraftingSpeedMultiplier // imprinting bonus factor default 0.2, 0, 0.2, 0, 0.2, 0.2, 0, 0.2, 0.2, 0.2, 0, 0 // i.e. stats without imprinting are by default: St, Ox, Te, TF, Cr // create new multiplierArray var newMultipliers = new double[Values.STATS_COUNT][]; for (int s = 0; s < Values.STATS_COUNT; s++) { newMultipliers[s] = new double[4]; if (newToOldIndices[s] >= 0) { for (int si = 0; si < 4; si++) newMultipliers[s][si] = ccOld.multipliers[newToOldIndices[s]][si]; } else { for (int si = 0; si < 4; si++) newMultipliers[s][si] = 1; } } ccOld.multipliers = newMultipliers; } ccNew.creatures = new List<Creature>(); foreach (CreatureOld c in ccOld.creatures) { Creature newC = new Creature() { addedToLibrary = c.addedToLibrary.Year < 2000 ? default(DateTime?) : c.addedToLibrary, ArkId = c.ArkId, ArkIdImported = c.ArkIdImported, colors = c.colors, cooldownUntil = c.cooldownUntil.Year < 2000 ? default(DateTime?) : c.cooldownUntil, domesticatedAt = c.domesticatedAt.Year < 2000 ? default(DateTime?) : c.domesticatedAt, fatherGuid = c.fatherGuid, flags = c.flags, generation = c.generation, growingLeft = c.growingLeft, growingPaused = c.growingPaused, growingUntil = c.growingUntil.Year < 2000 ? default(DateTime?) : c.growingUntil, guid = c.guid, imprinterName = c.imprinterName, imprintingBonus = c.imprintingBonus, isBred = c.isBred, motherGuid = c.motherGuid, mutationsMaternal = c.mutationsMaternal, mutationsPaternal = c.mutationsPaternal, name = c.name, note = c.note, owner = c.owner, server = c.server, sex = c.sex, Status = c.status, tags = c.tags, tamingEff = c.tamingEff, tribe = c.tribe }; ccNew.creatures.Add(newC); if (c.IsPlaceholder) newC.flags |= CreatureFlags.Placeholder; if (c.neutered) newC.flags |= CreatureFlags.Neutered; // set new species-id if (c.Species == null && !string.IsNullOrEmpty(c.speciesBlueprint)) c.Species = Values.V.SpeciesByBlueprint(c.speciesBlueprint); if (c.Species == null && Values.V.TryGetSpeciesByName(c.species, out Species speciesObject)) c.Species = speciesObject; newC.Species = c.Species; // fix statlevel-indices newC.levelsWild = Convert8To12(c.levelsWild); newC.levelsDom = Convert8To12(c.levelsDom); } ccNew.creaturesValues = new List<CreatureValues>(); foreach (var cvOld in ccOld.creaturesValues) { var cv = new CreatureValues() { ARKID = cvOld.ARKID, colorIDs = cvOld.colorIDs, cooldownUntil = cvOld.cooldownUntil.Year < 2000 ? default(DateTime?) : cvOld.cooldownUntil, domesticatedAt = cvOld.domesticatedAt.Year < 2000 ? default(DateTime?) : cvOld.domesticatedAt, fatherArkId = cvOld.fatherArkId, fatherGuid = cvOld.fatherGuid, growingUntil = cvOld.growingUntil.Year < 2000 ? default(DateTime?) : cvOld.growingUntil, guid = cvOld.guid, imprinterName = cvOld.imprinterName, imprintingBonus = cvOld.imprintingBonus, isBred = cvOld.isBred, isTamed = cvOld.isTamed, level = cvOld.level, levelsDom = cvOld.levelsDom, levelsWild = cvOld.levelsWild, motherArkId = cvOld.motherArkId, motherGuid = cvOld.motherGuid, mutationCounterFather = cvOld.mutationCounterFather, mutationCounterMother = cvOld.mutationCounterMother, name = cvOld.name, owner = cvOld.owner, server = cvOld.server, sex = cvOld.sex, speciesName = cvOld.species, statValues = cvOld.statValues, tamingEffMax = cvOld.tamingEffMax, tamingEffMin = cvOld.tamingEffMin, tribe = cvOld.tribe }; if (cvOld.neutered) cv.flags |= CreatureFlags.Neutered; if (Values.V.TryGetSpeciesByName(cvOld.species, out Species species)) cv.Species = species; ccNew.creaturesValues.Add(cv); // fix statlevel-indices cv.levelsWild = Convert8To12(cvOld.levelsWild); cv.levelsDom = Convert8To12(cvOld.levelsDom); cv.statValues = Convert8To12(cvOld.statValues); } } private static int[] Convert8To12(int[] a) { var newToOldIndices = new int[] { 0, 1, 7, 2, 3, -1, -1, 4, 5, 6, -1, -1 }; var newA = new int[Values.STATS_COUNT]; if (a.Length == 12) { return a; } else { for (int s = 0; s < Values.STATS_COUNT; s++) { if (newToOldIndices[s] >= 0) newA[s] = a[newToOldIndices[s]]; } } return newA; } private static double[] Convert8To12(double[] a) { var newToOldIndices = new int[] { 0, 1, 7, 2, 3, -1, -1, 4, 5, 6, -1, -1 }; var newA = new double[Values.STATS_COUNT]; if (a.Length == 12) { return a; } else { for (int s = 0; s < Values.STATS_COUNT; s++) { if (newToOldIndices[s] >= 0) newA[s] = a[newToOldIndices[s]]; } } return newA; } public static void TransferParameters(CreatureCollectionOld ccOld, CreatureCollection ccNew) { ccNew.allowMoreThanHundredImprinting = ccOld.allowMoreThanHundredImprinting; ccNew.changeCreatureStatusOnSavegameImport = ccOld.changeCreatureStatusOnSavegameImport; ccNew.considerWildLevelSteps = ccOld.considerWildLevelSteps; ccNew.incubationListEntries = ccOld.incubationListEntries.Select(ile => new IncubationTimerEntry { fatherGuid = ile.fatherGuid, incubationDuration = ile.incubationDuration, incubationEnd = ile.incubationEnd, motherGuid = ile.motherGuid, timerIsRunning = ile.timerIsRunning, }).ToList(); ccNew.maxBreedingSuggestions = ccOld.maxBreedingSuggestions; ccNew.maxChartLevel = ccOld.maxChartLevel; ccNew.maxDomLevel = ccOld.maxDomLevel; ccNew.maxServerLevel = ccOld.maxServerLevel; ccNew.noteList = ccOld.noteList; ccNew.ownerList = ccOld.ownerList; ccNew.players = ccOld.players; ccNew.serverList = ccOld.serverList; ccNew.singlePlayerSettings = ccOld.singlePlayerSettings; ccNew.tags = ccOld.tags; ccNew.tagsExclude = ccOld.tagsExclude; ccNew.tagsInclude = ccOld.tagsInclude; ccNew.timerListEntries = ccOld.timerListEntries.Select(tle => new TimerListEntry { creatureGuid = tle.creatureGuid, group = tle.group, name = tle.name, sound = tle.sound, time = tle.time }).ToList(); ccNew.tribes = ccOld.tribes; ccNew.wildLevelStep = ccOld.wildLevelStep; // check if multiplier-conversion is possible if (ccOld?.multipliers == null) return; ccNew.serverMultipliers = new ServerMultipliers { BabyImprintingStatScaleMultiplier = ccOld.imprintingMultiplier, BabyCuddleIntervalMultiplier = ccOld.babyCuddleIntervalMultiplier, TamingSpeedMultiplier = ccOld.tamingSpeedMultiplier, DinoCharacterFoodDrainMultiplier = ccOld.tamingFoodRateMultiplier, MatingIntervalMultiplier = ccOld.MatingIntervalMultiplier, EggHatchSpeedMultiplier = ccOld.EggHatchSpeedMultiplier, BabyMatureSpeedMultiplier = ccOld.BabyMatureSpeedMultiplier, BabyFoodConsumptionSpeedMultiplier = ccOld.BabyFoodConsumptionSpeedMultiplier, statMultipliers = ccOld.multipliers // was converted to 12-stats before }; ccNew.serverMultipliersEvents = new ServerMultipliers { BabyImprintingStatScaleMultiplier = ccOld.imprintingMultiplier, // cannot be changed in events BabyCuddleIntervalMultiplier = ccOld.babyCuddleIntervalMultiplierEvent, TamingSpeedMultiplier = ccOld.tamingSpeedMultiplierEvent, DinoCharacterFoodDrainMultiplier = ccOld.tamingFoodRateMultiplierEvent, MatingIntervalMultiplier = ccOld.MatingIntervalMultiplierEvent, EggHatchSpeedMultiplier = ccOld.EggHatchSpeedMultiplierEvent, BabyMatureSpeedMultiplier = ccOld.BabyMatureSpeedMultiplierEvent, BabyFoodConsumptionSpeedMultiplier = ccOld.BabyFoodConsumptionSpeedMultiplierEvent }; } } }
44.227891
253
0.537568
[ "MIT" ]
Leyrix/ARKStatsExtractor
ARKBreedingStats/oldLibraryFormat/FormatConverter.cs
13,005
C#
using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Authentication.JwtBearer; using Microsoft.AspNetCore.Builder; namespace Abp.VueDemo.Authentication.JwtBearer { public static class JwtTokenMiddleware { public static IApplicationBuilder UseJwtTokenMiddleware(this IApplicationBuilder app, string schema = JwtBearerDefaults.AuthenticationScheme) { return app.Use(async (ctx, next) => { if (ctx.User.Identity?.IsAuthenticated != true) { var result = await ctx.AuthenticateAsync(schema); if (result.Succeeded && result.Principal != null) { ctx.User = result.Principal; } } await next(); }); } } }
31.703704
149
0.568925
[ "MIT" ]
freeradius-xx/Abp.VueDemo
aspnet-core/src/Abp.VueDemo.Web.Core/Authentication/JwtBearer/JwtTokenMiddleware.cs
858
C#
using FluentAssertions; using FluentAssertions.Common; using Microsoft.Reactive.Testing; using System; using System.Collections.Immutable; using System.Reactive; using System.Reactive.Linq; using Xunit; using static Microsoft.Reactive.Testing.ReactiveTest; using static Rx.Test.ImmutableDictionaryExtensions; namespace Rx.Test { public class LunchTest { [Fact] public void LunchVotingShouldWork() { var scheduler = new TestScheduler(); var date = DateTime.Today.ToDateTimeOffset(); var deadline = date.Add(new TimeSpan(12, 00, 00)); var observer = scheduler.Start( () => scheduler .CreateHotObservable( OnNext(date.Add(06, 00, 00).Ticks, "Asia"), OnNext(date.Add(11, 27, 37).Ticks, "Asia"), OnNext(date.Add(11, 35, 43).Ticks, "Billa"), OnNext(date.Add(11, 47, 18).Ticks, "Asia"), OnNext(date.Add(11, 53, 22).Ticks, "Fiori"), OnNext(date.Add(12, 00, 00).Ticks, "Asia"), OnNext(date.Add(12, 00, 01).Ticks, "Asia")) .Scan( ImmutableDictionary<string, int>.Empty, (dict, key) => dict.AddOrUpdate(key, 1, i => i + 1)) .TakeUntil(deadline, scheduler), created: date.Ticks, subscribed: date.Ticks, disposed: date.AddDays(1).Ticks); var expected = new[] { OnNextDict(date.Add(06, 00, 00).Ticks, Dict("Asia", 1)), OnNextDict(date.Add(11, 27, 37).Ticks, Dict("Asia", 2)), OnNextDict(date.Add(11, 35, 43).Ticks, Dict("Asia", 2).Add("Billa", 1)), OnNextDict(date.Add(11, 47, 18).Ticks, Dict("Asia", 3).Add("Billa", 1)), OnNextDict(date.Add(11, 53, 22).Ticks, Dict("Asia", 3).Add("Billa", 1).Add("Fiori", 1)), OnNextDict(date.Add(12, 00, 00).Ticks, Dict("Asia", 4).Add("Billa", 1).Add("Fiori", 1)), OnCompleted(date.Add(12, 00, 00).Ticks, Dict("", 0)) }; observer .Messages .Should() .Equal(expected, (a, b) => b.Equals(a)); } private static Recorded<Notification<ImmutableDictionary<TKey, TValue>>> OnNextDict<TKey, TValue>( long ticks, ImmutableDictionary<TKey, TValue> value) { return OnNext( ticks, (ImmutableDictionary<TKey, TValue> dict) => dict.StructuralEquals(value)); } } }
40.41791
106
0.518833
[ "MIT" ]
johannesegger/Rx-WPF-Sample
Rx.Test/LunchTest.cs
2,710
C#
#pragma checksum "/home/daniel/Projects/AccountManager/AccountManager/Views/Home/NewAccount.cshtml" "{ff1816ec-aa5e-4d10-87f7-6f4963833460}" "8eda10a35b0096539d443a17f631f01f342de095" // <auto-generated/> #pragma warning disable 1591 [assembly: global::Microsoft.AspNetCore.Razor.Hosting.RazorCompiledItemAttribute(typeof(AspNetCore.Views_Home_NewAccount), @"mvc.1.0.view", @"/Views/Home/NewAccount.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 "/home/daniel/Projects/AccountManager/AccountManager/Views/_ViewImports.cshtml" using AccountManager.Models; #line default #line hidden #nullable disable [global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"8eda10a35b0096539d443a17f631f01f342de095", @"/Views/Home/NewAccount.cshtml")] [global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"a1eca3a717d70b7ee968df8e9b1cec53a2a3a559", @"/Views/_ViewImports.cshtml")] public class Views_Home_NewAccount : global::Microsoft.AspNetCore.Mvc.Razor.RazorPage<OnlineAccount> { private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_0 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("class", new global::Microsoft.AspNetCore.Html.HtmlString("text-danger"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_1 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("class", new global::Microsoft.AspNetCore.Html.HtmlString("form-control"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_2 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("rows", new global::Microsoft.AspNetCore.Html.HtmlString("5"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_3 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("asp-action", "NewAccount", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_4 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("method", "post", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_5 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("class", new global::Microsoft.AspNetCore.Html.HtmlString("p-2 m-2"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); #line hidden #pragma warning disable 0649 private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperExecutionContext __tagHelperExecutionContext; #pragma warning restore 0649 private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperRunner __tagHelperRunner = new global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperRunner(); #pragma warning disable 0169 private string __tagHelperStringValueBuffer; #pragma warning restore 0169 private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperScopeManager __backed__tagHelperScopeManager = null; private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperScopeManager __tagHelperScopeManager { get { if (__backed__tagHelperScopeManager == null) { __backed__tagHelperScopeManager = new global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperScopeManager(StartTagHelperWritingScope, EndTagHelperWritingScope); } return __backed__tagHelperScopeManager; } } private global::Microsoft.AspNetCore.Mvc.TagHelpers.ValidationSummaryTagHelper __Microsoft_AspNetCore_Mvc_TagHelpers_ValidationSummaryTagHelper; private global::Microsoft.AspNetCore.Mvc.TagHelpers.FormTagHelper __Microsoft_AspNetCore_Mvc_TagHelpers_FormTagHelper; private global::Microsoft.AspNetCore.Mvc.TagHelpers.RenderAtEndOfFormTagHelper __Microsoft_AspNetCore_Mvc_TagHelpers_RenderAtEndOfFormTagHelper; private global::Microsoft.AspNetCore.Mvc.TagHelpers.InputTagHelper __Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper; private global::Microsoft.AspNetCore.Mvc.TagHelpers.TextAreaTagHelper __Microsoft_AspNetCore_Mvc_TagHelpers_TextAreaTagHelper; #pragma warning disable 1998 public async override global::System.Threading.Tasks.Task ExecuteAsync() { WriteLiteral("<h2 class=\"p-2 m-2\">Create New Account</h2>\n"); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("div", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "8eda10a35b0096539d443a17f631f01f342de0955456", async() => { } ); __Microsoft_AspNetCore_Mvc_TagHelpers_ValidationSummaryTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.ValidationSummaryTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_ValidationSummaryTagHelper); #nullable restore #line 3 "/home/daniel/Projects/AccountManager/AccountManager/Views/Home/NewAccount.cshtml" __Microsoft_AspNetCore_Mvc_TagHelpers_ValidationSummaryTagHelper.ValidationSummary = global::Microsoft.AspNetCore.Mvc.Rendering.ValidationSummary.All; #line default #line hidden #nullable disable __tagHelperExecutionContext.AddTagHelperAttribute("asp-validation-summary", __Microsoft_AspNetCore_Mvc_TagHelpers_ValidationSummaryTagHelper.ValidationSummary, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_0); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); WriteLiteral("\n"); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("form", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "8eda10a35b0096539d443a17f631f01f342de0957033", async() => { WriteLiteral("\n <div class=\"form-group\">\n <label>Account Name</label>"); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("input", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.SelfClosing, "8eda10a35b0096539d443a17f631f01f342de0957354", async() => { } ); __Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.InputTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper); #nullable restore #line 6 "/home/daniel/Projects/AccountManager/AccountManager/Views/Home/NewAccount.cshtml" __Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper.For = ModelExpressionProvider.CreateModelExpression(ViewData, __model => __model.Name); #line default #line hidden #nullable disable __tagHelperExecutionContext.AddTagHelperAttribute("asp-for", __Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper.For, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_1); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); WriteLiteral("\n </div>\n <div class=\"form-group\">\n <label>User Name</label>"); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("input", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.SelfClosing, "8eda10a35b0096539d443a17f631f01f342de0958976", async() => { } ); __Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.InputTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper); #nullable restore #line 9 "/home/daniel/Projects/AccountManager/AccountManager/Views/Home/NewAccount.cshtml" __Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper.For = ModelExpressionProvider.CreateModelExpression(ViewData, __model => __model.UserId); #line default #line hidden #nullable disable __tagHelperExecutionContext.AddTagHelperAttribute("asp-for", __Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper.For, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_1); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); WriteLiteral("\n </div>\n <div class=\"form-group\">\n <label>Password</label>"); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("input", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.SelfClosing, "8eda10a35b0096539d443a17f631f01f342de09510599", async() => { } ); __Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.InputTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper); #nullable restore #line 12 "/home/daniel/Projects/AccountManager/AccountManager/Views/Home/NewAccount.cshtml" __Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper.For = ModelExpressionProvider.CreateModelExpression(ViewData, __model => __model.Password); #line default #line hidden #nullable disable __tagHelperExecutionContext.AddTagHelperAttribute("asp-for", __Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper.For, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_1); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); WriteLiteral("\n </div>\n <div class=\"form-group\">\n <label>Notes</label>"); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("textarea", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "8eda10a35b0096539d443a17f631f01f342de09512223", async() => { } ); __Microsoft_AspNetCore_Mvc_TagHelpers_TextAreaTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.TextAreaTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_TextAreaTagHelper); #nullable restore #line 15 "/home/daniel/Projects/AccountManager/AccountManager/Views/Home/NewAccount.cshtml" __Microsoft_AspNetCore_Mvc_TagHelpers_TextAreaTagHelper.For = ModelExpressionProvider.CreateModelExpression(ViewData, __model => __model.Notes); #line default #line hidden #nullable disable __tagHelperExecutionContext.AddTagHelperAttribute("asp-for", __Microsoft_AspNetCore_Mvc_TagHelpers_TextAreaTagHelper.For, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_1); __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_2); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); WriteLiteral("\n </div>\n <div class=\"text-center\">\n <input type=\"submit\" class=\"btn btn-primary\" value=\"Submit\" />\n </div>\n "); } ); __Microsoft_AspNetCore_Mvc_TagHelpers_FormTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.FormTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_FormTagHelper); __Microsoft_AspNetCore_Mvc_TagHelpers_RenderAtEndOfFormTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.RenderAtEndOfFormTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_RenderAtEndOfFormTagHelper); __Microsoft_AspNetCore_Mvc_TagHelpers_FormTagHelper.Action = (string)__tagHelperAttribute_3.Value; __tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_3); __Microsoft_AspNetCore_Mvc_TagHelpers_FormTagHelper.Method = (string)__tagHelperAttribute_4.Value; __tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_4); __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_5); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); } #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<OnlineAccount> Html { get; private set; } } } #pragma warning restore 1591
79.009662
350
0.75775
[ "MIT" ]
moorthidaniel/Account-Manager
obj/Debug/net5.0/Razor/Views/Home/NewAccount.cshtml.g.cs
16,355
C#
using NUnit.Framework; using System; using akarnokd.reactive_extensions; namespace akarnokd.reactive_extensions_test.single { [TestFixture] public class SingleDoTest { [Test] public void OnSuccess_Basic() { var count = 0; SingleSource.Just(1) .DoOnSuccess(v => count++) .Test() .AssertResult(1); Assert.AreEqual(1, count); } [Test] public void OnSuccess_Basic_Twice() { var count = 0; SingleSource.Just(1) .DoOnSuccess(v => count++) .DoOnSuccess(v => count++) .Test() .AssertResult(1); Assert.AreEqual(2, count); } [Test] public void OnAfterSuccess_Basic() { var count = -1; var to = new TestObserver<int>(); SingleSource.Just(1) .DoAfterSuccess(v => count = to.ItemCount) .SubscribeWith(to) .AssertResult(1); Assert.AreEqual(1, count); } [Test] public void OnAfterSuccess_Basic_Twice() { var count1 = -1; var count2 = -1; var to = new TestObserver<int>(); SingleSource.Just(1) .DoAfterSuccess(v => count1 = to.ItemCount) .DoAfterSuccess(v => count2 = to.ItemCount) .SubscribeWith(to) .AssertResult(1); Assert.AreEqual(1, count1); Assert.AreEqual(1, count2); } [Test] public void OnError_Basic() { var count = 0; SingleSource.Error<int>(new InvalidOperationException()) .DoOnError(e => count++) .Test() .AssertFailure(typeof(InvalidOperationException)); Assert.AreEqual(1, count); } [Test] public void OnError_Basic_Twice() { var count = 0; SingleSource.Error<int>(new InvalidOperationException()) .DoOnError(e => count++) .DoOnError(e => count++) .Test() .AssertFailure(typeof(InvalidOperationException)); Assert.AreEqual(2, count); } [Test] public void OnError_Crash() { var count = 0; SingleSource.Error<int>(new InvalidOperationException("outer")) .DoOnError(e => { count++; throw new InvalidOperationException("inner"); }) .Test() .AssertCompositeError(0, typeof(InvalidOperationException), "outer") .AssertCompositeError(1, typeof(InvalidOperationException), "inner"); ; Assert.AreEqual(1, count); } [Test] public void OnSubscribe_Basic() { var count = 0; SingleSource.Just(1) .DoOnSubscribe(s => count++) .Test() .AssertResult(1); Assert.AreEqual(1, count); } [Test] public void OnSubscribe_Basic_Twice() { var count = 0; SingleSource.Just(1) .DoOnSubscribe(s => count++) .DoOnSubscribe(s => count++) .Test() .AssertResult(1); Assert.AreEqual(2, count); } [Test] public void OnSubscribe_Crash() { var count = 0; SingleSource.Just(1) .DoOnSubscribe(s => { count++; throw new InvalidOperationException(); }) .Test() .AssertFailure(typeof(InvalidOperationException)); ; Assert.AreEqual(1, count); } [Test] public void Finally_Basic() { var count = 0; SingleSource.Just(1) .DoFinally(() => count++) .Test() .AssertResult(1); Assert.AreEqual(1, count); } [Test] public void Finally_Basic_Twice() { var count = 0; SingleSource.Just(1) .DoFinally(() => count++) .DoFinally(() => count++) .Test() .AssertResult(1); Assert.AreEqual(2, count); } [Test] public void Finally_Crash() { var count = 0; SingleSource.Just(1) .DoFinally(() => { count++; throw new InvalidOperationException(); }) .Test() .AssertResult(1); ; Assert.AreEqual(1, count); } [Test] public void OnDispose_Basic() { var count = 0; SingleSource.Never<int>() .DoOnDispose(() => count++) .Test(true) .AssertEmpty(); Assert.AreEqual(1, count); } [Test] public void OnDispose_Basic_Twice() { var count = 0; SingleSource.Never<int>() .DoOnDispose(() => count++) .DoOnDispose(() => count++) .Test(true) .AssertEmpty(); Assert.AreEqual(2, count); } [Test] public void OnDispose_Crash() { var count = 0; SingleSource.Never<int>() .DoOnDispose(() => { count++; throw new InvalidOperationException(); }) .Test(true) .AssertEmpty(); ; Assert.AreEqual(1, count); } [Test] public void OnDispose_Success() { var count = 0; SingleSource.Just(1) .DoOnDispose(() => { count++; }) .Test() .AssertResult(1); ; Assert.AreEqual(0, count); } [Test] public void OnDispose_Error() { var count = 0; SingleSource.Error<int>(new InvalidOperationException()) .DoOnDispose(() => { count++; }) .Test() .AssertFailure(typeof(InvalidOperationException)); ; Assert.AreEqual(0, count); } [Test] public void OnTerminate_Basic() { var count = 0; SingleSource.Just(1) .DoOnTerminate(() => count++) .Test() .AssertResult(1); Assert.AreEqual(1, count); } [Test] public void OnTerminate_Error() { var count = 0; SingleSource.Error<int>(new InvalidOperationException()) .DoOnTerminate(() => count++) .Test() .AssertFailure(typeof(InvalidOperationException)); Assert.AreEqual(1, count); } [Test] public void OnTerminate_Basic_Twice() { var count = 0; SingleSource.Just(1) .DoOnTerminate(() => count++) .DoOnTerminate(() => count++) .Test() .AssertResult(1); Assert.AreEqual(2, count); } [Test] public void OnTerminate_Crash() { var count = 0; SingleSource.Just(1) .DoOnTerminate(() => { count++; throw new InvalidOperationException(); }) .Test() .AssertFailure(typeof(InvalidOperationException)); ; Assert.AreEqual(1, count); } [Test] public void OnTerminate_Error_Crash() { var count = 0; SingleSource.Error<int>(new InvalidOperationException("main")) .DoOnTerminate(() => { count++; throw new InvalidOperationException("inner"); }) .Test() .AssertCompositeError(0, typeof(InvalidOperationException), "main") .AssertCompositeError(1, typeof(InvalidOperationException), "inner") ; ; Assert.AreEqual(1, count); } [Test] public void AfterTerminate_Basic() { var count = 0; SingleSource.Just(1) .DoAfterTerminate(() => count++) .Test() .AssertResult(1); Assert.AreEqual(1, count); } [Test] public void AfterTerminate_Error() { var count = 0; SingleSource.Error<int>(new InvalidOperationException()) .DoAfterTerminate(() => count++) .Test() .AssertFailure(typeof(InvalidOperationException)); Assert.AreEqual(1, count); } [Test] public void AferTerminate_Basic_Twice() { var count = 0; SingleSource.Just(1) .DoAfterTerminate(() => count++) .DoAfterTerminate(() => count++) .Test() .AssertResult(1); Assert.AreEqual(2, count); } [Test] public void AfterTerminate_Crash() { var count = 0; SingleSource.Just(1) .DoAfterTerminate(() => { count++; throw new InvalidOperationException(); }) .Test() .AssertResult(1); ; Assert.AreEqual(1, count); } [Test] public void AfterTerminate_Error_Crash() { var count = 0; SingleSource.Error<int>(new InvalidOperationException("main")) .DoAfterTerminate(() => { count++; throw new InvalidOperationException("inner"); }) .Test() .AssertFailure(typeof(InvalidOperationException)) .AssertError(typeof(InvalidOperationException), "main"); ; ; Assert.AreEqual(1, count); } [Test] public void All_Success() { var success = 0; var afterSuccess = 0; var error = 0; var terminate = 0; var afterterminate = 0; var subscribe = 0; var dispose = 0; var final = 0; SingleSource.Just(1) .DoOnSuccess(v => success++) .DoAfterSuccess(v => afterSuccess++) .DoOnError(e => error++) .DoOnTerminate(() => terminate++) .DoAfterTerminate(() => afterterminate++) .DoOnSubscribe(d => subscribe++) .DoOnDispose(() => dispose++) .DoFinally(() => final++) .Test() .AssertResult(1); Assert.AreEqual(1, success); Assert.AreEqual(1, afterSuccess); Assert.AreEqual(0, error); Assert.AreEqual(1, terminate); Assert.AreEqual(1, afterterminate); Assert.AreEqual(1, subscribe); Assert.AreEqual(0, dispose); Assert.AreEqual(1, final); } [Test] public void All_Error() { var success = 0; var afterSuccess = 0; var error = 0; var terminate = 0; var afterterminate = 0; var subscribe = 0; var dispose = 0; var final = 0; SingleSource.Error<int>(new InvalidOperationException()) .DoOnSuccess(v => success++) .DoOnSuccess(v => afterSuccess++) .DoOnError(e => error++) .DoOnTerminate(() => terminate++) .DoAfterTerminate(() => afterterminate++) .DoOnSubscribe(d => subscribe++) .DoOnDispose(() => dispose++) .DoFinally(() => final++) .Test() .AssertFailure(typeof(InvalidOperationException)); Assert.AreEqual(0, success); Assert.AreEqual(0, afterSuccess); Assert.AreEqual(1, error); Assert.AreEqual(1, terminate); Assert.AreEqual(1, afterterminate); Assert.AreEqual(1, subscribe); Assert.AreEqual(0, dispose); Assert.AreEqual(1, final); } } }
25.653021
85
0.43503
[ "Apache-2.0" ]
akarnokd/reactive-extensions
reactive-extensions-test/single/SingleDoTest.cs
13,162
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 storagegateway-2013-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.StorageGateway.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; using ThirdParty.Json.LitJson; namespace Amazon.StorageGateway.Model.Internal.MarshallTransformations { /// <summary> /// NFSFileShareDefaults Marshaller /// </summary> public class NFSFileShareDefaultsMarshaller : IRequestMarshaller<NFSFileShareDefaults, JsonMarshallerContext> { /// <summary> /// Unmarshaller the response from the service to the response class. /// </summary> /// <param name="requestObject"></param> /// <param name="context"></param> /// <returns></returns> public void Marshall(NFSFileShareDefaults requestObject, JsonMarshallerContext context) { if(requestObject.IsSetDirectoryMode()) { context.Writer.WritePropertyName("DirectoryMode"); context.Writer.Write(requestObject.DirectoryMode); } if(requestObject.IsSetFileMode()) { context.Writer.WritePropertyName("FileMode"); context.Writer.Write(requestObject.FileMode); } if(requestObject.IsSetGroupId()) { context.Writer.WritePropertyName("GroupId"); context.Writer.Write(requestObject.GroupId); } if(requestObject.IsSetOwnerId()) { context.Writer.WritePropertyName("OwnerId"); context.Writer.Write(requestObject.OwnerId); } } /// <summary> /// Singleton Marshaller. /// </summary> public readonly static NFSFileShareDefaultsMarshaller Instance = new NFSFileShareDefaultsMarshaller(); } }
33.75
114
0.657037
[ "Apache-2.0" ]
Bio2hazard/aws-sdk-net
sdk/src/Services/StorageGateway/Generated/Model/Internal/MarshallTransformations/NFSFileShareDefaultsMarshaller.cs
2,700
C#
using System; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Threading.Tasks; using DFC.Integration.AVFeed.Data.Interfaces; using Newtonsoft.Json; namespace DFC.Integration.AVFeed.Repository.Sitefinity { public class SitefinityODataContext<T> : IOdataContext<T> where T : class, new() { private ITokenClient tokenClient; private readonly IApplicationLogger logger; private readonly IAuditService auditService; private readonly IHttpClientService httpClientService; private const string CONTENT_TYPE = "application/json"; public SitefinityODataContext(ITokenClient tokenClient, IHttpClientService httpClient, IApplicationLogger logger, IAuditService auditService) { this.tokenClient = tokenClient; httpClientService = httpClient; this.logger = logger; this.auditService = auditService; } public async Task<HttpClient> GetHttpClientAsync() { var accessToken = await tokenClient.GetAccessTokenAsync(); var httpClient = httpClientService.GetHttpClient(); httpClient.SetBearerToken(accessToken); //ContentType = "application/json" httpClient.DefaultRequestHeaders.Add("X-SF-Service-Request", "true"); httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(CONTENT_TYPE)); return httpClient; } public async Task<PagedOdataResult<T>> GetResult(Uri requestUri, bool shouldAudit) { try { return await GetInternalAsync(requestUri, shouldAudit); } catch (UnauthorizedAccessException) { logger.Info($"Access denined, access token expired - will retry with new token - '{requestUri}'."); tokenClient.SetAccessToken(string.Empty); return await GetInternalAsync(requestUri, shouldAudit); } } private async Task<PagedOdataResult<T>> GetInternalAsync(Uri requestUri, bool shouldAudit) { using (var client = await GetHttpClientAsync()) { var resultMessage = await client.GetAsync(requestUri); if(resultMessage.StatusCode == System.Net.HttpStatusCode.Unauthorized) { throw new UnauthorizedAccessException(resultMessage.ReasonPhrase); } var result = await client.GetStringAsync(requestUri); logger.Info($"Requested with url - '{requestUri}'."); if (shouldAudit) { await auditService.AuditAsync($"{requestUri} | {result}"); } return JsonConvert.DeserializeObject<PagedOdataResult<T>>(result); } } public async Task<string> PostAsync(Uri requestUri, T data) { try { return await PostInternal(requestUri, data); } catch (UnauthorizedAccessException) { logger.Info($"Access denined, access token expired - will retry with new token - '{requestUri}'."); tokenClient.SetAccessToken(string.Empty); return await PostInternal(requestUri, data); } } private async Task<string> PostInternal(Uri requestUri, T data) { using (var client = await GetHttpClientAsync()) { var content = new StringContent(JsonConvert.SerializeObject(data), Encoding.UTF8, CONTENT_TYPE); var result = await client.PostAsync(requestUri, content); if (result.StatusCode == System.Net.HttpStatusCode.Unauthorized) { throw new UnauthorizedAccessException(result.ReasonPhrase); } logger.Info($"Posted to url - '{requestUri}', returned '{result.StatusCode}' and headers '{result.Headers}'."); var jsonContent = await result.Content.ReadAsStringAsync(); await auditService.AuditAsync($"Posted to url - {requestUri} | Returned -{jsonContent}"); if (!result.IsSuccessStatusCode) { logger.Error($"Failed to POST url - '{requestUri}', returned '{result.StatusCode}' and headers '{result.Headers}' and content '{jsonContent}'.", new HttpRequestException(jsonContent)); throw new HttpRequestException(jsonContent); } return jsonContent; } } public async Task<string> PutAsync(Uri requestUri, string relatedEntityLink) { try { return await PutChangedToPostInternalAsync(requestUri, relatedEntityLink); } catch (UnauthorizedAccessException) { logger.Info($"Access denined, access token expired - will retry with new token - '{requestUri}'."); tokenClient.SetAccessToken(string.Empty); return await PutChangedToPostInternalAsync(requestUri, relatedEntityLink); } } private async Task<string> PutChangedToPostInternalAsync(Uri requestUri, string relatedEntityLink) { using (var client = await GetHttpClientAsync()) { var content = new StringContent(relatedEntityLink, Encoding.UTF8, CONTENT_TYPE); //Changed to post as in the later version of sitefinity PUT is used to manipulate data in TEMP state, this locks the sitefinity item. var result = await client.PostAsync(requestUri, content); if (result.StatusCode == System.Net.HttpStatusCode.Unauthorized) { throw new UnauthorizedAccessException(result.ReasonPhrase); } logger.Info($"POST to url - '{requestUri}', returned '{result.StatusCode}' and headers '{result.Headers}'."); var jsonContent = await result.Content.ReadAsStringAsync(); await auditService.AuditAsync($"POST to url - {requestUri} | Returned - {jsonContent}"); if (!result.IsSuccessStatusCode) { logger.Error($"Failed to PUT url - '{requestUri}', returned '{result.StatusCode}' and headers '{result.Headers}' and content '{jsonContent}'.", new HttpRequestException(jsonContent)); throw new HttpRequestException(jsonContent); } return jsonContent; } } public async Task DeleteAsync(string requestUri) { try { await DeleteInternalAsync(requestUri); } catch (UnauthorizedAccessException) { logger.Info($"Access denined, access token expired - will retry with new token - '{requestUri}'."); tokenClient.SetAccessToken(string.Empty); await DeleteInternalAsync(requestUri); } } private async Task DeleteInternalAsync(string requestUri) { using (var client = await GetHttpClientAsync()) { var result = await client.DeleteAsync(requestUri); if (result.StatusCode == System.Net.HttpStatusCode.Unauthorized) { throw new UnauthorizedAccessException(result.ReasonPhrase); } logger.Info($"DELETE to url - '{requestUri}', returned '{result.StatusCode}' and headers '{result.Headers}'."); var jsonContent = await result.Content.ReadAsStringAsync(); await auditService.AuditAsync($"DELETE to url - {requestUri} | Returned - {jsonContent}"); } } } }
41.910526
204
0.59136
[ "MIT" ]
SkillsFundingAgency/dfc-integration-faa
DFC.Integration.AVFeed/DFC.Integration.AVFeed.Repository.Sitefinity/Base/SitefinityODataContext.cs
7,965
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.269 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace ClearCanvas.Enterprise.Authentication.Hibernate { using System; /// <summary> /// A strongly-typed resource class, for looking up localized strings, etc. /// </summary> // This class was auto-generated by the StronglyTypedResourceBuilder // class via a tool like ResGen or Visual Studio. // To add or remove a member, edit your .ResX file then rerun ResGen // with the /str option, or rebuild your VS project. [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] internal class SR { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal SR() { } /// <summary> /// Returns the cached ResourceManager instance used by this class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Resources.ResourceManager ResourceManager { get { if (object.ReferenceEquals(resourceMan, null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("ClearCanvas.Enterprise.Authentication.Hibernate.SR", typeof(SR).Assembly); resourceMan = temp; } return resourceMan; } } /// <summary> /// Overrides the current thread's CurrentUICulture property for all /// resource lookups using this strongly typed resource class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } } }
44.8125
189
0.601116
[ "Apache-2.0" ]
SNBnani/Xian
Enterprise/Authentication/Hibernate/SR.Designer.cs
2,870
C#
/* MIT License Copyright (c) 2016 JetBrains http://www.jetbrains.com 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; #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 GameScreen.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] object Test() => null; /// /// 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 | AttributeTargets.Class | AttributeTargets.Interface | AttributeTargets.GenericParameter)] public sealed class CanBeNullAttribute : Attribute { } /// <summary> /// Indicates that the value of the marked element could never be <c>null</c>. /// </summary> /// <example><code> /// [NotNull] object Foo() { /// return null; // Warning: Possible 'null' assignment /// } /// </code></example> [AttributeUsage( AttributeTargets.Method | AttributeTargets.Parameter | AttributeTargets.Property | AttributeTargets.Delegate | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Class | AttributeTargets.Interface | AttributeTargets.GenericParameter)] public sealed class NotNullAttribute : Attribute { } /// <summary> /// Can be appplied to symbols of types derived from IEnumerable as well as to symbols of Task /// and Lazy classes to indicate that the value of a collection item, of the Task.Result property /// or of the Lazy.Value property can never be null. /// </summary> [AttributeUsage( AttributeTargets.Method | AttributeTargets.Parameter | AttributeTargets.Property | AttributeTargets.Delegate | AttributeTargets.Field)] public sealed class ItemNotNullAttribute : Attribute { } /// <summary> /// Can be appplied to symbols of types derived from IEnumerable as well as to symbols of Task /// and Lazy classes to indicate that the value of a collection item, of the Task.Result property /// or of the Lazy.Value property can be null. /// </summary> [AttributeUsage( AttributeTargets.Method | AttributeTargets.Parameter | AttributeTargets.Property | AttributeTargets.Delegate | AttributeTargets.Field)] 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")] /// void ShowError(string message, params object[] args) { /* do something */ } /// /// void Foo() { /// ShowError("Failed: {0}"); // Warning: Non-existing argument in format string /// } /// </code></example> [AttributeUsage( AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Delegate)] public sealed class StringFormatMethodAttribute : Attribute { /// <param name="formatParameterName"> /// Specifies which parameter of an annotated method should be treated as format-string /// </param> public StringFormatMethodAttribute([NotNull] string formatParameterName) { FormatParameterName = formatParameterName; } [NotNull] 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, AllowMultiple = true)] public sealed class ValueProviderAttribute : Attribute { public ValueProviderAttribute([NotNull] 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> /// void Foo(string param) { /// if (param == null) /// throw new ArgumentNullException("par"); // Warning: Cannot resolve symbol /// } /// </code></example> [AttributeUsage(AttributeTargets.Parameter)] 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) { ... } /// /// 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)] public sealed class NotifyPropertyChangedInvocatorAttribute : Attribute { public NotifyPropertyChangedInvocatorAttribute() { } public NotifyPropertyChangedInvocatorAttribute([NotNull] string parameterName) { ParameterName = parameterName; } [CanBeNull] 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 (throws or terminates the process).<br/> /// Value <c>canbenull</c> 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. There is no notion of order rows, all rows are checked /// for applicability and applied per each program state tracked by R# analysis.<br/> /// </syntax> /// <examples><list> /// <item><code> /// [ContractAnnotation("=&gt; 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 =&gt; 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 =&gt; null; notnull =&gt; notnull")] /// public object Transform(object data) /// </code></item> /// <item><code> /// [ContractAnnotation("=&gt; true, result: notnull; =&gt; false, result: null")] /// public bool TryParse(string s, out Person result) /// </code></item> /// </list></examples> [AttributeUsage(AttributeTargets.Method, AllowMultiple = true)] public sealed class ContractAnnotationAttribute : Attribute { public ContractAnnotationAttribute([NotNull] string contract) : this(contract, false) { } public ContractAnnotationAttribute([NotNull] string contract, bool forceFullStates) { Contract = contract; ForceFullStates = forceFullStates; } [NotNull] 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)] /// class Foo { /// string str = "my string"; // Warning: Localizable string /// } /// </code></example> [AttributeUsage(AttributeTargets.All)] 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 { /// 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)] 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 /// class ComponentAttribute : Attribute { } /// /// [Component] // ComponentAttribute requires implementing IComponent interface /// class MyComponent : IComponent { } /// </code></example> [AttributeUsage(AttributeTargets.Class, AllowMultiple = true)] [BaseTypeRequired(typeof(Attribute))] 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)] 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)] 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(ImplicitUseTargetFlags.WithMembers)] public sealed class PublicAPIAttribute : Attribute { public PublicAPIAttribute() { } public PublicAPIAttribute([NotNull] string comment) { Comment = comment; } [CanBeNull] 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)] 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] int Multiply(int x, int y) => x * y; /// /// void M() { /// Multiply(123, 42); // Waring: Return value of pure method is not used /// } /// </code></example> [AttributeUsage(AttributeTargets.Method)] public sealed class PureAttribute : Attribute { } /// <summary> /// Indicates that the return value of method invocation must be used. /// </summary> [AttributeUsage(AttributeTargets.Method)] public sealed class MustUseReturnValueAttribute : Attribute { public MustUseReturnValueAttribute() { } public MustUseReturnValueAttribute([NotNull] string justification) { Justification = justification; } [CanBeNull] public string Justification { get; private set; } } /// <summary> /// Indicates the type member or parameter of some type, that should be used instead of all other ways /// to get the value that type. This annotation is useful when you have some "context" value evaluated /// and stored somewhere, meaning that all other ways to get this value must be consolidated with existing one. /// </summary> /// <example><code> /// class Foo { /// [ProvidesContext] IBarService _barService = ...; /// /// void ProcessNode(INode node) { /// DoSomething(node, node.GetGlobalServices().Bar); /// // ^ Warning: use value of '_barService' field /// } /// } /// </code></example> [AttributeUsage( AttributeTargets.Field | AttributeTargets.Property | AttributeTargets.Parameter | AttributeTargets.Method | AttributeTargets.Class | AttributeTargets.Interface | AttributeTargets.Struct | AttributeTargets.GenericParameter)] public sealed class ProvidesContextAttribute : 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)] public sealed class PathReferenceAttribute : Attribute { public PathReferenceAttribute() { } public PathReferenceAttribute([NotNull, PathReference] string basePath) { BasePath = basePath; } [CanBeNull] public string BasePath { get; private set; } } /// <summary> /// An extension method marked with this attribute is processed by ReSharper code completion /// as a 'Source Template'. When extension method is completed over some expression, it's source code /// is automatically expanded like a template at call site. /// </summary> /// <remarks> /// Template method body can contain valid source code and/or special comments starting with '$'. /// Text inside these comments is added as source code when the template is applied. Template parameters /// can be used either as additional method parameters or as identifiers wrapped in two '$' signs. /// Use the <see cref="MacroAttribute"/> attribute to specify macros for parameters. /// </remarks> /// <example> /// In this example, the 'forEach' method is a source template available over all values /// of enumerable types, producing ordinary C# 'foreach' statement and placing caret inside block: /// <code> /// [SourceTemplate] /// public static void forEach&lt;T&gt;(this IEnumerable&lt;T&gt; xs) { /// foreach (var x in xs) { /// //$ $END$ /// } /// } /// </code> /// </example> [AttributeUsage(AttributeTargets.Method)] public sealed class SourceTemplateAttribute : Attribute { } /// <summary> /// Allows specifying a macro for a parameter of a <see cref="SourceTemplateAttribute">source template</see>. /// </summary> /// <remarks> /// You can apply the attribute on the whole method or on any of its additional parameters. The macro expression /// is defined in the <see cref="MacroAttribute.Expression"/> property. When applied on a method, the target /// template parameter is defined in the <see cref="MacroAttribute.Target"/> property. To apply the macro silently /// for the parameter, set the <see cref="MacroAttribute.Editable"/> property value = -1. /// </remarks> /// <example> /// Applying the attribute on a source template method: /// <code> /// [SourceTemplate, Macro(Target = "item", Expression = "suggestVariableName()")] /// public static void forEach&lt;T&gt;(this IEnumerable&lt;T&gt; collection) { /// foreach (var item in collection) { /// //$ $END$ /// } /// } /// </code> /// Applying the attribute on a template method parameter: /// <code> /// [SourceTemplate] /// public static void something(this Entity x, [Macro(Expression = "guid()", Editable = -1)] string newguid) { /// /*$ var $x$Id = "$newguid$" + x.ToString(); /// x.DoSomething($x$Id); */ /// } /// </code> /// </example> [AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Method, AllowMultiple = true)] public sealed class MacroAttribute : Attribute { /// <summary> /// Allows specifying a macro that will be executed for a <see cref="SourceTemplateAttribute">source template</see> /// parameter when the template is expanded. /// </summary> [CanBeNull] public string Expression { get; set; } /// <summary> /// Allows specifying which occurrence of the target parameter becomes editable when the template is deployed. /// </summary> /// <remarks> /// If the target parameter is used several times in the template, only one occurrence becomes editable; /// other occurrences are changed synchronously. To specify the zero-based index of the editable occurrence, /// use values >= 0. To make the parameter non-editable when the template is expanded, use -1. /// </remarks>> public int Editable { get; set; } /// <summary> /// Identifies the target parameter of a <see cref="SourceTemplateAttribute">source template</see> if the /// <see cref="MacroAttribute"/> is applied on a template method. /// </summary> [CanBeNull] public string Target { get; set; } } [AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = true)] public sealed class AspMvcAreaMasterLocationFormatAttribute : Attribute { public AspMvcAreaMasterLocationFormatAttribute([NotNull] string format) { Format = format; } [NotNull] public string Format { get; private set; } } [AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = true)] public sealed class AspMvcAreaPartialViewLocationFormatAttribute : Attribute { public AspMvcAreaPartialViewLocationFormatAttribute([NotNull] string format) { Format = format; } [NotNull] public string Format { get; private set; } } [AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = true)] public sealed class AspMvcAreaViewLocationFormatAttribute : Attribute { public AspMvcAreaViewLocationFormatAttribute([NotNull] string format) { Format = format; } [NotNull] public string Format { get; private set; } } [AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = true)] public sealed class AspMvcMasterLocationFormatAttribute : Attribute { public AspMvcMasterLocationFormatAttribute([NotNull] string format) { Format = format; } [NotNull] public string Format { get; private set; } } [AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = true)] public sealed class AspMvcPartialViewLocationFormatAttribute : Attribute { public AspMvcPartialViewLocationFormatAttribute([NotNull] string format) { Format = format; } [NotNull] public string Format { get; private set; } } [AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = true)] public sealed class AspMvcViewLocationFormatAttribute : Attribute { public AspMvcViewLocationFormatAttribute([NotNull] string format) { Format = format; } [NotNull] 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)] public sealed class AspMvcActionAttribute : Attribute { public AspMvcActionAttribute() { } public AspMvcActionAttribute([NotNull] string anonymousProperty) { AnonymousProperty = anonymousProperty; } [CanBeNull] 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)] public sealed class AspMvcAreaAttribute : Attribute { public AspMvcAreaAttribute() { } public AspMvcAreaAttribute([NotNull] string anonymousProperty) { AnonymousProperty = anonymousProperty; } [CanBeNull] 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)] public sealed class AspMvcControllerAttribute : Attribute { public AspMvcControllerAttribute() { } public AspMvcControllerAttribute([NotNull] string anonymousProperty) { AnonymousProperty = anonymousProperty; } [CanBeNull] 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)] 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)] 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)] public sealed class AspMvcPartialViewAttribute : Attribute { } /// <summary> /// ASP.NET MVC attribute. Allows disabling inspections for MVC views within a class or a method. /// </summary> [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)] public sealed class AspMvcSuppressViewErrorAttribute : 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)] 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)] 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)] public sealed class AspMvcTemplateAttribute : Attribute { } /// <summary> /// ASP.NET MVC attribute. If applied to a parameter, indicates that the parameter /// is an MVC view component. 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)] public sealed class AspMvcViewAttribute : Attribute { } /// <summary> /// ASP.NET MVC attribute. If applied to a parameter, indicates that the parameter /// is an MVC view component name. /// </summary> [AttributeUsage(AttributeTargets.Parameter)] public sealed class AspMvcViewComponentAttribute : Attribute { } /// <summary> /// ASP.NET MVC attribute. If applied to a parameter, indicates that the parameter /// is an MVC view component view. If applied to a method, the MVC view component view name is default. /// </summary> [AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Method)] public sealed class AspMvcViewComponentViewAttribute : Attribute { } /// <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)] public sealed class AspMvcActionSelectorAttribute : Attribute { } [AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Property | AttributeTargets.Field)] public sealed class HtmlElementAttributesAttribute : Attribute { public HtmlElementAttributesAttribute() { } public HtmlElementAttributesAttribute([NotNull] string name) { Name = name; } [CanBeNull] public string Name { get; private set; } } [AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Field | AttributeTargets.Property)] 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)] public sealed class RazorSectionAttribute : Attribute { } /// <summary> /// Indicates how method, constructor invocation or property access /// over collection type affects content of the collection. /// </summary> [AttributeUsage(AttributeTargets.Method | AttributeTargets.Constructor | AttributeTargets.Property)] 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)] 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)] 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)] 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)] public sealed class LinqTunnelAttribute : Attribute { } /// <summary> /// Indicates that IEnumerable, passed as parameter, is not enumerated. /// </summary> [AttributeUsage(AttributeTargets.Parameter)] public sealed class NoEnumerationAttribute : Attribute { } /// <summary> /// Indicates that parameter is regular expression pattern. /// </summary> [AttributeUsage(AttributeTargets.Parameter)] public sealed class RegexPatternAttribute : 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.Class | AttributeTargets.Interface | AttributeTargets.Struct | AttributeTargets.Enum)] public sealed class NoReorderAttribute : 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)] public sealed class XamlItemsControlAttribute : Attribute { } /// <summary> /// XAML attribute. 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)] public sealed class XamlItemBindingOfItemsControlAttribute : Attribute { } [AttributeUsage(AttributeTargets.Class, AllowMultiple = true)] public sealed class AspChildControlTypeAttribute : Attribute { public AspChildControlTypeAttribute([NotNull] string tagName, [NotNull] Type controlType) { TagName = tagName; ControlType = controlType; } [NotNull] public string TagName { get; private set; } [NotNull] public Type ControlType { get; private set; } } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Method)] public sealed class AspDataFieldAttribute : Attribute { } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Method)] public sealed class AspDataFieldsAttribute : Attribute { } [AttributeUsage(AttributeTargets.Property)] public sealed class AspMethodPropertyAttribute : Attribute { } [AttributeUsage(AttributeTargets.Class, AllowMultiple = true)] public sealed class AspRequiredAttributeAttribute : Attribute { public AspRequiredAttributeAttribute([NotNull] string attribute) { Attribute = attribute; } [NotNull] public string Attribute { get; private set; } } [AttributeUsage(AttributeTargets.Property)] public sealed class AspTypePropertyAttribute : Attribute { public bool CreateConstructorReferences { get; private set; } public AspTypePropertyAttribute(bool createConstructorReferences) { CreateConstructorReferences = createConstructorReferences; } } [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)] public sealed class RazorImportNamespaceAttribute : Attribute { public RazorImportNamespaceAttribute([NotNull] string name) { Name = name; } [NotNull] public string Name { get; private set; } } [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)] public sealed class RazorInjectionAttribute : Attribute { public RazorInjectionAttribute([NotNull] string type, [NotNull] string fieldName) { Type = type; FieldName = fieldName; } [NotNull] public string Type { get; private set; } [NotNull] public string FieldName { get; private set; } } [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)] public sealed class RazorDirectiveAttribute : Attribute { public RazorDirectiveAttribute([NotNull] string directive) { Directive = directive; } [NotNull] public string Directive { get; private set; } } [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)] public sealed class RazorPageBaseTypeAttribute : Attribute { public RazorPageBaseTypeAttribute([NotNull] string baseType) { BaseType = baseType; } public RazorPageBaseTypeAttribute([NotNull] string baseType, string pageName) { BaseType = baseType; PageName = pageName; } [NotNull] public string BaseType { get; private set; } [CanBeNull] public string PageName { get; private set; } } [AttributeUsage(AttributeTargets.Method)] public sealed class RazorHelperCommonAttribute : Attribute { } [AttributeUsage(AttributeTargets.Property)] public sealed class RazorLayoutAttribute : Attribute { } [AttributeUsage(AttributeTargets.Method)] public sealed class RazorWriteLiteralMethodAttribute : Attribute { } [AttributeUsage(AttributeTargets.Method)] public sealed class RazorWriteMethodAttribute : Attribute { } [AttributeUsage(AttributeTargets.Parameter)] public sealed class RazorWriteMethodParameterAttribute : Attribute { } }
39.173709
120
0.708054
[ "MIT" ]
zerotwooneone/GameScreen
GameScreen/Properties/Annotations.cs
41,722
C#
using System; namespace Android.App { sealed partial class ServiceAttribute : Attribute, Java.Interop.IJniNameProviderAttribute { public string Name {get; set;} } }
25.625
92
0.639024
[ "MIT" ]
Wivra/java.interop
tests/Java.Interop.Tools.JavaCallableWrappers-Tests/Android.App/ServiceAttribute.cs
205
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. using System.Collections; using UnityEngine; using UnityEngine.SceneManagement; namespace Microsoft.MixedReality.Toolkit.Examples.Demos.EyeTracking { /// <summary> /// General useful utility functions. /// </summary> public static class EyeTrackingDemoUtils { /// <summary> /// Returns a correctly formatted filename removing invalid characters if necessary. /// </summary> /// <param name="unvalidatedFilename">The unvalidated filename</param> /// <returns>Validated filename.</returns> public static string GetValidFilename(string unvalidatedFilename) { char[] invalidChars = new char[] { '/', ':', '*', '?', '"', '<', '>', '|', '\\' }; string formattedFilename = unvalidatedFilename; foreach (char invalidChar in invalidChars) { formattedFilename = formattedFilename.Replace((invalidChar.ToString()), ""); } return formattedFilename; } /// <summary> /// Returns the full name of a given GameObject in the scene graph. /// </summary> /// <param name="go"></param> /// <returns></returns> public static string GetFullName(GameObject go) { bool valid; return GetFullName(go, out valid); } /// <summary> /// Returns the full name of a given GameObject in the scene graph. /// </summary> /// <param name="go"></param> /// <returns></returns> public static string GetFullName(GameObject go, out bool valid) { valid = false; if (go != null) { string goName = go.name; Transform g = go.transform; while (g.parent != null) { goName = g.parent.name + "\\" + goName; g = g.transform.parent; } valid = true; return goName; } return ""; } /// <summary> /// Normalize the given value based on the provided min and max values. /// </summary> /// <param name="value"></param> /// <param name="min"></param> /// <param name="max"></param> /// <returns></returns> public static float Normalize(float value, float min, float max) { if (value > max) return 1; if (value < min) return 0; return (value - min) / (max - min); } /// <summary> /// Shuffles the entries in a given array and returns the shuffled array. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="array"></param> /// <returns></returns> public static T[] RandomizeListOrder<T>(T[] array) { T[] arr = (T[])array.Clone(); for (int i = 0; i < arr.Length; i++) { T temp = arr[i]; int randomIndex = UnityEngine.Random.Range(i, arr.Length); arr[i] = arr[randomIndex]; arr[randomIndex] = temp; } return arr; } /// <summary> /// Returns the metric size in meters of a given Vector3 in visual angle in degrees and a given viewing distance in meters. /// </summary> /// <param name="visAngleInDegrees">In degrees.</param> /// <param name="distInMeters">In meters.</param> /// <returns></returns> public static Vector3 VisAngleInDegreesToMeters(Vector3 visAngleInDegrees, float distInMeters) { return new Vector3( VisAngleInDegreesToMeters(visAngleInDegrees.x, distInMeters), VisAngleInDegreesToMeters(visAngleInDegrees.y, distInMeters), VisAngleInDegreesToMeters(visAngleInDegrees.z, distInMeters)); } /// <summary> /// Computes the metric size (in meters) for a given visual angle size. /// </summary> /// <param name="visAngleInDegrees">In degrees.</param> /// <param name="distInMeters">In meters.</param> /// <returns></returns> public static float VisAngleInDegreesToMeters(float visAngleInDegrees, float distInMeters) { return (2 * Mathf.Tan(Mathf.Deg2Rad * visAngleInDegrees / 2) * distInMeters); } /// <summary> /// Loads a Unity scene with the given name. /// </summary> /// <param name="sceneToBeLoaded">Name of the scene to be loaded.</param> /// <returns></returns> public static IEnumerator LoadNewScene(string sceneToBeLoaded) { return LoadNewScene(sceneToBeLoaded, 0.5f); } /// <summary> /// Loads a Unity scene with the given name after a given delay in seconds. /// </summary> /// <param name="sceneToBeLoaded">Name of the scene to be loaded.</param> /// <param name="delayInSeconds">Delay in seconds to wait before loading the new scene.</param> /// <returns></returns> public static IEnumerator LoadNewScene(string sceneToBeLoaded, float delayInSeconds) { yield return new WaitForSeconds(delayInSeconds); SceneManager.LoadScene(sceneToBeLoaded); } /// <summary> /// Change the color of game object "gobj". /// </summary> /// <param name="gobj"></param> /// <param name="newColor"></param> /// <param name="originalColor">Enter "null" in case you're passing the original object and want to save the original color.</param> public static void GameObject_ChangeColor(GameObject gobj, Color newColor, ref Color? originalColor, bool onlyApplyToRootObj) { try { Renderer[] renderers = gobj.GetComponents<Renderer>(); for (int i = 0; i < renderers.Length; i++) { Material[] mats = renderers[i].materials; foreach (Material mat in mats) { Color c = mat.color; if (!originalColor.HasValue) originalColor = c; mat.color = newColor; } } if (!onlyApplyToRootObj) { renderers = gobj.GetComponentsInChildren<Renderer>(); for (int i = 0; i < renderers.Length; i++) { Material[] mats = renderers[i].materials; foreach (Material mat in mats) { mat.color = newColor; } } } } catch (MissingReferenceException) { // Just ignore. Usually happens after the game object already got destroyed, but the update sequence had already been started. } } /// <summary> /// Change the transparency of game object "gobj" with a transparency value between 0 and 1; /// </summary> /// <param name="gobj"></param> /// <param name="newTransparency"></param> public static void GameObject_ChangeTransparency(GameObject gobj, float newTransparency) { float origTransp = 0; // just a dummy variable to reuse the following function GameObject_ChangeTransparency(gobj, newTransparency, ref origTransp); } /// <summary> /// Change the transparency of game object "gobj" with a transparency value between 0 and 255 with the option to /// receive the original transparency value back. /// </summary> /// <param name="gobj"></param> /// <param name="transparency">Expected values range from 0 (fully transparent) to 1 (fully opaque).</param> /// <param name="originalTransparency">Input "-1" if you don't know the original transparency yet.</param> public static void GameObject_ChangeTransparency(GameObject gobj, float transparency, ref float originalTransparency) { try { // Go through renderers in main object Renderers_ChangeTransparency(gobj.GetComponents<Renderer>(), transparency, ref originalTransparency); // Go through renderers in children objects Renderers_ChangeTransparency(gobj.GetComponentsInChildren<Renderer>(), transparency, ref originalTransparency); } catch (MissingReferenceException) { // Just ignore; Usually happens after the game object already got destroyed, but the update sequence had already be started } } /// <summary> /// Change the transparency of a given array of renderers to a given transparency value between 0 and 255; /// </summary> /// <param name="renderers">Array of renderers to apply a new transparency value to.</param> /// <param name="transparency">Value between 0 and 255.</param> /// <param name="originalTransparency">Option to return the original transparency value.</param> private static void Renderers_ChangeTransparency(Renderer[] renderers, float transparency, ref float originalTransparency) { for (int i = 0; i < renderers.Length; i++) { Material[] mats = renderers[i].materials; foreach (Material mat in mats) { Color c = mat.color; if (originalTransparency == -1) originalTransparency = c.a; if (transparency < 1) { ChangeRenderMode.ChangeRenderModes(mat, ChangeRenderMode.BlendMode.Fade); } else { ChangeRenderMode.ChangeRenderModes(mat, ChangeRenderMode.BlendMode.Opaque); } mat.color = new Color(c.r, c.g, c.b, transparency); } } } } }
40.019084
142
0.544015
[ "MIT" ]
AdamMitchell-ms/MixedRealityToolkit-Unity
Assets/MixedRealityToolkit.Examples/Demos/EyeTracking/General/Scripts/Utils/Utils.cs
10,487
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.Globalization; using System.Linq; using System.Threading.Tasks; using Moq; using NuGet.Services.Entities; using NuGetGallery.Auditing; using NuGetGallery.Framework; using NuGetGallery.Infrastructure.Authentication; using NuGetGallery.Security; using NuGetGallery.TestUtils; using Xunit; namespace NuGetGallery { public class UserServiceFacts { public class TheFindByKeyMethod { [Theory] [InlineData(false)] [InlineData(true)] public void ReturnsTheUserForTheKey(bool includedDeletedRecords) { var user1 = new User { Username = "User1", Key = 1, EmailAddress = "new1@example.org" }; var user2 = new User { Username = "User2", Key = 2, EmailAddress = "new2@example.org" }; var service = new TestableUserServiceWithDBFaking { Users = new[] { user1, user2 } }; var result = service.FindByKey(1, includedDeletedRecords); Assert.Equal("User1", result.Username); } [Theory] [InlineData(false)] [InlineData(true)] public void ReturnsDeletedUserIfRequired(bool includedDeletedRecords) { var user1 = new User { Username = "User1", Key = 1, EmailAddress = "new1@example.org", IsDeleted = true }; var user2 = new User { Username = "User2", Key = 2, EmailAddress = "new2@example.org" }; var service = new TestableUserServiceWithDBFaking { Users = new[] { user1, user2 } }; var result = service.FindByKey(1, includedDeletedRecords); if (includedDeletedRecords) { Assert.Equal("User1", result.Username); } else { Assert.Null(result); } } } public class TheFindByUsernameMethod { [Theory] [InlineData(false)] [InlineData(true)] public void ReturnsTheUserForTheUsername(bool includedDeletedRecords) { var user1 = new User { Username = "User1", Key = 1, EmailAddress = "new1@example.org" }; var user2 = new User { Username = "User2", Key = 2, EmailAddress = "new2@example.org" }; var service = new TestableUserServiceWithDBFaking { Users = new[] { user1, user2 } }; var result = service.FindByUsername("User1", includedDeletedRecords); Assert.Equal("User1", result.Username); } [Theory] [InlineData(false)] [InlineData(true)] public void ReturnsDeletedUserIfRequired(bool includedDeletedRecords) { var user1 = new User { Username = "User1", Key = 1, EmailAddress = "new1@example.org", IsDeleted = true }; var user2 = new User { Username = "User2", Key = 2, EmailAddress = "new2@example.org" }; var service = new TestableUserServiceWithDBFaking { Users = new[] { user1, user2 } }; var result = service.FindByUsername("User1", includedDeletedRecords); if (includedDeletedRecords) { Assert.Equal("User1", result.Username); } else { Assert.Null(result); } } } public class TheAddMembershipRequestAsyncMethod { [Theory] [InlineData(false)] [InlineData(true)] public async Task WhenOrganizationIsNull_ThrowsException(bool isAdmin) { // Arrange var service = new TestableUserService(); // Act & Assert await Assert.ThrowsAsync<ArgumentNullException>(async () => { await service.AddMembershipRequestAsync(null, "member", isAdmin); }); service.MockEntitiesContext.Verify(c => c.SaveChangesAsync(), Times.Never); } public static IEnumerable<object[]> WhenAlreadyAMember_ThrowsEntityException_Data { get { foreach (var user in new Func<Fakes, User>[] { (Fakes fakes) => fakes.OrganizationCollaborator, (Fakes fakes) => fakes.OrganizationAdmin }) { foreach (var isAdmin in new[] { false, true }) { yield return MemberDataHelper.AsData(user, isAdmin); } } } } [Theory] [MemberData(nameof(WhenAlreadyAMember_ThrowsEntityException_Data))] public async Task WhenAlreadyAMember_ThrowsEntityException(Func<Fakes, User> getUser, bool isAdmin) { // Arrange var fakes = new Fakes(); var user = getUser(fakes); var service = new TestableUserService(); // Act & Assert var e = await Assert.ThrowsAsync<EntityException>(async () => { await service.AddMembershipRequestAsync(fakes.Organization, user.Username, isAdmin); }); Assert.Equal(string.Format(CultureInfo.CurrentCulture, Strings.AddMember_AlreadyAMember, user.Username), e.Message); service.MockEntitiesContext.Verify(c => c.SaveChangesAsync(), Times.Never); } [Theory] [InlineData(false, false)] [InlineData(false, true)] [InlineData(true, false)] [InlineData(true, true)] public async Task WhenExistingRequest_ReturnsExistingRequest(bool existingRequestIsAdmin, bool isAdmin) { // Arrange var fakes = new Fakes(); var service = new TestableUserService(); var existingRequest = new MembershipRequest { NewMember = fakes.User, ConfirmationToken = "token", IsAdmin = existingRequestIsAdmin }; fakes.Organization.MemberRequests.Add(existingRequest); // Act var request = await service.AddMembershipRequestAsync(fakes.Organization, fakes.User.Username, isAdmin); // Assert Assert.Equal(existingRequest, request); Assert.Equal(existingRequestIsAdmin || isAdmin, request.IsAdmin); service.MockEntitiesContext.Verify(c => c.SaveChangesAsync(), Times.Once); } [Theory] [InlineData(false)] [InlineData(true)] public async Task WhenMemberNameIsEmail_ThrowEntityException(bool isAdmin) { // Arrange var fakes = new Fakes(); var service = new TestableUserService(); service.MockUserRepository.Setup(r => r.GetAll()) .Returns(new[] { fakes.Organization }.AsQueryable()); // Act var e = await Assert.ThrowsAsync<EntityException>(async () => { await service.AddMembershipRequestAsync(fakes.Organization, "notAUser@email.com", isAdmin); }); Assert.Equal(Strings.AddMember_NameIsEmail, e.Message); service.MockEntitiesContext.Verify(c => c.SaveChangesAsync(), Times.Never); } [Theory] [InlineData(false)] [InlineData(true)] public async Task WhenMemberNotFound_ThrowEntityException(bool isAdmin) { // Arrange var fakes = new Fakes(); var service = new TestableUserService(); service.MockUserRepository.Setup(r => r.GetAll()) .Returns(new[] { fakes.Organization }.AsQueryable()); // Act var e = await Assert.ThrowsAsync<EntityException>(async () => { await service.AddMembershipRequestAsync(fakes.Organization, fakes.User.Username, isAdmin); }); Assert.Equal(string.Format(CultureInfo.CurrentCulture, Strings.AddMember_UserNotFound, fakes.User.Username), e.Message); service.MockEntitiesContext.Verify(c => c.SaveChangesAsync(), Times.Never); } [Theory] [InlineData(false)] [InlineData(true)] public async Task WhenMemberNotConfirmed_ThrowEntityException(bool isAdmin) { // Arrange var fakes = new Fakes(); var service = new TestableUserService(); service.MockUserRepository.Setup(r => r.GetAll()) .Returns(new[] { fakes.Organization, fakes.User }.AsQueryable()); fakes.User.EmailAddress = string.Empty; fakes.User.UnconfirmedEmailAddress = "unconfirmed@email.com"; // Act var e = await Assert.ThrowsAsync<EntityException>(async () => { await service.AddMembershipRequestAsync(fakes.Organization, fakes.User.Username, isAdmin); }); Assert.Equal(string.Format(CultureInfo.CurrentCulture, Strings.AddMember_UserNotConfirmed, fakes.User.Username), e.Message); service.MockEntitiesContext.Verify(c => c.SaveChangesAsync(), Times.Never); } [Theory] [InlineData(false)] [InlineData(true)] public async Task WhenMemberIsOrganization_ThrowEntityException(bool isAdmin) { // Arrange var fakes = new Fakes(); var service = new TestableUserService(); service.MockUserRepository.Setup(r => r.GetAll()) .Returns(new[] { fakes.OrganizationOwner, fakes.Organization }.AsQueryable()); fakes.User.EmailAddress = string.Empty; fakes.User.UnconfirmedEmailAddress = "unconfirmed@email.com"; // Act var e = await Assert.ThrowsAsync<EntityException>(async () => { await service.AddMembershipRequestAsync(fakes.OrganizationOwner, fakes.Organization.Username, isAdmin); }); Assert.Equal(string.Format(CultureInfo.CurrentCulture, Strings.AddMember_UserIsOrganization, fakes.Organization.Username), e.Message); service.MockEntitiesContext.Verify(c => c.SaveChangesAsync(), Times.Never); } [Theory] [InlineData(true)] [InlineData(false)] public async Task WhenSecurityPolicyEvaluationFails_ReturnsSuccess(bool isAdmin) { // Arrange var fakes = new Fakes(); var service = new TestableUserService(); var error = "error"; service.MockSecurityPolicyService .Setup(s => s.EvaluateOrganizationPoliciesAsync(SecurityPolicyAction.JoinOrganization, fakes.Organization, fakes.User)) .Returns(Task.FromResult(SecurityPolicyResult.CreateErrorResult(error))); service.MockUserRepository.Setup(r => r.GetAll()) .Returns(new[] { fakes.Organization, fakes.User }.AsQueryable()); // Act var e = await Assert.ThrowsAsync<EntityException>(async () => { await service.AddMembershipRequestAsync(fakes.Organization, fakes.User.Username, isAdmin); }); Assert.Equal(error, e.Message); service.MockEntitiesContext.Verify(c => c.SaveChangesAsync(), Times.Never); } [Theory] [InlineData(true)] [InlineData(false)] public async Task WhenSecurityPolicyEvaluationSucceeds_ReturnsSuccess(bool isAdmin) { // Arrange var fakes = new Fakes(); var service = new TestableUserService(); service.MockSecurityPolicyService .Setup(s => s.EvaluateOrganizationPoliciesAsync(SecurityPolicyAction.JoinOrganization, fakes.Organization, fakes.User)) .Returns(Task.FromResult(SecurityPolicyResult.SuccessResult)); service.MockUserRepository.Setup(r => r.GetAll()) .Returns(new[] { fakes.Organization, fakes.User }.AsQueryable()); // Act var request = await service.AddMembershipRequestAsync(fakes.Organization, fakes.User.Username, isAdmin); Assert.Equal(isAdmin, request.IsAdmin); Assert.Equal(fakes.User, request.NewMember); Assert.Equal(fakes.Organization, request.Organization); Assert.Contains(request, fakes.Organization.MemberRequests); service.MockEntitiesContext.Verify(c => c.SaveChangesAsync(), Times.Once); } } public class TheAddMemberAsyncMethod { public Fakes Fakes { get; } public TestableUserService UserService { get; } public TheAddMemberAsyncMethod() { Fakes = new Fakes(); UserService = new TestableUserService(); } [Fact] public async Task WhenOrganizationIsNull_ThrowsException() { // Act & Assert await Assert.ThrowsAsync<ArgumentNullException>(async () => { await UserService.AddMemberAsync(null, "member", "token"); }); UserService.MockEntitiesContext.Verify(c => c.SaveChangesAsync(), Times.Never); } [Fact] public async Task WhenRequestNotFound_ThrowsEntityException() { // Act & Assert var e = await Assert.ThrowsAsync<EntityException>(async () => { await UserService.AddMemberAsync(Fakes.Organization, Fakes.User.Username, "token"); }); Assert.Equal(string.Format(CultureInfo.CurrentCulture, Strings.AddMember_MissingRequest, Fakes.User.Username), e.Message); UserService.MockEntitiesContext.Verify(c => c.SaveChangesAsync(), Times.Never); } [Theory] [InlineData(false)] [InlineData(true)] public async Task WhenRequestWithTokenNotFound_ThrowsEntityException(bool isAdmin) { // Arrange UserService.MockSecurityPolicyService .Setup(s => s.EvaluateOrganizationPoliciesAsync(SecurityPolicyAction.JoinOrganization, Fakes.Organization, Fakes.User)) .Returns(Task.FromResult(SecurityPolicyResult.CreateErrorResult("error"))); Fakes.Organization.MemberRequests.Add(new MembershipRequest { NewMember = Fakes.User, ConfirmationToken = "token", IsAdmin = isAdmin }); // Act & Assert var e = await Assert.ThrowsAsync<EntityException>(async () => { await UserService.AddMemberAsync(Fakes.Organization, Fakes.User.Username, "wrongToken"); }); Assert.Equal(string.Format(CultureInfo.CurrentCulture, Strings.AddMember_MissingRequest, Fakes.User.Username), e.Message); UserService.MockEntitiesContext.Verify(c => c.SaveChangesAsync(), Times.Never); } [Theory] [InlineData(false)] [InlineData(true)] public async Task WhereMemberUnconfirmed_ThrowsEntityException(bool isAdmin) { // Arrange UserService.MockSecurityPolicyService .Setup(s => s.EvaluateOrganizationPoliciesAsync(SecurityPolicyAction.JoinOrganization, Fakes.Organization, Fakes.User)) .Returns(Task.FromResult(SecurityPolicyResult.CreateErrorResult("error"))); var token = "token"; Fakes.Organization.MemberRequests.Add(new MembershipRequest { NewMember = Fakes.User, ConfirmationToken = token, IsAdmin = isAdmin }); Fakes.User.EmailAddress = string.Empty; Fakes.User.UnconfirmedEmailAddress = "unconfirmed@email.com"; // Act & Assert var e = await Assert.ThrowsAsync<EntityException>(async () => { await UserService.AddMemberAsync(Fakes.Organization, Fakes.User.Username, token); }); Assert.Equal(string.Format(CultureInfo.CurrentCulture, Strings.AddMember_UserNotConfirmed, Fakes.User.Username), e.Message); UserService.MockEntitiesContext.Verify(c => c.SaveChangesAsync(), Times.Never); } [Theory] [InlineData(false)] [InlineData(true)] public async Task WhereMemberIsOrganization_ThrowsEntityException(bool isAdmin) { // Arrange UserService.MockSecurityPolicyService .Setup(s => s.EvaluateOrganizationPoliciesAsync(SecurityPolicyAction.JoinOrganization, Fakes.Organization, Fakes.OrganizationOwner)) .Returns(Task.FromResult(SecurityPolicyResult.CreateErrorResult("error"))); var token = "token"; Fakes.Organization.MemberRequests.Add(new MembershipRequest { NewMember = Fakes.OrganizationOwner, ConfirmationToken = token, IsAdmin = isAdmin }); // Act & Assert var e = await Assert.ThrowsAsync<EntityException>(async () => { await UserService.AddMemberAsync(Fakes.Organization, Fakes.OrganizationOwner.Username, token); }); Assert.Equal(string.Format(CultureInfo.CurrentCulture, Strings.AddMember_UserIsOrganization, Fakes.OrganizationOwner.Username), e.Message); UserService.MockEntitiesContext.Verify(c => c.SaveChangesAsync(), Times.Never); } [Theory] [InlineData(false)] [InlineData(true)] public async Task WhenMemberExists_UpdatesMember(bool isAdmin) { // Arrange UserService.MockUserRepository.Setup(r => r.GetAll()) .Returns(new[] { Fakes.User, Fakes.Organization }.AsQueryable()); var token = "token"; Fakes.Organization.MemberRequests.Add(new MembershipRequest { NewMember = Fakes.OrganizationCollaborator, ConfirmationToken = token, IsAdmin = isAdmin }); // Act var result = await UserService.AddMemberAsync(Fakes.Organization, Fakes.OrganizationCollaborator.Username, token); Assert.Equal(isAdmin, result.IsAdmin); Assert.Equal(Fakes.OrganizationCollaborator, result.Member); UserService.MockEntitiesContext.Verify(c => c.SaveChangesAsync(), Times.Once); Assert.True(UserService.Auditing.WroteRecord<UserAuditRecord>(ar => ar.Action == AuditedUserAction.UpdateOrganizationMember && ar.Username == Fakes.Organization.Username && ar.AffectedMemberUsername == Fakes.OrganizationCollaborator.Username && ar.AffectedMemberIsAdmin == isAdmin)); } [Theory] [InlineData(true)] [InlineData(false)] public async Task WhenRequestFoundWithUnconfirmedUser_ThrowsEntityException(bool isAdmin) { // Arrange var token = "token"; Fakes.Organization.MemberRequests.Add(new MembershipRequest { NewMember = Fakes.User, ConfirmationToken = token, IsAdmin = isAdmin }); Fakes.User.EmailAddress = string.Empty; Fakes.User.UnconfirmedEmailAddress = "unconfirmed@email.com"; // Act & Assert var e = await Assert.ThrowsAsync<EntityException>(async () => { await UserService.AddMemberAsync(Fakes.Organization, Fakes.User.Username, token); }); Assert.Equal(string.Format(CultureInfo.CurrentCulture, Strings.AddMember_UserNotConfirmed, Fakes.User.Username), e.Message); UserService.MockEntitiesContext.Verify(c => c.SaveChangesAsync(), Times.Never); } [Theory] [InlineData(false)] [InlineData(true)] public async Task WhenSecurityPolicyEvalutionFailure_ThrowsEntityException(bool isAdmin) { // Arrange var error = "error"; UserService.MockSecurityPolicyService .Setup(s => s.EvaluateOrganizationPoliciesAsync(SecurityPolicyAction.JoinOrganization, Fakes.Organization, Fakes.User)) .Returns(Task.FromResult(SecurityPolicyResult.CreateErrorResult(error))); var token = "token"; Fakes.Organization.MemberRequests.Add(new MembershipRequest { NewMember = Fakes.User, ConfirmationToken = token, IsAdmin = isAdmin }); // Act & Assert var e = await Assert.ThrowsAsync<EntityException>(async () => { await UserService.AddMemberAsync(Fakes.Organization, Fakes.User.Username, token); }); Assert.Equal(string.Format(CultureInfo.CurrentCulture, Strings.AddMember_PolicyFailure, error), e.Message); UserService.MockEntitiesContext.Verify(c => c.SaveChangesAsync(), Times.Never); } [Theory] [InlineData(true)] [InlineData(false)] public async Task WhenSecurityPolicyEvalutionSucceeds_CreatesMembership(bool isAdmin) { // Arrange UserService.MockSecurityPolicyService .Setup(s => s.EvaluateOrganizationPoliciesAsync(SecurityPolicyAction.JoinOrganization, Fakes.Organization, Fakes.User)) .Returns(Task.FromResult(SecurityPolicyResult.SuccessResult)); var token = "token"; Fakes.Organization.MemberRequests.Add(new MembershipRequest { NewMember = Fakes.User, ConfirmationToken = token, IsAdmin = isAdmin }); // Act var result = await UserService.AddMemberAsync(Fakes.Organization, Fakes.User.Username, token); // Assert Assert.Equal(isAdmin, result.IsAdmin); Assert.Equal(Fakes.User, result.Member); UserService.MockEntitiesContext.Verify(c => c.SaveChangesAsync(), Times.Once); Assert.True(UserService.Auditing.WroteRecord<UserAuditRecord>(ar => ar.Action == AuditedUserAction.AddOrganizationMember && ar.Username == Fakes.Organization.Username && ar.AffectedMemberUsername == Fakes.User.Username && ar.AffectedMemberIsAdmin == isAdmin)); } } public class TheDeleteMemberAsyncMethod { [Fact] public async Task WhenOrganizationIsNull_ThrowsException() { // Arrange var service = new TestableUserService(); // Act & Assert await Assert.ThrowsAsync<ArgumentNullException>(async () => { await service.DeleteMemberAsync(null, "member"); }); service.MockEntitiesContext.Verify(c => c.SaveChangesAsync(), Times.Never); } [Fact] public async Task WhenNoMatch_ThrowsEntityException() { // Arrange var service = new TestableUserService(); var memberName = "member"; // Act & Assert var e = await Assert.ThrowsAsync<EntityException>(async () => { await service.DeleteMemberAsync(new Organization(), memberName); }); Assert.Equal(string.Format(CultureInfo.CurrentCulture, Strings.UpdateOrDeleteMember_MemberNotFound, memberName), e.Message); service.MockEntitiesContext.Verify(c => c.SaveChangesAsync(), Times.Never); } [Fact] public async Task WhenLastAdmin_ThrowsEntityException() { // Arrange var fakes = new Fakes(); var service = new TestableUserService(); // Act & Assert var e = await Assert.ThrowsAsync<EntityException>(async () => { await service.DeleteMemberAsync(fakes.Organization, fakes.OrganizationAdmin.Username); }); service.MockEntitiesContext.Verify(c => c.SaveChangesAsync(), Times.Never); Assert.Equal( Strings.DeleteMember_CannotRemoveLastAdmin, e.Message); } [Fact] public async Task WhenNotLastAdmin_DeletesMembership() { // Arrange var fakes = new Fakes(); var service = new TestableUserService(); foreach (var m in fakes.Organization.Members) { m.IsAdmin = true; } // Act await service.DeleteMemberAsync(fakes.Organization, fakes.OrganizationAdmin.Username); // Assert service.MockEntitiesContext.Verify(c => c.SaveChangesAsync(), Times.Once); Assert.True(service.Auditing.WroteRecord<UserAuditRecord>(ar => ar.Action == AuditedUserAction.RemoveOrganizationMember && ar.Username == fakes.Organization.Username && ar.AffectedMemberUsername == fakes.OrganizationAdmin.Username && ar.AffectedMemberIsAdmin == true)); } [Fact] public async Task WhenCollaborator_DeletesMembership() { // Arrange var fakes = new Fakes(); var service = new TestableUserService(); // Act await service.DeleteMemberAsync(fakes.Organization, fakes.OrganizationCollaborator.Username); // Assert service.MockEntitiesContext.Verify(c => c.SaveChangesAsync(), Times.Once); Assert.True(service.Auditing.WroteRecord<UserAuditRecord>(ar => ar.Action == AuditedUserAction.RemoveOrganizationMember && ar.Username == fakes.Organization.Username && ar.AffectedMemberUsername == fakes.OrganizationCollaborator.Username && ar.AffectedMemberIsAdmin == false)); } } public class TheRejectMembershipRequestAsyncMethod { [Fact] public async Task WhenOrganizationIsNull_ThrowsException() { // Arrange var service = new TestableUserService(); // Act & Assert await Assert.ThrowsAsync<ArgumentNullException>(async () => { await service.RejectMembershipRequestAsync(null, "member", "token"); }); service.MockEntitiesContext.Verify(c => c.SaveChangesAsync(), Times.Never); } [Fact] public async Task WhenNoExistingRequest_ThrowsEntityException() { // Arrange var service = new TestableUserService(); var memberName = "member"; // Act & Assert var e = await Assert.ThrowsAsync<EntityException>(async () => { await service.RejectMembershipRequestAsync(new Organization { MemberRequests = new MembershipRequest[0] }, memberName, "token"); }); Assert.Equal(string.Format(CultureInfo.CurrentCulture, Strings.RejectMembershipRequest_NotFound, memberName), e.Message); service.MockEntitiesContext.Verify(c => c.SaveChangesAsync(), Times.Never); } [Fact] public async Task WhenExistingRequestWithDifferentToken_ThrowsEntityException() { // Arrange var service = new TestableUserService(); var memberName = "member"; var token = "token"; var organization = new Organization { MemberRequests = new List<MembershipRequest> { new MembershipRequest { NewMember = new User(memberName), ConfirmationToken = "differentToken" } } }; // Act & Assert var e = await Assert.ThrowsAsync<EntityException>(async () => { await service.RejectMembershipRequestAsync(organization, memberName, token); }); Assert.Equal(string.Format(CultureInfo.CurrentCulture, Strings.RejectMembershipRequest_NotFound, memberName), e.Message); service.MockEntitiesContext.Verify(c => c.SaveChangesAsync(), Times.Never); } [Fact] public async Task WithExistingRequest_Succeeds() { // Arrange var fakes = new Fakes(); var service = new TestableUserService(); var memberName = "member"; var token = "token"; var organization = new Organization { MemberRequests = new List<MembershipRequest> { new MembershipRequest { NewMember = new User(memberName), ConfirmationToken = token } } }; // Act & Assert await service.RejectMembershipRequestAsync(organization, memberName, token); Assert.True(!organization.MemberRequests.Any()); service.MockEntitiesContext.Verify(c => c.SaveChangesAsync(), Times.Once); } } public class TheCancelMembershipRequestAsyncMethod { [Fact] public async Task WhenOrganizationIsNull_ThrowsException() { // Arrange var service = new TestableUserService(); // Act & Assert await Assert.ThrowsAsync<ArgumentNullException>(async () => { await service.CancelMembershipRequestAsync(null, "member"); }); service.MockEntitiesContext.Verify(c => c.SaveChangesAsync(), Times.Never); } [Fact] public async Task WhenNoExistingRequest_ThrowsEntityException() { // Arrange var service = new TestableUserService(); var memberName = "member"; // Act & Assert var e = await Assert.ThrowsAsync<EntityException>(async () => { await service.CancelMembershipRequestAsync(new Organization { MemberRequests = new MembershipRequest[0] }, memberName); }); Assert.Equal(string.Format(CultureInfo.CurrentCulture, Strings.CancelMembershipRequest_MissingRequest, memberName), e.Message); service.MockEntitiesContext.Verify(c => c.SaveChangesAsync(), Times.Never); } [Fact] public async Task WithExistingRequest_Succeeds() { // Arrange var fakes = new Fakes(); var service = new TestableUserService(); var memberName = "member"; var newMember = new User(memberName); var organization = new Organization { MemberRequests = new List<MembershipRequest> { new MembershipRequest { NewMember = newMember, ConfirmationToken = "token" } } }; // Act & Assert var pendingMember = await service.CancelMembershipRequestAsync(organization, memberName); Assert.True(!organization.MemberRequests.Any()); Assert.Equal(newMember, pendingMember); service.MockEntitiesContext.Verify(c => c.SaveChangesAsync(), Times.Once); } } public class TheUpdateMemberAsyncMethod { [Fact] public async Task WhenOrganizationIsNull_ThrowsException() { // Arrange var service = new TestableUserService(); // Act & Assert await Assert.ThrowsAsync<ArgumentNullException>(async () => { await service.UpdateMemberAsync(null, "member", false); }); } [Fact] public async Task WhenMemberNotFound_ThrowsEntityException() { // Arrange var fakes = new Fakes(); var service = new TestableUserService(); // Act & Assert var e = await Assert.ThrowsAsync<EntityException>(async () => { await service.UpdateMemberAsync(fakes.Organization, fakes.User.Username, false); }); Assert.Equal(string.Format(CultureInfo.CurrentCulture, Strings.UpdateOrDeleteMember_MemberNotFound, fakes.User.Username), e.Message); service.MockEntitiesContext.Verify(c => c.SaveChangesAsync(), Times.Never); } [Fact] public async Task WhenRemovingLastAdmin_ThrowsEntityException() { // Arrange var fakes = new Fakes(); var service = new TestableUserService(); // Act & Assert var e = await Assert.ThrowsAsync<EntityException>(async () => { await service.UpdateMemberAsync(fakes.Organization, fakes.OrganizationAdmin.Username, false); }); service.MockEntitiesContext.Verify(c => c.SaveChangesAsync(), Times.Never); Assert.Equal( Strings.UpdateMember_CannotRemoveLastAdmin, e.Message); } [Fact] public async Task WhenNotDemotingLastAdmin_ReturnsSuccess() { // Arrange var fakes = new Fakes(); var service = new TestableUserService(); foreach (var m in fakes.Organization.Members) { m.IsAdmin = true; } // Act var result = await service.UpdateMemberAsync(fakes.Organization, fakes.OrganizationAdmin.Username, false); // Assert Assert.False(result.IsAdmin); Assert.Equal(fakes.OrganizationAdmin, result.Member); service.MockEntitiesContext.Verify(c => c.SaveChangesAsync(), Times.Once); Assert.True(service.Auditing.WroteRecord<UserAuditRecord>(ar => ar.Action == AuditedUserAction.UpdateOrganizationMember && ar.Username == fakes.Organization.Username && ar.AffectedMemberUsername == fakes.OrganizationAdmin.Username && ar.AffectedMemberIsAdmin == false)); } [Fact] public async Task WhenPromotingCollaboratorToAdmin_ReturnsSuccess() { // Arrange var fakes = new Fakes(); var service = new TestableUserService(); // Act var result = await service.UpdateMemberAsync(fakes.Organization, fakes.OrganizationCollaborator.Username, true); // Assert Assert.True(result.IsAdmin); Assert.Equal(fakes.OrganizationCollaborator, result.Member); service.MockEntitiesContext.Verify(c => c.SaveChangesAsync(), Times.Once); Assert.True(service.Auditing.WroteRecord<UserAuditRecord>(ar => ar.Action == AuditedUserAction.UpdateOrganizationMember && ar.Username == fakes.Organization.Username && ar.AffectedMemberUsername == fakes.OrganizationCollaborator.Username && ar.AffectedMemberIsAdmin == true)); } public static IEnumerable<object[]> WhenMembershipMatches_DoesNotSaveChanges_Data => new object[][] { new object[] { new Func<Fakes, User>((Fakes fakes) => fakes.OrganizationAdmin), true }, new object[] { new Func<Fakes, User>((Fakes fakes) => fakes.OrganizationCollaborator), false } }; [Theory] [MemberData(nameof(WhenMembershipMatches_DoesNotSaveChanges_Data))] public async Task WhenMembershipMatches_DoesNotSaveChanges(Func<Fakes, User> getMember, bool isAdmin) { // Arrange var fakes = new Fakes(); var service = new TestableUserService(); var member = getMember(fakes); // Act var result = await service.UpdateMemberAsync(fakes.Organization, member.Username, isAdmin); // Assert Assert.Equal(isAdmin, result.IsAdmin); Assert.Equal(member, result.Member); service.MockEntitiesContext.Verify(c => c.SaveChangesAsync(), Times.Never); Assert.False(service.Auditing.WroteRecord<UserAuditRecord>()); } } public class TheConfirmEmailAddressMethod { [Fact] public async Task WithTokenThatDoesNotMatchUserReturnsFalse() { var user = new User { Username = "username", EmailConfirmationToken = "token" }; var service = new TestableUserService(); var confirmed = await service.ConfirmEmailAddress(user, "not-token"); Assert.False(confirmed); } [Fact] public async Task ThrowsForDuplicateConfirmedEmailAddresses() { var user = new User { Username = "User1", Key = 1, EmailAddress = "old@example.org", UnconfirmedEmailAddress = "new@example.org", EmailConfirmationToken = "token" }; var conflictingUser = new User { Username = "User2", Key = 2, EmailAddress = "new@example.org" }; var service = new TestableUserServiceWithDBFaking { Users = new[] { user, conflictingUser } }; var ex = await AssertEx.Throws<EntityException>(() => service.ConfirmEmailAddress(user, "token")); Assert.Equal(String.Format(Strings.EmailAddressBeingUsed, "new@example.org"), ex.Message); } [Fact] public async Task WithTokenThatDoesMatchUserConfirmsUserAndReturnsTrue() { var user = new User { Username = "username", EmailConfirmationToken = "secret", UnconfirmedEmailAddress = "new@example.com" }; var service = new TestableUserService(); var confirmed = await service.ConfirmEmailAddress(user, "secret"); Assert.True(confirmed); Assert.True(user.Confirmed); Assert.Equal("new@example.com", user.EmailAddress); Assert.Null(user.UnconfirmedEmailAddress); Assert.Null(user.EmailConfirmationToken); } [Fact] public async Task ForUserWithConfirmedEmailWithTokenThatDoesMatchUserConfirmsUserAndReturnsTrue() { var user = new User { Username = "username", EmailConfirmationToken = "secret", EmailAddress = "existing@example.com", UnconfirmedEmailAddress = "new@example.com" }; var service = new TestableUserService(); var confirmed = await service.ConfirmEmailAddress(user, "secret"); Assert.True(confirmed); Assert.True(user.Confirmed); Assert.Equal("new@example.com", user.EmailAddress); Assert.Null(user.UnconfirmedEmailAddress); Assert.Null(user.EmailConfirmationToken); } [Fact] public async Task WithNullUserThrowsArgumentNullException() { var service = new TestableUserService(); await AssertEx.Throws<ArgumentNullException>(() => service.ConfirmEmailAddress(null, "token")); } [Fact] public async Task WithEmptyTokenThrowsArgumentNullException() { var service = new TestableUserService(); await AssertEx.Throws<ArgumentNullException>(() => service.ConfirmEmailAddress(new User(), "")); } [Fact] public async Task WritesAuditRecord() { var user = new User { Username = "username", EmailConfirmationToken = "secret", EmailAddress = "existing@example.com", UnconfirmedEmailAddress = "new@example.com" }; var service = new TestableUserService(); var confirmed = await service.ConfirmEmailAddress(user, "secret"); Assert.True(service.Auditing.WroteRecord<UserAuditRecord>(ar => ar.Action == AuditedUserAction.ConfirmEmail && ar.AffectedEmailAddress == "new@example.com")); } } public class TheFindByEmailAddressMethod { [Fact] public void ReturnsNullIfMultipleMatchesExist() { var user = new User { Username = "User1", Key = 1, EmailAddress = "new@example.org" }; var conflictingUser = new User { Username = "User2", Key = 2, EmailAddress = "new@example.org" }; var service = new TestableUserServiceWithDBFaking { Users = new[] { user, conflictingUser } }; var result = service.FindByEmailAddress("new@example.org"); Assert.Null(result); } } public class TheChangeEmailMethod { [Fact] public async Task SetsUnconfirmedEmailWhenEmailIsChanged() { var user = new User { Username = "Bob", EmailAddress = "old@example.org" }; var service = new TestableUserServiceWithDBFaking { Users = new[] { user } }; service.MockConfig .Setup(x => x.ConfirmEmailAddresses) .Returns(true); await service.ChangeEmailAddress(user, "new@example.org"); Assert.Equal("old@example.org", user.EmailAddress); Assert.Equal("new@example.org", user.UnconfirmedEmailAddress); service.FakeEntitiesContext.VerifyCommitChanges(); } [Fact] public async Task AutomaticallyConfirmsWhenConfirmEmailAddressesConfigurationIsFalse() { var user = new User { Username = "Bob", EmailAddress = "old@example.org" }; var service = new TestableUserServiceWithDBFaking { Users = new[] { user } }; service.MockConfig .Setup(x => x.ConfirmEmailAddresses) .Returns(false); await service.ChangeEmailAddress(user, "new@example.org"); Assert.Equal("new@example.org", user.EmailAddress); Assert.Null(user.UnconfirmedEmailAddress); Assert.Null(user.EmailConfirmationToken); service.FakeEntitiesContext.VerifyCommitChanges(); } /// <summary> /// It has to change the pending confirmation token whenever address changes because otherwise you can do /// 1. change address, get confirmation email /// 2. change email address again to something you don't own /// 3. hit confirm and you confirmed an email address you don't own /// </summary> [Fact] public async Task ModifiesConfirmationTokenWhenEmailAddressChanged() { var user = new User { EmailAddress = "old@example.com", EmailConfirmationToken = "pending-token" }; var service = new TestableUserServiceWithDBFaking { Users = new User[] { user }, }; service.MockConfig .Setup(x => x.ConfirmEmailAddresses) .Returns(true); await service.ChangeEmailAddress(user, "new@example.com"); Assert.NotNull(user.EmailConfirmationToken); Assert.NotEmpty(user.EmailConfirmationToken); Assert.NotEqual("pending-token", user.EmailConfirmationToken); service.FakeEntitiesContext.VerifyCommitChanges(); } /// <summary> /// It would be annoying if you start seeing pending email changes as a result of NOT changing your email address. /// </summary> [Fact] public async Task DoesNotModifyAnythingWhenConfirmedEmailAddressNotChanged() { var user = new User { EmailAddress = "old@example.com", UnconfirmedEmailAddress = null, EmailConfirmationToken = null }; var service = new TestableUserServiceWithDBFaking { Users = new User[] { user }, }; service.MockConfig .Setup(x => x.ConfirmEmailAddresses) .Returns(true); await service.ChangeEmailAddress(user, "old@example.com"); Assert.True(user.Confirmed); Assert.Equal("old@example.com", user.EmailAddress); Assert.Null(user.UnconfirmedEmailAddress); Assert.Null(user.EmailConfirmationToken); } /// <summary> /// Because it's bad if your confirmation email no longer works because you did a no-op email address change. /// </summary> [Theory] [InlineData("something@else.com")] [InlineData(null)] public async Task DoesNotModifyConfirmationTokenWhenUnconfirmedEmailAddressNotChanged(string confirmedEmailAddress) { var user = new User { EmailAddress = confirmedEmailAddress, UnconfirmedEmailAddress = "old@example.com", EmailConfirmationToken = "pending-token" }; var service = new TestableUserServiceWithDBFaking { Users = new User[] { user }, }; service.MockConfig .Setup(x => x.ConfirmEmailAddresses) .Returns(true); await service.ChangeEmailAddress(user, "old@example.com"); Assert.Equal("pending-token", user.EmailConfirmationToken); } [Fact] public async Task DoesNotLetYouUseSomeoneElsesConfirmedEmailAddress() { var user = new User { EmailAddress = "old@example.com", Key = 1 }; var conflictingUser = new User { EmailAddress = "new@example.com", Key = 2 }; var service = new TestableUserServiceWithDBFaking { Users = new User[] { user, conflictingUser }, }; var e = await AssertEx.Throws<EntityException>(() => service.ChangeEmailAddress(user, "new@example.com")); Assert.Equal(string.Format(Strings.EmailAddressBeingUsed, "new@example.com"), e.Message); Assert.Equal("old@example.com", user.EmailAddress); } [Fact] public async Task WritesAuditRecord() { // Arrange var user = new User { Username = "Bob", EmailAddress = "old@example.org" }; var service = new TestableUserServiceWithDBFaking { Users = new[] { user } }; // Act await service.ChangeEmailAddress(user, "new@example.org"); // Assert Assert.True(service.Auditing.WroteRecord<UserAuditRecord>(ar => ar.Action == AuditedUserAction.ChangeEmail && ar.AffectedEmailAddress == "new@example.org" && ar.EmailAddress == "old@example.org")); } } public class TheCancelChangeEmailAddressMethod { [Fact] public async Task ClearsUnconfirmedEmail() { var user = new User { Username = "Bob", UnconfirmedEmailAddress = "unconfirmedEmail@example.org", EmailAddress = "confirmedEmail@example.org" }; var service = new TestableUserServiceWithDBFaking { Users = new[] { user } }; await service.CancelChangeEmailAddress(user); Assert.Equal("confirmedEmail@example.org", user.EmailAddress); Assert.Null(user.UnconfirmedEmailAddress); service.FakeEntitiesContext.VerifyCommitChanges(); } [Fact] public async Task ClearsEmailConfirmationToken() { var user = new User { Username = "Bob", EmailConfirmationToken = Guid.NewGuid().ToString() ,UnconfirmedEmailAddress = "unconfirmedEmail@example.org", EmailAddress = "confirmedEmail@example.org" }; var service = new TestableUserServiceWithDBFaking { Users = new[] { user } }; await service.CancelChangeEmailAddress(user); Assert.Equal("confirmedEmail@example.org", user.EmailAddress); Assert.Null(user.EmailConfirmationToken); service.FakeEntitiesContext.VerifyCommitChanges(); } [Fact] public async Task WritesAuditRecord() { // Arrange var user = new User { Username = "Bob", EmailConfirmationToken = Guid.NewGuid().ToString(), UnconfirmedEmailAddress = "unconfirmedEmail@example.org", EmailAddress = "confirmedEmail@example.org" }; var service = new TestableUserServiceWithDBFaking { Users = new[] { user } }; // Act await service.CancelChangeEmailAddress(user); // Assert Assert.True(service.Auditing.WroteRecord<UserAuditRecord>(ar => ar.Action == AuditedUserAction.CancelChangeEmail && ar.AffectedEmailAddress == "unconfirmedEmail@example.org" && ar.EmailAddress == "confirmedEmail@example.org")); } } public class TheChangeMultiFactorAuthenticationMethod { [Theory] [InlineData(true)] [InlineData(false)] public async Task UpdatesMultiFactorSettings(bool enable2FA) { // Arrange var user = new User(); var service = new TestableUserService(); // Act await service.ChangeMultiFactorAuthentication(user, enable2FA, null); // Assert Assert.Equal(user.EnableMultiFactorAuthentication, enable2FA); service.MockUserRepository.Verify(x => x.CommitChangesAsync(), Times.Once); service.MockTelemetryService.Verify(x => x.TrackUserChangedMultiFactorAuthentication(user, enable2FA, It.IsAny<string>()), Times.Once); } } public class TheUpdateProfileMethod { [Fact] public async Task SavesEmailSettings() { var user = new User { EmailAddress = "old@example.org", EmailAllowed = true, NotifyPackagePushed = true}; var service = new TestableUserService(); service.MockUserRepository .Setup(r => r.GetAll()) .Returns(new[] { user }.AsQueryable()); // Disable notifications await service.ChangeEmailSubscriptionAsync(user, false, false); Assert.False(user.EmailAllowed); Assert.False(user.NotifyPackagePushed); // Enable contact notifications await service.ChangeEmailSubscriptionAsync(user, true, false); Assert.True(user.EmailAllowed); Assert.False(user.NotifyPackagePushed); // Disable notifications await service.ChangeEmailSubscriptionAsync(user, false, false); Assert.False(user.EmailAllowed); Assert.False(user.NotifyPackagePushed); // Enable package pushed notifications await service.ChangeEmailSubscriptionAsync(user, false, true); Assert.False(user.EmailAllowed); Assert.True(user.NotifyPackagePushed); // Disable notifications await service.ChangeEmailSubscriptionAsync(user, false, false); Assert.False(user.EmailAllowed); Assert.False(user.NotifyPackagePushed); // Enable all notifications await service.ChangeEmailSubscriptionAsync(user, true, true); Assert.True(user.EmailAllowed); Assert.True(user.NotifyPackagePushed); service.MockUserRepository .Verify(r => r.CommitChangesAsync()); } [Fact] public async Task ThrowsArgumentExceptionForNullUser() { var service = new TestableUserService(); await ContractAssert.ThrowsArgNullAsync(async () => await service.ChangeEmailSubscriptionAsync(null, emailAllowed: true, notifyPackagePushed: true), "user"); } } public class TheCanTransformToOrganizationBaseMethod { protected virtual bool Invoke(TestableUserService service, User accountToTransform, out string errorReason) { return service.CanTransformUserToOrganization(accountToTransform, out errorReason); } [Fact] public void WhenAccountIsNotConfirmed_ReturnsFalse() { // Arrange var service = new TestableUserService(); var unconfirmedUser = new User() { UnconfirmedEmailAddress = "unconfirmed@example.com" }; // Act var result = Invoke(service, unconfirmedUser, out var errorReason); // Assert Assert.False(result); Assert.Equal(errorReason, String.Format(CultureInfo.CurrentCulture, Strings.TransformAccount_AccountNotConfirmed, unconfirmedUser.Username)); } [Fact] public void WhenAccountIsOrganization_ReturnsFalse() { // Arrange var service = new TestableUserService(); var fakes = new Fakes(); // Act var result = Invoke(service, fakes.Organization, out var errorReason); // Assert Assert.False(result); Assert.Equal(errorReason, String.Format(CultureInfo.CurrentCulture, Strings.TransformAccount_AccountIsAnOrganization, fakes.Organization.Username)); } [Fact] public void WhenAccountHasMemberships_ReturnsFalse() { // Arrange var service = new TestableUserService(); var fakes = new Fakes(); // Act var result = Invoke(service, fakes.OrganizationCollaborator, out var errorReason); // Assert Assert.False(result); Assert.Equal(errorReason, String.Format(CultureInfo.CurrentCulture, Strings.TransformAccount_AccountHasMemberships, fakes.OrganizationCollaborator.Username)); } } public class TheCanTransformToOrganizationMethod : TheCanTransformToOrganizationBaseMethod { [Fact] public void WhenAccountHasNoMemberships_ReturnsTrue() { // Arrange var service = new TestableUserService(); var fakes = new Fakes(); var user = fakes.User; var passwordConfigMock = new Mock<ILoginDiscontinuationConfiguration>(); service.MockConfigObjectService .Setup(x => x.LoginDiscontinuationConfiguration) .Returns(passwordConfigMock.Object); // Act var result = Invoke(service, user, out var errorReason); // Assert Assert.True(result); } } public class TheCanTransformToOrganizationWithAdminMethod : TheCanTransformToOrganizationBaseMethod { protected override bool Invoke(TestableUserService service, User accountToTransform, out string errorReason) { return service.CanTransformUserToOrganization(accountToTransform, null, out errorReason); } [Fact] public void WhenAdminMatchesAccountToTransform_ReturnsFalse() { // Arrange var service = new TestableUserService(); var fakes = new Fakes(); var user = fakes.User; var passwordConfigMock = new Mock<ILoginDiscontinuationConfiguration>(); service.MockConfigObjectService .Setup(x => x.LoginDiscontinuationConfiguration) .Returns(passwordConfigMock.Object); // Act string errorReason; var result = service.CanTransformUserToOrganization(user, user, out errorReason); // Assert Assert.False(result); Assert.Equal(errorReason, String.Format(CultureInfo.CurrentCulture, Strings.TransformAccount_AdminMustBeDifferentAccount, user.Username)); } [Fact] public void WhenAdminIsNotConfirmed_ReturnsFalse() { // Arrange var service = new TestableUserService(); var fakes = new Fakes(); var unconfirmedUser = new User() { UnconfirmedEmailAddress = "unconfirmed@example.com" }; var user = fakes.User; var passwordConfigMock = new Mock<ILoginDiscontinuationConfiguration>(); service.MockConfigObjectService .Setup(x => x.LoginDiscontinuationConfiguration) .Returns(passwordConfigMock.Object); // Act string errorReason; var result = service.CanTransformUserToOrganization(user, unconfirmedUser, out errorReason); // Assert Assert.False(result); Assert.Equal(errorReason, String.Format(CultureInfo.CurrentCulture, Strings.TransformAccount_AdminAccountNotConfirmed, unconfirmedUser.Username)); } [Fact] public void WhenAdminIsOrganization_ReturnsFalse() { // Arrange var service = new TestableUserService(); var fakes = new Fakes(); var user = fakes.User; var organization = fakes.Organization; var passwordConfigMock = new Mock<ILoginDiscontinuationConfiguration>(); service.MockConfigObjectService .Setup(x => x.LoginDiscontinuationConfiguration) .Returns(passwordConfigMock.Object); // Act string errorReason; var result = service.CanTransformUserToOrganization(user, organization, out errorReason); // Assert Assert.False(result); Assert.Equal(errorReason, String.Format(CultureInfo.CurrentCulture, Strings.TransformAccount_AdminAccountIsOrganization, organization.Username)); } } public class TheRequestTransformToOrganizationAccountMethod { [Fact] public async Task WhenAccountIsNull_ThrowsNullRefException() { var service = new TestableUserService(); await ContractAssert.ThrowsArgNullAsync( async () => await service.RequestTransformToOrganizationAccount(accountToTransform: null, adminUser: new User("admin")), "accountToTransform"); } [Fact] public async Task WhenAdminUserIsNull_ThrowsNullRefException() { var service = new TestableUserService(); await ContractAssert.ThrowsArgNullAsync( async () => await service.RequestTransformToOrganizationAccount(accountToTransform: new User("account"), adminUser: null), "adminUser"); } [Fact] public Task WhenExistingRequest_Overwrites() { return VerifyCreatesRequest(testOverwrite: true); } [Fact] public Task WhenNoExistingRequest_CreatesNew() { return VerifyCreatesRequest(testOverwrite: false); } private async Task VerifyCreatesRequest(bool testOverwrite) { // Arrange var service = new TestableUserService(); var account = new User("Account"); var admin = CreateAdminUser(); service.MockUserRepository.Setup(r => r.CommitChangesAsync()).Returns(Task.CompletedTask).Verifiable(); DateTime? requestDate = null; string requestToken = null; for (int i = 0; i < (testOverwrite ? 2 : 1); i++) { // Act await service.RequestTransformToOrganizationAccount(account, admin); if (testOverwrite) { if (requestDate != null) { Assert.True(requestDate < account.OrganizationMigrationRequest.RequestDate); Assert.NotEqual(requestToken, account.OrganizationMigrationRequest.ConfirmationToken); } requestDate = account.OrganizationMigrationRequest.RequestDate; requestToken = account.OrganizationMigrationRequest.ConfirmationToken; await Task.Delay(500); // ensure next requestDate is in future } // Assert service.MockUserRepository.Verify(r => r.CommitChangesAsync(), Times.Once); service.MockUserRepository.ResetCalls(); Assert.NotNull(account.OrganizationMigrationRequest); Assert.Equal(account, account.OrganizationMigrationRequest.NewOrganization); Assert.Equal(admin, account.OrganizationMigrationRequest.AdminUser); Assert.False(String.IsNullOrEmpty(account.OrganizationMigrationRequest.ConfirmationToken)); if (testOverwrite) { admin = CreateAdminUser(); } } } private User CreateAdminUser() { var admin = new User($"Admin-{DateTime.UtcNow.Ticks}"); admin.Credentials.Add( new CredentialBuilder().CreateExternalCredential( issuer: "MicrosoftAccount", value: "abc123", identity: "Admin", tenantId: "zyx987")); return admin; } } public class TheTransformToOrganizationAccountMethod { private TestableUserService _service = new TestableUserService(); private const string TransformedUsername = "Account"; private const string AdminUsername = "Admin"; private const string Token = "token"; [Fact] public async Task WhenThereIsNoMigrationRequest_Fails() { Assert.False(await InvokeTransformUserToOrganization( 3, migrationRequest: null, admin: new User(AdminUsername) { Credentials = new Credential[0] })); } [Fact] public async Task WhenAdminUserDoesNotMatch_Fails() { Assert.False(await InvokeTransformUserToOrganization( 3, new OrganizationMigrationRequest { AdminUser = new User(AdminUsername) { Key = 1, Credentials = new Credential[0] }, ConfirmationToken = Token, RequestDate = DateTime.UtcNow }, admin: new User("OtherAdmin") { Key = 2, Credentials = new Credential[0] })); } [Fact] public async Task WhenTokenDoesNotMatch_Fails() { var admin = new User(AdminUsername) { Credentials = new Credential[0] }; Assert.False(await InvokeTransformUserToOrganization( 3, new OrganizationMigrationRequest { AdminUser = admin, ConfirmationToken = "othertoken", RequestDate = DateTime.UtcNow }, admin)); } [Fact] public async Task WhenAdminHasNoTenant_TransformsAccountWithoutPolicy() { var tenantlessAdminUsername = "adminWithNoTenant"; Assert.True(await InvokeTransformUserToOrganization(3, new User(tenantlessAdminUsername) { Credentials = new Credential[0] })); Assert.True(_service.Auditing.WroteRecord<UserAuditRecord>(ar => ar.Action == AuditedUserAction.TransformOrganization && ar.Username == TransformedUsername && ar.AffectedMemberUsername == tenantlessAdminUsername && ar.AffectedMemberIsAdmin == true)); } [Fact] public async Task WhenAdminHasUnsupportedTenant_TransformsAccountWithoutPolicy() { var mockLoginDiscontinuationConfiguration = new Mock<ILoginDiscontinuationConfiguration>(); mockLoginDiscontinuationConfiguration .Setup(x => x.IsTenantIdPolicySupportedForOrganization(It.IsAny<string>(), It.IsAny<string>())) .Returns(false); _service.MockConfigObjectService .Setup(x => x.LoginDiscontinuationConfiguration) .Returns(mockLoginDiscontinuationConfiguration.Object); Assert.True(await InvokeTransformUserToOrganization(3)); Assert.True(_service.Auditing.WroteRecord<UserAuditRecord>(ar => ar.Action == AuditedUserAction.TransformOrganization && ar.Username == TransformedUsername && ar.AffectedMemberUsername == AdminUsername && ar.AffectedMemberIsAdmin == true)); } [Fact] public async Task WhenAdminHasSupportedTenant_TransformsAccountWithPolicy() { var mockLoginDiscontinuationConfiguration = new Mock<ILoginDiscontinuationConfiguration>(); mockLoginDiscontinuationConfiguration .Setup(x => x.IsTenantIdPolicySupportedForOrganization(It.IsAny<string>(), It.IsAny<string>())) .Returns(true); _service.MockConfigObjectService .Setup(x => x.LoginDiscontinuationConfiguration) .Returns(mockLoginDiscontinuationConfiguration.Object); Assert.True(await InvokeTransformUserToOrganization(3, subscribesToPolicy: true)); Assert.True(_service.Auditing.WroteRecord<UserAuditRecord>(ar => ar.Action == AuditedUserAction.TransformOrganization && ar.Username == TransformedUsername && ar.AffectedMemberUsername == AdminUsername && ar.AffectedMemberIsAdmin == true)); } [Theory] [InlineData(0)] [InlineData(-1)] public async Task WhenSqlResultIsZeroOrLess_ReturnsFalse(int affectedRecords) { var mockLoginDiscontinuationConfiguration = new Mock<ILoginDiscontinuationConfiguration>(); mockLoginDiscontinuationConfiguration .Setup(x => x.IsTenantIdPolicySupportedForOrganization(It.IsAny<string>(), It.IsAny<string>())) .Returns(false); _service.MockConfigObjectService .Setup(x => x.LoginDiscontinuationConfiguration) .Returns(mockLoginDiscontinuationConfiguration.Object); Assert.False(await InvokeTransformUserToOrganization(affectedRecords)); Assert.False(_service.Auditing.WroteRecord<UserAuditRecord>()); } [Theory] [InlineData(1)] [InlineData(3)] public async Task WhenSqlResultIsPositive_ReturnsTrue(int affectedRecords) { var mockLoginDiscontinuationConfiguration = new Mock<ILoginDiscontinuationConfiguration>(); mockLoginDiscontinuationConfiguration .Setup(x => x.IsTenantIdPolicySupportedForOrganization(It.IsAny<string>(), It.IsAny<string>())) .Returns(false); _service.MockConfigObjectService .Setup(x => x.LoginDiscontinuationConfiguration) .Returns(mockLoginDiscontinuationConfiguration.Object); Assert.True(await InvokeTransformUserToOrganization(affectedRecords)); Assert.True(_service.Auditing.WroteRecord<UserAuditRecord>(ar => ar.Action == AuditedUserAction.TransformOrganization && ar.Username == TransformedUsername && ar.AffectedMemberUsername == AdminUsername && ar.AffectedMemberIsAdmin == true)); } private Task<bool> InvokeTransformUserToOrganization( int affectedRecords, User admin = null, bool subscribesToPolicy = false) { admin = admin ?? new User(AdminUsername) { Credentials = new Credential[] { new CredentialBuilder().CreateExternalCredential( issuer: "AzureActiveDirectory", value: "abc123", identity: "Admin", tenantId: "zyx987") } }; var migrationRequest = new OrganizationMigrationRequest { AdminUser = admin, ConfirmationToken = Token, RequestDate = DateTime.UtcNow, }; return InvokeTransformUserToOrganization(affectedRecords, migrationRequest, admin, subscribesToPolicy); } private Task<bool> InvokeTransformUserToOrganization( int affectedRecords, OrganizationMigrationRequest migrationRequest, User admin, bool subscribesToPolicy = false) { // Arrange var account = new User(TransformedUsername); account.OrganizationMigrationRequest = migrationRequest; _service.MockDatabase .Setup(db => db.ExecuteSqlResourceAsync(It.IsAny<string>(), It.IsAny<object[]>())) .Returns(Task.FromResult(affectedRecords)); // Act var result = _service.TransformUserToOrganization(account, admin, "token"); _service.MockSecurityPolicyService .Verify( sp => sp.SubscribeAsync(It.IsAny<User>(), It.IsAny<IUserSecurityPolicySubscription>(), true), subscribesToPolicy ? Times.Once() : Times.Never()); return result; } } public class TheAddOrganizationAccountMethod { private const string OrgName = "myOrg"; private const string OrgEmail = "myOrg@myOrg.com"; private const string AdminName = "orgAdmin"; private static DateTime OrgCreatedUtc = new DateTime(2018, 2, 21); private TestableUserService _service = new TestableUserService(); public static IEnumerable<object[]> ConfirmEmailAddresses_Config => MemberDataHelper.AsDataSet(false, true); [Theory] [MemberData(nameof(ConfirmEmailAddresses_Config))] public async Task WithUsernameConflict_ThrowsEntityException(bool confirmEmailAddresses) { var conflictUsername = "ialreadyexist"; SetUpConfirmEmailAddressesConfig(confirmEmailAddresses); _service.MockEntitiesContext .Setup(x => x.Users) .Returns(new[] { new User(conflictUsername) }.MockDbSet().Object); var exception = await Assert.ThrowsAsync<EntityException>(() => InvokeAddOrganization(orgName: conflictUsername)); Assert.Equal(String.Format(CultureInfo.CurrentCulture, Strings.UsernameNotAvailable, conflictUsername), exception.Message); _service.MockOrganizationRepository.Verify(x => x.InsertOnCommit(It.IsAny<Organization>()), Times.Never()); _service.MockSecurityPolicyService.Verify(sp => sp.SubscribeAsync(It.IsAny<User>(), It.IsAny<IUserSecurityPolicySubscription>(), false), Times.Never()); _service.MockEntitiesContext.Verify(x => x.SaveChangesAsync(), Times.Never()); Assert.False(_service.Auditing.WroteRecord<UserAuditRecord>()); } [Theory] [MemberData(nameof(ConfirmEmailAddresses_Config))] public async Task WithEmailConflict_ThrowsEntityException(bool confirmEmailAddresses) { var conflictEmail = "ialreadyexist@existence.com"; SetUpConfirmEmailAddressesConfig(confirmEmailAddresses); _service.MockEntitiesContext .Setup(x => x.Users) .Returns(new[] { new User("user") { EmailAddress = conflictEmail } }.MockDbSet().Object); var exception = await Assert.ThrowsAsync<EntityException>(() => InvokeAddOrganization(orgEmail: conflictEmail)); Assert.Equal(String.Format(CultureInfo.CurrentCulture, Strings.EmailAddressBeingUsed, conflictEmail), exception.Message); _service.MockOrganizationRepository.Verify(x => x.InsertOnCommit(It.IsAny<Organization>()), Times.Never()); _service.MockSecurityPolicyService.Verify(sp => sp.SubscribeAsync(It.IsAny<User>(), It.IsAny<IUserSecurityPolicySubscription>(), false), Times.Never()); _service.MockEntitiesContext.Verify(x => x.SaveChangesAsync(), Times.Never()); Assert.False(_service.Auditing.WroteRecord<UserAuditRecord>()); } [Theory] [MemberData(nameof(ConfirmEmailAddresses_Config))] public async Task WhenAdminHasNoTenant_ReturnsNewOrgWithoutPolicy(bool confirmEmailAddresses) { _service.MockEntitiesContext .Setup(x => x.Users) .Returns(Enumerable.Empty<User>().MockDbSet().Object); SetUpConfirmEmailAddressesConfig(confirmEmailAddresses); var org = await InvokeAddOrganization(admin: new User(AdminName) { Credentials = new Credential[0] }); AssertNewOrganizationReturned(org, subscribedToPolicy: false, confirmEmailAddresses: confirmEmailAddresses); } [Theory] [MemberData(nameof(ConfirmEmailAddresses_Config))] public async Task WhenAdminHasUnsupportedTenant_ReturnsNewOrgWithoutPolicy(bool confirmEmailAddresses) { _service.MockEntitiesContext .Setup(x => x.Users) .Returns(Enumerable.Empty<User>().MockDbSet().Object); SetUpConfirmEmailAddressesConfig(confirmEmailAddresses); var mockLoginDiscontinuationConfiguration = new Mock<ILoginDiscontinuationConfiguration>(); mockLoginDiscontinuationConfiguration .Setup(x => x.IsTenantIdPolicySupportedForOrganization(It.IsAny<string>(), It.IsAny<string>())) .Returns(false); _service.MockConfigObjectService .Setup(x => x.LoginDiscontinuationConfiguration) .Returns(mockLoginDiscontinuationConfiguration.Object); var org = await InvokeAddOrganization(); AssertNewOrganizationReturned(org, subscribedToPolicy: false, confirmEmailAddresses: confirmEmailAddresses); } [Theory] [MemberData(nameof(ConfirmEmailAddresses_Config))] public async Task WhenSubscribingToPolicyFails_ReturnsNewOrgWithoutPolicy(bool confirmEmailAddresses) { _service.MockEntitiesContext .Setup(x => x.Users) .Returns(Enumerable.Empty<User>().MockDbSet().Object); SetUpConfirmEmailAddressesConfig(confirmEmailAddresses); var mockLoginDiscontinuationConfiguration = new Mock<ILoginDiscontinuationConfiguration>(); mockLoginDiscontinuationConfiguration .Setup(x => x.IsTenantIdPolicySupportedForOrganization(It.IsAny<string>(), It.IsAny<string>())) .Returns(true); _service.MockConfigObjectService .Setup(x => x.LoginDiscontinuationConfiguration) .Returns(mockLoginDiscontinuationConfiguration.Object); _service.MockSecurityPolicyService .Setup(sp => sp.SubscribeAsync(It.IsAny<User>(), It.IsAny<IUserSecurityPolicySubscription>(), false)) .Returns(Task.FromResult(false)); var org = await InvokeAddOrganization(); AssertNewOrganizationReturned(org, subscribedToPolicy: true, confirmEmailAddresses: confirmEmailAddresses); } [Theory] [MemberData(nameof(ConfirmEmailAddresses_Config))] public async Task WhenSubscribingToPolicySucceeds_ReturnsNewOrg(bool confirmEmailAddresses) { _service.MockEntitiesContext .Setup(x => x.Users) .Returns(Enumerable.Empty<User>().MockDbSet().Object); SetUpConfirmEmailAddressesConfig(confirmEmailAddresses); var mockLoginDiscontinuationConfiguration = new Mock<ILoginDiscontinuationConfiguration>(); mockLoginDiscontinuationConfiguration .Setup(x => x.IsTenantIdPolicySupportedForOrganization(It.IsAny<string>(), It.IsAny<string>())) .Returns(true); _service.MockConfigObjectService .Setup(x => x.LoginDiscontinuationConfiguration) .Returns(mockLoginDiscontinuationConfiguration.Object); _service.MockSecurityPolicyService .Setup(sp => sp.SubscribeAsync(It.IsAny<User>(), It.IsAny<IUserSecurityPolicySubscription>(), false)) .Returns(Task.FromResult(true)); var org = await InvokeAddOrganization(); AssertNewOrganizationReturned(org, subscribedToPolicy: true, confirmEmailAddresses: confirmEmailAddresses); } private Task<Organization> InvokeAddOrganization(string orgName = OrgName, string orgEmail = OrgEmail, User admin = null) { // Arrange admin = admin ?? new User(AdminName) { Credentials = new Credential[] { new CredentialBuilder().CreateExternalCredential( issuer: "AzureActiveDirectory", value: "abc123", identity: "Admin", tenantId: "zyx987") } }; _service.MockDateTimeProvider .Setup(x => x.UtcNow) .Returns(OrgCreatedUtc); // Act return _service.AddOrganizationAsync(orgName, orgEmail, admin); } private void AssertNewOrganizationReturned(Organization org, bool subscribedToPolicy, bool confirmEmailAddresses) { Assert.Equal(OrgName, org.Username); if (confirmEmailAddresses) { Assert.Null(org.EmailAddress); Assert.Equal(OrgEmail, org.UnconfirmedEmailAddress); Assert.NotNull(org.EmailConfirmationToken); } else { Assert.Null(org.UnconfirmedEmailAddress); Assert.Equal(OrgEmail, org.EmailAddress); Assert.Null(org.EmailConfirmationToken); } Assert.Equal(OrgCreatedUtc, org.CreatedUtc); Assert.True(org.EmailAllowed); Assert.True(org.NotifyPackagePushed); // Both the organization and the admin must have a membership to each other. Func<Membership, bool> hasMembership = m => m.Member.Username == AdminName && m.Organization.Username == OrgName && m.IsAdmin; Assert.Contains(org.Members, m => hasMembership(m) && m.Member.Organizations.Any(hasMembership)); _service.MockOrganizationRepository.Verify(x => x.InsertOnCommit(It.IsAny<Organization>()), Times.Once()); _service.MockSecurityPolicyService.Verify( sp => sp.SubscribeAsync(It.IsAny<User>(), It.IsAny<IUserSecurityPolicySubscription>(), false), subscribedToPolicy ? Times.Once() : Times.Never()); Assert.True(_service.Auditing.WroteRecord<UserAuditRecord>(ar => ar.Action == AuditedUserAction.AddOrganization && ar.Username == org.Username && ar.AffectedMemberUsername == AdminName && ar.AffectedMemberIsAdmin == true)); _service.MockEntitiesContext.Verify(x => x.SaveChangesAsync(), Times.Once()); } private void SetUpConfirmEmailAddressesConfig(bool confirmEmailAddresses) { _service.MockConfig .Setup(x => x.ConfirmEmailAddresses) .Returns(confirmEmailAddresses); } } public class TheRejectTransformUserToOrganizationRequestMethod { public async Task IfNoExistingRequest_ReturnsFalse() { var accountToTransform = new User("norequest"); var service = new TestableUserService(); var result = await service.RejectTransformUserToOrganizationRequest(accountToTransform, null, null); Assert.False(result); service.MockUserRepository.Verify(x => x.CommitChangesAsync(), Times.Never); } public async Task IfAdminUserNull_ReturnsFalse() { var accountToTransform = new User("hasrequest") { OrganizationMigrationRequest = new OrganizationMigrationRequest() }; var service = new TestableUserService(); var result = await service.RejectTransformUserToOrganizationRequest(accountToTransform, null, null); Assert.False(result); service.MockUserRepository.Verify(x => x.CommitChangesAsync(), Times.Never); } public async Task IfAdminUserDoesntMatchRequest_ReturnsFalse() { var admin = new User("requestAdmin"); var wrongAdmin = new User("admin"); var accountToTransform = new User("hasrequest") { OrganizationMigrationRequest = new OrganizationMigrationRequest { AdminUser = admin } }; var service = new TestableUserService(); var result = await service.RejectTransformUserToOrganizationRequest(accountToTransform, wrongAdmin, null); Assert.False(result); service.MockUserRepository.Verify(x => x.CommitChangesAsync(), Times.Never); } public async Task IfTokenDoesntMatch_ReturnsFalse() { var admin = new User("admin"); var accountToTransform = new User("hasrequest") { OrganizationMigrationRequest = new OrganizationMigrationRequest { AdminUser = admin, ConfirmationToken = "token" } }; var service = new TestableUserService(); var result = await service.RejectTransformUserToOrganizationRequest(accountToTransform, admin, "wrongToken"); Assert.False(result); service.MockUserRepository.Verify(x => x.CommitChangesAsync(), Times.Never); } public async Task IfTokenMatches_RemovesRequest() { var token = "token"; var admin = new User("admin"); var accountToTransform = new User("hasrequest") { OrganizationMigrationRequest = new OrganizationMigrationRequest { AdminUser = admin, ConfirmationToken = token } }; var service = new TestableUserService(); var result = await service.RejectTransformUserToOrganizationRequest(accountToTransform, admin, token); Assert.True(result); Assert.Null(accountToTransform.OrganizationMigrationRequest); service.MockUserRepository.Verify(x => x.CommitChangesAsync(), Times.Once); } } public class TheGetSiteAdminsMethod { [Fact] public void ReturnsExpectedUsers() { var adminRole = new Role { Key = 0, Name = Constants.AdminRoleName }; var notAdminUser = new User { Username = "notAdminUser", Key = 1, EmailAddress = "notAdminUser@example.org" }; var notAdminDeletedUser = new User { Username = "notAdminDeletedUser", Key = 1, EmailAddress = "notAdminDeletedUser@example.org" }; var adminUser = new User { Username = "adminUser", Key = 1, EmailAddress = "adminUser@example.org" }; adminRole.Users.Add(adminUser); adminUser.Roles.Add(adminRole); var adminDeletedUser = new User { Username = "adminDeletedUser", Key = 1, EmailAddress = "adminDeletedUser@example.org" }; adminRole.Users.Add(adminDeletedUser); adminDeletedUser.Roles.Add(adminRole); var service = new TestableUserServiceWithDBFaking { Users = new[] { notAdminUser, notAdminDeletedUser, adminUser, adminDeletedUser }, Roles = new[] { adminRole } }; var result = service.GetSiteAdmins(); Assert.Equal(1, result.Count); Assert.Equal(adminUser, result.Single()); } } public class TheSetIsAdministratorMethod { [Theory] [InlineData(false)] [InlineData(true)] public Task ThrowsArgumentNullExceptionIfUserNull(bool isAdmin) { var service = new TestableUserService(); return Assert.ThrowsAsync<ArgumentNullException>(() => service.SetIsAdministrator(null, isAdmin)); } [Theory] [InlineData(false)] [InlineData(true)] public Task ThrowsInvalidOperationExceptionIfRoleNull(bool isAdmin) { var user = new User(); var service = new TestableUserService(); return Assert.ThrowsAsync<InvalidOperationException>(() => service.SetIsAdministrator(user, isAdmin)); } [Fact] public async Task AddsAdminCorrectly() { // Arrange var adminRole = new Role { Key = 0, Name = Constants.AdminRoleName }; var user = new User { Username = "user", Key = 1, EmailAddress = "user@example.org" }; var service = new TestableUserServiceWithDBFaking { Users = new[] { user }, Roles = new[] { adminRole } }; // Act await service.SetIsAdministrator(user, true); // Assert service.FakeEntitiesContext.VerifyCommitChanges(); Assert.Contains(user, adminRole.Users); Assert.Contains(adminRole, user.Roles); } [Fact] public async Task RemovesAdminCorrectly() { // Arrange var adminRole = new Role { Key = 0, Name = Constants.AdminRoleName }; var user = new User { Username = "user", Key = 1, EmailAddress = "user@example.org" }; adminRole.Users.Add(user); user.Roles.Add(adminRole); var service = new TestableUserServiceWithDBFaking { Users = new[] { user }, Roles = new[] { adminRole } }; // Act await service.SetIsAdministrator(user, false); // Assert service.FakeEntitiesContext.VerifyCommitChanges(); Assert.DoesNotContain(user, adminRole.Users); Assert.DoesNotContain(adminRole, user.Roles); } } } }
41.519214
212
0.548249
[ "Apache-2.0" ]
Acidburn0zzz/NuGetGallery
tests/NuGetGallery.Facts/Services/UserServiceFacts.cs
95,081
C#
//----------------------------------------------------------------------- // <copyright file="ObjectFactoryTests.cs" company="Marimer LLC"> // Copyright (c) Marimer LLC. All rights reserved. // Website: https://cslanet.com // </copyright> // <summary>Always make sure to cleanup after each test </summary> //----------------------------------------------------------------------- using System; using System.Configuration; using System.Collections.Generic; using System.Linq; using System.Text; #if !NUNIT using Microsoft.VisualStudio.TestTools.UnitTesting; #else using NUnit.Framework; using TestClass = NUnit.Framework.TestFixtureAttribute; using TestInitialize = NUnit.Framework.SetUpAttribute; using TestCleanup = NUnit.Framework.TearDownAttribute; using TestMethod = NUnit.Framework.TestAttribute; #endif namespace Csla.Test.ObjectFactory { [TestClass] public class ObjectFactoryTests { /// <summary> /// Always make sure to cleanup after each test /// </summary> [TestCleanup] public void Cleanup() { Csla.ApplicationContext.User = new System.Security.Principal.GenericPrincipal( new System.Security.Principal.GenericIdentity(string.Empty), new string[] { }); Csla.ApplicationContext.DataPortalProxy = "Local"; Csla.DataPortal.ResetProxyType(); Csla.Server.FactoryDataPortal.FactoryLoader = null; Csla.ApplicationContext.GlobalContext.Clear(); } [TestMethod] [TestCategory("SkipWhenLiveUnitTesting")] public void Create() { Csla.ApplicationContext.User = new System.Security.Claims.ClaimsPrincipal(); Csla.ApplicationContext.DataPortalProxy = "Csla.Testing.Business.TestProxies.AppDomainProxy, Csla.Testing.Business"; Csla.Server.FactoryDataPortal.FactoryLoader = new ObjectFactoryLoader(); var root = Csla.DataPortal.Create<Root>(); Assert.AreEqual("Create", root.Data, "Data should match"); Assert.AreEqual(Csla.ApplicationContext.ExecutionLocations.Server, root.Location, "Location should match"); Assert.IsTrue(root.IsNew, "Should be new"); Assert.IsTrue(root.IsDirty, "Should be dirty"); } [TestMethod] public void CreateLocal() { Csla.ApplicationContext.DataPortalProxy = "Csla.Testing.Business.TestProxies.AppDomainProxy, Csla.Testing.Business"; Csla.Server.FactoryDataPortal.FactoryLoader = new ObjectFactoryLoader(8); var root = Csla.DataPortal.Create<Root>("abc"); Assert.AreEqual("Create abc", root.Data, "Data should match"); Assert.AreEqual(Csla.ApplicationContext.ExecutionLocations.Client, root.Location, "Location should match"); Assert.IsTrue(root.IsNew, "Should be new"); Assert.IsTrue(root.IsDirty, "Should be dirty"); } [TestMethod] public void CreateWithParam() { Csla.ApplicationContext.User = new System.Security.Claims.ClaimsPrincipal(); Csla.ApplicationContext.DataPortalProxy = "Csla.Testing.Business.TestProxies.AppDomainProxy, Csla.Testing.Business"; Csla.Server.FactoryDataPortal.FactoryLoader = new ObjectFactoryLoader(); var root = Csla.DataPortal.Create<Root>("abc"); Assert.AreEqual("Create abc", root.Data, "Data should match"); Assert.AreEqual(Csla.ApplicationContext.ExecutionLocations.Client, root.Location, "Location should match"); Assert.IsTrue(root.IsNew, "Should be new"); Assert.IsTrue(root.IsDirty, "Should be dirty"); } // this test needs to be updated when the factory model is updated // to use DI and multi-property criteria [Ignore] [TestMethod] [ExpectedException(typeof(MissingMethodException))] public void CreateMissing() { Csla.ApplicationContext.User = new System.Security.Claims.ClaimsPrincipal(); Csla.ApplicationContext.DataPortalProxy = "Csla.Testing.Business.TestProxies.AppDomainProxy, Csla.Testing.Business"; Csla.Server.FactoryDataPortal.FactoryLoader = new ObjectFactoryLoader(1); try { var root = Csla.DataPortal.Create<Root>("abc", 123); } catch (DataPortalException ex) { throw ex.BusinessException; } } [TestMethod] public void FetchNoCriteria() { Csla.Server.FactoryDataPortal.FactoryLoader = new ObjectFactoryLoader(); var root = Csla.DataPortal.Fetch<Root>(); Assert.AreEqual("Fetch", root.Data, "Data should match"); Assert.IsFalse(root.IsNew, "Should not be new"); Assert.IsFalse(root.IsDirty, "Should not be dirty"); } [TestMethod] public void FetchCriteria() { Csla.Server.FactoryDataPortal.FactoryLoader = new ObjectFactoryLoader(); var root = Csla.DataPortal.Fetch<Root>("abc"); Assert.AreEqual("abc", root.Data, "Data should match"); Assert.IsFalse(root.IsNew, "Should not be new"); Assert.IsFalse(root.IsDirty, "Should not be dirty"); } [TestMethod] public void Update() { Csla.Server.FactoryDataPortal.FactoryLoader = new ObjectFactoryLoader(); var root = new Root(); root.Data = "abc"; root = Csla.DataPortal.Update<Root>(root); Assert.AreEqual(TransactionalTypes.Manual, root.TransactionalType, "Transactional type should match"); Assert.AreEqual("Update", root.Data, "Data should match"); Assert.IsFalse(root.IsNew, "Should not be new"); Assert.IsFalse(root.IsDirty, "Should not be dirty"); } [TestMethod] public void UpdateTransactionScope() { Csla.Server.FactoryDataPortal.FactoryLoader = new ObjectFactoryLoader(1); var root = new Root(); root.Data = "abc"; root = Csla.DataPortal.Update<Root>(root); Assert.AreEqual(TransactionalTypes.TransactionScope, root.TransactionalType, "Transactional type should match"); Assert.AreEqual("Serializable", root.IsolationLevel, "Transactional isolation should match"); Assert.AreEqual(30, root.TransactionTimeout, "Transactional timeout should match"); Assert.AreEqual("Update", root.Data, "Data should match"); Assert.IsFalse(root.IsNew, "Should not be new"); Assert.IsFalse(root.IsDirty, "Should not be dirty"); } [TestMethod] public void UpdateTransactionScopeUsingCustomTransactionLevelAndTimeout() { ApplicationContext.DefaultTransactionIsolationLevel = TransactionIsolationLevel.RepeatableRead; ApplicationContext.DefaultTransactionTimeoutInSeconds = 45; Csla.Server.FactoryDataPortal.FactoryLoader = new ObjectFactoryLoader(4); var root = new Root(); root.Data = "abc"; root = Csla.DataPortal.Update<Root>(root); Assert.AreEqual(TransactionalTypes.TransactionScope, root.TransactionalType, "Transactional type should match"); Assert.AreEqual("ReadCommitted", root.IsolationLevel, "Transactional isolation should match"); Assert.AreEqual(100, root.TransactionTimeout, "Transactional timeout should match"); Assert.AreEqual("Update", root.Data, "Data should match"); Assert.IsFalse(root.IsNew, "Should not be new"); Assert.IsFalse(root.IsDirty, "Should not be dirty"); } [TestMethod] public void UpdateTransactionScopeUsingDefaultTransactionLevelAndTimeout() { ApplicationContext.DefaultTransactionIsolationLevel = TransactionIsolationLevel.RepeatableRead; ApplicationContext.DefaultTransactionTimeoutInSeconds = 45; Csla.Server.FactoryDataPortal.FactoryLoader = new ObjectFactoryLoader(5); var root = new Root(); root.Data = "abc"; root = Csla.DataPortal.Update<Root>(root); Assert.AreEqual(TransactionalTypes.TransactionScope, root.TransactionalType, "Transactional type should match"); Assert.AreEqual("RepeatableRead", root.IsolationLevel, "Transactional isolation should match"); Assert.AreEqual(45, root.TransactionTimeout, "Transactional timeout should match"); Assert.AreEqual("Update", root.Data, "Data should match"); Assert.IsFalse(root.IsNew, "Should not be new"); Assert.IsFalse(root.IsDirty, "Should not be dirty"); } #if DEBUG [TestMethod] [Ignore] public void UpdateEnerpriseServicesTransactionCustomTransactionLevel() { ApplicationContext.DefaultTransactionIsolationLevel = TransactionIsolationLevel.RepeatableRead; Csla.Server.FactoryDataPortal.FactoryLoader = new ObjectFactoryLoader(6); var root = new Root(); root.Data = "abc"; root = Csla.DataPortal.Update<Root>(root); Assert.AreEqual(TransactionalTypes.EnterpriseServices, root.TransactionalType, "Transactional type should match"); Assert.AreEqual("ReadCommitted", root.IsolationLevel, "Transactional isolation should match"); Assert.AreEqual("Update", root.Data, "Data should match"); Assert.IsFalse(root.IsNew, "Should not be new"); Assert.IsFalse(root.IsDirty, "Should not be dirty"); } [TestMethod] [Ignore] public void UpdateEnerpriseServicesTransactionDefaultTransactionLevel() { ApplicationContext.DefaultTransactionIsolationLevel = TransactionIsolationLevel.RepeatableRead; Csla.Server.FactoryDataPortal.FactoryLoader = new ObjectFactoryLoader(7); var root = new Root(); root.Data = "abc"; root = Csla.DataPortal.Update<Root>(root); Assert.AreEqual(TransactionalTypes.EnterpriseServices, root.TransactionalType, "Transactional type should match"); Assert.AreEqual("RepeatableRead", root.IsolationLevel, "Transactional isolation should match"); Assert.AreEqual("Update", root.Data, "Data should match"); Assert.IsFalse(root.IsNew, "Should not be new"); Assert.IsFalse(root.IsDirty, "Should not be dirty"); } #endif [TestMethod] public void Delete() { Csla.ApplicationContext.GlobalContext.Clear(); Csla.Server.FactoryDataPortal.FactoryLoader = new ObjectFactoryLoader(); Csla.DataPortal.Delete<Root>("abc"); Assert.AreEqual("Delete", Csla.ApplicationContext.GlobalContext["ObjectFactory"].ToString(), "Data should match"); } [TestMethod] public void FetchLoadProperty() { Csla.Server.FactoryDataPortal.FactoryLoader = new ObjectFactoryLoader(3); var root = Csla.DataPortal.Fetch<Root>(); Assert.AreEqual("Fetch", root.Data, "Data should match"); Assert.IsFalse(root.IsNew, "Should not be new"); Assert.IsFalse(root.IsDirty, "Should not be dirty"); } [TestMethod] public void DataPortalExecute_OnCommandObjectWithLocalProxy_CallsFactoryExecute() { Csla.ApplicationContext.GlobalContext.Clear(); Csla.Server.FactoryDataPortal.FactoryLoader = null; var test = CommandObject.Execute(); // return value is set in Execute method in CommandObjectFactory Assert.IsTrue(test); } [TestMethod] [ExpectedException(typeof(DataPortalException))] public void DataPortalExecute_OnCommandObjectWithFalseExecuteMethod_ThrowsExeptionMehodNotFound() { try { Csla.ApplicationContext.GlobalContext.Clear(); Csla.Server.FactoryDataPortal.FactoryLoader = null; var test = CommandObjectMissingFactoryMethod.Execute(); } catch (DataPortalException ex) { // inner exception should be System.NotImplementedException and mesaage should contain methodname Assert.AreEqual(typeof(System.NotImplementedException), ex.InnerException.GetType()); Assert.IsTrue(ex.InnerException.Message.Contains("ExecuteMissingMethod")); // rethrow exception throw; } Assert.Fail("Should throw exception"); } } }
39.668919
122
0.697837
[ "MIT" ]
BaHXeLiSiHg/csla
Source/Csla.test/ObjectFactory/ObjectFactoryTests.cs
11,744
C#
/* * Copyright (c) 2018 THL A29 Limited, a Tencent company. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ namespace TencentCloud.Bmvpc.V20180625.Models { using Newtonsoft.Json; using System.Collections.Generic; using TencentCloud.Common; public class DescribeSubnetByDeviceResponse : AbstractModel { /// <summary> /// 子网个数 /// </summary> [JsonProperty("TotalCount")] public ulong? TotalCount{ get; set; } /// <summary> /// 子网列表 /// </summary> [JsonProperty("Data")] public SubnetInfo[] Data{ get; set; } /// <summary> /// 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 /// </summary> [JsonProperty("RequestId")] public string RequestId{ get; set; } /// <summary> /// For internal usage only. DO NOT USE IT. /// </summary> internal override void ToMap(Dictionary<string, string> map, string prefix) { this.SetParamSimple(map, prefix + "TotalCount", this.TotalCount); this.SetParamArrayObj(map, prefix + "Data.", this.Data); this.SetParamSimple(map, prefix + "RequestId", this.RequestId); } } }
30.603448
83
0.627606
[ "Apache-2.0" ]
ImEdisonJiang/tencentcloud-sdk-dotnet
TencentCloud/Bmvpc/V20180625/Models/DescribeSubnetByDeviceResponse.cs
1,849
C#
using System; using System.Linq; using System.IO; using System.Text; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using PureCloudPlatform.Client.V2.Client; namespace PureCloudPlatform.Client.V2.Model { /// <summary> /// QueueConversationEventTopicJourneyAction /// </summary> [DataContract] public partial class QueueConversationEventTopicJourneyAction : IEquatable<QueueConversationEventTopicJourneyAction> { /// <summary> /// Initializes a new instance of the <see cref="QueueConversationEventTopicJourneyAction" /> class. /// </summary> /// <param name="Id">Id.</param> /// <param name="ActionMap">ActionMap.</param> public QueueConversationEventTopicJourneyAction(string Id = null, QueueConversationEventTopicJourneyActionMap ActionMap = null) { this.Id = Id; this.ActionMap = ActionMap; } /// <summary> /// Gets or Sets Id /// </summary> [DataMember(Name="id", EmitDefaultValue=false)] public string Id { get; set; } /// <summary> /// Gets or Sets ActionMap /// </summary> [DataMember(Name="actionMap", EmitDefaultValue=false)] public QueueConversationEventTopicJourneyActionMap ActionMap { 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 QueueConversationEventTopicJourneyAction {\n"); sb.Append(" Id: ").Append(Id).Append("\n"); sb.Append(" ActionMap: ").Append(ActionMap).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 string ToJson() { return JsonConvert.SerializeObject(this, Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="obj">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object obj) { // credit: http://stackoverflow.com/a/10454552/677735 return this.Equals(obj as QueueConversationEventTopicJourneyAction); } /// <summary> /// Returns true if QueueConversationEventTopicJourneyAction instances are equal /// </summary> /// <param name="other">Instance of QueueConversationEventTopicJourneyAction to be compared</param> /// <returns>Boolean</returns> public bool Equals(QueueConversationEventTopicJourneyAction other) { // credit: http://stackoverflow.com/a/10454552/677735 if (other == null) return false; return true && ( this.Id == other.Id || this.Id != null && this.Id.Equals(other.Id) ) && ( this.ActionMap == other.ActionMap || this.ActionMap != null && this.ActionMap.Equals(other.ActionMap) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { // credit: http://stackoverflow.com/a/263416/677735 unchecked // Overflow is fine, just wrap { int hash = 41; // Suitable nullity checks etc, of course :) if (this.Id != null) hash = hash * 59 + this.Id.GetHashCode(); if (this.ActionMap != null) hash = hash * 59 + this.ActionMap.GetHashCode(); return hash; } } } }
31.013699
135
0.53136
[ "MIT" ]
nmusco/platform-client-sdk-dotnet
build/src/PureCloudPlatform.Client.V2/Model/QueueConversationEventTopicJourneyAction.cs
4,528
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ [assembly: global::Xamarin.Forms.Xaml.XamlResourceIdAttribute("chambaap.Views.InterviewsPage.xaml", "Views/InterviewsPage.xaml", typeof(global::chambaap.Views.InterviewsPage))] namespace chambaap.Views { [global::Xamarin.Forms.Xaml.XamlFilePathAttribute("Views/InterviewsPage.xaml")] public partial class InterviewsPage : global::Xamarin.Forms.ContentPage { [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Xamarin.Forms.Build.Tasks.XamlG", "2.0.0.0")] private global::Xamarin.Forms.SearchBar searcher; [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Xamarin.Forms.Build.Tasks.XamlG", "2.0.0.0")] private void InitializeComponent() { global::Xamarin.Forms.Xaml.Extensions.LoadFromXaml(this, typeof(InterviewsPage)); searcher = global::Xamarin.Forms.NameScopeExtensions.FindByName<global::Xamarin.Forms.SearchBar>(this, "searcher"); } } }
46.793103
176
0.622697
[ "MIT" ]
stbndev/chambapp
chambaap/chambaap/obj/Release/netstandard2.0/Views/InterviewsPage.xaml.g.cs
1,357
C#
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Collections.Generic; using System.Linq; using Hyak.Common; using Microsoft.Azure; using Microsoft.Azure.Management.SiteRecovery.Models; namespace Microsoft.Azure.Management.SiteRecovery.Models { /// <summary> /// The response model for the list servers operation. /// </summary> public partial class RecoveryServicesProviderListResponse : AzureOperationResponse { private string _nextLink; /// <summary> /// Optional. Next Link. /// </summary> public string NextLink { get { return this._nextLink; } set { this._nextLink = value; } } private IList<RecoveryServicesProvider> _recoveryServicesProviders; /// <summary> /// Optional. The list of servers for the given vault. /// </summary> public IList<RecoveryServicesProvider> RecoveryServicesProviders { get { return this._recoveryServicesProviders; } set { this._recoveryServicesProviders = value; } } /// <summary> /// Initializes a new instance of the /// RecoveryServicesProviderListResponse class. /// </summary> public RecoveryServicesProviderListResponse() { this.RecoveryServicesProviders = new LazyList<RecoveryServicesProvider>(); } } }
32.352941
86
0.660909
[ "Apache-2.0" ]
ailn/azure-sdk-for-net
src/ResourceManagement/SiteRecovery/SiteRecoveryManagement/Generated/Models/RecoveryServicesProviderListResponse.cs
2,200
C#
using System; using System.Collections; /// <summary> /// Sign(System.Decimal) /// </summary> public class MathSign1 { public static int Main(string[] args) { MathSign1 test = new MathSign1(); TestLibrary.TestFramework.BeginTestCase("Testing System.Math.Sign(System.Decimal)..."); if (test.RunTests()) { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("PASS"); return 100; } else { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("FAIL"); return 0; } } public bool RunTests() { bool retVal = true; TestLibrary.TestFramework.LogInformation("[Positive]"); retVal = PosTest1() && retVal; retVal = PosTest2() && retVal; retVal = PosTest3() && retVal; retVal = PosTest4() && retVal; retVal = PosTest5() && retVal; retVal = PosTest6() && retVal; retVal = PosTest7() && retVal; return retVal; } public bool PosTest1() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest1: Verify Decimal.MaxValue is a positive number."); try { Decimal dec = Decimal.MaxValue; if (Math.Sign(dec) != 1) { TestLibrary.TestFramework.LogError("P01.1", "Decimal.MaxValue is not a positive number!"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("P01.2", "Unexpected exception occurs: " + e); retVal = false; } return retVal; } public bool PosTest2() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest2: Verify Decimal.MinValue is a negative number."); try { Decimal dec = Decimal.MinValue; if (Math.Sign(dec) != -1) { TestLibrary.TestFramework.LogError("P02.1", "Decimal.MinValue is not a negative number!"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("P02.2", "Unexpected exception occurs: " + e); retVal = false; } return retVal; } public bool PosTest3() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest3: Verify Decimal.One is a positive number."); try { Decimal dec = Decimal.One; if (Math.Sign(dec) != 1) { TestLibrary.TestFramework.LogError("P03.1", "Decimal.One is not a positive number!"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("P03.2", "Unexpected exception occurs: " + e); retVal = false; } return retVal; } public bool PosTest4() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest4: Verify Decimal.MinusOne is a negative number."); try { Decimal dec = Decimal.MinusOne; if (Math.Sign(dec) != -1) { TestLibrary.TestFramework.LogError("P04.1", "Decimal.MinusOne is not a negative number!"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("P04.2", "Unexpected exception occurs: " + e); retVal = false; } return retVal; } public bool PosTest5() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest5: Verify Decimal.Zero is zero."); try { Decimal zero = 0M; if (Math.Sign(zero) != 0) { TestLibrary.TestFramework.LogError("P05.1", "Decimal.Zero is not zero!"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("P05.2", "Unexpected exception occurs: " + e); retVal = false; } return retVal; } public bool PosTest6() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest6: Verify the return value should be 1 when the decimal is positive."); try { Decimal dec = 123.456M; if (Math.Sign(dec) != 1) { TestLibrary.TestFramework.LogError("P06.1", "The return value is not 1 when the decimal is positive!"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("P06.2", "Unexpected exception occurs: " + e); retVal = false; } return retVal; } public bool PosTest7() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest7: Verify the return value should be -1 when the decimal is negative."); try { Decimal dec = -123.456M; if (Math.Sign(dec) != -1) { TestLibrary.TestFramework.LogError("P07.1", "The return value is not -1 when the decimal is negative!"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("P07.2", "Unexpected exception occurs: " + e); retVal = false; } return retVal; } }
27.456311
128
0.526167
[ "MIT" ]
CyberSys/coreclr-mono
tests/src/CoreMangLib/cti/system/math/mathsign1.cs
5,656
C#
using OpenQA.Selenium; using PossumLabs.Specflow.Core.Logging; using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Text; namespace PossumLabs.Specflow.Selenium.Selectors { public class WebElementSourceLog { public WebElementSourceLog() { WebElementSources = new ConcurrentDictionary<IWebElement, WebElementSource>(); Order = 0; } private int Order { get; set; } public class WebElementSource { public WebElementSource(string page, By by, int order) { Page = page; By= by; Order = order; } public string Page { get; } public By By { get; } public string SelectorType { get; set; } public string SelectorConstructor { get; set; } public int Order { get; set; } } public void Add(IWebElement e, string page, By by) { var o = -1; lock (this) o = Order++; WebElementSources.TryAdd(e, new WebElementSource(page, by, o)); } public WebElementSource Get(IWebElement e) { if (WebElementSources.TryGetValue(e, out var value)) return value; return null; } private ConcurrentDictionary<IWebElement, WebElementSource> WebElementSources { get; } public void Log(ILog logger) { logger.Section(this.GetType().Name, new { Elements = WebElementSources.Values .Where(x => x.By != null) .OrderBy(x => x.Order) .Select(x => new { x.Page, x.SelectorType, x.SelectorConstructor, x.By }) }); } } }
27.549296
94
0.513804
[ "MIT" ]
BasHamer/PossumLabs.Specflow.Selenium
PossumLabs.Specflow.Selenium/Selectors/WebElementSourceLog.cs
1,958
C#
using System; using System.Collections.Generic; using System.Dynamic; using System.Linq; using System.Text; using System.Threading.Tasks; using ImpromptuInterface; namespace NullObject { public class Null<T> : DynamicObject where T : class { public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result) { var name = binder.Name; result = Activator.CreateInstance(binder.ReturnType); return true; } public static T Instance { get { if (!typeof(T).IsInterface) { throw new ArgumentException("I must be an interface type"); } return new Null<T>().ActLike<T>(); } } } //usage //var log = Null<ILog>.Instance; //var ba = new BankAccount(log); }
25.222222
105
0.562775
[ "MIT" ]
BetterYan/DesignPatternPractice
Behavioral Patterns/NullObject/3.Dynamic.cs
910
C#
// ------------------------------------------------------------------------------ // <auto-generated> // This code was generated by SpecFlow (https://www.specflow.org/). // SpecFlow Version:3.5.0.0 // SpecFlow Generator Version:3.5.0.0 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> // ------------------------------------------------------------------------------ #region Designer generated code #pragma warning disable namespace SFA.DAS.EmployerIncentives.Api.AcceptanceTests.Features { using TechTalk.SpecFlow; using System; using System.Linq; [System.CodeDom.Compiler.GeneratedCodeAttribute("TechTalk.SpecFlow", "3.5.0.0")] [System.Runtime.CompilerServices.CompilerGeneratedAttribute()] [NUnit.Framework.TestFixtureAttribute()] [NUnit.Framework.DescriptionAttribute("LegalEntityCreated")] [NUnit.Framework.CategoryAttribute("database")] [NUnit.Framework.CategoryAttribute("api")] public partial class LegalEntityCreatedFeature { private TechTalk.SpecFlow.ITestRunner testRunner; private string[] _featureTags = new string[] { "database", "api"}; #line 1 "LegalEntityCreated.feature" #line hidden [NUnit.Framework.OneTimeSetUpAttribute()] public virtual void FeatureSetup() { testRunner = TechTalk.SpecFlow.TestRunnerManager.GetTestRunner(); TechTalk.SpecFlow.FeatureInfo featureInfo = new TechTalk.SpecFlow.FeatureInfo(new System.Globalization.CultureInfo("en-US"), "Features", "LegalEntityCreated", "\tWhen a legal entity has been added to an account\r\n\tThen is is available in Emplo" + "yer Incentives", ProgrammingLanguage.CSharp, new string[] { "database", "api"}); testRunner.OnFeatureStart(featureInfo); } [NUnit.Framework.OneTimeTearDownAttribute()] public virtual void FeatureTearDown() { testRunner.OnFeatureEnd(); testRunner = null; } [NUnit.Framework.SetUpAttribute()] public virtual void TestInitialize() { } [NUnit.Framework.TearDownAttribute()] public virtual void TestTearDown() { testRunner.OnScenarioEnd(); } public virtual void ScenarioInitialize(TechTalk.SpecFlow.ScenarioInfo scenarioInfo) { testRunner.OnScenarioInitialize(scenarioInfo); testRunner.ScenarioContext.ScenarioContainer.RegisterInstanceAs<NUnit.Framework.TestContext>(NUnit.Framework.TestContext.CurrentContext); } public virtual void ScenarioStart() { testRunner.OnScenarioStart(); } public virtual void ScenarioCleanup() { testRunner.CollectScenarioErrors(); } [NUnit.Framework.TestAttribute()] [NUnit.Framework.DescriptionAttribute("A legal entity is added to an account")] public virtual void ALegalEntityIsAddedToAnAccount() { string[] tagsOfScenario = ((string[])(null)); System.Collections.Specialized.OrderedDictionary argumentsOfScenario = new System.Collections.Specialized.OrderedDictionary(); TechTalk.SpecFlow.ScenarioInfo scenarioInfo = new TechTalk.SpecFlow.ScenarioInfo("A legal entity is added to an account", null, tagsOfScenario, argumentsOfScenario); #line 7 this.ScenarioInitialize(scenarioInfo); #line hidden bool isScenarioIgnored = default(bool); bool isFeatureIgnored = default(bool); if ((tagsOfScenario != null)) { isScenarioIgnored = tagsOfScenario.Where(__entry => __entry != null).Where(__entry => String.Equals(__entry, "ignore", StringComparison.CurrentCultureIgnoreCase)).Any(); } if ((this._featureTags != null)) { isFeatureIgnored = this._featureTags.Where(__entry => __entry != null).Where(__entry => String.Equals(__entry, "ignore", StringComparison.CurrentCultureIgnoreCase)).Any(); } if ((isScenarioIgnored || isFeatureIgnored)) { testRunner.SkipScenario(); } else { this.ScenarioStart(); #line 8 testRunner.Given("the legal entity is in not Employer Incentives", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "Given "); #line hidden #line 9 testRunner.When("the legal entity is added to an account", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "When "); #line hidden #line 10 testRunner.Then("the legal entity should be available in Employer Incentives", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "Then "); #line hidden } this.ScenarioCleanup(); } [NUnit.Framework.TestAttribute()] [NUnit.Framework.DescriptionAttribute("A legal entity associated to an account is already available in Employer Incentiv" + "es")] public virtual void ALegalEntityAssociatedToAnAccountIsAlreadyAvailableInEmployerIncentives() { string[] tagsOfScenario = ((string[])(null)); System.Collections.Specialized.OrderedDictionary argumentsOfScenario = new System.Collections.Specialized.OrderedDictionary(); TechTalk.SpecFlow.ScenarioInfo scenarioInfo = new TechTalk.SpecFlow.ScenarioInfo("A legal entity associated to an account is already available in Employer Incentiv" + "es", null, tagsOfScenario, argumentsOfScenario); #line 12 this.ScenarioInitialize(scenarioInfo); #line hidden bool isScenarioIgnored = default(bool); bool isFeatureIgnored = default(bool); if ((tagsOfScenario != null)) { isScenarioIgnored = tagsOfScenario.Where(__entry => __entry != null).Where(__entry => String.Equals(__entry, "ignore", StringComparison.CurrentCultureIgnoreCase)).Any(); } if ((this._featureTags != null)) { isFeatureIgnored = this._featureTags.Where(__entry => __entry != null).Where(__entry => String.Equals(__entry, "ignore", StringComparison.CurrentCultureIgnoreCase)).Any(); } if ((isScenarioIgnored || isFeatureIgnored)) { testRunner.SkipScenario(); } else { this.ScenarioStart(); #line 13 testRunner.Given("the legal entity is already available in Employer Incentives", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "Given "); #line hidden #line 14 testRunner.When("the legal entity is added to an account", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "When "); #line hidden #line 15 testRunner.Then("the legal entity should still be available in Employer Incentives", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "Then "); #line hidden } this.ScenarioCleanup(); } [NUnit.Framework.TestAttribute()] [NUnit.Framework.DescriptionAttribute("A legal entity that is not valid in Employer Incentives is not added to an accoun" + "t")] public virtual void ALegalEntityThatIsNotValidInEmployerIncentivesIsNotAddedToAnAccount() { string[] tagsOfScenario = ((string[])(null)); System.Collections.Specialized.OrderedDictionary argumentsOfScenario = new System.Collections.Specialized.OrderedDictionary(); TechTalk.SpecFlow.ScenarioInfo scenarioInfo = new TechTalk.SpecFlow.ScenarioInfo("A legal entity that is not valid in Employer Incentives is not added to an accoun" + "t", null, tagsOfScenario, argumentsOfScenario); #line 17 this.ScenarioInitialize(scenarioInfo); #line hidden bool isScenarioIgnored = default(bool); bool isFeatureIgnored = default(bool); if ((tagsOfScenario != null)) { isScenarioIgnored = tagsOfScenario.Where(__entry => __entry != null).Where(__entry => String.Equals(__entry, "ignore", StringComparison.CurrentCultureIgnoreCase)).Any(); } if ((this._featureTags != null)) { isFeatureIgnored = this._featureTags.Where(__entry => __entry != null).Where(__entry => String.Equals(__entry, "ignore", StringComparison.CurrentCultureIgnoreCase)).Any(); } if ((isScenarioIgnored || isFeatureIgnored)) { testRunner.SkipScenario(); } else { this.ScenarioStart(); #line 18 testRunner.Given("the legal entity is not valid for Employer Incentives", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "Given "); #line hidden #line 19 testRunner.When("the legal entity is added to an account", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "When "); #line hidden #line 20 testRunner.Then("the legal entity should not be available in Employer Incentives", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "Then "); #line hidden } this.ScenarioCleanup(); } } } #pragma warning restore #endregion
44.838095
260
0.628292
[ "MIT" ]
uk-gov-mirror/SkillsFundingAgency.das-employer-incentives
src/SFA.DAS.EmployerIncentives.Api.AcceptanceTests/Features/LegalEntityCreated.feature.cs
9,418
C#
// *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.Aws.WafV2.Outputs { [OutputType] public sealed class WebAclRuleStatementNotStatementStatementAndStatementStatementAndStatementStatementXssMatchStatementFieldToMatchBody { [OutputConstructor] private WebAclRuleStatementNotStatementStatementAndStatementStatementAndStatementStatementXssMatchStatementFieldToMatchBody() { } } }
32.090909
139
0.776204
[ "ECL-2.0", "Apache-2.0" ]
Otanikotani/pulumi-aws
sdk/dotnet/WafV2/Outputs/WebAclRuleStatementNotStatementStatementAndStatementStatementAndStatementStatementXssMatchStatementFieldToMatchBody.cs
706
C#
using System.Collections.ObjectModel; namespace JohnCena.Mset.Data.ThreeD { internal struct ThreeDModel { public string ModelName { get; set; } public int VertexCount { get; set; } public int FaceCount { get; set; } public ReadOnlyCollection<ThreeDVertex> Vertices { get; set; } public ReadOnlyCollection<ThreeDFace> Faces { get; set; } public ReadOnlyCollection<ThreeDNormal> Normals { get; set; } public ReadOnlyCollection<ThreeDBinormal> Binormals { get; set; } public ReadOnlyCollection<ThreeDTangent> Tangents { get; set; } public ReadOnlyCollection<ThreeDTextureCoordinate> TextureCoordinates { get; set; } public ReadOnlyCollection<ThreeDTextureCoordinate> TextureCoordinates3 { get; set; } public ReadOnlyCollection<ThreeDColor> Colors { get; set; } public ReadOnlyCollection<ThreeDVertex> Vertices2 { get; set; } public ReadOnlyCollection<ThreeDNormal> Normals2 { get; set; } } }
40.4
92
0.69802
[ "Apache-2.0" ]
PlumberTaskForce/MSET-Decompiler
JohnCena.MSet/Data/ThreeD/ThreeDModel.cs
1,012
C#
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.InteropServices; using System.Text; using System.Threading.Tasks; namespace RawInput.Touchpad { internal static class TouchpadHelper { #region Win32 [DllImport("User32", SetLastError = true)] private static extern uint GetRawInputDeviceList( [Out] RAWINPUTDEVICELIST[] pRawInputDeviceList, ref uint puiNumDevices, uint cbSize); [StructLayout(LayoutKind.Sequential)] private struct RAWINPUTDEVICELIST { public IntPtr hDevice; public uint dwType; // RIM_TYPEMOUSE or RIM_TYPEKEYBOARD or RIM_TYPEHID } private const uint RIM_TYPEMOUSE = 0; private const uint RIM_TYPEKEYBOARD = 1; private const uint RIM_TYPEHID = 2; [DllImport("User32.dll", SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] private static extern bool RegisterRawInputDevices( RAWINPUTDEVICE[] pRawInputDevices, uint uiNumDevices, uint cbSize); [StructLayout(LayoutKind.Sequential)] private struct RAWINPUTDEVICE { public ushort usUsagePage; public ushort usUsage; public uint dwFlags; // RIDEV_INPUTSINK public IntPtr hwndTarget; } private const uint RIDEV_INPUTSINK = 0x00000100; [DllImport("User32.dll", SetLastError = true)] private static extern uint GetRawInputData( IntPtr hRawInput, // lParam in WM_INPUT uint uiCommand, // RID_HEADER IntPtr pData, ref uint pcbSize, uint cbSizeHeader); private const uint RID_INPUT = 0x10000003; [StructLayout(LayoutKind.Sequential)] private struct RAWINPUT { public RAWINPUTHEADER Header; public RAWHID Hid; } [StructLayout(LayoutKind.Sequential)] private struct RAWINPUTHEADER { public uint dwType; // RIM_TYPEMOUSE or RIM_TYPEKEYBOARD or RIM_TYPEHID public uint dwSize; public IntPtr hDevice; public IntPtr wParam; // wParam in WM_INPUT } [StructLayout(LayoutKind.Sequential)] private struct RAWHID { public uint dwSizeHid; public uint dwCount; public IntPtr bRawData; // This is not for use. } [DllImport("User32.dll", SetLastError = true)] private static extern uint GetRawInputDeviceInfo( IntPtr hDevice, // hDevice by RAWINPUTHEADER uint uiCommand, // RIDI_PREPARSEDDATA IntPtr pData, ref uint pcbSize); [DllImport("User32.dll", SetLastError = true)] private static extern uint GetRawInputDeviceInfo( IntPtr hDevice, // hDevice by RAWINPUTDEVICELIST uint uiCommand, // RIDI_DEVICEINFO ref RID_DEVICE_INFO pData, ref uint pcbSize); private const uint RIDI_PREPARSEDDATA = 0x20000005; private const uint RIDI_DEVICEINFO = 0x2000000b; [StructLayout(LayoutKind.Sequential)] private struct RID_DEVICE_INFO { public uint cbSize; // This is determined to accommodate RID_DEVICE_INFO_KEYBOARD. public uint dwType; public RID_DEVICE_INFO_HID hid; } [StructLayout(LayoutKind.Sequential)] private struct RID_DEVICE_INFO_HID { public uint dwVendorId; public uint dwProductId; public uint dwVersionNumber; public ushort usUsagePage; public ushort usUsage; } [DllImport("Hid.dll", SetLastError = true)] private static extern uint HidP_GetCaps( IntPtr PreparsedData, out HIDP_CAPS Capabilities); private const uint HIDP_STATUS_SUCCESS = 0x00110000; [StructLayout(LayoutKind.Sequential)] private struct HIDP_CAPS { public ushort Usage; public ushort UsagePage; public ushort InputReportByteLength; public ushort OutputReportByteLength; public ushort FeatureReportByteLength; [MarshalAs(UnmanagedType.ByValArray, SizeConst = 17)] public ushort[] Reserved; public ushort NumberLinkCollectionNodes; public ushort NumberInputButtonCaps; public ushort NumberInputValueCaps; public ushort NumberInputDataIndices; public ushort NumberOutputButtonCaps; public ushort NumberOutputValueCaps; public ushort NumberOutputDataIndices; public ushort NumberFeatureButtonCaps; public ushort NumberFeatureValueCaps; public ushort NumberFeatureDataIndices; } [DllImport("Hid.dll", CharSet = CharSet.Auto)] private static extern uint HidP_GetValueCaps( HIDP_REPORT_TYPE ReportType, [Out] HIDP_VALUE_CAPS[] ValueCaps, ref ushort ValueCapsLength, IntPtr PreparsedData); private enum HIDP_REPORT_TYPE { HidP_Input, HidP_Output, HidP_Feature } [StructLayout(LayoutKind.Sequential)] private struct HIDP_VALUE_CAPS { public ushort UsagePage; public byte ReportID; [MarshalAs(UnmanagedType.U1)] public bool IsAlias; public ushort BitField; public ushort LinkCollection; public ushort LinkUsage; public ushort LinkUsagePage; [MarshalAs(UnmanagedType.U1)] public bool IsRange; [MarshalAs(UnmanagedType.U1)] public bool IsStringRange; [MarshalAs(UnmanagedType.U1)] public bool IsDesignatorRange; [MarshalAs(UnmanagedType.U1)] public bool IsAbsolute; [MarshalAs(UnmanagedType.U1)] public bool HasNull; public byte Reserved; public ushort BitSize; public ushort ReportCount; [MarshalAs(UnmanagedType.ByValArray, SizeConst = 5)] public ushort[] Reserved2; public uint UnitsExp; public uint Units; public int LogicalMin; public int LogicalMax; public int PhysicalMin; public int PhysicalMax; // Range public ushort UsageMin; public ushort UsageMax; public ushort StringMin; public ushort StringMax; public ushort DesignatorMin; public ushort DesignatorMax; public ushort DataIndexMin; public ushort DataIndexMax; // NotRange public ushort Usage => UsageMin; // ushort Reserved1; public ushort StringIndex => StringMin; // ushort Reserved2; public ushort DesignatorIndex => DesignatorMin; // ushort Reserved3; public ushort DataIndex => DataIndexMin; // ushort Reserved4; } [DllImport("Hid.dll", CharSet = CharSet.Auto)] private static extern uint HidP_GetUsageValue( HIDP_REPORT_TYPE ReportType, ushort UsagePage, ushort LinkCollection, ushort Usage, out uint UsageValue, IntPtr PreparsedData, IntPtr Report, uint ReportLength); #endregion public static bool Exists() { uint deviceListCount = 0; uint rawInputDeviceListSize = (uint)Marshal.SizeOf<RAWINPUTDEVICELIST>(); if (GetRawInputDeviceList( null, ref deviceListCount, rawInputDeviceListSize) != 0) { return false; } var devices = new RAWINPUTDEVICELIST[deviceListCount]; if (GetRawInputDeviceList( devices, ref deviceListCount, rawInputDeviceListSize) != deviceListCount) { return false; } foreach (var device in devices.Where(x => x.dwType == RIM_TYPEHID)) { uint deviceInfoSize = 0; if (GetRawInputDeviceInfo( device.hDevice, RIDI_DEVICEINFO, IntPtr.Zero, ref deviceInfoSize) != 0) { continue; } var deviceInfo = new RID_DEVICE_INFO { cbSize = deviceInfoSize }; if (GetRawInputDeviceInfo( device.hDevice, RIDI_DEVICEINFO, ref deviceInfo, ref deviceInfoSize) == unchecked((uint)-1)) { continue; } if ((deviceInfo.hid.usUsagePage == 0x000D) && (deviceInfo.hid.usUsage == 0x0005)) { return true; } } return false; } public static bool RegisterInput(IntPtr windowHandle) { // Precision Touchpad (PTP) in HID Clients Supported in Windows // https://docs.microsoft.com/en-us/windows-hardware/drivers/hid/hid-architecture#hid-clients-supported-in-windows var device = new RAWINPUTDEVICE { usUsagePage = 0x000D, usUsage = 0x0005, dwFlags = 0, // WM_INPUT messages come only when the window is in the foreground. hwndTarget = windowHandle }; return RegisterRawInputDevices(new[] { device }, 1, (uint)Marshal.SizeOf<RAWINPUTDEVICE>()); } public const int WM_INPUT = 0x00FF; public const int RIM_INPUT = 0; public const int RIM_INPUTSINK = 1; public static TouchpadContact[] ParseInput(IntPtr lParam) { // Get RAWINPUT. uint rawInputSize = 0; uint rawInputHeaderSize = (uint)Marshal.SizeOf<RAWINPUTHEADER>(); if (GetRawInputData( lParam, RID_INPUT, IntPtr.Zero, ref rawInputSize, rawInputHeaderSize) != 0) { return null; } RAWINPUT rawInput; byte[] rawHidRawData; IntPtr rawInputPointer = IntPtr.Zero; try { rawInputPointer = Marshal.AllocHGlobal((int)rawInputSize); if (GetRawInputData( lParam, RID_INPUT, rawInputPointer, ref rawInputSize, rawInputHeaderSize) != rawInputSize) { return null; } rawInput = Marshal.PtrToStructure<RAWINPUT>(rawInputPointer); var rawInputData = new byte[rawInputSize]; Marshal.Copy(rawInputPointer, rawInputData, 0, rawInputData.Length); rawHidRawData = new byte[rawInput.Hid.dwSizeHid * rawInput.Hid.dwCount]; int rawInputOffset = (int)rawInputSize - rawHidRawData.Length; Buffer.BlockCopy(rawInputData, rawInputOffset, rawHidRawData, 0, rawHidRawData.Length); } finally { Marshal.FreeHGlobal(rawInputPointer); } // Parse RAWINPUT. IntPtr rawHidRawDataPointer = Marshal.AllocHGlobal(rawHidRawData.Length); Marshal.Copy(rawHidRawData, 0, rawHidRawDataPointer, rawHidRawData.Length); IntPtr preparsedDataPointer = IntPtr.Zero; try { uint preparsedDataSize = 0; if (GetRawInputDeviceInfo( rawInput.Header.hDevice, RIDI_PREPARSEDDATA, IntPtr.Zero, ref preparsedDataSize) != 0) { return null; } preparsedDataPointer = Marshal.AllocHGlobal((int)preparsedDataSize); if (GetRawInputDeviceInfo( rawInput.Header.hDevice, RIDI_PREPARSEDDATA, preparsedDataPointer, ref preparsedDataSize) != preparsedDataSize) { return null; } if (HidP_GetCaps( preparsedDataPointer, out HIDP_CAPS caps) != HIDP_STATUS_SUCCESS) { return null; } ushort valueCapsLength = caps.NumberInputValueCaps; var valueCaps = new HIDP_VALUE_CAPS[valueCapsLength]; if (HidP_GetValueCaps( HIDP_REPORT_TYPE.HidP_Input, valueCaps, ref valueCapsLength, preparsedDataPointer) != HIDP_STATUS_SUCCESS) { return null; } uint scanTime = 0; uint contactCount = 0; TouchpadContactCreator creator = new(); List<TouchpadContact> contacts = new(); foreach (var valueCap in valueCaps.OrderBy(x => x.LinkCollection)) { if (HidP_GetUsageValue( HIDP_REPORT_TYPE.HidP_Input, valueCap.UsagePage, valueCap.LinkCollection, valueCap.Usage, out uint value, preparsedDataPointer, rawHidRawDataPointer, (uint)rawHidRawData.Length) != HIDP_STATUS_SUCCESS) { continue; } // Usage Page and ID in Windows Precision Touchpad input reports // https://docs.microsoft.com/en-us/windows-hardware/design/component-guidelines/windows-precision-touchpad-required-hid-top-level-collections#windows-precision-touchpad-input-reports switch (valueCap.LinkCollection) { case 0: switch (valueCap.UsagePage, valueCap.Usage) { case (0x0D, 0x56): // Scan Time scanTime = value; break; case (0x0D, 0x54): // Contact Count contactCount = value; break; } break; default: switch (valueCap.UsagePage, valueCap.Usage) { case (0x0D, 0x51): // Contact ID creator.ContactId = (int)value; break; case (0x01, 0x30): // X creator.X = (int)value; break; case (0x01, 0x31): // Y creator.Y = (int)value; break; } break; } if (creator.TryCreate(out TouchpadContact contact)) { contacts.Add(contact); if (contacts.Count >= contactCount) break; creator.Clear(); } } return contacts.ToArray(); } finally { Marshal.FreeHGlobal(rawHidRawDataPointer); Marshal.FreeHGlobal(preparsedDataPointer); } } } }
26.035343
189
0.675717
[ "MIT" ]
emoacht/RawInput.Touchpad
Source/RawInput.Touchpad/TouchpadHelper.cs
12,525
C#
/* Copyright 2013-present MongoDB Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using MongoDB.Driver.Core.Clusters; using MongoDB.Driver.Core.Servers; namespace MongoDB.Driver.Core.Events { /// <preliminary/> /// <summary> /// Occurs before a server is closed. /// </summary> public struct ServerClosingEvent { private readonly ServerId _serverId; /// <summary> /// Initializes a new instance of the <see cref="ServerClosingEvent"/> struct. /// </summary> /// <param name="serverId">The server identifier.</param> public ServerClosingEvent(ServerId serverId) { _serverId = serverId; } /// <summary> /// Gets the cluster identifier. /// </summary> public ClusterId ClusterId { get { return _serverId.ClusterId; } } /// <summary> /// Gets the server identifier. /// </summary> public ServerId ServerId { get { return _serverId; } } } }
28.490909
86
0.630504
[ "MIT" ]
13294029724/ET
Server/ThirdParty/MongoDBDriver/MongoDB.Driver.Core/Core/Events/ServerClosingEvent.cs
1,567
C#
using System.Web.Mvc; using System.Web.Routing; namespace AzureSqlDatabaseStressTestTool { public class RouteConfig { public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapRoute( name: "Default", url: "{controller}/{action}/{id}", defaults: new { controller = "Testing", action = "Index", id = UrlParameter.Optional } ); routes.Add(new Route("Testing/Index", new MvcRouteHandler()) { Defaults = new RouteValueDictionary(new { controller = "Testing", action = "Index" }), DataTokens = new RouteValueDictionary(new { scheme = "https" }) }); } } }
30.884615
102
0.559153
[ "MIT" ]
kiyoaki/AzurePerformanceTesting
FromWebsites/App_Start/RouteConfig.cs
805
C#
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the route53resolver-2018-04-01.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.Route53Resolver.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; using ThirdParty.Json.LitJson; namespace Amazon.Route53Resolver.Model.Internal.MarshallTransformations { /// <summary> /// Tag Marshaller /// </summary> public class TagMarshaller : IRequestMarshaller<Tag, JsonMarshallerContext> { /// <summary> /// Unmarshaller the response from the service to the response class. /// </summary> /// <param name="requestObject"></param> /// <param name="context"></param> /// <returns></returns> public void Marshall(Tag requestObject, JsonMarshallerContext context) { if(requestObject.IsSetKey()) { context.Writer.WritePropertyName("Key"); context.Writer.Write(requestObject.Key); } if(requestObject.IsSetValue()) { context.Writer.WritePropertyName("Value"); context.Writer.Write(requestObject.Value); } } /// <summary> /// Singleton Marshaller. /// </summary> public readonly static TagMarshaller Instance = new TagMarshaller(); } }
31.632353
113
0.662018
[ "Apache-2.0" ]
Hazy87/aws-sdk-net
sdk/src/Services/Route53Resolver/Generated/Model/Internal/MarshallTransformations/TagMarshaller.cs
2,151
C#
using System.Collections.Generic; using System.Linq; using IDSR.CondorReader.Core.ns11.DomainModels; namespace IDSR.CondorReader.Core.ns11.ReportRows { public class MonthlyPurchasesReceivingRow { public MonthlyPurchasesReceivingRow(IGrouping<long, CdrReceivingLine> grp) { Receiving = grp.FirstOrDefault()?.Parent; Lines = grp.ToList(); } public CdrReceiving Receiving { get; } public List<CdrReceivingLine> Lines { get; } //public string Label => Order?.Description; //public double? Total => Order?.NetTotal; } }
28.727273
82
0.642405
[ "MIT" ]
peterson1/indie-ds-readers
IDSR.CondorReader.Core.ns11/ReportRows/MonthlyPurchasesReceivingRow.cs
634
C#
/* Copyright 2009-2021 Intel Corporation Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using System; using System.Windows.Forms; namespace MeshCentralRouter { public partial class KVMStats : Form { public KVMViewer viewer; public KVMStats(KVMViewer viewer) { this.viewer = viewer; InitializeComponent(); Translate.TranslateControl(this); } private void refreshTimer_Tick(object sender, EventArgs e) { kvmInBytesLabel.Text = string.Format(((viewer.bytesIn == 1)? Translate.T(Properties.Resources.OneByte): Translate.T(Properties.Resources.XBytes)), viewer.bytesIn); kvmOutBytesLabel.Text = string.Format(((viewer.bytesOut == 1) ? Translate.T(Properties.Resources.OneByte) : Translate.T(Properties.Resources.XBytes)), viewer.bytesOut); kvmCompInBytesLabel.Text = string.Format(((viewer.bytesInCompressed == 1) ? Translate.T(Properties.Resources.OneByte) : Translate.T(Properties.Resources.XBytes)), viewer.bytesInCompressed); kvmCompOutBytesLabel.Text = string.Format(((viewer.bytesOutCompressed == 1) ? Translate.T(Properties.Resources.OneByte) : Translate.T(Properties.Resources.XBytes)), viewer.bytesOutCompressed); if (viewer.bytesIn == 0) { inRatioLabel.Text = "0%"; } else { inRatioLabel.Text = (100 - ((viewer.bytesInCompressed * 100) / viewer.bytesIn)) + "%"; } if (viewer.bytesOut == 0) { outRatioLabel.Text = "0%"; } else { outRatioLabel.Text = (100 - ((viewer.bytesOutCompressed * 100) / viewer.bytesOut)) + "%"; } } private void KVMStats_FormClosing(object sender, FormClosingEventArgs e) { refreshTimer.Enabled = false; } private void KVMStats_Load(object sender, EventArgs e) { refreshTimer.Enabled = true; refreshTimer_Tick(this, null); Text = viewer.Text; } private void okButton_Click(object sender, EventArgs e) { viewer.closeKvmStats(); } } }
38.695652
204
0.64794
[ "Apache-2.0" ]
SPEMoorthy/MeshCentralRouter
KVMStats.cs
2,672
C#
// Copyright (c) Microsoft Corporation. All rights reserved. #region Using directives using System; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Security.Permissions; #endregion // 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: ComVisible(false)] [assembly: CLSCompliant(false)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: AssemblyTitle("client")] [assembly: AssemblyDescription("Asynchronous")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Microsoft Corporation")] [assembly: AssemblyProduct("Windows Communication Foundation and Windows Workflow Foundation SDK")] [assembly: AssemblyCopyright("Copyright (c) Microsoft Corporation")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // 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 Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion("3.5")] [assembly: AssemblyFileVersionAttribute("3.5")]
34.615385
99
0.771111
[ "Apache-2.0" ]
jdm7dv/visual-studio
Samples/NET 4.6/WF_WCF_Samples/WCF/Basic/Contract/Service/Asynchronous/CS/client/Properties/AssemblyInfo.cs
1,352
C#
using Gtk; using NLog; using SlimeSimulation.Controller.WindowController.Templates; using SlimeSimulation.View.WindowComponent.SimulationControlComponent; namespace SlimeSimulation.View.Factories { class SimulationAdaptionPhaseControlBoxFactory : ISimulationControlBoxFactory { private static readonly Logger Logger = LogManager.GetCurrentClassLogger(); public AbstractSimulationControlBox MakeControlBox(SimulationStepAbstractWindowController simulationStepAbstractWindowController, Window parentWindow) { Logger.Debug("[MakeControlBox] Making"); return new AdaptionPhaseControlBox(simulationStepAbstractWindowController, parentWindow); } } }
37.578947
158
0.792717
[ "Apache-2.0" ]
willb611/SlimeSimulation
SlimeSimulation/View/Factories/SimulationAdaptionPhaseControlBoxFactory.cs
714
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using System.Threading.Tasks; using AdaptiveExpressions.Properties; using Microsoft.Bot.Builder.Adapters; using Microsoft.Bot.Builder.Dialogs.Adaptive.Actions; using Microsoft.Bot.Builder.Dialogs.Adaptive.Conditions; using Microsoft.Bot.Builder.Dialogs.Adaptive.Testing.HttpRequestMocks; using Microsoft.Bot.Builder.Dialogs.Adaptive.Testing.Mocks; using Microsoft.Bot.Builder.Dialogs.Adaptive.Testing.PropertyMocks; using Microsoft.Bot.Builder.Dialogs.Adaptive.Testing.TestActions; using Microsoft.Bot.Builder.Dialogs.Adaptive.Testing.UserTokenMocks; using Microsoft.Bot.Builder.Dialogs.Declarative.Resources; using Microsoft.Bot.Schema; using Microsoft.Extensions.Configuration; using Newtonsoft.Json; using Newtonsoft.Json.Serialization; namespace Microsoft.Bot.Builder.Dialogs.Adaptive.Testing { /// <summary> /// A mock Test Script that can be used for unit testing of bot logic. /// </summary> /// <remarks>You can use this class to mimic input from a a user or a channel to validate /// that the bot or adapter responds as expected.</remarks> /// <seealso cref="TestAdapter"/> public class TestScript { [JsonProperty("$kind")] public const string Kind = "Microsoft.Test.Script"; private static JsonSerializerSettings serializerSettings = new JsonSerializerSettings() { Formatting = Formatting.Indented, NullValueHandling = NullValueHandling.Ignore, DefaultValueHandling = DefaultValueHandling.Ignore }; private static IConfiguration defaultConfiguration = new ConfigurationBuilder().Build(); /// <summary> /// Initializes a new instance of the <see cref="TestScript"/> class. /// </summary> /// <remarks>If adapter is not provided a standard test adapter with all services will be registered.</remarks> public TestScript() { Configuration = new ConfigurationBuilder().AddInMemoryCollection().Build(); } /// <summary> /// Gets or sets configuration to use for the test. /// </summary> /// <value> /// IConfiguration to use for the test. /// </value> [JsonIgnore] public IConfiguration Configuration { get; set; } /// <summary> /// Gets or sets the description property. /// </summary> /// <value> /// A description of the test sequence. /// </value> [JsonProperty("description")] public string Description { get; set; } /// <summary> /// Gets or sets the RootDialog. /// </summary> /// <value> /// The dialog to use for the root dialog. /// </value> [JsonProperty("dialog")] public Dialog Dialog { get; set; } /// <summary> /// Gets or sets the locale. /// </summary> /// <value>the locale (Default:en-us).</value> [JsonProperty("locale")] public string Locale { get; set; } = "en-us"; /// <summary> /// Gets or sets the mock data for Microsoft.HttpRequest. /// </summary> /// <value> /// A list of mocks. In first match first use order. /// </value> [JsonProperty("httpRequestMocks")] public List<HttpRequestMock> HttpRequestMocks { get; set; } = new List<HttpRequestMock>(); /// <summary> /// Gets or sets the mock data for Microsoft.OAuthInput. /// </summary> /// <value> /// A list of mocks. /// </value> [JsonProperty("userTokenMocks")] public List<UserTokenMock> UserTokenMocks { get; set; } = new List<UserTokenMock>(); /// <summary> /// Gets or sets the mock data for properties. /// </summary> /// <value> /// A list of property mocks. In first match first use order. /// </value> [JsonProperty("propertyMocks")] public List<PropertyMock> PropertyMocks { get; set; } = new List<PropertyMock>(); /// <summary> /// Gets or sets the test script actions. /// </summary> /// <value> /// The sequence of test actions to perform to validate the dialog behavior. /// </value> [JsonProperty("script")] public List<TestAction> Script { get; set; } = new List<TestAction>(); /// <summary> /// Gets or sets a value indicating whether trace activities should be passed to the test script. /// </summary> /// <value>If true then trace activities will be sent to the test script.</value> [JsonProperty("enableTrace")] public bool EnableTrace { get; set; } = false; /// <summary> /// Build default test adapter. /// </summary> /// <param name="resourceExplorer">Resource explorer to use.</param> /// <param name="testName">Name of test.</param> /// <returns>Test adapter.</returns> public TestAdapter DefaultTestAdapter(ResourceExplorer resourceExplorer, [CallerMemberName] string testName = null) { var storage = new MemoryStorage(); var convoState = new ConversationState(storage); var userState = new UserState(storage); var adapter = (TestAdapter)new TestAdapter(TestAdapter.CreateConversation(testName)) .Use(new RegisterClassMiddleware<IConfiguration>(this.Configuration)) .UseStorage(storage) .UseBotState(userState, convoState) .Use(new TranscriptLoggerMiddleware(new TraceTranscriptLogger(traceActivity: false))); adapter.OnTurnError += (context, err) => context.SendActivityAsync(err.Message); return adapter; } /// <summary> /// Starts the execution of the test sequence. /// </summary> /// <remarks>This methods sends the activities from the user to the bot and /// checks the responses from the bot based on the TestActions.</remarks> /// <param name="resourceExplorer">The resource explorer to use.</param> /// <param name="testName">Name of the test.</param> /// <param name="callback">The bot logic.</param> /// <param name="adapter">optional test adapter.</param> /// <returns>Runs the exchange between the user and the bot.</returns> public async Task ExecuteAsync(ResourceExplorer resourceExplorer, [CallerMemberName] string testName = null, BotCallbackHandler callback = null, TestAdapter adapter = null) { if (adapter == null) { adapter = DefaultTestAdapter(resourceExplorer, testName); } adapter.EnableTrace = this.EnableTrace; adapter.Locale = this.Locale; adapter.Use(new MockHttpRequestMiddleware(HttpRequestMocks)); adapter.Use(new MockSettingsMiddleware(PropertyMocks)); foreach (var userToken in UserTokenMocks) { userToken.Setup(adapter); } if (callback != null) { foreach (var testAction in this.Script) { await testAction.ExecuteAsync(adapter, callback).ConfigureAwait(false); } } else { var dm = new DialogManager(WrapDialogForPropertyMocks(this.Dialog)) .UseResourceExplorer(resourceExplorer) .UseLanguageGeneration(); foreach (var testAction in this.Script) { await testAction.ExecuteAsync(adapter, dm.OnTurnAsync).ConfigureAwait(false); } } } /// <summary> /// Adds a message activity from the user to the bot. /// </summary> /// <param name="userSays">The text of the message to send.</param> /// <param name="path">path.</param> /// <param name="line">line number.</param> /// <returns>A new <see cref="TestScript"/> object that appends a new message activity from the user to the modeled exchange.</returns> /// <remarks>This method does not modify the original <see cref="TestScript"/> object.</remarks> public TestScript Send(string userSays, [CallerFilePath] string path = "", [CallerLineNumber] int line = 0) { this.Script.Add(new UserSays(path: path, line: line) { Text = userSays }); return this; } /// <summary> /// Adds an activity from the user to the bot. /// </summary> /// <param name="userActivity">The activity to send.</param> /// <param name="path">path.</param> /// <param name="line">line number.</param> /// <returns>A new <see cref="TestScript"/> object that appends a new activity from the user to the modeled exchange.</returns> /// <remarks>This method does not modify the original <see cref="TestScript"/> object.</remarks> public TestScript Send(IActivity userActivity, [CallerFilePath] string path = "", [CallerLineNumber] int line = 0) { this.Script.Add(new UserActivity(path: path, line: line) { Activity = (Activity)userActivity }); return this; } public TestScript SendConversationUpdate([CallerFilePath] string path = "", [CallerLineNumber] int line = 0) { this.Script.Add(new UserConversationUpdate(path: path, line: line)); return this; } /// <summary> /// Adds a delay in the conversation. /// </summary> /// <param name="ms">The delay length in milliseconds.</param> /// <param name="path">path.</param> /// <param name="line">line number.</param> /// <returns>A new <see cref="TestScript"/> object that appends a delay to the modeled exchange.</returns> /// <remarks>This method does not modify the original <see cref="TestScript"/> object.</remarks> public TestScript Delay(uint ms, [CallerFilePath] string path = "", [CallerLineNumber] int line = 0) { this.Script.Add(new UserDelay(path: path, line: line) { Timespan = ms }); return this; } /// <summary> /// Adds a delay in the conversation. /// </summary> /// <param name="timespan">The delay length in TimeSpan.</param> /// <param name="path">path.</param> /// <param name="line">line number.</param> /// <returns>A new <see cref="TestScript"/> object that appends a delay to the modeled exchange.</returns> /// <remarks>This method does not modify the original <see cref="TestScript"/> object.</remarks> public TestScript Delay(TimeSpan timespan, [CallerFilePath] string path = "", [CallerLineNumber] int line = 0) { this.Script.Add(new UserDelay(path: path, line: line) { Timespan = (uint)timespan.TotalMilliseconds }); return this; } /// <summary> /// Adds an assertion that the turn processing logic responds as expected. /// </summary> /// <param name="expected">The expected text of a message from the bot.</param> /// <param name="description">A message to send if the actual response is not as expected.</param> /// <param name="timeout">The amount of time in milliseconds within which a response is expected.</param> /// <param name="assertions">assertions.</param> /// <param name="path">path.</param> /// <param name="line">line number.</param> /// <returns>A new <see cref="TestScript"/> object that appends this assertion to the modeled exchange.</returns> /// <remarks>This method does not modify the original <see cref="TestScript"/> object.</remarks> /// <exception cref="Exception">The bot did not respond as expected.</exception> public TestScript AssertReply(string expected, string description = null, uint timeout = 3000, string[] assertions = null, [CallerFilePath] string path = "", [CallerLineNumber] int line = 0) { var action = new AssertReply(path: path, line: line) { Text = expected, Description = description, Timeout = timeout, Exact = true }; if (assertions != null) { action.Assertions.AddRange(assertions); } this.Script.Add(action); return this; } /// <summary> /// Adds an assertion that the turn processing logic responds as expected. /// </summary> /// <param name="assertions">assertions.</param> /// <param name="description">A message to send if the actual response is not as expected.</param> /// <param name="timeout">The amount of time in milliseconds within which a response is expected.</param> /// <param name="path">path.</param> /// <param name="line">line number.</param> /// <returns>A new <see cref="TestScript"/> object that appends this assertion to the modeled exchange.</returns> /// <remarks>This method does not modify the original <see cref="TestScript"/> object.</remarks> /// <exception cref="Exception">The bot did not respond as expected.</exception> public TestScript AssertReplyActivity(string[] assertions, string description = null, uint timeout = 3000, [CallerFilePath] string path = "", [CallerLineNumber] int line = 0) { var action = new AssertReplyActivity(path: path, line: line) { Description = description, Timeout = timeout }; if (assertions != null) { action.Assertions.AddRange(assertions); } this.Script.Add(action); return this; } /// <summary> /// Adds an assertion that the turn processing logic responds as expected. /// </summary> /// <param name="expected">The part of the expected text of a message from the bot.</param> /// <param name="description">A message to send if the actual response is not as expected.</param> /// <param name="timeout">The amount of time in milliseconds within which a response is expected.</param> /// <param name="path">path.</param> /// <param name="line">line number.</param> /// <returns>A new <see cref="TestScript"/> object that appends this assertion to the modeled exchange.</returns> /// <remarks>This method does not modify the original <see cref="TestScript"/> object.</remarks> /// <exception cref="Exception">The bot did not respond as expected.</exception> public TestScript AssertReplyContains(string expected, string description = null, uint timeout = 3000, [CallerFilePath] string path = "", [CallerLineNumber] int line = 0) { this.Script.Add(new AssertReply(path: path, line: line) { Text = expected, Description = description, Timeout = timeout, Exact = false }); return this; } /// <summary> /// Shortcut for calling <see cref="Send(string, string, int)"/> followed by <see cref="AssertReply(string, string, uint, string[], string, int)"/>. /// </summary> /// <param name="userSays">The text of the message to send.</param> /// <param name="expected">The expected text of a message from the bot.</param> /// <param name="description">A message to send if the actual response is not as expected.</param> /// <param name="timeout">The amount of time in milliseconds within which a response is expected.</param> /// <param name="path">path.</param> /// <param name="line">line number.</param> /// <returns>A new <see cref="TestScript"/> object that appends this exchange to the modeled exchange.</returns> /// <remarks>This method does not modify the original <see cref="TestScript"/> object.</remarks> /// <exception cref="Exception">The bot did not respond as expected.</exception> public TestScript Test(string userSays, string expected, string description = null, uint timeout = 3000, [CallerFilePath] string path = "", [CallerLineNumber] int line = 0) { this.Script.Add(new UserSays(path: path, line: line) { Text = userSays }); this.Script.Add(new AssertReply(path: path, line: line) { Text = expected, Description = description, Timeout = timeout, Exact = true }); return this; } /// <summary> /// Adds an assertion that the bot's response is contained within a set of acceptable responses. /// </summary> /// <param name="candidates">The set of acceptable messages.</param> /// <param name="description">A message to send if the actual response is not as expected.</param> /// <param name="timeout">The amount of time in milliseconds within which a response is expected.</param> /// <param name="path">path.</param> /// <param name="line">line number.</param> /// <returns>A new <see cref="TestScript"/> object that appends this assertion to the modeled exchange.</returns> /// <remarks>This method does not modify the original <see cref="TestScript"/> object.</remarks> /// <exception cref="Exception">The bot did not respond as expected.</exception> public TestScript AssertReplyOneOf(string[] candidates, string description = null, uint timeout = 3000, [CallerFilePath] string path = "", [CallerLineNumber] int line = 0) { this.Script.Add(new AssertReplyOneOf(path: path, line: line) { Text = candidates.ToList<string>(), Description = description, Timeout = timeout, Exact = true }); return this; } private Dialog WrapDialogForPropertyMocks(Dialog dialog) { string settingsPrefix = $"{ScopePath.Settings}."; var setPropertiesDialog = new SetProperties(); var hasSet = new HashSet<string>(); foreach (var property in PropertyMocks) { if (property is PropertiesMock mock) { foreach (var assignment in mock.Assignments) { // Note we only check if it is for settings here. if (!assignment.Property.StartsWith(settingsPrefix, StringComparison.Ordinal)) { if (!hasSet.Contains(assignment.Property)) { setPropertiesDialog.Assignments.Add(new Adaptive.Actions.PropertyAssignment { Property = new StringExpression(assignment.Property), Value = new ValueExpression(assignment.Value) }); hasSet.Add(assignment.Property); } } } } } if (hasSet.Count == 0) { return dialog; } else { var rootDialog = new AdaptiveDialog(); rootDialog.Triggers.Add(new OnBeginDialog { Actions = new List<Dialog> { setPropertiesDialog, new ReplaceDialog { Dialog = dialog } } }); return rootDialog; } } #if SAVESCRIPT public Task SaveScriptAsync(string folder, [CallerMemberName] string testName = null) { folder = Path.Combine(GetProjectPath(), PathUtils.NormalizePath($"tests\\{folder}")); if (!Directory.Exists(folder)) { Directory.CreateDirectory(folder); } if (this.Dialog is DialogContainer container && container.Dialogs.GetDialogs().Any()) { folder = Path.Combine(folder, testName); if (!Directory.Exists(folder)) { Directory.CreateDirectory(folder); } SaveContainerDialogs(container, folder); } File.WriteAllText(Path.Combine(folder, $"{testName}.test.dialog"), JsonConvert.SerializeObject(this, serializerSettings)); return Task.CompletedTask; } private static string GetProjectPath() { var parent = Environment.CurrentDirectory; while (!string.IsNullOrEmpty(parent)) { if (Directory.EnumerateFiles(parent, "*proj").Any()) { break; } else { parent = Path.GetDirectoryName(parent); } } return parent; } private void SaveContainerDialogs(DialogContainer container, string folder) { foreach (var dialog in container.Dialogs.GetDialogs()) { var filePath = Path.GetFullPath(Path.Combine(folder, $"{dialog.Id}.dialog")); File.WriteAllText(filePath, JsonConvert.SerializeObject(dialog, serializerSettings)); if (dialog is DialogContainer container2) { SaveContainerDialogs(container2, folder); } } } #endif internal class IgnoreEmptyEnumerablesResolver : DefaultContractResolver { protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization) { var property = base.CreateProperty(member, memberSerialization); if (typeof(IEnumerable).IsAssignableFrom(property.PropertyType) && property.PropertyType != typeof(string)) { property.ShouldSerialize = instance => { var enumer = instance .GetType() .GetProperty(member.Name) .GetValue(instance, null) as IEnumerable; if (enumer != null) { // check to see if there is at least one item in the Enumerable return enumer.GetEnumerator().MoveNext(); } else { // if the enumerable is null, we defer the decision to NullValueHandling return true; } }; } return property; } } } }
45.744094
198
0.581547
[ "MIT" ]
Remy-Pf/botbuilder-dotnet
libraries/Microsoft.Bot.Builder.Dialogs.Adaptive.Testing/TestScript.cs
23,240
C#
using UnityEngine; using System.Collections; using System.Reflection; using System; /// <summary> /// 反射工具类 /// 作者:笨木头 www.benmutou.com /// 使用本代码时,请保留作者信息 /// </summary> public class ReflectUtil { /// <summary> /// 给属性赋值 /// </summary> /// <typeparam name="T">对象类型</typeparam> /// <param name="value">值</param> /// <param name="pi">反射的属性对象</param> /// <param name="obj">被赋值的对象</param> public static void PiSetValue<T>(string value, PropertyInfo pi, T obj) { /* ChangeType无法强制转换可空类型,所以需要这样特殊处理(参考:http://bbs.csdn.net/topics/320213735) */ if (pi.PropertyType.FullName.IndexOf("Boolean") > 0) { /* 布尔类型要特殊处理 */ pi.SetValue(obj, Convert.ChangeType(Convert.ToInt16(value), (Nullable.GetUnderlyingType(pi.PropertyType) ?? pi.PropertyType)), null); } else { pi.SetValue(obj, Convert.ChangeType(value, (Nullable.GetUnderlyingType(pi.PropertyType) ?? pi.PropertyType)), null); } } }
29.735294
145
0.615232
[ "MIT" ]
musicvs/MutCSVLoaderForUnity
Assets/Scripts/CSVLoader/ReflectUtil.cs
1,179
C#
using System; namespace Lab_30_MVC_Core.Models { public class ErrorViewModel { public string RequestId { get; set; } public bool ShowRequestId => !string.IsNullOrEmpty(RequestId); } }
19.363636
70
0.676056
[ "MIT" ]
rbrownsparta/SpartaLabs
New_Labs/Lab_30_MVC_Core/Models/ErrorViewModel.cs
213
C#
using System; namespace Harmony.Sdk.Reactive { public class AbstractObservable<TType> : IObservable<TType> { Func<IObserver<TType>, IDisposable> _subscriber; public AbstractObservable(Func<IObserver<TType>, IDisposable> subscriber) { if (subscriber == null) throw new ArgumentNullException("subscriber"); _subscriber = subscriber; } #region IObservable implementation public IDisposable Subscribe(IObserver<TType> observer) { return _subscriber(observer); } #endregion } }
22
81
0.616883
[ "MIT" ]
mumusan/harmony
Harmony/Reactive/AbstractObservable.cs
616
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Player : MonoBehaviour { public int health = 3; public float speed; public float jumpForce; public GameObject bow; public Transform firePoint; private bool isJumping; private bool doubleJump; private bool isFire; private bool canFire = true; private Rigidbody2D rig; private Animator anim; public float movement; public bool isMobile; public bool touchJump; public bool touchFire; // Start is called before the first frame update void Start() { rig = GetComponent<Rigidbody2D>(); anim = GetComponent<Animator>(); GameController.instance.UpdateLives(health); } // Update is called once per frame void Update() { Jump(); BowFire(); } void FixedUpdate() { Move(); } //metodo para mover o player e tambem habilitar animações de mover void Move() { if (!isMobile) { //se não pressionar nada valor 0. Pressionar direito valor maximo 1. Esquerda valor maximo -1 movement = Input.GetAxis("Horizontal"); } //adiciona velocidade ao corpo do personagem no eixo x e y rig.velocity = new Vector2(movement * speed, rig.velocity.y); //andando pra direita if(movement > 0) { if (!isJumping) { anim.SetInteger("Transition", 1); } transform.eulerAngles = new Vector3(0,0,0); } //andando pra esquerda if(movement < 0) { if (!isJumping) { anim.SetInteger("Transition", 1); } transform.eulerAngles = new Vector3(0, 180, 0); } //metodo para permitir a animação iddle, se o player estiver parado, e não estiver pulando, e não estiver atirando, if(movement == 0 && !isJumping && !isFire) { anim.SetInteger("Transition", 0); } } //metodo para fazer o player pular duas vezes e tambem habilitar animações de pular void Jump() { if (Input.GetButtonDown("Jump") || touchJump) { //checando se a variavel isJumping é false if (!isJumping) { anim.SetInteger("Transition", 2); rig.AddForce(new Vector2(0, jumpForce), ForceMode2D.Impulse); doubleJump = true; isJumping = true; } else { //checando se a variavel doublejump é true if (doubleJump) { anim.SetInteger("Transition", 2); rig.AddForce(new Vector2(0, jumpForce * 1), ForceMode2D.Impulse); doubleJump = false; } } touchJump = false; } } //metodo para fazer o player atirar void BowFire() { StartCoroutine("Fire"); } //corotina para fazer o player atirar, voltar a idle e poder atirar de novo/tambem habilitar animações de atirar IEnumerator Fire() { if (Input.GetKeyDown(KeyCode.E) || touchFire && canFire == true) { canFire = false; touchFire = false; isFire = true; anim.SetInteger("Transition", 3); GameObject Bow = Instantiate(bow, firePoint.position, firePoint.rotation); if (transform.rotation.y == 0) { Bow.GetComponent<Bow>().isRight = true; } if (transform.rotation.y == 180) { Bow.GetComponent<Bow>().isRight = false; } yield return new WaitForSeconds(0.2f); isFire = false; anim.SetInteger("Transition", 0); canFire = true; Debug.Log("atirei"); } } //metodo para fazer o player tomar dano/tambem habilita animação de hit/chama game over public void Damage(int dmg) { health -= dmg; GameController.instance.UpdateLives(health); anim.SetTrigger("hit"); if (transform.rotation.y == 0) { transform.position += new Vector3(-0.5f,0,0); } if (transform.rotation.y == 180) { transform.position += new Vector3(0.5f, 0, 0); } if (health <= 0) { //chamar game over GameController.instance.GameOver(); } } //metodo para aumentar a vida do player public void IncreaseLife(int value) { health += value; GameController.instance.UpdateLives(health); } //metódo para controlar o player de pular somente do chão/ permitir o player de dar mais de dois pulos void OnCollisionEnter2D(Collision2D coll) { if (coll.gameObject.layer == 8) { isJumping = false; } if (coll.gameObject.layer == 9) { GameController.instance.GameOver(); } } }
24.990431
123
0.529581
[ "MIT" ]
ErickLima13/Game-Plataforma
GamePlataforma/Assets/Scripts/Player.cs
5,242
C#
// <copyright file="AssemblyInfo.cs" company="Microsoft Open Technologies, Inc."> // Copyright 2011-2013 Microsoft Open Technologies, Inc. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // </copyright> using System.Reflection; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Katana.Performance.ReferenceApp.Tests")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [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("c0d0d30c-21a2-415f-ba63-6db45de8a650")]
40.815789
84
0.760799
[ "Apache-2.0" ]
15901213541/-OAuth2.0
tests/Katana.Performance.ReferenceApp.Tests/Properties/AssemblyInfo.cs
1,551
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace ImageScaling.Properties { [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "14.0.0.0")] internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase { private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings()))); public static Settings Default { get { return defaultInstance; } } } }
39.518519
151
0.582006
[ "MIT" ]
21pages/WPF-Samples
PerMonitorDPI/ImageScaling/Properties/Settings.Designer.cs
1,069
C#
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ using System.Collections.Generic; using Aliyun.Acs.Core; namespace Aliyun.Acs.quickbi_public.Model.V20200808 { public class AuthorizeMenuResponse : AcsResponse { private string requestId; private int? result; private bool? success; public string RequestId { get { return requestId; } set { requestId = value; } } public int? Result { get { return result; } set { result = value; } } public bool? Success { get { return success; } set { success = value; } } } }
20.15493
63
0.661775
[ "Apache-2.0" ]
aliyun/aliyun-openapi-net-sdk
aliyun-net-sdk-quickbi-public/Quickbi_public/Model/V20200808/AuthorizeMenuResponse.cs
1,431
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ #pragma warning disable 414 namespace DontClose { /// [Microsoft.VisualStudio.Tools.Applications.Runtime.StartupObjectAttribute(0)] [global::System.Security.Permissions.PermissionSetAttribute(global::System.Security.Permissions.SecurityAction.Demand, Name="FullTrust")] public sealed partial class ThisAddIn : Microsoft.Office.Tools.Outlook.OutlookAddInBase { internal Microsoft.Office.Tools.CustomTaskPaneCollection CustomTaskPanes; [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Tools.Office.ProgrammingModel.dll", "15.0.0.0")] private global::System.Object missing = global::System.Type.Missing; [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Tools.Office.ProgrammingModel.dll", "15.0.0.0")] internal Microsoft.Office.Interop.Outlook.Application Application; /// [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Never)] public ThisAddIn(global::Microsoft.Office.Tools.Outlook.Factory factory, global::System.IServiceProvider serviceProvider) : base(factory, serviceProvider, "AddIn", "ThisAddIn") { Globals.Factory = factory; } /// [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Tools.Office.ProgrammingModel.dll", "15.0.0.0")] [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Never)] protected override void Initialize() { base.Initialize(); this.Application = this.GetHostItem<Microsoft.Office.Interop.Outlook.Application>(typeof(Microsoft.Office.Interop.Outlook.Application), "Application"); Globals.ThisAddIn = this; global::System.Windows.Forms.Application.EnableVisualStyles(); this.InitializeCachedData(); this.InitializeControls(); this.InitializeComponents(); this.InitializeData(); } /// [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Tools.Office.ProgrammingModel.dll", "15.0.0.0")] [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Never)] protected override void FinishInitialization() { this.InternalStartup(); this.OnStartup(); } /// [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Tools.Office.ProgrammingModel.dll", "15.0.0.0")] [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Never)] protected override void InitializeDataBindings() { this.BeginInitialization(); this.BindToData(); this.EndInitialization(); } /// [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Tools.Office.ProgrammingModel.dll", "15.0.0.0")] [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Never)] private void InitializeCachedData() { if ((this.DataHost == null)) { return; } if (this.DataHost.IsCacheInitialized) { this.DataHost.FillCachedData(this); } } /// [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Tools.Office.ProgrammingModel.dll", "15.0.0.0")] [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Never)] private void InitializeData() { } /// [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Tools.Office.ProgrammingModel.dll", "15.0.0.0")] [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Never)] private void BindToData() { } /// [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] private void StartCaching(string MemberName) { this.DataHost.StartCaching(this, MemberName); } /// [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] private void StopCaching(string MemberName) { this.DataHost.StopCaching(this, MemberName); } /// [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] private bool IsCached(string MemberName) { return this.DataHost.IsCached(this, MemberName); } /// [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Tools.Office.ProgrammingModel.dll", "15.0.0.0")] [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Never)] private void BeginInitialization() { this.BeginInit(); this.CustomTaskPanes.BeginInit(); } /// [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Tools.Office.ProgrammingModel.dll", "15.0.0.0")] [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Never)] private void EndInitialization() { this.CustomTaskPanes.EndInit(); this.EndInit(); } /// [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Tools.Office.ProgrammingModel.dll", "15.0.0.0")] [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Never)] private void InitializeControls() { this.CustomTaskPanes = Globals.Factory.CreateCustomTaskPaneCollection(null, null, "CustomTaskPanes", "CustomTaskPanes", this); } /// [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Tools.Office.ProgrammingModel.dll", "15.0.0.0")] [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Never)] private void InitializeComponents() { } /// [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] private bool NeedsFill(string MemberName) { return this.DataHost.NeedsFill(this, MemberName); } /// [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Tools.Office.ProgrammingModel.dll", "15.0.0.0")] [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Never)] protected override void OnShutdown() { this.CustomTaskPanes.Dispose(); base.OnShutdown(); } } /// [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Tools.Office.ProgrammingModel.dll", "15.0.0.0")] internal sealed partial class Globals { /// private Globals() { } private static ThisAddIn _ThisAddIn; private static global::Microsoft.Office.Tools.Outlook.Factory _factory; private static ThisRibbonCollection _ThisRibbonCollection; private static ThisFormRegionCollection _ThisFormRegionCollection; internal static ThisAddIn ThisAddIn { get { return _ThisAddIn; } set { if ((_ThisAddIn == null)) { _ThisAddIn = value; } else { throw new System.NotSupportedException(); } } } internal static global::Microsoft.Office.Tools.Outlook.Factory Factory { get { return _factory; } set { if ((_factory == null)) { _factory = value; } else { throw new System.NotSupportedException(); } } } internal static ThisRibbonCollection Ribbons { get { if ((_ThisRibbonCollection == null)) { _ThisRibbonCollection = new ThisRibbonCollection(_factory.GetRibbonFactory()); } return _ThisRibbonCollection; } } internal static ThisFormRegionCollection FormRegions { get { if ((_ThisFormRegionCollection == null)) { _ThisFormRegionCollection = new ThisFormRegionCollection(Globals.ThisAddIn.GetFormRegions()); } return _ThisFormRegionCollection; } } } /// [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Tools.Office.ProgrammingModel.dll", "15.0.0.0")] internal sealed partial class ThisRibbonCollection : Microsoft.Office.Tools.Ribbon.RibbonCollectionBase { /// internal ThisRibbonCollection(global::Microsoft.Office.Tools.Ribbon.RibbonFactory factory) : base(factory) { } internal ThisRibbonCollection this[Microsoft.Office.Interop.Outlook.Inspector inspector] { get { return this.GetRibbonContextCollection<ThisRibbonCollection>(inspector); } } internal ThisRibbonCollection this[Microsoft.Office.Interop.Outlook.Explorer explorer] { get { return this.GetRibbonContextCollection<ThisRibbonCollection>(explorer); } } } /// [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] internal sealed partial class ThisFormRegionCollection : Microsoft.Office.Tools.Outlook.FormRegionCollectionBase { /// public ThisFormRegionCollection(System.Collections.Generic.IList<Microsoft.Office.Tools.Outlook.IFormRegion> list) : base(list) { } internal WindowFormRegionCollection this[Microsoft.Office.Interop.Outlook.Explorer explorer] { get { return ((WindowFormRegionCollection)(Globals.ThisAddIn.GetFormRegions(explorer, typeof(WindowFormRegionCollection)))); } } internal WindowFormRegionCollection this[Microsoft.Office.Interop.Outlook.Inspector inspector] { get { return ((WindowFormRegionCollection)(Globals.ThisAddIn.GetFormRegions(inspector, typeof(WindowFormRegionCollection)))); } } } /// [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] internal sealed partial class WindowFormRegionCollection : Microsoft.Office.Tools.Outlook.FormRegionCollectionBase { /// public WindowFormRegionCollection(System.Collections.Generic.IList<Microsoft.Office.Tools.Outlook.IFormRegion> list) : base(list) { } } }
47.034843
164
0.632639
[ "MIT" ]
ctudoudou/OutlookAddIn4DontCloseMe
DontClose/ThisAddIn.Designer.cs
13,501
C#
// <auto-generated /> using System; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Migrations; using Microsoft.EntityFrameworkCore.Storage.ValueConversion; namespace FishSpinDays.Data.Migrations { [DbContext(typeof(FishSpinDaysDbContext))] [Migration("00000000000000_CreateIdentitySchema")] partial class CreateIdentitySchema { protected override void BuildTargetModel(ModelBuilder modelBuilder) { #pragma warning disable 612, 618 modelBuilder .HasAnnotation("ProductVersion", "2.1.0") .HasAnnotation("Relational:MaxIdentifierLength", 128) .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole", b => { b.Property<string>("Id") .ValueGeneratedOnAdd(); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken(); b.Property<string>("Name") .HasMaxLength(256); b.Property<string>("NormalizedName") .HasMaxLength(256); b.HasKey("Id"); b.HasIndex("NormalizedName") .IsUnique() .HasName("RoleNameIndex") .HasFilter("[NormalizedName] IS NOT NULL"); b.ToTable("AspNetRoles"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<string>", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("ClaimType"); b.Property<string>("ClaimValue"); b.Property<string>("RoleId") .IsRequired(); b.HasKey("Id"); b.HasIndex("RoleId"); b.ToTable("AspNetRoleClaims"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUser", b => { b.Property<string>("Id") .ValueGeneratedOnAdd(); b.Property<int>("AccessFailedCount"); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken(); b.Property<string>("Email") .HasMaxLength(256); b.Property<bool>("EmailConfirmed"); b.Property<bool>("LockoutEnabled"); b.Property<DateTimeOffset?>("LockoutEnd"); b.Property<string>("NormalizedEmail") .HasMaxLength(256); b.Property<string>("NormalizedUserName") .HasMaxLength(256); b.Property<string>("PasswordHash"); b.Property<string>("PhoneNumber"); b.Property<bool>("PhoneNumberConfirmed"); b.Property<string>("SecurityStamp"); b.Property<bool>("TwoFactorEnabled"); b.Property<string>("UserName") .HasMaxLength(256); b.HasKey("Id"); b.HasIndex("NormalizedEmail") .HasName("EmailIndex"); b.HasIndex("NormalizedUserName") .IsUnique() .HasName("UserNameIndex") .HasFilter("[NormalizedUserName] IS NOT NULL"); b.ToTable("AspNetUsers"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<string>", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("ClaimType"); b.Property<string>("ClaimValue"); b.Property<string>("UserId") .IsRequired(); b.HasKey("Id"); b.HasIndex("UserId"); b.ToTable("AspNetUserClaims"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<string>", b => { b.Property<string>("LoginProvider") .HasMaxLength(128); b.Property<string>("ProviderKey") .HasMaxLength(128); b.Property<string>("ProviderDisplayName"); b.Property<string>("UserId") .IsRequired(); b.HasKey("LoginProvider", "ProviderKey"); b.HasIndex("UserId"); b.ToTable("AspNetUserLogins"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<string>", b => { b.Property<string>("UserId"); b.Property<string>("RoleId"); b.HasKey("UserId", "RoleId"); b.HasIndex("RoleId"); b.ToTable("AspNetUserRoles"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<string>", b => { b.Property<string>("UserId"); b.Property<string>("LoginProvider") .HasMaxLength(128); b.Property<string>("Name") .HasMaxLength(128); b.Property<string>("Value"); b.HasKey("UserId", "LoginProvider", "Name"); b.ToTable("AspNetUserTokens"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<string>", b => { b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole") .WithMany() .HasForeignKey("RoleId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<string>", b => { b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser") .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<string>", b => { b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser") .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<string>", b => { b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole") .WithMany() .HasForeignKey("RoleId") .OnDelete(DeleteBehavior.Cascade); b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser") .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<string>", b => { b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser") .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade); }); #pragma warning restore 612, 618 } } }
35.080508
125
0.487378
[ "MIT" ]
hrimar/MyFirstOwnWebProject-FishSpinDays
FishSpinDays/FishSpinDays.Data/Migrations/00000000000000_CreateIdentitySchema.Designer.cs
8,279
C#
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; namespace GISShare.Controls.Plugin.WinForm { public partial class UIViewForm : Form { public UIViewForm(GISShare.Controls.WinForm.WFNew.View.NodeViewItem nodeViewItem) { InitializeComponent(); // // // this.nodeViewItemTree1.NodeViewItems.Add(nodeViewItem); } private void btnExpandAll_MouseClick(object sender, MouseEventArgs e) { this.nodeViewItemTree1.ExpandAll(); } private void btnCollapseAll_MouseClick(object sender, MouseEventArgs e) { this.nodeViewItemTree1.CollapseAll(); } } }
25
89
0.644848
[ "MIT" ]
gisshare2015/GISShare.Controls.WinForm
GISShare.Controls.Plugin.WinForm/ChildForm/UIViewForm.cs
827
C#
using UnityEngine; using System.Collections; public class ExitOnEscape : MonoBehaviour { void Update () { if(Input.GetKeyUp(KeyCode.Escape)) Application.Quit(); // TODO: "Are you sure?" } }
17.25
51
0.681159
[ "Unlicense" ]
kaefergeneral/ZeldaVR
ZeldaVR/Assets/Immersio/General/ExitOnEscape.cs
207
C#
using MediatR; using Microsoft.Extensions.DependencyInjection; namespace Project.Application.Configuration.Commands { public static class Dependencies { public static IServiceCollection RegisterRequestHandlers( this IServiceCollection services) { return services.AddMediatR(typeof(Dependencies).Assembly); } } }
24.933333
70
0.708556
[ "MIT" ]
henrygustavo/cqrs-api
Project.Application/Configuration/Commands/Dependencies.cs
376
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class DroneBlades : MonoBehaviour { public GameObject BladeOne, BladeTwo, BladeThree, BladeFour; public int RotationsPerMinute = 200; private void Update() { if (Drone.instance != null) { RotateBladeThree(); RotateBladeFour(); RotateBladeOne(); RotateBladeTwo(); } } private void RotateBladeThree() { Vector3 temp = new Vector3(0, 3 * RotationsPerMinute * Time.deltaTime, 0);//rotate a certain amount per minute by default if(Drone.instance.Pitch != 0 || Drone.instance.Roll != 0) { temp = new Vector3(0, 15 * RotationsPerMinute * Time.deltaTime, 0); if (Drone.instance.Pitch > 0) //if going forward { temp.y *= (Mathf.Clamp(1 - Drone.instance.Pitch, 0.25f, 0.5f)); } else if (Drone.instance.Pitch < 0) //if going back { temp.y *= (Mathf.Clamp(Mathf.Abs(Drone.instance.Pitch), 0.5f, 1f)); } if (Drone.instance.Roll > 0) { temp.y *= (Mathf.Clamp(Drone.instance.Roll, 0.5f, 1f)); } else if (Drone.instance.Roll < 0) { temp.y *= (Mathf.Clamp(1 - Mathf.Abs(Drone.instance.Roll), 0.25f, 0.5f)); } } BladeThree.transform.Rotate(temp); } private void RotateBladeFour() { Vector3 temp = new Vector3(0, 3 * RotationsPerMinute * Time.deltaTime, 0);//rotate a certain amount per minute by default if (Drone.instance.Pitch != 0 || Drone.instance.Roll != 0) { temp = new Vector3(0, 15 * RotationsPerMinute * Time.deltaTime, 0); if (Drone.instance.Pitch > 0) //if going forward { temp.y *= (Mathf.Clamp(1 - Drone.instance.Pitch, 0.25f, 0.5f)); } else if (Drone.instance.Pitch < 0) //if going back { temp.y *= (Mathf.Clamp(Mathf.Abs(Drone.instance.Pitch), 0.5f, 1f)); } if (Drone.instance.Roll < 0) { temp.y *= (Mathf.Clamp(Mathf.Abs(Drone.instance.Roll), 0.5f, 1f)); } else if (Drone.instance.Roll > 0) { temp.y *= (Mathf.Clamp(1 - Mathf.Abs(Drone.instance.Roll), 0.25f, 0.5f)); } } BladeFour.transform.Rotate(temp); } private void RotateBladeOne() { Vector3 temp = new Vector3(0, 3 * RotationsPerMinute * Time.deltaTime, 0);//rotate a certain amount per minute by default if (Drone.instance.Pitch != 0 || Drone.instance.Roll != 0) { temp = new Vector3(0, 15 * RotationsPerMinute * Time.deltaTime, 0); if (Drone.instance.Pitch > 0) //if going forward { temp.y *= (Mathf.Clamp(Drone.instance.Pitch, 0.5f, 1f)); } else if (Drone.instance.Pitch < 0) //if going back { temp.y *= (Mathf.Clamp(1 - Mathf.Abs(Drone.instance.Pitch), 0.25f, 0.5f)); } if (Drone.instance.Roll < 0) { temp.y *= (Mathf.Clamp(Mathf.Abs(Drone.instance.Roll), 0.5f, 1f)); } else if (Drone.instance.Roll > 0) { temp.y *= (Mathf.Clamp(1 - Mathf.Abs(Drone.instance.Roll), 0.25f, 0.5f)); } } BladeOne.transform.Rotate(temp); } private void RotateBladeTwo() { Vector3 temp = new Vector3(0, 3 * RotationsPerMinute * Time.deltaTime, 0);//rotate a certain amount per minute by default if (Drone.instance.Pitch != 0 || Drone.instance.Roll != 0) { temp = new Vector3(0, 15 * RotationsPerMinute * Time.deltaTime, 0); if (Drone.instance.Pitch > 0) //if going forward { temp.y *= (Mathf.Clamp(Drone.instance.Pitch, 0.5f, 1f)); } else if (Drone.instance.Pitch < 0) //if going back { temp.y *= (Mathf.Clamp(1 - Mathf.Abs(Drone.instance.Pitch), 0.25f, 0.5f)); } if (Drone.instance.Roll < 0) { temp.y *= (Mathf.Clamp(1 - Drone.instance.Roll, 0.25f, 0.5f)); } else if (Drone.instance.Roll > 0) { temp.y *= (Mathf.Clamp( Mathf.Abs(Drone.instance.Roll), 0.5f, 1f)); } } BladeTwo.transform.Rotate(temp); } }
36.92
129
0.51571
[ "MIT" ]
pertinate/ParcEx
ParcEx/Assets/Scripts/Drone control/DroneBlades.cs
4,617
C#
/* * MIT License - Copyright(c) 2020 Sean Moss * This file is subject to the terms and conditions of the MIT License, the text of which can be found in the 'LICENSE' * file at the root of this repository, or online at <https://opensource.org/licenses/MIT>. */ /// This file was generated by VVKGen. Edits to this file will be lost on next generation. using System; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; namespace Vulkan { public unsafe static partial class StaticFunctionTable { /* Global Functions */ private static readonly delegate* unmanaged<VkInstanceCreateInfo*, VkAllocationCallbacks*, VulkanHandle<VkInstance>*, VkResult> _vkCreateInstance = null; private static readonly delegate* unmanaged<VulkanHandle<VkDevice>, byte*, delegate* unmanaged<void>> _vkGetDeviceProcAddr = null; private static readonly delegate* unmanaged<VulkanHandle<VkInstance>, byte*, delegate* unmanaged<void>> _vkGetInstanceProcAddr = null; private static readonly delegate* unmanaged<uint*, VkResult> _vkEnumerateInstanceVersion = null; private static readonly delegate* unmanaged<uint*, VkLayerProperties*, VkResult> _vkEnumerateInstanceLayerProperties = null; private static readonly delegate* unmanaged<byte*, uint*, VkExtensionProperties*, VkResult> _vkEnumerateInstanceExtensionProperties = null; /* Instance Functions */ private static delegate* unmanaged<VulkanHandle<VkInstance>, VkAllocationCallbacks*, void> _vkDestroyInstance = null; private static delegate* unmanaged<VulkanHandle<VkInstance>, uint*, VulkanHandle<VkPhysicalDevice>*, VkResult> _vkEnumeratePhysicalDevices = null; private static delegate* unmanaged<VulkanHandle<VkPhysicalDevice>, VkPhysicalDeviceProperties*, void> _vkGetPhysicalDeviceProperties = null; private static delegate* unmanaged<VulkanHandle<VkPhysicalDevice>, uint*, VkQueueFamilyProperties*, void> _vkGetPhysicalDeviceQueueFamilyProperties = null; private static delegate* unmanaged<VulkanHandle<VkPhysicalDevice>, VkPhysicalDeviceMemoryProperties*, void> _vkGetPhysicalDeviceMemoryProperties = null; private static delegate* unmanaged<VulkanHandle<VkPhysicalDevice>, VkPhysicalDeviceFeatures*, void> _vkGetPhysicalDeviceFeatures = null; private static delegate* unmanaged<VulkanHandle<VkPhysicalDevice>, VkFormat, VkFormatProperties*, void> _vkGetPhysicalDeviceFormatProperties = null; private static delegate* unmanaged<VulkanHandle<VkPhysicalDevice>, VkFormat, VkImageType, VkImageTiling, VkImageUsageFlags, VkImageCreateFlags, VkImageFormatProperties*, VkResult> _vkGetPhysicalDeviceImageFormatProperties = null; private static delegate* unmanaged<VulkanHandle<VkPhysicalDevice>, VkDeviceCreateInfo*, VkAllocationCallbacks*, VulkanHandle<VkDevice>*, VkResult> _vkCreateDevice = null; private static delegate* unmanaged<VulkanHandle<VkPhysicalDevice>, uint*, VkLayerProperties*, VkResult> _vkEnumerateDeviceLayerProperties = null; private static delegate* unmanaged<VulkanHandle<VkPhysicalDevice>, byte*, uint*, VkExtensionProperties*, VkResult> _vkEnumerateDeviceExtensionProperties = null; private static delegate* unmanaged<VulkanHandle<VkPhysicalDevice>, VkFormat, VkImageType, VkSampleCountFlags, VkImageUsageFlags, VkImageTiling, uint*, VkSparseImageFormatProperties*, void> _vkGetPhysicalDeviceSparseImageFormatProperties = null; private static delegate* unmanaged<VulkanHandle<VkInstance>, VkAndroidSurfaceCreateInfoKHR*, VkAllocationCallbacks*, VulkanHandle<VkSurfaceKHR>*, VkResult> _vkCreateAndroidSurfaceKHR = null; private static delegate* unmanaged<VulkanHandle<VkPhysicalDevice>, uint*, VkDisplayPropertiesKHR*, VkResult> _vkGetPhysicalDeviceDisplayPropertiesKHR = null; private static delegate* unmanaged<VulkanHandle<VkPhysicalDevice>, uint*, VkDisplayPlanePropertiesKHR*, VkResult> _vkGetPhysicalDeviceDisplayPlanePropertiesKHR = null; private static delegate* unmanaged<VulkanHandle<VkPhysicalDevice>, uint, uint*, VulkanHandle<VkDisplayKHR>*, VkResult> _vkGetDisplayPlaneSupportedDisplaysKHR = null; private static delegate* unmanaged<VulkanHandle<VkPhysicalDevice>, VulkanHandle<VkDisplayKHR>, uint*, VkDisplayModePropertiesKHR*, VkResult> _vkGetDisplayModePropertiesKHR = null; private static delegate* unmanaged<VulkanHandle<VkPhysicalDevice>, VulkanHandle<VkDisplayKHR>, VkDisplayModeCreateInfoKHR*, VkAllocationCallbacks*, VulkanHandle<VkDisplayModeKHR>*, VkResult> _vkCreateDisplayModeKHR = null; private static delegate* unmanaged<VulkanHandle<VkPhysicalDevice>, VulkanHandle<VkDisplayModeKHR>, uint, VkDisplayPlaneCapabilitiesKHR*, VkResult> _vkGetDisplayPlaneCapabilitiesKHR = null; private static delegate* unmanaged<VulkanHandle<VkInstance>, VkDisplaySurfaceCreateInfoKHR*, VkAllocationCallbacks*, VulkanHandle<VkSurfaceKHR>*, VkResult> _vkCreateDisplayPlaneSurfaceKHR = null; private static delegate* unmanaged<VulkanHandle<VkInstance>, VulkanHandle<VkSurfaceKHR>, VkAllocationCallbacks*, void> _vkDestroySurfaceKHR = null; private static delegate* unmanaged<VulkanHandle<VkPhysicalDevice>, uint, VulkanHandle<VkSurfaceKHR>, VkBool32*, VkResult> _vkGetPhysicalDeviceSurfaceSupportKHR = null; private static delegate* unmanaged<VulkanHandle<VkPhysicalDevice>, VulkanHandle<VkSurfaceKHR>, VkSurfaceCapabilitiesKHR*, VkResult> _vkGetPhysicalDeviceSurfaceCapabilitiesKHR = null; private static delegate* unmanaged<VulkanHandle<VkPhysicalDevice>, VulkanHandle<VkSurfaceKHR>, uint*, VkSurfaceFormatKHR*, VkResult> _vkGetPhysicalDeviceSurfaceFormatsKHR = null; private static delegate* unmanaged<VulkanHandle<VkPhysicalDevice>, VulkanHandle<VkSurfaceKHR>, uint*, VkPresentModeKHR*, VkResult> _vkGetPhysicalDeviceSurfacePresentModesKHR = null; private static delegate* unmanaged<VulkanHandle<VkInstance>, VkViSurfaceCreateInfoNN*, VkAllocationCallbacks*, VulkanHandle<VkSurfaceKHR>*, VkResult> _vkCreateViSurfaceNN = null; private static delegate* unmanaged<VulkanHandle<VkInstance>, VkWaylandSurfaceCreateInfoKHR*, VkAllocationCallbacks*, VulkanHandle<VkSurfaceKHR>*, VkResult> _vkCreateWaylandSurfaceKHR = null; private static delegate* unmanaged<VulkanHandle<VkPhysicalDevice>, uint, void*, VkBool32> _vkGetPhysicalDeviceWaylandPresentationSupportKHR = null; private static delegate* unmanaged<VulkanHandle<VkInstance>, VkWin32SurfaceCreateInfoKHR*, VkAllocationCallbacks*, VulkanHandle<VkSurfaceKHR>*, VkResult> _vkCreateWin32SurfaceKHR = null; private static delegate* unmanaged<VulkanHandle<VkPhysicalDevice>, uint, VkBool32> _vkGetPhysicalDeviceWin32PresentationSupportKHR = null; private static delegate* unmanaged<VulkanHandle<VkInstance>, VkXlibSurfaceCreateInfoKHR*, VkAllocationCallbacks*, VulkanHandle<VkSurfaceKHR>*, VkResult> _vkCreateXlibSurfaceKHR = null; private static delegate* unmanaged<VulkanHandle<VkPhysicalDevice>, uint, void*, ulong, VkBool32> _vkGetPhysicalDeviceXlibPresentationSupportKHR = null; private static delegate* unmanaged<VulkanHandle<VkInstance>, VkXcbSurfaceCreateInfoKHR*, VkAllocationCallbacks*, VulkanHandle<VkSurfaceKHR>*, VkResult> _vkCreateXcbSurfaceKHR = null; private static delegate* unmanaged<VulkanHandle<VkPhysicalDevice>, uint, void*, uint, VkBool32> _vkGetPhysicalDeviceXcbPresentationSupportKHR = null; private static delegate* unmanaged<VulkanHandle<VkInstance>, VkDirectFBSurfaceCreateInfoEXT*, VkAllocationCallbacks*, VulkanHandle<VkSurfaceKHR>*, VkResult> _vkCreateDirectFBSurfaceEXT = null; private static delegate* unmanaged<VulkanHandle<VkPhysicalDevice>, uint, void*, VkBool32> _vkGetPhysicalDeviceDirectFBPresentationSupportEXT = null; private static delegate* unmanaged<VulkanHandle<VkInstance>, VkImagePipeSurfaceCreateInfoFUCHSIA*, VkAllocationCallbacks*, VulkanHandle<VkSurfaceKHR>*, VkResult> _vkCreateImagePipeSurfaceFUCHSIA = null; private static delegate* unmanaged<VulkanHandle<VkInstance>, VkStreamDescriptorSurfaceCreateInfoGGP*, VkAllocationCallbacks*, VulkanHandle<VkSurfaceKHR>*, VkResult> _vkCreateStreamDescriptorSurfaceGGP = null; private static delegate* unmanaged<VulkanHandle<VkInstance>, VkDebugReportCallbackCreateInfoEXT*, VkAllocationCallbacks*, VulkanHandle<VkDebugReportCallbackEXT>*, VkResult> _vkCreateDebugReportCallbackEXT = null; private static delegate* unmanaged<VulkanHandle<VkInstance>, VulkanHandle<VkDebugReportCallbackEXT>, VkAllocationCallbacks*, void> _vkDestroyDebugReportCallbackEXT = null; private static delegate* unmanaged<VulkanHandle<VkInstance>, VkDebugReportFlagsEXT, VkDebugReportObjectTypeEXT, ulong, ulong, int, byte*, byte*, void> _vkDebugReportMessageEXT = null; private static delegate* unmanaged<VulkanHandle<VkPhysicalDevice>, VkFormat, VkImageType, VkImageTiling, VkImageUsageFlags, VkImageCreateFlags, VkExternalMemoryHandleTypeFlagsNV, VkExternalImageFormatPropertiesNV*, VkResult> _vkGetPhysicalDeviceExternalImageFormatPropertiesNV = null; private static delegate* unmanaged<VulkanHandle<VkPhysicalDevice>, VkPhysicalDeviceFeatures2*, void> _vkGetPhysicalDeviceFeatures2 = null; private static delegate* unmanaged<VulkanHandle<VkPhysicalDevice>, VkPhysicalDeviceFeatures2*, void> _vkGetPhysicalDeviceFeatures2KHR = null; private static delegate* unmanaged<VulkanHandle<VkPhysicalDevice>, VkPhysicalDeviceProperties2*, void> _vkGetPhysicalDeviceProperties2 = null; private static delegate* unmanaged<VulkanHandle<VkPhysicalDevice>, VkPhysicalDeviceProperties2*, void> _vkGetPhysicalDeviceProperties2KHR = null; private static delegate* unmanaged<VulkanHandle<VkPhysicalDevice>, VkFormat, VkFormatProperties2*, void> _vkGetPhysicalDeviceFormatProperties2 = null; private static delegate* unmanaged<VulkanHandle<VkPhysicalDevice>, VkFormat, VkFormatProperties2*, void> _vkGetPhysicalDeviceFormatProperties2KHR = null; private static delegate* unmanaged<VulkanHandle<VkPhysicalDevice>, VkPhysicalDeviceImageFormatInfo2*, VkImageFormatProperties2*, VkResult> _vkGetPhysicalDeviceImageFormatProperties2 = null; private static delegate* unmanaged<VulkanHandle<VkPhysicalDevice>, VkPhysicalDeviceImageFormatInfo2*, VkImageFormatProperties2*, VkResult> _vkGetPhysicalDeviceImageFormatProperties2KHR = null; private static delegate* unmanaged<VulkanHandle<VkPhysicalDevice>, uint*, VkQueueFamilyProperties2*, void> _vkGetPhysicalDeviceQueueFamilyProperties2 = null; private static delegate* unmanaged<VulkanHandle<VkPhysicalDevice>, uint*, VkQueueFamilyProperties2*, void> _vkGetPhysicalDeviceQueueFamilyProperties2KHR = null; private static delegate* unmanaged<VulkanHandle<VkPhysicalDevice>, VkPhysicalDeviceMemoryProperties2*, void> _vkGetPhysicalDeviceMemoryProperties2 = null; private static delegate* unmanaged<VulkanHandle<VkPhysicalDevice>, VkPhysicalDeviceMemoryProperties2*, void> _vkGetPhysicalDeviceMemoryProperties2KHR = null; private static delegate* unmanaged<VulkanHandle<VkPhysicalDevice>, VkPhysicalDeviceSparseImageFormatInfo2*, uint*, VkSparseImageFormatProperties2*, void> _vkGetPhysicalDeviceSparseImageFormatProperties2 = null; private static delegate* unmanaged<VulkanHandle<VkPhysicalDevice>, VkPhysicalDeviceSparseImageFormatInfo2*, uint*, VkSparseImageFormatProperties2*, void> _vkGetPhysicalDeviceSparseImageFormatProperties2KHR = null; private static delegate* unmanaged<VulkanHandle<VkPhysicalDevice>, VkPhysicalDeviceExternalBufferInfo*, VkExternalBufferProperties*, void> _vkGetPhysicalDeviceExternalBufferProperties = null; private static delegate* unmanaged<VulkanHandle<VkPhysicalDevice>, VkPhysicalDeviceExternalBufferInfo*, VkExternalBufferProperties*, void> _vkGetPhysicalDeviceExternalBufferPropertiesKHR = null; private static delegate* unmanaged<VulkanHandle<VkPhysicalDevice>, VkPhysicalDeviceExternalSemaphoreInfo*, VkExternalSemaphoreProperties*, void> _vkGetPhysicalDeviceExternalSemaphoreProperties = null; private static delegate* unmanaged<VulkanHandle<VkPhysicalDevice>, VkPhysicalDeviceExternalSemaphoreInfo*, VkExternalSemaphoreProperties*, void> _vkGetPhysicalDeviceExternalSemaphorePropertiesKHR = null; private static delegate* unmanaged<VulkanHandle<VkPhysicalDevice>, VkPhysicalDeviceExternalFenceInfo*, VkExternalFenceProperties*, void> _vkGetPhysicalDeviceExternalFenceProperties = null; private static delegate* unmanaged<VulkanHandle<VkPhysicalDevice>, VkPhysicalDeviceExternalFenceInfo*, VkExternalFenceProperties*, void> _vkGetPhysicalDeviceExternalFencePropertiesKHR = null; private static delegate* unmanaged<VulkanHandle<VkPhysicalDevice>, VulkanHandle<VkDisplayKHR>, VkResult> _vkReleaseDisplayEXT = null; private static delegate* unmanaged<VulkanHandle<VkPhysicalDevice>, void*, VulkanHandle<VkDisplayKHR>, VkResult> _vkAcquireXlibDisplayEXT = null; private static delegate* unmanaged<VulkanHandle<VkPhysicalDevice>, void*, ulong, VulkanHandle<VkDisplayKHR>*, VkResult> _vkGetRandROutputDisplayEXT = null; private static delegate* unmanaged<VulkanHandle<VkPhysicalDevice>, VulkanHandle<VkDisplayKHR>, VkResult> _vkAcquireWinrtDisplayNV = null; private static delegate* unmanaged<VulkanHandle<VkPhysicalDevice>, uint, VulkanHandle<VkDisplayKHR>*, VkResult> _vkGetWinrtDisplayNV = null; private static delegate* unmanaged<VulkanHandle<VkPhysicalDevice>, VulkanHandle<VkSurfaceKHR>, VkSurfaceCapabilities2EXT*, VkResult> _vkGetPhysicalDeviceSurfaceCapabilities2EXT = null; private static delegate* unmanaged<VulkanHandle<VkInstance>, uint*, VkPhysicalDeviceGroupProperties*, VkResult> _vkEnumeratePhysicalDeviceGroups = null; private static delegate* unmanaged<VulkanHandle<VkInstance>, uint*, VkPhysicalDeviceGroupProperties*, VkResult> _vkEnumeratePhysicalDeviceGroupsKHR = null; private static delegate* unmanaged<VulkanHandle<VkPhysicalDevice>, VulkanHandle<VkSurfaceKHR>, uint*, VkRect2D*, VkResult> _vkGetPhysicalDevicePresentRectanglesKHR = null; private static delegate* unmanaged<VulkanHandle<VkInstance>, VkIOSSurfaceCreateInfoMVK*, VkAllocationCallbacks*, VulkanHandle<VkSurfaceKHR>*, VkResult> _vkCreateIOSSurfaceMVK = null; private static delegate* unmanaged<VulkanHandle<VkInstance>, VkMacOSSurfaceCreateInfoMVK*, VkAllocationCallbacks*, VulkanHandle<VkSurfaceKHR>*, VkResult> _vkCreateMacOSSurfaceMVK = null; private static delegate* unmanaged<VulkanHandle<VkInstance>, VkMetalSurfaceCreateInfoEXT*, VkAllocationCallbacks*, VulkanHandle<VkSurfaceKHR>*, VkResult> _vkCreateMetalSurfaceEXT = null; private static delegate* unmanaged<VulkanHandle<VkPhysicalDevice>, VkSampleCountFlags, VkMultisamplePropertiesEXT*, void> _vkGetPhysicalDeviceMultisamplePropertiesEXT = null; private static delegate* unmanaged<VulkanHandle<VkPhysicalDevice>, VkPhysicalDeviceSurfaceInfo2KHR*, VkSurfaceCapabilities2KHR*, VkResult> _vkGetPhysicalDeviceSurfaceCapabilities2KHR = null; private static delegate* unmanaged<VulkanHandle<VkPhysicalDevice>, VkPhysicalDeviceSurfaceInfo2KHR*, uint*, VkSurfaceFormat2KHR*, VkResult> _vkGetPhysicalDeviceSurfaceFormats2KHR = null; private static delegate* unmanaged<VulkanHandle<VkPhysicalDevice>, uint*, VkDisplayProperties2KHR*, VkResult> _vkGetPhysicalDeviceDisplayProperties2KHR = null; private static delegate* unmanaged<VulkanHandle<VkPhysicalDevice>, uint*, VkDisplayPlaneProperties2KHR*, VkResult> _vkGetPhysicalDeviceDisplayPlaneProperties2KHR = null; private static delegate* unmanaged<VulkanHandle<VkPhysicalDevice>, VulkanHandle<VkDisplayKHR>, uint*, VkDisplayModeProperties2KHR*, VkResult> _vkGetDisplayModeProperties2KHR = null; private static delegate* unmanaged<VulkanHandle<VkPhysicalDevice>, VkDisplayPlaneInfo2KHR*, VkDisplayPlaneCapabilities2KHR*, VkResult> _vkGetDisplayPlaneCapabilities2KHR = null; private static delegate* unmanaged<VulkanHandle<VkPhysicalDevice>, uint*, VkTimeDomainEXT*, VkResult> _vkGetPhysicalDeviceCalibrateableTimeDomainsEXT = null; private static delegate* unmanaged<VulkanHandle<VkInstance>, VkDebugUtilsMessengerCreateInfoEXT*, VkAllocationCallbacks*, VulkanHandle<VkDebugUtilsMessengerEXT>*, VkResult> _vkCreateDebugUtilsMessengerEXT = null; private static delegate* unmanaged<VulkanHandle<VkInstance>, VulkanHandle<VkDebugUtilsMessengerEXT>, VkAllocationCallbacks*, void> _vkDestroyDebugUtilsMessengerEXT = null; private static delegate* unmanaged<VulkanHandle<VkInstance>, VkDebugUtilsMessageSeverityFlagsEXT, VkDebugUtilsMessageTypeFlagsEXT, VkDebugUtilsMessengerCallbackDataEXT*, void> _vkSubmitDebugUtilsMessageEXT = null; private static delegate* unmanaged<VulkanHandle<VkPhysicalDevice>, uint*, VkCooperativeMatrixPropertiesNV*, VkResult> _vkGetPhysicalDeviceCooperativeMatrixPropertiesNV = null; private static delegate* unmanaged<VulkanHandle<VkPhysicalDevice>, VkPhysicalDeviceSurfaceInfo2KHR*, uint*, VkPresentModeKHR*, VkResult> _vkGetPhysicalDeviceSurfacePresentModes2EXT = null; private static delegate* unmanaged<VulkanHandle<VkPhysicalDevice>, uint, uint*, VkPerformanceCounterKHR*, VkPerformanceCounterDescriptionKHR*, VkResult> _vkEnumeratePhysicalDeviceQueueFamilyPerformanceQueryCountersKHR = null; private static delegate* unmanaged<VulkanHandle<VkPhysicalDevice>, VkQueryPoolPerformanceCreateInfoKHR*, uint*, void> _vkGetPhysicalDeviceQueueFamilyPerformanceQueryPassesKHR = null; private static delegate* unmanaged<VulkanHandle<VkInstance>, VkHeadlessSurfaceCreateInfoEXT*, VkAllocationCallbacks*, VulkanHandle<VkSurfaceKHR>*, VkResult> _vkCreateHeadlessSurfaceEXT = null; private static delegate* unmanaged<VulkanHandle<VkPhysicalDevice>, uint*, VkFramebufferMixedSamplesCombinationNV*, VkResult> _vkGetPhysicalDeviceSupportedFramebufferMixedSamplesCombinationsNV = null; private static delegate* unmanaged<VulkanHandle<VkPhysicalDevice>, uint*, VkPhysicalDeviceToolPropertiesEXT*, VkResult> _vkGetPhysicalDeviceToolPropertiesEXT = null; private static delegate* unmanaged<VulkanHandle<VkPhysicalDevice>, uint*, VkPhysicalDeviceFragmentShadingRateKHR*, VkResult> _vkGetPhysicalDeviceFragmentShadingRatesKHR = null; /* Device Functions */ private static delegate* unmanaged<VulkanHandle<VkDevice>, VkAllocationCallbacks*, void> _vkDestroyDevice = null; private static delegate* unmanaged<VulkanHandle<VkDevice>, uint, uint, VulkanHandle<VkQueue>*, void> _vkGetDeviceQueue = null; private static delegate* unmanaged<VulkanHandle<VkQueue>, uint, VkSubmitInfo*, VulkanHandle<VkFence>, VkResult> _vkQueueSubmit = null; private static delegate* unmanaged<VulkanHandle<VkQueue>, VkResult> _vkQueueWaitIdle = null; private static delegate* unmanaged<VulkanHandle<VkDevice>, VkResult> _vkDeviceWaitIdle = null; private static delegate* unmanaged<VulkanHandle<VkDevice>, VkMemoryAllocateInfo*, VkAllocationCallbacks*, VulkanHandle<VkDeviceMemory>*, VkResult> _vkAllocateMemory = null; private static delegate* unmanaged<VulkanHandle<VkDevice>, VulkanHandle<VkDeviceMemory>, VkAllocationCallbacks*, void> _vkFreeMemory = null; private static delegate* unmanaged<VulkanHandle<VkDevice>, VulkanHandle<VkDeviceMemory>, ulong, ulong, VkMemoryMapFlags, void**, VkResult> _vkMapMemory = null; private static delegate* unmanaged<VulkanHandle<VkDevice>, VulkanHandle<VkDeviceMemory>, void> _vkUnmapMemory = null; private static delegate* unmanaged<VulkanHandle<VkDevice>, uint, VkMappedMemoryRange*, VkResult> _vkFlushMappedMemoryRanges = null; private static delegate* unmanaged<VulkanHandle<VkDevice>, uint, VkMappedMemoryRange*, VkResult> _vkInvalidateMappedMemoryRanges = null; private static delegate* unmanaged<VulkanHandle<VkDevice>, VulkanHandle<VkDeviceMemory>, ulong*, void> _vkGetDeviceMemoryCommitment = null; private static delegate* unmanaged<VulkanHandle<VkDevice>, VulkanHandle<VkBuffer>, VkMemoryRequirements*, void> _vkGetBufferMemoryRequirements = null; private static delegate* unmanaged<VulkanHandle<VkDevice>, VulkanHandle<VkBuffer>, VulkanHandle<VkDeviceMemory>, ulong, VkResult> _vkBindBufferMemory = null; private static delegate* unmanaged<VulkanHandle<VkDevice>, VulkanHandle<VkImage>, VkMemoryRequirements*, void> _vkGetImageMemoryRequirements = null; private static delegate* unmanaged<VulkanHandle<VkDevice>, VulkanHandle<VkImage>, VulkanHandle<VkDeviceMemory>, ulong, VkResult> _vkBindImageMemory = null; private static delegate* unmanaged<VulkanHandle<VkDevice>, VulkanHandle<VkImage>, uint*, VkSparseImageMemoryRequirements*, void> _vkGetImageSparseMemoryRequirements = null; private static delegate* unmanaged<VulkanHandle<VkQueue>, uint, VkBindSparseInfo*, VulkanHandle<VkFence>, VkResult> _vkQueueBindSparse = null; private static delegate* unmanaged<VulkanHandle<VkDevice>, VkFenceCreateInfo*, VkAllocationCallbacks*, VulkanHandle<VkFence>*, VkResult> _vkCreateFence = null; private static delegate* unmanaged<VulkanHandle<VkDevice>, VulkanHandle<VkFence>, VkAllocationCallbacks*, void> _vkDestroyFence = null; private static delegate* unmanaged<VulkanHandle<VkDevice>, uint, VulkanHandle<VkFence>*, VkResult> _vkResetFences = null; private static delegate* unmanaged<VulkanHandle<VkDevice>, VulkanHandle<VkFence>, VkResult> _vkGetFenceStatus = null; private static delegate* unmanaged<VulkanHandle<VkDevice>, uint, VulkanHandle<VkFence>*, VkBool32, ulong, VkResult> _vkWaitForFences = null; private static delegate* unmanaged<VulkanHandle<VkDevice>, VkSemaphoreCreateInfo*, VkAllocationCallbacks*, VulkanHandle<VkSemaphore>*, VkResult> _vkCreateSemaphore = null; private static delegate* unmanaged<VulkanHandle<VkDevice>, VulkanHandle<VkSemaphore>, VkAllocationCallbacks*, void> _vkDestroySemaphore = null; private static delegate* unmanaged<VulkanHandle<VkDevice>, VkEventCreateInfo*, VkAllocationCallbacks*, VulkanHandle<VkEvent>*, VkResult> _vkCreateEvent = null; private static delegate* unmanaged<VulkanHandle<VkDevice>, VulkanHandle<VkEvent>, VkAllocationCallbacks*, void> _vkDestroyEvent = null; private static delegate* unmanaged<VulkanHandle<VkDevice>, VulkanHandle<VkEvent>, VkResult> _vkGetEventStatus = null; private static delegate* unmanaged<VulkanHandle<VkDevice>, VulkanHandle<VkEvent>, VkResult> _vkSetEvent = null; private static delegate* unmanaged<VulkanHandle<VkDevice>, VulkanHandle<VkEvent>, VkResult> _vkResetEvent = null; private static delegate* unmanaged<VulkanHandle<VkDevice>, VkQueryPoolCreateInfo*, VkAllocationCallbacks*, VulkanHandle<VkQueryPool>*, VkResult> _vkCreateQueryPool = null; private static delegate* unmanaged<VulkanHandle<VkDevice>, VulkanHandle<VkQueryPool>, VkAllocationCallbacks*, void> _vkDestroyQueryPool = null; private static delegate* unmanaged<VulkanHandle<VkDevice>, VulkanHandle<VkQueryPool>, uint, uint, ulong, void*, ulong, VkQueryResultFlags, VkResult> _vkGetQueryPoolResults = null; private static delegate* unmanaged<VulkanHandle<VkDevice>, VulkanHandle<VkQueryPool>, uint, uint, void> _vkResetQueryPool = null; private static delegate* unmanaged<VulkanHandle<VkDevice>, VulkanHandle<VkQueryPool>, uint, uint, void> _vkResetQueryPoolEXT = null; private static delegate* unmanaged<VulkanHandle<VkDevice>, VkBufferCreateInfo*, VkAllocationCallbacks*, VulkanHandle<VkBuffer>*, VkResult> _vkCreateBuffer = null; private static delegate* unmanaged<VulkanHandle<VkDevice>, VulkanHandle<VkBuffer>, VkAllocationCallbacks*, void> _vkDestroyBuffer = null; private static delegate* unmanaged<VulkanHandle<VkDevice>, VkBufferViewCreateInfo*, VkAllocationCallbacks*, VulkanHandle<VkBufferView>*, VkResult> _vkCreateBufferView = null; private static delegate* unmanaged<VulkanHandle<VkDevice>, VulkanHandle<VkBufferView>, VkAllocationCallbacks*, void> _vkDestroyBufferView = null; private static delegate* unmanaged<VulkanHandle<VkDevice>, VkImageCreateInfo*, VkAllocationCallbacks*, VulkanHandle<VkImage>*, VkResult> _vkCreateImage = null; private static delegate* unmanaged<VulkanHandle<VkDevice>, VulkanHandle<VkImage>, VkAllocationCallbacks*, void> _vkDestroyImage = null; private static delegate* unmanaged<VulkanHandle<VkDevice>, VulkanHandle<VkImage>, VkImageSubresource*, VkSubresourceLayout*, void> _vkGetImageSubresourceLayout = null; private static delegate* unmanaged<VulkanHandle<VkDevice>, VkImageViewCreateInfo*, VkAllocationCallbacks*, VulkanHandle<VkImageView>*, VkResult> _vkCreateImageView = null; private static delegate* unmanaged<VulkanHandle<VkDevice>, VulkanHandle<VkImageView>, VkAllocationCallbacks*, void> _vkDestroyImageView = null; private static delegate* unmanaged<VulkanHandle<VkDevice>, VkShaderModuleCreateInfo*, VkAllocationCallbacks*, VulkanHandle<VkShaderModule>*, VkResult> _vkCreateShaderModule = null; private static delegate* unmanaged<VulkanHandle<VkDevice>, VulkanHandle<VkShaderModule>, VkAllocationCallbacks*, void> _vkDestroyShaderModule = null; private static delegate* unmanaged<VulkanHandle<VkDevice>, VkPipelineCacheCreateInfo*, VkAllocationCallbacks*, VulkanHandle<VkPipelineCache>*, VkResult> _vkCreatePipelineCache = null; private static delegate* unmanaged<VulkanHandle<VkDevice>, VulkanHandle<VkPipelineCache>, VkAllocationCallbacks*, void> _vkDestroyPipelineCache = null; private static delegate* unmanaged<VulkanHandle<VkDevice>, VulkanHandle<VkPipelineCache>, ulong*, void*, VkResult> _vkGetPipelineCacheData = null; private static delegate* unmanaged<VulkanHandle<VkDevice>, VulkanHandle<VkPipelineCache>, uint, VulkanHandle<VkPipelineCache>*, VkResult> _vkMergePipelineCaches = null; private static delegate* unmanaged<VulkanHandle<VkDevice>, VulkanHandle<VkPipelineCache>, uint, VkGraphicsPipelineCreateInfo*, VkAllocationCallbacks*, VulkanHandle<VkPipeline>*, VkResult> _vkCreateGraphicsPipelines = null; private static delegate* unmanaged<VulkanHandle<VkDevice>, VulkanHandle<VkPipelineCache>, uint, VkComputePipelineCreateInfo*, VkAllocationCallbacks*, VulkanHandle<VkPipeline>*, VkResult> _vkCreateComputePipelines = null; private static delegate* unmanaged<VulkanHandle<VkDevice>, VulkanHandle<VkPipeline>, VkAllocationCallbacks*, void> _vkDestroyPipeline = null; private static delegate* unmanaged<VulkanHandle<VkDevice>, VkPipelineLayoutCreateInfo*, VkAllocationCallbacks*, VulkanHandle<VkPipelineLayout>*, VkResult> _vkCreatePipelineLayout = null; private static delegate* unmanaged<VulkanHandle<VkDevice>, VulkanHandle<VkPipelineLayout>, VkAllocationCallbacks*, void> _vkDestroyPipelineLayout = null; private static delegate* unmanaged<VulkanHandle<VkDevice>, VkSamplerCreateInfo*, VkAllocationCallbacks*, VulkanHandle<VkSampler>*, VkResult> _vkCreateSampler = null; private static delegate* unmanaged<VulkanHandle<VkDevice>, VulkanHandle<VkSampler>, VkAllocationCallbacks*, void> _vkDestroySampler = null; private static delegate* unmanaged<VulkanHandle<VkDevice>, VkDescriptorSetLayoutCreateInfo*, VkAllocationCallbacks*, VulkanHandle<VkDescriptorSetLayout>*, VkResult> _vkCreateDescriptorSetLayout = null; private static delegate* unmanaged<VulkanHandle<VkDevice>, VulkanHandle<VkDescriptorSetLayout>, VkAllocationCallbacks*, void> _vkDestroyDescriptorSetLayout = null; private static delegate* unmanaged<VulkanHandle<VkDevice>, VkDescriptorPoolCreateInfo*, VkAllocationCallbacks*, VulkanHandle<VkDescriptorPool>*, VkResult> _vkCreateDescriptorPool = null; private static delegate* unmanaged<VulkanHandle<VkDevice>, VulkanHandle<VkDescriptorPool>, VkAllocationCallbacks*, void> _vkDestroyDescriptorPool = null; private static delegate* unmanaged<VulkanHandle<VkDevice>, VulkanHandle<VkDescriptorPool>, VkDescriptorPoolResetFlags, VkResult> _vkResetDescriptorPool = null; private static delegate* unmanaged<VulkanHandle<VkDevice>, VkDescriptorSetAllocateInfo*, VulkanHandle<VkDescriptorSet>*, VkResult> _vkAllocateDescriptorSets = null; private static delegate* unmanaged<VulkanHandle<VkDevice>, VulkanHandle<VkDescriptorPool>, uint, VulkanHandle<VkDescriptorSet>*, VkResult> _vkFreeDescriptorSets = null; private static delegate* unmanaged<VulkanHandle<VkDevice>, uint, VkWriteDescriptorSet*, uint, VkCopyDescriptorSet*, void> _vkUpdateDescriptorSets = null; private static delegate* unmanaged<VulkanHandle<VkDevice>, VkFramebufferCreateInfo*, VkAllocationCallbacks*, VulkanHandle<VkFramebuffer>*, VkResult> _vkCreateFramebuffer = null; private static delegate* unmanaged<VulkanHandle<VkDevice>, VulkanHandle<VkFramebuffer>, VkAllocationCallbacks*, void> _vkDestroyFramebuffer = null; private static delegate* unmanaged<VulkanHandle<VkDevice>, VkRenderPassCreateInfo*, VkAllocationCallbacks*, VulkanHandle<VkRenderPass>*, VkResult> _vkCreateRenderPass = null; private static delegate* unmanaged<VulkanHandle<VkDevice>, VulkanHandle<VkRenderPass>, VkAllocationCallbacks*, void> _vkDestroyRenderPass = null; private static delegate* unmanaged<VulkanHandle<VkDevice>, VulkanHandle<VkRenderPass>, VkExtent2D*, void> _vkGetRenderAreaGranularity = null; private static delegate* unmanaged<VulkanHandle<VkDevice>, VkCommandPoolCreateInfo*, VkAllocationCallbacks*, VulkanHandle<VkCommandPool>*, VkResult> _vkCreateCommandPool = null; private static delegate* unmanaged<VulkanHandle<VkDevice>, VulkanHandle<VkCommandPool>, VkAllocationCallbacks*, void> _vkDestroyCommandPool = null; private static delegate* unmanaged<VulkanHandle<VkDevice>, VulkanHandle<VkCommandPool>, VkCommandPoolResetFlags, VkResult> _vkResetCommandPool = null; private static delegate* unmanaged<VulkanHandle<VkDevice>, VkCommandBufferAllocateInfo*, VulkanHandle<VkCommandBuffer>*, VkResult> _vkAllocateCommandBuffers = null; private static delegate* unmanaged<VulkanHandle<VkDevice>, VulkanHandle<VkCommandPool>, uint, VulkanHandle<VkCommandBuffer>*, void> _vkFreeCommandBuffers = null; private static delegate* unmanaged<VulkanHandle<VkCommandBuffer>, VkCommandBufferBeginInfo*, VkResult> _vkBeginCommandBuffer = null; private static delegate* unmanaged<VulkanHandle<VkCommandBuffer>, VkResult> _vkEndCommandBuffer = null; private static delegate* unmanaged<VulkanHandle<VkCommandBuffer>, VkCommandBufferResetFlags, VkResult> _vkResetCommandBuffer = null; private static delegate* unmanaged<VulkanHandle<VkCommandBuffer>, VkPipelineBindPoint, VulkanHandle<VkPipeline>, void> _vkCmdBindPipeline = null; private static delegate* unmanaged<VulkanHandle<VkCommandBuffer>, uint, uint, VkViewport*, void> _vkCmdSetViewport = null; private static delegate* unmanaged<VulkanHandle<VkCommandBuffer>, uint, uint, VkRect2D*, void> _vkCmdSetScissor = null; private static delegate* unmanaged<VulkanHandle<VkCommandBuffer>, float, void> _vkCmdSetLineWidth = null; private static delegate* unmanaged<VulkanHandle<VkCommandBuffer>, float, float, float, void> _vkCmdSetDepthBias = null; private static delegate* unmanaged<VulkanHandle<VkCommandBuffer>, float*, void> _vkCmdSetBlendConstants = null; private static delegate* unmanaged<VulkanHandle<VkCommandBuffer>, float, float, void> _vkCmdSetDepthBounds = null; private static delegate* unmanaged<VulkanHandle<VkCommandBuffer>, VkStencilFaceFlags, uint, void> _vkCmdSetStencilCompareMask = null; private static delegate* unmanaged<VulkanHandle<VkCommandBuffer>, VkStencilFaceFlags, uint, void> _vkCmdSetStencilWriteMask = null; private static delegate* unmanaged<VulkanHandle<VkCommandBuffer>, VkStencilFaceFlags, uint, void> _vkCmdSetStencilReference = null; private static delegate* unmanaged<VulkanHandle<VkCommandBuffer>, VkPipelineBindPoint, VulkanHandle<VkPipelineLayout>, uint, uint, VulkanHandle<VkDescriptorSet>*, uint, uint*, void> _vkCmdBindDescriptorSets = null; private static delegate* unmanaged<VulkanHandle<VkCommandBuffer>, VulkanHandle<VkBuffer>, ulong, VkIndexType, void> _vkCmdBindIndexBuffer = null; private static delegate* unmanaged<VulkanHandle<VkCommandBuffer>, uint, uint, VulkanHandle<VkBuffer>*, ulong*, void> _vkCmdBindVertexBuffers = null; private static delegate* unmanaged<VulkanHandle<VkCommandBuffer>, uint, uint, uint, uint, void> _vkCmdDraw = null; private static delegate* unmanaged<VulkanHandle<VkCommandBuffer>, uint, uint, uint, int, uint, void> _vkCmdDrawIndexed = null; private static delegate* unmanaged<VulkanHandle<VkCommandBuffer>, VulkanHandle<VkBuffer>, ulong, uint, uint, void> _vkCmdDrawIndirect = null; private static delegate* unmanaged<VulkanHandle<VkCommandBuffer>, VulkanHandle<VkBuffer>, ulong, uint, uint, void> _vkCmdDrawIndexedIndirect = null; private static delegate* unmanaged<VulkanHandle<VkCommandBuffer>, uint, uint, uint, void> _vkCmdDispatch = null; private static delegate* unmanaged<VulkanHandle<VkCommandBuffer>, VulkanHandle<VkBuffer>, ulong, void> _vkCmdDispatchIndirect = null; private static delegate* unmanaged<VulkanHandle<VkCommandBuffer>, VulkanHandle<VkBuffer>, VulkanHandle<VkBuffer>, uint, VkBufferCopy*, void> _vkCmdCopyBuffer = null; private static delegate* unmanaged<VulkanHandle<VkCommandBuffer>, VulkanHandle<VkImage>, VkImageLayout, VulkanHandle<VkImage>, VkImageLayout, uint, VkImageCopy*, void> _vkCmdCopyImage = null; private static delegate* unmanaged<VulkanHandle<VkCommandBuffer>, VulkanHandle<VkImage>, VkImageLayout, VulkanHandle<VkImage>, VkImageLayout, uint, VkImageBlit*, VkFilter, void> _vkCmdBlitImage = null; private static delegate* unmanaged<VulkanHandle<VkCommandBuffer>, VulkanHandle<VkBuffer>, VulkanHandle<VkImage>, VkImageLayout, uint, VkBufferImageCopy*, void> _vkCmdCopyBufferToImage = null; private static delegate* unmanaged<VulkanHandle<VkCommandBuffer>, VulkanHandle<VkImage>, VkImageLayout, VulkanHandle<VkBuffer>, uint, VkBufferImageCopy*, void> _vkCmdCopyImageToBuffer = null; private static delegate* unmanaged<VulkanHandle<VkCommandBuffer>, VulkanHandle<VkBuffer>, ulong, ulong, void*, void> _vkCmdUpdateBuffer = null; private static delegate* unmanaged<VulkanHandle<VkCommandBuffer>, VulkanHandle<VkBuffer>, ulong, ulong, uint, void> _vkCmdFillBuffer = null; private static delegate* unmanaged<VulkanHandle<VkCommandBuffer>, VulkanHandle<VkImage>, VkImageLayout, VkClearColorValue*, uint, VkImageSubresourceRange*, void> _vkCmdClearColorImage = null; private static delegate* unmanaged<VulkanHandle<VkCommandBuffer>, VulkanHandle<VkImage>, VkImageLayout, VkClearDepthStencilValue*, uint, VkImageSubresourceRange*, void> _vkCmdClearDepthStencilImage = null; private static delegate* unmanaged<VulkanHandle<VkCommandBuffer>, uint, VkClearAttachment*, uint, VkClearRect*, void> _vkCmdClearAttachments = null; private static delegate* unmanaged<VulkanHandle<VkCommandBuffer>, VulkanHandle<VkImage>, VkImageLayout, VulkanHandle<VkImage>, VkImageLayout, uint, VkImageResolve*, void> _vkCmdResolveImage = null; private static delegate* unmanaged<VulkanHandle<VkCommandBuffer>, VulkanHandle<VkEvent>, VkPipelineStageFlags, void> _vkCmdSetEvent = null; private static delegate* unmanaged<VulkanHandle<VkCommandBuffer>, VulkanHandle<VkEvent>, VkPipelineStageFlags, void> _vkCmdResetEvent = null; private static delegate* unmanaged<VulkanHandle<VkCommandBuffer>, uint, VulkanHandle<VkEvent>*, VkPipelineStageFlags, VkPipelineStageFlags, uint, VkMemoryBarrier*, uint, VkBufferMemoryBarrier*, uint, VkImageMemoryBarrier*, void> _vkCmdWaitEvents = null; private static delegate* unmanaged<VulkanHandle<VkCommandBuffer>, VkPipelineStageFlags, VkPipelineStageFlags, VkDependencyFlags, uint, VkMemoryBarrier*, uint, VkBufferMemoryBarrier*, uint, VkImageMemoryBarrier*, void> _vkCmdPipelineBarrier = null; private static delegate* unmanaged<VulkanHandle<VkCommandBuffer>, VulkanHandle<VkQueryPool>, uint, VkQueryControlFlags, void> _vkCmdBeginQuery = null; private static delegate* unmanaged<VulkanHandle<VkCommandBuffer>, VulkanHandle<VkQueryPool>, uint, void> _vkCmdEndQuery = null; private static delegate* unmanaged<VulkanHandle<VkCommandBuffer>, VkConditionalRenderingBeginInfoEXT*, void> _vkCmdBeginConditionalRenderingEXT = null; private static delegate* unmanaged<VulkanHandle<VkCommandBuffer>, void> _vkCmdEndConditionalRenderingEXT = null; private static delegate* unmanaged<VulkanHandle<VkCommandBuffer>, VulkanHandle<VkQueryPool>, uint, uint, void> _vkCmdResetQueryPool = null; private static delegate* unmanaged<VulkanHandle<VkCommandBuffer>, VkPipelineStageFlags, VulkanHandle<VkQueryPool>, uint, void> _vkCmdWriteTimestamp = null; private static delegate* unmanaged<VulkanHandle<VkCommandBuffer>, VulkanHandle<VkQueryPool>, uint, uint, VulkanHandle<VkBuffer>, ulong, ulong, VkQueryResultFlags, void> _vkCmdCopyQueryPoolResults = null; private static delegate* unmanaged<VulkanHandle<VkCommandBuffer>, VulkanHandle<VkPipelineLayout>, VkShaderStageFlags, uint, uint, void*, void> _vkCmdPushConstants = null; private static delegate* unmanaged<VulkanHandle<VkCommandBuffer>, VkRenderPassBeginInfo*, VkSubpassContents, void> _vkCmdBeginRenderPass = null; private static delegate* unmanaged<VulkanHandle<VkCommandBuffer>, VkSubpassContents, void> _vkCmdNextSubpass = null; private static delegate* unmanaged<VulkanHandle<VkCommandBuffer>, void> _vkCmdEndRenderPass = null; private static delegate* unmanaged<VulkanHandle<VkCommandBuffer>, uint, VulkanHandle<VkCommandBuffer>*, void> _vkCmdExecuteCommands = null; private static delegate* unmanaged<VulkanHandle<VkDevice>, uint, VkSwapchainCreateInfoKHR*, VkAllocationCallbacks*, VulkanHandle<VkSwapchainKHR>*, VkResult> _vkCreateSharedSwapchainsKHR = null; private static delegate* unmanaged<VulkanHandle<VkDevice>, VkSwapchainCreateInfoKHR*, VkAllocationCallbacks*, VulkanHandle<VkSwapchainKHR>*, VkResult> _vkCreateSwapchainKHR = null; private static delegate* unmanaged<VulkanHandle<VkDevice>, VulkanHandle<VkSwapchainKHR>, VkAllocationCallbacks*, void> _vkDestroySwapchainKHR = null; private static delegate* unmanaged<VulkanHandle<VkDevice>, VulkanHandle<VkSwapchainKHR>, uint*, VulkanHandle<VkImage>*, VkResult> _vkGetSwapchainImagesKHR = null; private static delegate* unmanaged<VulkanHandle<VkDevice>, VulkanHandle<VkSwapchainKHR>, ulong, VulkanHandle<VkSemaphore>, VulkanHandle<VkFence>, uint*, VkResult> _vkAcquireNextImageKHR = null; private static delegate* unmanaged<VulkanHandle<VkQueue>, VkPresentInfoKHR*, VkResult> _vkQueuePresentKHR = null; private static delegate* unmanaged<VulkanHandle<VkDevice>, VkDebugMarkerObjectNameInfoEXT*, VkResult> _vkDebugMarkerSetObjectNameEXT = null; private static delegate* unmanaged<VulkanHandle<VkDevice>, VkDebugMarkerObjectTagInfoEXT*, VkResult> _vkDebugMarkerSetObjectTagEXT = null; private static delegate* unmanaged<VulkanHandle<VkCommandBuffer>, VkDebugMarkerMarkerInfoEXT*, void> _vkCmdDebugMarkerBeginEXT = null; private static delegate* unmanaged<VulkanHandle<VkCommandBuffer>, void> _vkCmdDebugMarkerEndEXT = null; private static delegate* unmanaged<VulkanHandle<VkCommandBuffer>, VkDebugMarkerMarkerInfoEXT*, void> _vkCmdDebugMarkerInsertEXT = null; private static delegate* unmanaged<VulkanHandle<VkDevice>, VulkanHandle<VkDeviceMemory>, VkExternalMemoryHandleTypeFlagsNV, void**, VkResult> _vkGetMemoryWin32HandleNV = null; private static delegate* unmanaged<VulkanHandle<VkCommandBuffer>, VkBool32, VkGeneratedCommandsInfoNV*, void> _vkCmdExecuteGeneratedCommandsNV = null; private static delegate* unmanaged<VulkanHandle<VkCommandBuffer>, VkGeneratedCommandsInfoNV*, void> _vkCmdPreprocessGeneratedCommandsNV = null; private static delegate* unmanaged<VulkanHandle<VkCommandBuffer>, VkPipelineBindPoint, VulkanHandle<VkPipeline>, uint, void> _vkCmdBindPipelineShaderGroupNV = null; private static delegate* unmanaged<VulkanHandle<VkDevice>, VkGeneratedCommandsMemoryRequirementsInfoNV*, VkMemoryRequirements2*, void> _vkGetGeneratedCommandsMemoryRequirementsNV = null; private static delegate* unmanaged<VulkanHandle<VkDevice>, VkIndirectCommandsLayoutCreateInfoNV*, VkAllocationCallbacks*, VulkanHandle<VkIndirectCommandsLayoutNV>*, VkResult> _vkCreateIndirectCommandsLayoutNV = null; private static delegate* unmanaged<VulkanHandle<VkDevice>, VulkanHandle<VkIndirectCommandsLayoutNV>, VkAllocationCallbacks*, void> _vkDestroyIndirectCommandsLayoutNV = null; private static delegate* unmanaged<VulkanHandle<VkCommandBuffer>, VkPipelineBindPoint, VulkanHandle<VkPipelineLayout>, uint, uint, VkWriteDescriptorSet*, void> _vkCmdPushDescriptorSetKHR = null; private static delegate* unmanaged<VulkanHandle<VkDevice>, VulkanHandle<VkCommandPool>, VkCommandPoolTrimFlags, void> _vkTrimCommandPool = null; private static delegate* unmanaged<VulkanHandle<VkDevice>, VulkanHandle<VkCommandPool>, VkCommandPoolTrimFlags, void> _vkTrimCommandPoolKHR = null; private static delegate* unmanaged<VulkanHandle<VkDevice>, VkMemoryGetWin32HandleInfoKHR*, void**, VkResult> _vkGetMemoryWin32HandleKHR = null; private static delegate* unmanaged<VulkanHandle<VkDevice>, VkExternalMemoryHandleTypeFlags, void*, VkMemoryWin32HandlePropertiesKHR*, VkResult> _vkGetMemoryWin32HandlePropertiesKHR = null; private static delegate* unmanaged<VulkanHandle<VkDevice>, VkMemoryGetFdInfoKHR*, int*, VkResult> _vkGetMemoryFdKHR = null; private static delegate* unmanaged<VulkanHandle<VkDevice>, VkExternalMemoryHandleTypeFlags, int, VkMemoryFdPropertiesKHR*, VkResult> _vkGetMemoryFdPropertiesKHR = null; private static delegate* unmanaged<VulkanHandle<VkDevice>, VkSemaphoreGetWin32HandleInfoKHR*, void**, VkResult> _vkGetSemaphoreWin32HandleKHR = null; private static delegate* unmanaged<VulkanHandle<VkDevice>, VkImportSemaphoreWin32HandleInfoKHR*, VkResult> _vkImportSemaphoreWin32HandleKHR = null; private static delegate* unmanaged<VulkanHandle<VkDevice>, VkSemaphoreGetFdInfoKHR*, int*, VkResult> _vkGetSemaphoreFdKHR = null; private static delegate* unmanaged<VulkanHandle<VkDevice>, VkImportSemaphoreFdInfoKHR*, VkResult> _vkImportSemaphoreFdKHR = null; private static delegate* unmanaged<VulkanHandle<VkDevice>, VkFenceGetWin32HandleInfoKHR*, void**, VkResult> _vkGetFenceWin32HandleKHR = null; private static delegate* unmanaged<VulkanHandle<VkDevice>, VkImportFenceWin32HandleInfoKHR*, VkResult> _vkImportFenceWin32HandleKHR = null; private static delegate* unmanaged<VulkanHandle<VkDevice>, VkFenceGetFdInfoKHR*, int*, VkResult> _vkGetFenceFdKHR = null; private static delegate* unmanaged<VulkanHandle<VkDevice>, VkImportFenceFdInfoKHR*, VkResult> _vkImportFenceFdKHR = null; private static delegate* unmanaged<VulkanHandle<VkDevice>, VulkanHandle<VkDisplayKHR>, VkDisplayPowerInfoEXT*, VkResult> _vkDisplayPowerControlEXT = null; private static delegate* unmanaged<VulkanHandle<VkDevice>, VkDeviceEventInfoEXT*, VkAllocationCallbacks*, VulkanHandle<VkFence>*, VkResult> _vkRegisterDeviceEventEXT = null; private static delegate* unmanaged<VulkanHandle<VkDevice>, VulkanHandle<VkDisplayKHR>, VkDisplayEventInfoEXT*, VkAllocationCallbacks*, VulkanHandle<VkFence>*, VkResult> _vkRegisterDisplayEventEXT = null; private static delegate* unmanaged<VulkanHandle<VkDevice>, VulkanHandle<VkSwapchainKHR>, VkSurfaceCounterFlagsEXT, ulong*, VkResult> _vkGetSwapchainCounterEXT = null; private static delegate* unmanaged<VulkanHandle<VkDevice>, uint, uint, uint, VkPeerMemoryFeatureFlags*, void> _vkGetDeviceGroupPeerMemoryFeatures = null; private static delegate* unmanaged<VulkanHandle<VkDevice>, uint, uint, uint, VkPeerMemoryFeatureFlags*, void> _vkGetDeviceGroupPeerMemoryFeaturesKHR = null; private static delegate* unmanaged<VulkanHandle<VkDevice>, uint, VkBindBufferMemoryInfo*, VkResult> _vkBindBufferMemory2 = null; private static delegate* unmanaged<VulkanHandle<VkDevice>, uint, VkBindBufferMemoryInfo*, VkResult> _vkBindBufferMemory2KHR = null; private static delegate* unmanaged<VulkanHandle<VkDevice>, uint, VkBindImageMemoryInfo*, VkResult> _vkBindImageMemory2 = null; private static delegate* unmanaged<VulkanHandle<VkDevice>, uint, VkBindImageMemoryInfo*, VkResult> _vkBindImageMemory2KHR = null; private static delegate* unmanaged<VulkanHandle<VkCommandBuffer>, uint, void> _vkCmdSetDeviceMask = null; private static delegate* unmanaged<VulkanHandle<VkCommandBuffer>, uint, void> _vkCmdSetDeviceMaskKHR = null; private static delegate* unmanaged<VulkanHandle<VkDevice>, VkDeviceGroupPresentCapabilitiesKHR*, VkResult> _vkGetDeviceGroupPresentCapabilitiesKHR = null; private static delegate* unmanaged<VulkanHandle<VkDevice>, VulkanHandle<VkSurfaceKHR>, VkDeviceGroupPresentModeFlagsKHR*, VkResult> _vkGetDeviceGroupSurfacePresentModesKHR = null; private static delegate* unmanaged<VulkanHandle<VkDevice>, VkAcquireNextImageInfoKHR*, uint*, VkResult> _vkAcquireNextImage2KHR = null; private static delegate* unmanaged<VulkanHandle<VkCommandBuffer>, uint, uint, uint, uint, uint, uint, void> _vkCmdDispatchBase = null; private static delegate* unmanaged<VulkanHandle<VkCommandBuffer>, uint, uint, uint, uint, uint, uint, void> _vkCmdDispatchBaseKHR = null; private static delegate* unmanaged<VulkanHandle<VkDevice>, VkDescriptorUpdateTemplateCreateInfo*, VkAllocationCallbacks*, VulkanHandle<VkDescriptorUpdateTemplate>*, VkResult> _vkCreateDescriptorUpdateTemplate = null; private static delegate* unmanaged<VulkanHandle<VkDevice>, VkDescriptorUpdateTemplateCreateInfo*, VkAllocationCallbacks*, VulkanHandle<VkDescriptorUpdateTemplate>*, VkResult> _vkCreateDescriptorUpdateTemplateKHR = null; private static delegate* unmanaged<VulkanHandle<VkDevice>, VulkanHandle<VkDescriptorUpdateTemplate>, VkAllocationCallbacks*, void> _vkDestroyDescriptorUpdateTemplate = null; private static delegate* unmanaged<VulkanHandle<VkDevice>, VulkanHandle<VkDescriptorUpdateTemplate>, VkAllocationCallbacks*, void> _vkDestroyDescriptorUpdateTemplateKHR = null; private static delegate* unmanaged<VulkanHandle<VkDevice>, VulkanHandle<VkDescriptorSet>, VulkanHandle<VkDescriptorUpdateTemplate>, void*, void> _vkUpdateDescriptorSetWithTemplate = null; private static delegate* unmanaged<VulkanHandle<VkDevice>, VulkanHandle<VkDescriptorSet>, VulkanHandle<VkDescriptorUpdateTemplate>, void*, void> _vkUpdateDescriptorSetWithTemplateKHR = null; private static delegate* unmanaged<VulkanHandle<VkCommandBuffer>, VulkanHandle<VkDescriptorUpdateTemplate>, VulkanHandle<VkPipelineLayout>, uint, void*, void> _vkCmdPushDescriptorSetWithTemplateKHR = null; private static delegate* unmanaged<VulkanHandle<VkDevice>, uint, VulkanHandle<VkSwapchainKHR>*, VkHdrMetadataEXT*, void> _vkSetHdrMetadataEXT = null; private static delegate* unmanaged<VulkanHandle<VkDevice>, VulkanHandle<VkSwapchainKHR>, VkResult> _vkGetSwapchainStatusKHR = null; private static delegate* unmanaged<VulkanHandle<VkDevice>, VulkanHandle<VkSwapchainKHR>, VkRefreshCycleDurationGOOGLE*, VkResult> _vkGetRefreshCycleDurationGOOGLE = null; private static delegate* unmanaged<VulkanHandle<VkDevice>, VulkanHandle<VkSwapchainKHR>, uint*, VkPastPresentationTimingGOOGLE*, VkResult> _vkGetPastPresentationTimingGOOGLE = null; private static delegate* unmanaged<VulkanHandle<VkCommandBuffer>, uint, uint, VkViewportWScalingNV*, void> _vkCmdSetViewportWScalingNV = null; private static delegate* unmanaged<VulkanHandle<VkCommandBuffer>, uint, uint, VkRect2D*, void> _vkCmdSetDiscardRectangleEXT = null; private static delegate* unmanaged<VulkanHandle<VkCommandBuffer>, VkSampleLocationsInfoEXT*, void> _vkCmdSetSampleLocationsEXT = null; private static delegate* unmanaged<VulkanHandle<VkDevice>, VkBufferMemoryRequirementsInfo2*, VkMemoryRequirements2*, void> _vkGetBufferMemoryRequirements2 = null; private static delegate* unmanaged<VulkanHandle<VkDevice>, VkBufferMemoryRequirementsInfo2*, VkMemoryRequirements2*, void> _vkGetBufferMemoryRequirements2KHR = null; private static delegate* unmanaged<VulkanHandle<VkDevice>, VkImageMemoryRequirementsInfo2*, VkMemoryRequirements2*, void> _vkGetImageMemoryRequirements2 = null; private static delegate* unmanaged<VulkanHandle<VkDevice>, VkImageMemoryRequirementsInfo2*, VkMemoryRequirements2*, void> _vkGetImageMemoryRequirements2KHR = null; private static delegate* unmanaged<VulkanHandle<VkDevice>, VkImageSparseMemoryRequirementsInfo2*, uint*, VkSparseImageMemoryRequirements2*, void> _vkGetImageSparseMemoryRequirements2 = null; private static delegate* unmanaged<VulkanHandle<VkDevice>, VkImageSparseMemoryRequirementsInfo2*, uint*, VkSparseImageMemoryRequirements2*, void> _vkGetImageSparseMemoryRequirements2KHR = null; private static delegate* unmanaged<VulkanHandle<VkDevice>, VkSamplerYcbcrConversionCreateInfo*, VkAllocationCallbacks*, VulkanHandle<VkSamplerYcbcrConversion>*, VkResult> _vkCreateSamplerYcbcrConversion = null; private static delegate* unmanaged<VulkanHandle<VkDevice>, VkSamplerYcbcrConversionCreateInfo*, VkAllocationCallbacks*, VulkanHandle<VkSamplerYcbcrConversion>*, VkResult> _vkCreateSamplerYcbcrConversionKHR = null; private static delegate* unmanaged<VulkanHandle<VkDevice>, VulkanHandle<VkSamplerYcbcrConversion>, VkAllocationCallbacks*, void> _vkDestroySamplerYcbcrConversion = null; private static delegate* unmanaged<VulkanHandle<VkDevice>, VulkanHandle<VkSamplerYcbcrConversion>, VkAllocationCallbacks*, void> _vkDestroySamplerYcbcrConversionKHR = null; private static delegate* unmanaged<VulkanHandle<VkDevice>, VkDeviceQueueInfo2*, VulkanHandle<VkQueue>*, void> _vkGetDeviceQueue2 = null; private static delegate* unmanaged<VulkanHandle<VkDevice>, VkValidationCacheCreateInfoEXT*, VkAllocationCallbacks*, VulkanHandle<VkValidationCacheEXT>*, VkResult> _vkCreateValidationCacheEXT = null; private static delegate* unmanaged<VulkanHandle<VkDevice>, VulkanHandle<VkValidationCacheEXT>, VkAllocationCallbacks*, void> _vkDestroyValidationCacheEXT = null; private static delegate* unmanaged<VulkanHandle<VkDevice>, VulkanHandle<VkValidationCacheEXT>, ulong*, void*, VkResult> _vkGetValidationCacheDataEXT = null; private static delegate* unmanaged<VulkanHandle<VkDevice>, VulkanHandle<VkValidationCacheEXT>, uint, VulkanHandle<VkValidationCacheEXT>*, VkResult> _vkMergeValidationCachesEXT = null; private static delegate* unmanaged<VulkanHandle<VkDevice>, VkDescriptorSetLayoutCreateInfo*, VkDescriptorSetLayoutSupport*, void> _vkGetDescriptorSetLayoutSupport = null; private static delegate* unmanaged<VulkanHandle<VkDevice>, VkDescriptorSetLayoutCreateInfo*, VkDescriptorSetLayoutSupport*, void> _vkGetDescriptorSetLayoutSupportKHR = null; private static delegate* unmanaged<VulkanHandle<VkDevice>, VkFormat, VkImageUsageFlags, int*, VkResult> _vkGetSwapchainGrallocUsageANDROID = null; private static delegate* unmanaged<VulkanHandle<VkDevice>, VkFormat, VkImageUsageFlags, VkSwapchainImageUsageFlagsANDROID, ulong*, ulong*, VkResult> _vkGetSwapchainGrallocUsage2ANDROID = null; private static delegate* unmanaged<VulkanHandle<VkDevice>, VulkanHandle<VkImage>, int, VulkanHandle<VkSemaphore>, VulkanHandle<VkFence>, VkResult> _vkAcquireImageANDROID = null; private static delegate* unmanaged<VulkanHandle<VkQueue>, uint, VulkanHandle<VkSemaphore>*, VulkanHandle<VkImage>, int*, VkResult> _vkQueueSignalReleaseImageANDROID = null; private static delegate* unmanaged<VulkanHandle<VkDevice>, VulkanHandle<VkPipeline>, VkShaderStageFlags, VkShaderInfoTypeAMD, ulong*, void*, VkResult> _vkGetShaderInfoAMD = null; private static delegate* unmanaged<VulkanHandle<VkDevice>, VulkanHandle<VkSwapchainKHR>, VkBool32, void> _vkSetLocalDimmingAMD = null; private static delegate* unmanaged<VulkanHandle<VkDevice>, uint, VkCalibratedTimestampInfoEXT*, ulong*, ulong*, VkResult> _vkGetCalibratedTimestampsEXT = null; private static delegate* unmanaged<VulkanHandle<VkDevice>, VkDebugUtilsObjectNameInfoEXT*, VkResult> _vkSetDebugUtilsObjectNameEXT = null; private static delegate* unmanaged<VulkanHandle<VkDevice>, VkDebugUtilsObjectTagInfoEXT*, VkResult> _vkSetDebugUtilsObjectTagEXT = null; private static delegate* unmanaged<VulkanHandle<VkQueue>, VkDebugUtilsLabelEXT*, void> _vkQueueBeginDebugUtilsLabelEXT = null; private static delegate* unmanaged<VulkanHandle<VkQueue>, void> _vkQueueEndDebugUtilsLabelEXT = null; private static delegate* unmanaged<VulkanHandle<VkQueue>, VkDebugUtilsLabelEXT*, void> _vkQueueInsertDebugUtilsLabelEXT = null; private static delegate* unmanaged<VulkanHandle<VkCommandBuffer>, VkDebugUtilsLabelEXT*, void> _vkCmdBeginDebugUtilsLabelEXT = null; private static delegate* unmanaged<VulkanHandle<VkCommandBuffer>, void> _vkCmdEndDebugUtilsLabelEXT = null; private static delegate* unmanaged<VulkanHandle<VkCommandBuffer>, VkDebugUtilsLabelEXT*, void> _vkCmdInsertDebugUtilsLabelEXT = null; private static delegate* unmanaged<VulkanHandle<VkDevice>, VkExternalMemoryHandleTypeFlags, void*, VkMemoryHostPointerPropertiesEXT*, VkResult> _vkGetMemoryHostPointerPropertiesEXT = null; private static delegate* unmanaged<VulkanHandle<VkCommandBuffer>, VkPipelineStageFlags, VulkanHandle<VkBuffer>, ulong, uint, void> _vkCmdWriteBufferMarkerAMD = null; private static delegate* unmanaged<VulkanHandle<VkDevice>, VkRenderPassCreateInfo2*, VkAllocationCallbacks*, VulkanHandle<VkRenderPass>*, VkResult> _vkCreateRenderPass2 = null; private static delegate* unmanaged<VulkanHandle<VkDevice>, VkRenderPassCreateInfo2*, VkAllocationCallbacks*, VulkanHandle<VkRenderPass>*, VkResult> _vkCreateRenderPass2KHR = null; private static delegate* unmanaged<VulkanHandle<VkCommandBuffer>, VkRenderPassBeginInfo*, VkSubpassBeginInfo*, void> _vkCmdBeginRenderPass2 = null; private static delegate* unmanaged<VulkanHandle<VkCommandBuffer>, VkRenderPassBeginInfo*, VkSubpassBeginInfo*, void> _vkCmdBeginRenderPass2KHR = null; private static delegate* unmanaged<VulkanHandle<VkCommandBuffer>, VkSubpassBeginInfo*, VkSubpassEndInfo*, void> _vkCmdNextSubpass2 = null; private static delegate* unmanaged<VulkanHandle<VkCommandBuffer>, VkSubpassBeginInfo*, VkSubpassEndInfo*, void> _vkCmdNextSubpass2KHR = null; private static delegate* unmanaged<VulkanHandle<VkCommandBuffer>, VkSubpassEndInfo*, void> _vkCmdEndRenderPass2 = null; private static delegate* unmanaged<VulkanHandle<VkCommandBuffer>, VkSubpassEndInfo*, void> _vkCmdEndRenderPass2KHR = null; private static delegate* unmanaged<VulkanHandle<VkDevice>, VulkanHandle<VkSemaphore>, ulong*, VkResult> _vkGetSemaphoreCounterValue = null; private static delegate* unmanaged<VulkanHandle<VkDevice>, VulkanHandle<VkSemaphore>, ulong*, VkResult> _vkGetSemaphoreCounterValueKHR = null; private static delegate* unmanaged<VulkanHandle<VkDevice>, VkSemaphoreWaitInfo*, ulong, VkResult> _vkWaitSemaphores = null; private static delegate* unmanaged<VulkanHandle<VkDevice>, VkSemaphoreWaitInfo*, ulong, VkResult> _vkWaitSemaphoresKHR = null; private static delegate* unmanaged<VulkanHandle<VkDevice>, VkSemaphoreSignalInfo*, VkResult> _vkSignalSemaphore = null; private static delegate* unmanaged<VulkanHandle<VkDevice>, VkSemaphoreSignalInfo*, VkResult> _vkSignalSemaphoreKHR = null; private static delegate* unmanaged<VulkanHandle<VkDevice>, void*, VkAndroidHardwareBufferPropertiesANDROID*, VkResult> _vkGetAndroidHardwareBufferPropertiesANDROID = null; private static delegate* unmanaged<VulkanHandle<VkDevice>, VkMemoryGetAndroidHardwareBufferInfoANDROID*, void**, VkResult> _vkGetMemoryAndroidHardwareBufferANDROID = null; private static delegate* unmanaged<VulkanHandle<VkCommandBuffer>, VulkanHandle<VkBuffer>, ulong, VulkanHandle<VkBuffer>, ulong, uint, uint, void> _vkCmdDrawIndirectCount = null; private static delegate* unmanaged<VulkanHandle<VkCommandBuffer>, VulkanHandle<VkBuffer>, ulong, VulkanHandle<VkBuffer>, ulong, uint, uint, void> _vkCmdDrawIndirectCountKHR = null; private static delegate* unmanaged<VulkanHandle<VkCommandBuffer>, VulkanHandle<VkBuffer>, ulong, VulkanHandle<VkBuffer>, ulong, uint, uint, void> _vkCmdDrawIndirectCountAMD = null; private static delegate* unmanaged<VulkanHandle<VkCommandBuffer>, VulkanHandle<VkBuffer>, ulong, VulkanHandle<VkBuffer>, ulong, uint, uint, void> _vkCmdDrawIndexedIndirectCount = null; private static delegate* unmanaged<VulkanHandle<VkCommandBuffer>, VulkanHandle<VkBuffer>, ulong, VulkanHandle<VkBuffer>, ulong, uint, uint, void> _vkCmdDrawIndexedIndirectCountKHR = null; private static delegate* unmanaged<VulkanHandle<VkCommandBuffer>, VulkanHandle<VkBuffer>, ulong, VulkanHandle<VkBuffer>, ulong, uint, uint, void> _vkCmdDrawIndexedIndirectCountAMD = null; private static delegate* unmanaged<VulkanHandle<VkCommandBuffer>, void*, void> _vkCmdSetCheckpointNV = null; private static delegate* unmanaged<VulkanHandle<VkQueue>, uint*, VkCheckpointDataNV*, void> _vkGetQueueCheckpointDataNV = null; private static delegate* unmanaged<VulkanHandle<VkCommandBuffer>, uint, uint, VulkanHandle<VkBuffer>*, ulong*, ulong*, void> _vkCmdBindTransformFeedbackBuffersEXT = null; private static delegate* unmanaged<VulkanHandle<VkCommandBuffer>, uint, uint, VulkanHandle<VkBuffer>*, ulong*, void> _vkCmdBeginTransformFeedbackEXT = null; private static delegate* unmanaged<VulkanHandle<VkCommandBuffer>, uint, uint, VulkanHandle<VkBuffer>*, ulong*, void> _vkCmdEndTransformFeedbackEXT = null; private static delegate* unmanaged<VulkanHandle<VkCommandBuffer>, VulkanHandle<VkQueryPool>, uint, VkQueryControlFlags, uint, void> _vkCmdBeginQueryIndexedEXT = null; private static delegate* unmanaged<VulkanHandle<VkCommandBuffer>, VulkanHandle<VkQueryPool>, uint, uint, void> _vkCmdEndQueryIndexedEXT = null; private static delegate* unmanaged<VulkanHandle<VkCommandBuffer>, uint, uint, VulkanHandle<VkBuffer>, ulong, uint, uint, void> _vkCmdDrawIndirectByteCountEXT = null; private static delegate* unmanaged<VulkanHandle<VkCommandBuffer>, uint, uint, VkRect2D*, void> _vkCmdSetExclusiveScissorNV = null; private static delegate* unmanaged<VulkanHandle<VkCommandBuffer>, VulkanHandle<VkImageView>, VkImageLayout, void> _vkCmdBindShadingRateImageNV = null; private static delegate* unmanaged<VulkanHandle<VkCommandBuffer>, uint, uint, VkShadingRatePaletteNV*, void> _vkCmdSetViewportShadingRatePaletteNV = null; private static delegate* unmanaged<VulkanHandle<VkCommandBuffer>, VkCoarseSampleOrderTypeNV, uint, VkCoarseSampleOrderCustomNV*, void> _vkCmdSetCoarseSampleOrderNV = null; private static delegate* unmanaged<VulkanHandle<VkCommandBuffer>, uint, uint, void> _vkCmdDrawMeshTasksNV = null; private static delegate* unmanaged<VulkanHandle<VkCommandBuffer>, VulkanHandle<VkBuffer>, ulong, uint, uint, void> _vkCmdDrawMeshTasksIndirectNV = null; private static delegate* unmanaged<VulkanHandle<VkCommandBuffer>, VulkanHandle<VkBuffer>, ulong, VulkanHandle<VkBuffer>, ulong, uint, uint, void> _vkCmdDrawMeshTasksIndirectCountNV = null; private static delegate* unmanaged<VulkanHandle<VkDevice>, VulkanHandle<VkPipeline>, uint, VkResult> _vkCompileDeferredNV = null; private static delegate* unmanaged<VulkanHandle<VkDevice>, VkAccelerationStructureCreateInfoNV*, VkAllocationCallbacks*, VulkanHandle<VkAccelerationStructureNV>*, VkResult> _vkCreateAccelerationStructureNV = null; private static delegate* unmanaged<VulkanHandle<VkDevice>, VulkanHandle<VkAccelerationStructureKHR>, VkAllocationCallbacks*, void> _vkDestroyAccelerationStructureKHR = null; private static delegate* unmanaged<VulkanHandle<VkDevice>, VulkanHandle<VkAccelerationStructureNV>, VkAllocationCallbacks*, void> _vkDestroyAccelerationStructureNV = null; private static delegate* unmanaged<VulkanHandle<VkDevice>, VkAccelerationStructureMemoryRequirementsInfoNV*, VkMemoryRequirements2KHR*, void> _vkGetAccelerationStructureMemoryRequirementsNV = null; private static delegate* unmanaged<VulkanHandle<VkDevice>, uint, VkBindAccelerationStructureMemoryInfoNV*, VkResult> _vkBindAccelerationStructureMemoryNV = null; private static delegate* unmanaged<VulkanHandle<VkCommandBuffer>, VulkanHandle<VkAccelerationStructureNV>, VulkanHandle<VkAccelerationStructureNV>, VkCopyAccelerationStructureModeKHR, void> _vkCmdCopyAccelerationStructureNV = null; private static delegate* unmanaged<VulkanHandle<VkCommandBuffer>, VkCopyAccelerationStructureInfoKHR*, void> _vkCmdCopyAccelerationStructureKHR = null; private static delegate* unmanaged<VulkanHandle<VkDevice>, VulkanHandle<VkDeferredOperationKHR>, VkCopyAccelerationStructureInfoKHR*, VkResult> _vkCopyAccelerationStructureKHR = null; private static delegate* unmanaged<VulkanHandle<VkCommandBuffer>, VkCopyAccelerationStructureToMemoryInfoKHR*, void> _vkCmdCopyAccelerationStructureToMemoryKHR = null; private static delegate* unmanaged<VulkanHandle<VkDevice>, VulkanHandle<VkDeferredOperationKHR>, VkCopyAccelerationStructureToMemoryInfoKHR*, VkResult> _vkCopyAccelerationStructureToMemoryKHR = null; private static delegate* unmanaged<VulkanHandle<VkCommandBuffer>, VkCopyMemoryToAccelerationStructureInfoKHR*, void> _vkCmdCopyMemoryToAccelerationStructureKHR = null; private static delegate* unmanaged<VulkanHandle<VkDevice>, VulkanHandle<VkDeferredOperationKHR>, VkCopyMemoryToAccelerationStructureInfoKHR*, VkResult> _vkCopyMemoryToAccelerationStructureKHR = null; private static delegate* unmanaged<VulkanHandle<VkCommandBuffer>, uint, VulkanHandle<VkAccelerationStructureKHR>*, VkQueryType, VulkanHandle<VkQueryPool>, uint, void> _vkCmdWriteAccelerationStructuresPropertiesKHR = null; private static delegate* unmanaged<VulkanHandle<VkCommandBuffer>, uint, VulkanHandle<VkAccelerationStructureNV>*, VkQueryType, VulkanHandle<VkQueryPool>, uint, void> _vkCmdWriteAccelerationStructuresPropertiesNV = null; private static delegate* unmanaged<VulkanHandle<VkCommandBuffer>, VkAccelerationStructureInfoNV*, VulkanHandle<VkBuffer>, ulong, VkBool32, VulkanHandle<VkAccelerationStructureNV>, VulkanHandle<VkAccelerationStructureNV>, VulkanHandle<VkBuffer>, ulong, void> _vkCmdBuildAccelerationStructureNV = null; private static delegate* unmanaged<VulkanHandle<VkDevice>, uint, VulkanHandle<VkAccelerationStructureKHR>*, VkQueryType, ulong, void*, ulong, VkResult> _vkWriteAccelerationStructuresPropertiesKHR = null; private static delegate* unmanaged<VulkanHandle<VkCommandBuffer>, VkStridedDeviceAddressRegionKHR*, VkStridedDeviceAddressRegionKHR*, VkStridedDeviceAddressRegionKHR*, VkStridedDeviceAddressRegionKHR*, uint, uint, uint, void> _vkCmdTraceRaysKHR = null; private static delegate* unmanaged<VulkanHandle<VkCommandBuffer>, VulkanHandle<VkBuffer>, ulong, VulkanHandle<VkBuffer>, ulong, ulong, VulkanHandle<VkBuffer>, ulong, ulong, VulkanHandle<VkBuffer>, ulong, ulong, uint, uint, uint, void> _vkCmdTraceRaysNV = null; private static delegate* unmanaged<VulkanHandle<VkDevice>, VulkanHandle<VkPipeline>, uint, uint, ulong, void*, VkResult> _vkGetRayTracingShaderGroupHandlesKHR = null; private static delegate* unmanaged<VulkanHandle<VkDevice>, VulkanHandle<VkPipeline>, uint, uint, ulong, void*, VkResult> _vkGetRayTracingShaderGroupHandlesNV = null; private static delegate* unmanaged<VulkanHandle<VkDevice>, VulkanHandle<VkPipeline>, uint, uint, ulong, void*, VkResult> _vkGetRayTracingCaptureReplayShaderGroupHandlesKHR = null; private static delegate* unmanaged<VulkanHandle<VkDevice>, VulkanHandle<VkAccelerationStructureNV>, ulong, void*, VkResult> _vkGetAccelerationStructureHandleNV = null; private static delegate* unmanaged<VulkanHandle<VkDevice>, VulkanHandle<VkPipelineCache>, uint, VkRayTracingPipelineCreateInfoNV*, VkAllocationCallbacks*, VulkanHandle<VkPipeline>*, VkResult> _vkCreateRayTracingPipelinesNV = null; private static delegate* unmanaged<VulkanHandle<VkDevice>, VulkanHandle<VkDeferredOperationKHR>, VulkanHandle<VkPipelineCache>, uint, VkRayTracingPipelineCreateInfoKHR*, VkAllocationCallbacks*, VulkanHandle<VkPipeline>*, VkResult> _vkCreateRayTracingPipelinesKHR = null; private static delegate* unmanaged<VulkanHandle<VkCommandBuffer>, VkStridedDeviceAddressRegionKHR*, VkStridedDeviceAddressRegionKHR*, VkStridedDeviceAddressRegionKHR*, VkStridedDeviceAddressRegionKHR*, ulong, void> _vkCmdTraceRaysIndirectKHR = null; private static delegate* unmanaged<VulkanHandle<VkDevice>, VkAccelerationStructureVersionInfoKHR*, VkAccelerationStructureCompatibilityKHR*, void> _vkGetDeviceAccelerationStructureCompatibilityKHR = null; private static delegate* unmanaged<VulkanHandle<VkDevice>, VulkanHandle<VkPipeline>, uint, VkShaderGroupShaderKHR, ulong> _vkGetRayTracingShaderGroupStackSizeKHR = null; private static delegate* unmanaged<VulkanHandle<VkCommandBuffer>, uint, void> _vkCmdSetRayTracingPipelineStackSizeKHR = null; private static delegate* unmanaged<VulkanHandle<VkDevice>, VkImageViewHandleInfoNVX*, uint> _vkGetImageViewHandleNVX = null; private static delegate* unmanaged<VulkanHandle<VkDevice>, VulkanHandle<VkImageView>, VkImageViewAddressPropertiesNVX*, VkResult> _vkGetImageViewAddressNVX = null; private static delegate* unmanaged<VulkanHandle<VkDevice>, VkPhysicalDeviceSurfaceInfo2KHR*, VkDeviceGroupPresentModeFlagsKHR*, VkResult> _vkGetDeviceGroupSurfacePresentModes2EXT = null; private static delegate* unmanaged<VulkanHandle<VkDevice>, VulkanHandle<VkSwapchainKHR>, VkResult> _vkAcquireFullScreenExclusiveModeEXT = null; private static delegate* unmanaged<VulkanHandle<VkDevice>, VulkanHandle<VkSwapchainKHR>, VkResult> _vkReleaseFullScreenExclusiveModeEXT = null; private static delegate* unmanaged<VulkanHandle<VkDevice>, VkAcquireProfilingLockInfoKHR*, VkResult> _vkAcquireProfilingLockKHR = null; private static delegate* unmanaged<VulkanHandle<VkDevice>, void> _vkReleaseProfilingLockKHR = null; private static delegate* unmanaged<VulkanHandle<VkDevice>, VulkanHandle<VkImage>, VkImageDrmFormatModifierPropertiesEXT*, VkResult> _vkGetImageDrmFormatModifierPropertiesEXT = null; private static delegate* unmanaged<VulkanHandle<VkDevice>, VkBufferDeviceAddressInfo*, ulong> _vkGetBufferOpaqueCaptureAddress = null; private static delegate* unmanaged<VulkanHandle<VkDevice>, VkBufferDeviceAddressInfo*, ulong> _vkGetBufferOpaqueCaptureAddressKHR = null; private static delegate* unmanaged<VulkanHandle<VkDevice>, VkBufferDeviceAddressInfo*, ulong> _vkGetBufferDeviceAddress = null; private static delegate* unmanaged<VulkanHandle<VkDevice>, VkBufferDeviceAddressInfo*, ulong> _vkGetBufferDeviceAddressKHR = null; private static delegate* unmanaged<VulkanHandle<VkDevice>, VkBufferDeviceAddressInfo*, ulong> _vkGetBufferDeviceAddressEXT = null; private static delegate* unmanaged<VulkanHandle<VkDevice>, VkInitializePerformanceApiInfoINTEL*, VkResult> _vkInitializePerformanceApiINTEL = null; private static delegate* unmanaged<VulkanHandle<VkDevice>, void> _vkUninitializePerformanceApiINTEL = null; private static delegate* unmanaged<VulkanHandle<VkCommandBuffer>, VkPerformanceMarkerInfoINTEL*, VkResult> _vkCmdSetPerformanceMarkerINTEL = null; private static delegate* unmanaged<VulkanHandle<VkCommandBuffer>, VkPerformanceStreamMarkerInfoINTEL*, VkResult> _vkCmdSetPerformanceStreamMarkerINTEL = null; private static delegate* unmanaged<VulkanHandle<VkCommandBuffer>, VkPerformanceOverrideInfoINTEL*, VkResult> _vkCmdSetPerformanceOverrideINTEL = null; private static delegate* unmanaged<VulkanHandle<VkDevice>, VkPerformanceConfigurationAcquireInfoINTEL*, VulkanHandle<VkPerformanceConfigurationINTEL>*, VkResult> _vkAcquirePerformanceConfigurationINTEL = null; private static delegate* unmanaged<VulkanHandle<VkDevice>, VulkanHandle<VkPerformanceConfigurationINTEL>, VkResult> _vkReleasePerformanceConfigurationINTEL = null; private static delegate* unmanaged<VulkanHandle<VkQueue>, VulkanHandle<VkPerformanceConfigurationINTEL>, VkResult> _vkQueueSetPerformanceConfigurationINTEL = null; private static delegate* unmanaged<VulkanHandle<VkDevice>, VkPerformanceParameterTypeINTEL, VkPerformanceValueINTEL*, VkResult> _vkGetPerformanceParameterINTEL = null; private static delegate* unmanaged<VulkanHandle<VkDevice>, VkDeviceMemoryOpaqueCaptureAddressInfo*, ulong> _vkGetDeviceMemoryOpaqueCaptureAddress = null; private static delegate* unmanaged<VulkanHandle<VkDevice>, VkDeviceMemoryOpaqueCaptureAddressInfo*, ulong> _vkGetDeviceMemoryOpaqueCaptureAddressKHR = null; private static delegate* unmanaged<VulkanHandle<VkDevice>, VkPipelineInfoKHR*, uint*, VkPipelineExecutablePropertiesKHR*, VkResult> _vkGetPipelineExecutablePropertiesKHR = null; private static delegate* unmanaged<VulkanHandle<VkDevice>, VkPipelineExecutableInfoKHR*, uint*, VkPipelineExecutableStatisticKHR*, VkResult> _vkGetPipelineExecutableStatisticsKHR = null; private static delegate* unmanaged<VulkanHandle<VkDevice>, VkPipelineExecutableInfoKHR*, uint*, VkPipelineExecutableInternalRepresentationKHR*, VkResult> _vkGetPipelineExecutableInternalRepresentationsKHR = null; private static delegate* unmanaged<VulkanHandle<VkCommandBuffer>, uint, ushort, void> _vkCmdSetLineStippleEXT = null; private static delegate* unmanaged<VulkanHandle<VkDevice>, VkAccelerationStructureCreateInfoKHR*, VkAllocationCallbacks*, VulkanHandle<VkAccelerationStructureKHR>*, VkResult> _vkCreateAccelerationStructureKHR = null; private static delegate* unmanaged<VulkanHandle<VkCommandBuffer>, uint, VkAccelerationStructureBuildGeometryInfoKHR*, VkAccelerationStructureBuildRangeInfoKHR**, void> _vkCmdBuildAccelerationStructuresKHR = null; private static delegate* unmanaged<VulkanHandle<VkCommandBuffer>, uint, VkAccelerationStructureBuildGeometryInfoKHR*, ulong*, uint*, uint**, void> _vkCmdBuildAccelerationStructuresIndirectKHR = null; private static delegate* unmanaged<VulkanHandle<VkDevice>, VulkanHandle<VkDeferredOperationKHR>, uint, VkAccelerationStructureBuildGeometryInfoKHR*, VkAccelerationStructureBuildRangeInfoKHR**, VkResult> _vkBuildAccelerationStructuresKHR = null; private static delegate* unmanaged<VulkanHandle<VkDevice>, VkAccelerationStructureDeviceAddressInfoKHR*, ulong> _vkGetAccelerationStructureDeviceAddressKHR = null; private static delegate* unmanaged<VulkanHandle<VkDevice>, VkAllocationCallbacks*, VulkanHandle<VkDeferredOperationKHR>*, VkResult> _vkCreateDeferredOperationKHR = null; private static delegate* unmanaged<VulkanHandle<VkDevice>, VulkanHandle<VkDeferredOperationKHR>, VkAllocationCallbacks*, void> _vkDestroyDeferredOperationKHR = null; private static delegate* unmanaged<VulkanHandle<VkDevice>, VulkanHandle<VkDeferredOperationKHR>, uint> _vkGetDeferredOperationMaxConcurrencyKHR = null; private static delegate* unmanaged<VulkanHandle<VkDevice>, VulkanHandle<VkDeferredOperationKHR>, VkResult> _vkGetDeferredOperationResultKHR = null; private static delegate* unmanaged<VulkanHandle<VkDevice>, VulkanHandle<VkDeferredOperationKHR>, VkResult> _vkDeferredOperationJoinKHR = null; private static delegate* unmanaged<VulkanHandle<VkCommandBuffer>, VkCullModeFlags, void> _vkCmdSetCullModeEXT = null; private static delegate* unmanaged<VulkanHandle<VkCommandBuffer>, VkFrontFace, void> _vkCmdSetFrontFaceEXT = null; private static delegate* unmanaged<VulkanHandle<VkCommandBuffer>, VkPrimitiveTopology, void> _vkCmdSetPrimitiveTopologyEXT = null; private static delegate* unmanaged<VulkanHandle<VkCommandBuffer>, uint, VkViewport*, void> _vkCmdSetViewportWithCountEXT = null; private static delegate* unmanaged<VulkanHandle<VkCommandBuffer>, uint, VkRect2D*, void> _vkCmdSetScissorWithCountEXT = null; private static delegate* unmanaged<VulkanHandle<VkCommandBuffer>, uint, uint, VulkanHandle<VkBuffer>*, ulong*, ulong*, ulong*, void> _vkCmdBindVertexBuffers2EXT = null; private static delegate* unmanaged<VulkanHandle<VkCommandBuffer>, VkBool32, void> _vkCmdSetDepthTestEnableEXT = null; private static delegate* unmanaged<VulkanHandle<VkCommandBuffer>, VkBool32, void> _vkCmdSetDepthWriteEnableEXT = null; private static delegate* unmanaged<VulkanHandle<VkCommandBuffer>, VkCompareOp, void> _vkCmdSetDepthCompareOpEXT = null; private static delegate* unmanaged<VulkanHandle<VkCommandBuffer>, VkBool32, void> _vkCmdSetDepthBoundsTestEnableEXT = null; private static delegate* unmanaged<VulkanHandle<VkCommandBuffer>, VkBool32, void> _vkCmdSetStencilTestEnableEXT = null; private static delegate* unmanaged<VulkanHandle<VkCommandBuffer>, VkStencilFaceFlags, VkStencilOp, VkStencilOp, VkStencilOp, VkCompareOp, void> _vkCmdSetStencilOpEXT = null; private static delegate* unmanaged<VulkanHandle<VkDevice>, VkPrivateDataSlotCreateInfoEXT*, VkAllocationCallbacks*, VulkanHandle<VkPrivateDataSlotEXT>*, VkResult> _vkCreatePrivateDataSlotEXT = null; private static delegate* unmanaged<VulkanHandle<VkDevice>, VulkanHandle<VkPrivateDataSlotEXT>, VkAllocationCallbacks*, void> _vkDestroyPrivateDataSlotEXT = null; private static delegate* unmanaged<VulkanHandle<VkDevice>, VkObjectType, ulong, VulkanHandle<VkPrivateDataSlotEXT>, ulong, VkResult> _vkSetPrivateDataEXT = null; private static delegate* unmanaged<VulkanHandle<VkDevice>, VkObjectType, ulong, VulkanHandle<VkPrivateDataSlotEXT>, ulong*, void> _vkGetPrivateDataEXT = null; private static delegate* unmanaged<VulkanHandle<VkCommandBuffer>, VkCopyBufferInfo2KHR*, void> _vkCmdCopyBuffer2KHR = null; private static delegate* unmanaged<VulkanHandle<VkCommandBuffer>, VkCopyImageInfo2KHR*, void> _vkCmdCopyImage2KHR = null; private static delegate* unmanaged<VulkanHandle<VkCommandBuffer>, VkBlitImageInfo2KHR*, void> _vkCmdBlitImage2KHR = null; private static delegate* unmanaged<VulkanHandle<VkCommandBuffer>, VkCopyBufferToImageInfo2KHR*, void> _vkCmdCopyBufferToImage2KHR = null; private static delegate* unmanaged<VulkanHandle<VkCommandBuffer>, VkCopyImageToBufferInfo2KHR*, void> _vkCmdCopyImageToBuffer2KHR = null; private static delegate* unmanaged<VulkanHandle<VkCommandBuffer>, VkResolveImageInfo2KHR*, void> _vkCmdResolveImage2KHR = null; private static delegate* unmanaged<VulkanHandle<VkCommandBuffer>, VkExtent2D*, VkFragmentShadingRateCombinerOpKHR*, void> _vkCmdSetFragmentShadingRateKHR = null; private static delegate* unmanaged<VulkanHandle<VkCommandBuffer>, VkFragmentShadingRateNV, VkFragmentShadingRateCombinerOpKHR*, void> _vkCmdSetFragmentShadingRateEnumNV = null; private static delegate* unmanaged<VulkanHandle<VkDevice>, VkAccelerationStructureBuildTypeKHR, VkAccelerationStructureBuildGeometryInfoKHR*, uint*, VkAccelerationStructureBuildSizesInfoKHR*, void> _vkGetAccelerationStructureBuildSizesKHR = null; /// <summary>Initializes the instance-level functions in the table.</summary> static void InitFunctionTable(VulkanHandle<VkInstance> inst, VkVersion version) { if (!inst) throw new ArgumentException("Cannot initialize function table with null instance"); void* addr = null; InstanceVersion = version; _vkDestroyInstance = (delegate* unmanaged<VulkanHandle<VkInstance>, VkAllocationCallbacks*, void>)LoadFunc(inst, "vkDestroyInstance"); _vkEnumeratePhysicalDevices = (delegate* unmanaged<VulkanHandle<VkInstance>, uint*, VulkanHandle<VkPhysicalDevice>*, VkResult>)LoadFunc(inst, "vkEnumeratePhysicalDevices"); _vkGetPhysicalDeviceProperties = (delegate* unmanaged<VulkanHandle<VkPhysicalDevice>, VkPhysicalDeviceProperties*, void>)LoadFunc(inst, "vkGetPhysicalDeviceProperties"); _vkGetPhysicalDeviceQueueFamilyProperties = (delegate* unmanaged<VulkanHandle<VkPhysicalDevice>, uint*, VkQueueFamilyProperties*, void>)LoadFunc(inst, "vkGetPhysicalDeviceQueueFamilyProperties"); _vkGetPhysicalDeviceMemoryProperties = (delegate* unmanaged<VulkanHandle<VkPhysicalDevice>, VkPhysicalDeviceMemoryProperties*, void>)LoadFunc(inst, "vkGetPhysicalDeviceMemoryProperties"); _vkGetPhysicalDeviceFeatures = (delegate* unmanaged<VulkanHandle<VkPhysicalDevice>, VkPhysicalDeviceFeatures*, void>)LoadFunc(inst, "vkGetPhysicalDeviceFeatures"); _vkGetPhysicalDeviceFormatProperties = (delegate* unmanaged<VulkanHandle<VkPhysicalDevice>, VkFormat, VkFormatProperties*, void>)LoadFunc(inst, "vkGetPhysicalDeviceFormatProperties"); _vkGetPhysicalDeviceImageFormatProperties = (delegate* unmanaged<VulkanHandle<VkPhysicalDevice>, VkFormat, VkImageType, VkImageTiling, VkImageUsageFlags, VkImageCreateFlags, VkImageFormatProperties*, VkResult>)LoadFunc(inst, "vkGetPhysicalDeviceImageFormatProperties"); _vkCreateDevice = (delegate* unmanaged<VulkanHandle<VkPhysicalDevice>, VkDeviceCreateInfo*, VkAllocationCallbacks*, VulkanHandle<VkDevice>*, VkResult>)LoadFunc(inst, "vkCreateDevice"); _vkEnumerateDeviceLayerProperties = (delegate* unmanaged<VulkanHandle<VkPhysicalDevice>, uint*, VkLayerProperties*, VkResult>)LoadFunc(inst, "vkEnumerateDeviceLayerProperties"); _vkEnumerateDeviceExtensionProperties = (delegate* unmanaged<VulkanHandle<VkPhysicalDevice>, byte*, uint*, VkExtensionProperties*, VkResult>)LoadFunc(inst, "vkEnumerateDeviceExtensionProperties"); _vkGetPhysicalDeviceSparseImageFormatProperties = (delegate* unmanaged<VulkanHandle<VkPhysicalDevice>, VkFormat, VkImageType, VkSampleCountFlags, VkImageUsageFlags, VkImageTiling, uint*, VkSparseImageFormatProperties*, void>)LoadFunc(inst, "vkGetPhysicalDeviceSparseImageFormatProperties"); if (TryLoadFunc(inst, "vkCreateAndroidSurfaceKHR", out addr)) { _vkCreateAndroidSurfaceKHR = (delegate* unmanaged<VulkanHandle<VkInstance>, VkAndroidSurfaceCreateInfoKHR*, VkAllocationCallbacks*, VulkanHandle<VkSurfaceKHR>*, VkResult>)addr; } if (TryLoadFunc(inst, "vkGetPhysicalDeviceDisplayPropertiesKHR", out addr)) { _vkGetPhysicalDeviceDisplayPropertiesKHR = (delegate* unmanaged<VulkanHandle<VkPhysicalDevice>, uint*, VkDisplayPropertiesKHR*, VkResult>)addr; } if (TryLoadFunc(inst, "vkGetPhysicalDeviceDisplayPlanePropertiesKHR", out addr)) { _vkGetPhysicalDeviceDisplayPlanePropertiesKHR = (delegate* unmanaged<VulkanHandle<VkPhysicalDevice>, uint*, VkDisplayPlanePropertiesKHR*, VkResult>)addr; } if (TryLoadFunc(inst, "vkGetDisplayPlaneSupportedDisplaysKHR", out addr)) { _vkGetDisplayPlaneSupportedDisplaysKHR = (delegate* unmanaged<VulkanHandle<VkPhysicalDevice>, uint, uint*, VulkanHandle<VkDisplayKHR>*, VkResult>)addr; } if (TryLoadFunc(inst, "vkGetDisplayModePropertiesKHR", out addr)) { _vkGetDisplayModePropertiesKHR = (delegate* unmanaged<VulkanHandle<VkPhysicalDevice>, VulkanHandle<VkDisplayKHR>, uint*, VkDisplayModePropertiesKHR*, VkResult>)addr; } if (TryLoadFunc(inst, "vkCreateDisplayModeKHR", out addr)) { _vkCreateDisplayModeKHR = (delegate* unmanaged<VulkanHandle<VkPhysicalDevice>, VulkanHandle<VkDisplayKHR>, VkDisplayModeCreateInfoKHR*, VkAllocationCallbacks*, VulkanHandle<VkDisplayModeKHR>*, VkResult>)addr; } if (TryLoadFunc(inst, "vkGetDisplayPlaneCapabilitiesKHR", out addr)) { _vkGetDisplayPlaneCapabilitiesKHR = (delegate* unmanaged<VulkanHandle<VkPhysicalDevice>, VulkanHandle<VkDisplayModeKHR>, uint, VkDisplayPlaneCapabilitiesKHR*, VkResult>)addr; } if (TryLoadFunc(inst, "vkCreateDisplayPlaneSurfaceKHR", out addr)) { _vkCreateDisplayPlaneSurfaceKHR = (delegate* unmanaged<VulkanHandle<VkInstance>, VkDisplaySurfaceCreateInfoKHR*, VkAllocationCallbacks*, VulkanHandle<VkSurfaceKHR>*, VkResult>)addr; } if (TryLoadFunc(inst, "vkDestroySurfaceKHR", out addr)) { _vkDestroySurfaceKHR = (delegate* unmanaged<VulkanHandle<VkInstance>, VulkanHandle<VkSurfaceKHR>, VkAllocationCallbacks*, void>)addr; } if (TryLoadFunc(inst, "vkGetPhysicalDeviceSurfaceSupportKHR", out addr)) { _vkGetPhysicalDeviceSurfaceSupportKHR = (delegate* unmanaged<VulkanHandle<VkPhysicalDevice>, uint, VulkanHandle<VkSurfaceKHR>, VkBool32*, VkResult>)addr; } if (TryLoadFunc(inst, "vkGetPhysicalDeviceSurfaceCapabilitiesKHR", out addr)) { _vkGetPhysicalDeviceSurfaceCapabilitiesKHR = (delegate* unmanaged<VulkanHandle<VkPhysicalDevice>, VulkanHandle<VkSurfaceKHR>, VkSurfaceCapabilitiesKHR*, VkResult>)addr; } if (TryLoadFunc(inst, "vkGetPhysicalDeviceSurfaceFormatsKHR", out addr)) { _vkGetPhysicalDeviceSurfaceFormatsKHR = (delegate* unmanaged<VulkanHandle<VkPhysicalDevice>, VulkanHandle<VkSurfaceKHR>, uint*, VkSurfaceFormatKHR*, VkResult>)addr; } if (TryLoadFunc(inst, "vkGetPhysicalDeviceSurfacePresentModesKHR", out addr)) { _vkGetPhysicalDeviceSurfacePresentModesKHR = (delegate* unmanaged<VulkanHandle<VkPhysicalDevice>, VulkanHandle<VkSurfaceKHR>, uint*, VkPresentModeKHR*, VkResult>)addr; } if (TryLoadFunc(inst, "vkCreateViSurfaceNN", out addr)) { _vkCreateViSurfaceNN = (delegate* unmanaged<VulkanHandle<VkInstance>, VkViSurfaceCreateInfoNN*, VkAllocationCallbacks*, VulkanHandle<VkSurfaceKHR>*, VkResult>)addr; } if (TryLoadFunc(inst, "vkCreateWaylandSurfaceKHR", out addr)) { _vkCreateWaylandSurfaceKHR = (delegate* unmanaged<VulkanHandle<VkInstance>, VkWaylandSurfaceCreateInfoKHR*, VkAllocationCallbacks*, VulkanHandle<VkSurfaceKHR>*, VkResult>)addr; } if (TryLoadFunc(inst, "vkGetPhysicalDeviceWaylandPresentationSupportKHR", out addr)) { _vkGetPhysicalDeviceWaylandPresentationSupportKHR = (delegate* unmanaged<VulkanHandle<VkPhysicalDevice>, uint, void*, VkBool32>)addr; } if (TryLoadFunc(inst, "vkCreateWin32SurfaceKHR", out addr)) { _vkCreateWin32SurfaceKHR = (delegate* unmanaged<VulkanHandle<VkInstance>, VkWin32SurfaceCreateInfoKHR*, VkAllocationCallbacks*, VulkanHandle<VkSurfaceKHR>*, VkResult>)addr; } if (TryLoadFunc(inst, "vkGetPhysicalDeviceWin32PresentationSupportKHR", out addr)) { _vkGetPhysicalDeviceWin32PresentationSupportKHR = (delegate* unmanaged<VulkanHandle<VkPhysicalDevice>, uint, VkBool32>)addr; } if (TryLoadFunc(inst, "vkCreateXlibSurfaceKHR", out addr)) { _vkCreateXlibSurfaceKHR = (delegate* unmanaged<VulkanHandle<VkInstance>, VkXlibSurfaceCreateInfoKHR*, VkAllocationCallbacks*, VulkanHandle<VkSurfaceKHR>*, VkResult>)addr; } if (TryLoadFunc(inst, "vkGetPhysicalDeviceXlibPresentationSupportKHR", out addr)) { _vkGetPhysicalDeviceXlibPresentationSupportKHR = (delegate* unmanaged<VulkanHandle<VkPhysicalDevice>, uint, void*, ulong, VkBool32>)addr; } if (TryLoadFunc(inst, "vkCreateXcbSurfaceKHR", out addr)) { _vkCreateXcbSurfaceKHR = (delegate* unmanaged<VulkanHandle<VkInstance>, VkXcbSurfaceCreateInfoKHR*, VkAllocationCallbacks*, VulkanHandle<VkSurfaceKHR>*, VkResult>)addr; } if (TryLoadFunc(inst, "vkGetPhysicalDeviceXcbPresentationSupportKHR", out addr)) { _vkGetPhysicalDeviceXcbPresentationSupportKHR = (delegate* unmanaged<VulkanHandle<VkPhysicalDevice>, uint, void*, uint, VkBool32>)addr; } if (TryLoadFunc(inst, "vkCreateDirectFBSurfaceEXT", out addr)) { _vkCreateDirectFBSurfaceEXT = (delegate* unmanaged<VulkanHandle<VkInstance>, VkDirectFBSurfaceCreateInfoEXT*, VkAllocationCallbacks*, VulkanHandle<VkSurfaceKHR>*, VkResult>)addr; } if (TryLoadFunc(inst, "vkGetPhysicalDeviceDirectFBPresentationSupportEXT", out addr)) { _vkGetPhysicalDeviceDirectFBPresentationSupportEXT = (delegate* unmanaged<VulkanHandle<VkPhysicalDevice>, uint, void*, VkBool32>)addr; } if (TryLoadFunc(inst, "vkCreateImagePipeSurfaceFUCHSIA", out addr)) { _vkCreateImagePipeSurfaceFUCHSIA = (delegate* unmanaged<VulkanHandle<VkInstance>, VkImagePipeSurfaceCreateInfoFUCHSIA*, VkAllocationCallbacks*, VulkanHandle<VkSurfaceKHR>*, VkResult>)addr; } if (TryLoadFunc(inst, "vkCreateStreamDescriptorSurfaceGGP", out addr)) { _vkCreateStreamDescriptorSurfaceGGP = (delegate* unmanaged<VulkanHandle<VkInstance>, VkStreamDescriptorSurfaceCreateInfoGGP*, VkAllocationCallbacks*, VulkanHandle<VkSurfaceKHR>*, VkResult>)addr; } if (TryLoadFunc(inst, "vkCreateDebugReportCallbackEXT", out addr)) { _vkCreateDebugReportCallbackEXT = (delegate* unmanaged<VulkanHandle<VkInstance>, VkDebugReportCallbackCreateInfoEXT*, VkAllocationCallbacks*, VulkanHandle<VkDebugReportCallbackEXT>*, VkResult>)addr; } if (TryLoadFunc(inst, "vkDestroyDebugReportCallbackEXT", out addr)) { _vkDestroyDebugReportCallbackEXT = (delegate* unmanaged<VulkanHandle<VkInstance>, VulkanHandle<VkDebugReportCallbackEXT>, VkAllocationCallbacks*, void>)addr; } if (TryLoadFunc(inst, "vkDebugReportMessageEXT", out addr)) { _vkDebugReportMessageEXT = (delegate* unmanaged<VulkanHandle<VkInstance>, VkDebugReportFlagsEXT, VkDebugReportObjectTypeEXT, ulong, ulong, int, byte*, byte*, void>)addr; } if (TryLoadFunc(inst, "vkGetPhysicalDeviceExternalImageFormatPropertiesNV", out addr)) { _vkGetPhysicalDeviceExternalImageFormatPropertiesNV = (delegate* unmanaged<VulkanHandle<VkPhysicalDevice>, VkFormat, VkImageType, VkImageTiling, VkImageUsageFlags, VkImageCreateFlags, VkExternalMemoryHandleTypeFlagsNV, VkExternalImageFormatPropertiesNV*, VkResult>)addr; } if (version >= VkVersion.VK_VERSION_1_1) { _vkGetPhysicalDeviceFeatures2 = (delegate* unmanaged<VulkanHandle<VkPhysicalDevice>, VkPhysicalDeviceFeatures2*, void>)LoadFunc(inst, "vkGetPhysicalDeviceFeatures2"); } _vkGetPhysicalDeviceFeatures2KHR = _vkGetPhysicalDeviceFeatures2; if ((_vkGetPhysicalDeviceFeatures2KHR == null) && TryLoadFunc(inst, "vkGetPhysicalDeviceFeatures2KHR", out addr)) { _vkGetPhysicalDeviceFeatures2KHR = (delegate* unmanaged<VulkanHandle<VkPhysicalDevice>, VkPhysicalDeviceFeatures2*, void>)addr; } if (version >= VkVersion.VK_VERSION_1_1) { _vkGetPhysicalDeviceProperties2 = (delegate* unmanaged<VulkanHandle<VkPhysicalDevice>, VkPhysicalDeviceProperties2*, void>)LoadFunc(inst, "vkGetPhysicalDeviceProperties2"); } _vkGetPhysicalDeviceProperties2KHR = _vkGetPhysicalDeviceProperties2; if ((_vkGetPhysicalDeviceProperties2KHR == null) && TryLoadFunc(inst, "vkGetPhysicalDeviceProperties2KHR", out addr)) { _vkGetPhysicalDeviceProperties2KHR = (delegate* unmanaged<VulkanHandle<VkPhysicalDevice>, VkPhysicalDeviceProperties2*, void>)addr; } if (version >= VkVersion.VK_VERSION_1_1) { _vkGetPhysicalDeviceFormatProperties2 = (delegate* unmanaged<VulkanHandle<VkPhysicalDevice>, VkFormat, VkFormatProperties2*, void>)LoadFunc(inst, "vkGetPhysicalDeviceFormatProperties2"); } _vkGetPhysicalDeviceFormatProperties2KHR = _vkGetPhysicalDeviceFormatProperties2; if ((_vkGetPhysicalDeviceFormatProperties2KHR == null) && TryLoadFunc(inst, "vkGetPhysicalDeviceFormatProperties2KHR", out addr)) { _vkGetPhysicalDeviceFormatProperties2KHR = (delegate* unmanaged<VulkanHandle<VkPhysicalDevice>, VkFormat, VkFormatProperties2*, void>)addr; } if (version >= VkVersion.VK_VERSION_1_1) { _vkGetPhysicalDeviceImageFormatProperties2 = (delegate* unmanaged<VulkanHandle<VkPhysicalDevice>, VkPhysicalDeviceImageFormatInfo2*, VkImageFormatProperties2*, VkResult>)LoadFunc(inst, "vkGetPhysicalDeviceImageFormatProperties2"); } _vkGetPhysicalDeviceImageFormatProperties2KHR = _vkGetPhysicalDeviceImageFormatProperties2; if ((_vkGetPhysicalDeviceImageFormatProperties2KHR == null) && TryLoadFunc(inst, "vkGetPhysicalDeviceImageFormatProperties2KHR", out addr)) { _vkGetPhysicalDeviceImageFormatProperties2KHR = (delegate* unmanaged<VulkanHandle<VkPhysicalDevice>, VkPhysicalDeviceImageFormatInfo2*, VkImageFormatProperties2*, VkResult>)addr; } if (version >= VkVersion.VK_VERSION_1_1) { _vkGetPhysicalDeviceQueueFamilyProperties2 = (delegate* unmanaged<VulkanHandle<VkPhysicalDevice>, uint*, VkQueueFamilyProperties2*, void>)LoadFunc(inst, "vkGetPhysicalDeviceQueueFamilyProperties2"); } _vkGetPhysicalDeviceQueueFamilyProperties2KHR = _vkGetPhysicalDeviceQueueFamilyProperties2; if ((_vkGetPhysicalDeviceQueueFamilyProperties2KHR == null) && TryLoadFunc(inst, "vkGetPhysicalDeviceQueueFamilyProperties2KHR", out addr)) { _vkGetPhysicalDeviceQueueFamilyProperties2KHR = (delegate* unmanaged<VulkanHandle<VkPhysicalDevice>, uint*, VkQueueFamilyProperties2*, void>)addr; } if (version >= VkVersion.VK_VERSION_1_1) { _vkGetPhysicalDeviceMemoryProperties2 = (delegate* unmanaged<VulkanHandle<VkPhysicalDevice>, VkPhysicalDeviceMemoryProperties2*, void>)LoadFunc(inst, "vkGetPhysicalDeviceMemoryProperties2"); } _vkGetPhysicalDeviceMemoryProperties2KHR = _vkGetPhysicalDeviceMemoryProperties2; if ((_vkGetPhysicalDeviceMemoryProperties2KHR == null) && TryLoadFunc(inst, "vkGetPhysicalDeviceMemoryProperties2KHR", out addr)) { _vkGetPhysicalDeviceMemoryProperties2KHR = (delegate* unmanaged<VulkanHandle<VkPhysicalDevice>, VkPhysicalDeviceMemoryProperties2*, void>)addr; } if (version >= VkVersion.VK_VERSION_1_1) { _vkGetPhysicalDeviceSparseImageFormatProperties2 = (delegate* unmanaged<VulkanHandle<VkPhysicalDevice>, VkPhysicalDeviceSparseImageFormatInfo2*, uint*, VkSparseImageFormatProperties2*, void>)LoadFunc(inst, "vkGetPhysicalDeviceSparseImageFormatProperties2"); } _vkGetPhysicalDeviceSparseImageFormatProperties2KHR = _vkGetPhysicalDeviceSparseImageFormatProperties2; if ((_vkGetPhysicalDeviceSparseImageFormatProperties2KHR == null) && TryLoadFunc(inst, "vkGetPhysicalDeviceSparseImageFormatProperties2KHR", out addr)) { _vkGetPhysicalDeviceSparseImageFormatProperties2KHR = (delegate* unmanaged<VulkanHandle<VkPhysicalDevice>, VkPhysicalDeviceSparseImageFormatInfo2*, uint*, VkSparseImageFormatProperties2*, void>)addr; } if (version >= VkVersion.VK_VERSION_1_1) { _vkGetPhysicalDeviceExternalBufferProperties = (delegate* unmanaged<VulkanHandle<VkPhysicalDevice>, VkPhysicalDeviceExternalBufferInfo*, VkExternalBufferProperties*, void>)LoadFunc(inst, "vkGetPhysicalDeviceExternalBufferProperties"); } _vkGetPhysicalDeviceExternalBufferPropertiesKHR = _vkGetPhysicalDeviceExternalBufferProperties; if ((_vkGetPhysicalDeviceExternalBufferPropertiesKHR == null) && TryLoadFunc(inst, "vkGetPhysicalDeviceExternalBufferPropertiesKHR", out addr)) { _vkGetPhysicalDeviceExternalBufferPropertiesKHR = (delegate* unmanaged<VulkanHandle<VkPhysicalDevice>, VkPhysicalDeviceExternalBufferInfo*, VkExternalBufferProperties*, void>)addr; } if (version >= VkVersion.VK_VERSION_1_1) { _vkGetPhysicalDeviceExternalSemaphoreProperties = (delegate* unmanaged<VulkanHandle<VkPhysicalDevice>, VkPhysicalDeviceExternalSemaphoreInfo*, VkExternalSemaphoreProperties*, void>)LoadFunc(inst, "vkGetPhysicalDeviceExternalSemaphoreProperties"); } _vkGetPhysicalDeviceExternalSemaphorePropertiesKHR = _vkGetPhysicalDeviceExternalSemaphoreProperties; if ((_vkGetPhysicalDeviceExternalSemaphorePropertiesKHR == null) && TryLoadFunc(inst, "vkGetPhysicalDeviceExternalSemaphorePropertiesKHR", out addr)) { _vkGetPhysicalDeviceExternalSemaphorePropertiesKHR = (delegate* unmanaged<VulkanHandle<VkPhysicalDevice>, VkPhysicalDeviceExternalSemaphoreInfo*, VkExternalSemaphoreProperties*, void>)addr; } if (version >= VkVersion.VK_VERSION_1_1) { _vkGetPhysicalDeviceExternalFenceProperties = (delegate* unmanaged<VulkanHandle<VkPhysicalDevice>, VkPhysicalDeviceExternalFenceInfo*, VkExternalFenceProperties*, void>)LoadFunc(inst, "vkGetPhysicalDeviceExternalFenceProperties"); } _vkGetPhysicalDeviceExternalFencePropertiesKHR = _vkGetPhysicalDeviceExternalFenceProperties; if ((_vkGetPhysicalDeviceExternalFencePropertiesKHR == null) && TryLoadFunc(inst, "vkGetPhysicalDeviceExternalFencePropertiesKHR", out addr)) { _vkGetPhysicalDeviceExternalFencePropertiesKHR = (delegate* unmanaged<VulkanHandle<VkPhysicalDevice>, VkPhysicalDeviceExternalFenceInfo*, VkExternalFenceProperties*, void>)addr; } if (TryLoadFunc(inst, "vkReleaseDisplayEXT", out addr)) { _vkReleaseDisplayEXT = (delegate* unmanaged<VulkanHandle<VkPhysicalDevice>, VulkanHandle<VkDisplayKHR>, VkResult>)addr; } if (TryLoadFunc(inst, "vkAcquireXlibDisplayEXT", out addr)) { _vkAcquireXlibDisplayEXT = (delegate* unmanaged<VulkanHandle<VkPhysicalDevice>, void*, VulkanHandle<VkDisplayKHR>, VkResult>)addr; } if (TryLoadFunc(inst, "vkGetRandROutputDisplayEXT", out addr)) { _vkGetRandROutputDisplayEXT = (delegate* unmanaged<VulkanHandle<VkPhysicalDevice>, void*, ulong, VulkanHandle<VkDisplayKHR>*, VkResult>)addr; } if (TryLoadFunc(inst, "vkAcquireWinrtDisplayNV", out addr)) { _vkAcquireWinrtDisplayNV = (delegate* unmanaged<VulkanHandle<VkPhysicalDevice>, VulkanHandle<VkDisplayKHR>, VkResult>)addr; } if (TryLoadFunc(inst, "vkGetWinrtDisplayNV", out addr)) { _vkGetWinrtDisplayNV = (delegate* unmanaged<VulkanHandle<VkPhysicalDevice>, uint, VulkanHandle<VkDisplayKHR>*, VkResult>)addr; } if (TryLoadFunc(inst, "vkGetPhysicalDeviceSurfaceCapabilities2EXT", out addr)) { _vkGetPhysicalDeviceSurfaceCapabilities2EXT = (delegate* unmanaged<VulkanHandle<VkPhysicalDevice>, VulkanHandle<VkSurfaceKHR>, VkSurfaceCapabilities2EXT*, VkResult>)addr; } if (version >= VkVersion.VK_VERSION_1_1) { _vkEnumeratePhysicalDeviceGroups = (delegate* unmanaged<VulkanHandle<VkInstance>, uint*, VkPhysicalDeviceGroupProperties*, VkResult>)LoadFunc(inst, "vkEnumeratePhysicalDeviceGroups"); } _vkEnumeratePhysicalDeviceGroupsKHR = _vkEnumeratePhysicalDeviceGroups; if ((_vkEnumeratePhysicalDeviceGroupsKHR == null) && TryLoadFunc(inst, "vkEnumeratePhysicalDeviceGroupsKHR", out addr)) { _vkEnumeratePhysicalDeviceGroupsKHR = (delegate* unmanaged<VulkanHandle<VkInstance>, uint*, VkPhysicalDeviceGroupProperties*, VkResult>)addr; } if (TryLoadFunc(inst, "vkGetPhysicalDevicePresentRectanglesKHR", out addr)) { _vkGetPhysicalDevicePresentRectanglesKHR = (delegate* unmanaged<VulkanHandle<VkPhysicalDevice>, VulkanHandle<VkSurfaceKHR>, uint*, VkRect2D*, VkResult>)addr; } if (TryLoadFunc(inst, "vkCreateIOSSurfaceMVK", out addr)) { _vkCreateIOSSurfaceMVK = (delegate* unmanaged<VulkanHandle<VkInstance>, VkIOSSurfaceCreateInfoMVK*, VkAllocationCallbacks*, VulkanHandle<VkSurfaceKHR>*, VkResult>)addr; } if (TryLoadFunc(inst, "vkCreateMacOSSurfaceMVK", out addr)) { _vkCreateMacOSSurfaceMVK = (delegate* unmanaged<VulkanHandle<VkInstance>, VkMacOSSurfaceCreateInfoMVK*, VkAllocationCallbacks*, VulkanHandle<VkSurfaceKHR>*, VkResult>)addr; } if (TryLoadFunc(inst, "vkCreateMetalSurfaceEXT", out addr)) { _vkCreateMetalSurfaceEXT = (delegate* unmanaged<VulkanHandle<VkInstance>, VkMetalSurfaceCreateInfoEXT*, VkAllocationCallbacks*, VulkanHandle<VkSurfaceKHR>*, VkResult>)addr; } if (TryLoadFunc(inst, "vkGetPhysicalDeviceMultisamplePropertiesEXT", out addr)) { _vkGetPhysicalDeviceMultisamplePropertiesEXT = (delegate* unmanaged<VulkanHandle<VkPhysicalDevice>, VkSampleCountFlags, VkMultisamplePropertiesEXT*, void>)addr; } if (TryLoadFunc(inst, "vkGetPhysicalDeviceSurfaceCapabilities2KHR", out addr)) { _vkGetPhysicalDeviceSurfaceCapabilities2KHR = (delegate* unmanaged<VulkanHandle<VkPhysicalDevice>, VkPhysicalDeviceSurfaceInfo2KHR*, VkSurfaceCapabilities2KHR*, VkResult>)addr; } if (TryLoadFunc(inst, "vkGetPhysicalDeviceSurfaceFormats2KHR", out addr)) { _vkGetPhysicalDeviceSurfaceFormats2KHR = (delegate* unmanaged<VulkanHandle<VkPhysicalDevice>, VkPhysicalDeviceSurfaceInfo2KHR*, uint*, VkSurfaceFormat2KHR*, VkResult>)addr; } if (TryLoadFunc(inst, "vkGetPhysicalDeviceDisplayProperties2KHR", out addr)) { _vkGetPhysicalDeviceDisplayProperties2KHR = (delegate* unmanaged<VulkanHandle<VkPhysicalDevice>, uint*, VkDisplayProperties2KHR*, VkResult>)addr; } if (TryLoadFunc(inst, "vkGetPhysicalDeviceDisplayPlaneProperties2KHR", out addr)) { _vkGetPhysicalDeviceDisplayPlaneProperties2KHR = (delegate* unmanaged<VulkanHandle<VkPhysicalDevice>, uint*, VkDisplayPlaneProperties2KHR*, VkResult>)addr; } if (TryLoadFunc(inst, "vkGetDisplayModeProperties2KHR", out addr)) { _vkGetDisplayModeProperties2KHR = (delegate* unmanaged<VulkanHandle<VkPhysicalDevice>, VulkanHandle<VkDisplayKHR>, uint*, VkDisplayModeProperties2KHR*, VkResult>)addr; } if (TryLoadFunc(inst, "vkGetDisplayPlaneCapabilities2KHR", out addr)) { _vkGetDisplayPlaneCapabilities2KHR = (delegate* unmanaged<VulkanHandle<VkPhysicalDevice>, VkDisplayPlaneInfo2KHR*, VkDisplayPlaneCapabilities2KHR*, VkResult>)addr; } if (TryLoadFunc(inst, "vkGetPhysicalDeviceCalibrateableTimeDomainsEXT", out addr)) { _vkGetPhysicalDeviceCalibrateableTimeDomainsEXT = (delegate* unmanaged<VulkanHandle<VkPhysicalDevice>, uint*, VkTimeDomainEXT*, VkResult>)addr; } if (TryLoadFunc(inst, "vkCreateDebugUtilsMessengerEXT", out addr)) { _vkCreateDebugUtilsMessengerEXT = (delegate* unmanaged<VulkanHandle<VkInstance>, VkDebugUtilsMessengerCreateInfoEXT*, VkAllocationCallbacks*, VulkanHandle<VkDebugUtilsMessengerEXT>*, VkResult>)addr; } if (TryLoadFunc(inst, "vkDestroyDebugUtilsMessengerEXT", out addr)) { _vkDestroyDebugUtilsMessengerEXT = (delegate* unmanaged<VulkanHandle<VkInstance>, VulkanHandle<VkDebugUtilsMessengerEXT>, VkAllocationCallbacks*, void>)addr; } if (TryLoadFunc(inst, "vkSubmitDebugUtilsMessageEXT", out addr)) { _vkSubmitDebugUtilsMessageEXT = (delegate* unmanaged<VulkanHandle<VkInstance>, VkDebugUtilsMessageSeverityFlagsEXT, VkDebugUtilsMessageTypeFlagsEXT, VkDebugUtilsMessengerCallbackDataEXT*, void>)addr; } if (TryLoadFunc(inst, "vkGetPhysicalDeviceCooperativeMatrixPropertiesNV", out addr)) { _vkGetPhysicalDeviceCooperativeMatrixPropertiesNV = (delegate* unmanaged<VulkanHandle<VkPhysicalDevice>, uint*, VkCooperativeMatrixPropertiesNV*, VkResult>)addr; } if (TryLoadFunc(inst, "vkGetPhysicalDeviceSurfacePresentModes2EXT", out addr)) { _vkGetPhysicalDeviceSurfacePresentModes2EXT = (delegate* unmanaged<VulkanHandle<VkPhysicalDevice>, VkPhysicalDeviceSurfaceInfo2KHR*, uint*, VkPresentModeKHR*, VkResult>)addr; } if (TryLoadFunc(inst, "vkEnumeratePhysicalDeviceQueueFamilyPerformanceQueryCountersKHR", out addr)) { _vkEnumeratePhysicalDeviceQueueFamilyPerformanceQueryCountersKHR = (delegate* unmanaged<VulkanHandle<VkPhysicalDevice>, uint, uint*, VkPerformanceCounterKHR*, VkPerformanceCounterDescriptionKHR*, VkResult>)addr; } if (TryLoadFunc(inst, "vkGetPhysicalDeviceQueueFamilyPerformanceQueryPassesKHR", out addr)) { _vkGetPhysicalDeviceQueueFamilyPerformanceQueryPassesKHR = (delegate* unmanaged<VulkanHandle<VkPhysicalDevice>, VkQueryPoolPerformanceCreateInfoKHR*, uint*, void>)addr; } if (TryLoadFunc(inst, "vkCreateHeadlessSurfaceEXT", out addr)) { _vkCreateHeadlessSurfaceEXT = (delegate* unmanaged<VulkanHandle<VkInstance>, VkHeadlessSurfaceCreateInfoEXT*, VkAllocationCallbacks*, VulkanHandle<VkSurfaceKHR>*, VkResult>)addr; } if (TryLoadFunc(inst, "vkGetPhysicalDeviceSupportedFramebufferMixedSamplesCombinationsNV", out addr)) { _vkGetPhysicalDeviceSupportedFramebufferMixedSamplesCombinationsNV = (delegate* unmanaged<VulkanHandle<VkPhysicalDevice>, uint*, VkFramebufferMixedSamplesCombinationNV*, VkResult>)addr; } if (TryLoadFunc(inst, "vkGetPhysicalDeviceToolPropertiesEXT", out addr)) { _vkGetPhysicalDeviceToolPropertiesEXT = (delegate* unmanaged<VulkanHandle<VkPhysicalDevice>, uint*, VkPhysicalDeviceToolPropertiesEXT*, VkResult>)addr; } if (TryLoadFunc(inst, "vkGetPhysicalDeviceFragmentShadingRatesKHR", out addr)) { _vkGetPhysicalDeviceFragmentShadingRatesKHR = (delegate* unmanaged<VulkanHandle<VkPhysicalDevice>, uint*, VkPhysicalDeviceFragmentShadingRateKHR*, VkResult>)addr; } } /// <summary>Initializes the device-level functions in the table.</summary> static void InitFunctionTable(VulkanHandle<VkDevice> dev, VkVersion version) { if (!dev) throw new ArgumentException("Cannot initialize function table with null device"); void* addr = null; DeviceVersion = version; _vkDestroyInstance = (delegate* unmanaged<VulkanHandle<VkInstance>, VkAllocationCallbacks*, void>)LoadFunc(dev, "vkDestroyInstance"); _vkEnumeratePhysicalDevices = (delegate* unmanaged<VulkanHandle<VkInstance>, uint*, VulkanHandle<VkPhysicalDevice>*, VkResult>)LoadFunc(dev, "vkEnumeratePhysicalDevices"); _vkGetPhysicalDeviceProperties = (delegate* unmanaged<VulkanHandle<VkPhysicalDevice>, VkPhysicalDeviceProperties*, void>)LoadFunc(dev, "vkGetPhysicalDeviceProperties"); _vkGetPhysicalDeviceQueueFamilyProperties = (delegate* unmanaged<VulkanHandle<VkPhysicalDevice>, uint*, VkQueueFamilyProperties*, void>)LoadFunc(dev, "vkGetPhysicalDeviceQueueFamilyProperties"); _vkGetPhysicalDeviceMemoryProperties = (delegate* unmanaged<VulkanHandle<VkPhysicalDevice>, VkPhysicalDeviceMemoryProperties*, void>)LoadFunc(dev, "vkGetPhysicalDeviceMemoryProperties"); _vkGetPhysicalDeviceFeatures = (delegate* unmanaged<VulkanHandle<VkPhysicalDevice>, VkPhysicalDeviceFeatures*, void>)LoadFunc(dev, "vkGetPhysicalDeviceFeatures"); _vkGetPhysicalDeviceFormatProperties = (delegate* unmanaged<VulkanHandle<VkPhysicalDevice>, VkFormat, VkFormatProperties*, void>)LoadFunc(dev, "vkGetPhysicalDeviceFormatProperties"); _vkGetPhysicalDeviceImageFormatProperties = (delegate* unmanaged<VulkanHandle<VkPhysicalDevice>, VkFormat, VkImageType, VkImageTiling, VkImageUsageFlags, VkImageCreateFlags, VkImageFormatProperties*, VkResult>)LoadFunc(dev, "vkGetPhysicalDeviceImageFormatProperties"); _vkCreateDevice = (delegate* unmanaged<VulkanHandle<VkPhysicalDevice>, VkDeviceCreateInfo*, VkAllocationCallbacks*, VulkanHandle<VkDevice>*, VkResult>)LoadFunc(dev, "vkCreateDevice"); _vkEnumerateDeviceLayerProperties = (delegate* unmanaged<VulkanHandle<VkPhysicalDevice>, uint*, VkLayerProperties*, VkResult>)LoadFunc(dev, "vkEnumerateDeviceLayerProperties"); _vkEnumerateDeviceExtensionProperties = (delegate* unmanaged<VulkanHandle<VkPhysicalDevice>, byte*, uint*, VkExtensionProperties*, VkResult>)LoadFunc(dev, "vkEnumerateDeviceExtensionProperties"); _vkGetPhysicalDeviceSparseImageFormatProperties = (delegate* unmanaged<VulkanHandle<VkPhysicalDevice>, VkFormat, VkImageType, VkSampleCountFlags, VkImageUsageFlags, VkImageTiling, uint*, VkSparseImageFormatProperties*, void>)LoadFunc(dev, "vkGetPhysicalDeviceSparseImageFormatProperties"); if (TryLoadFunc(dev, "vkCreateAndroidSurfaceKHR", out addr)) { _vkCreateAndroidSurfaceKHR = (delegate* unmanaged<VulkanHandle<VkInstance>, VkAndroidSurfaceCreateInfoKHR*, VkAllocationCallbacks*, VulkanHandle<VkSurfaceKHR>*, VkResult>)addr; } if (TryLoadFunc(dev, "vkGetPhysicalDeviceDisplayPropertiesKHR", out addr)) { _vkGetPhysicalDeviceDisplayPropertiesKHR = (delegate* unmanaged<VulkanHandle<VkPhysicalDevice>, uint*, VkDisplayPropertiesKHR*, VkResult>)addr; } if (TryLoadFunc(dev, "vkGetPhysicalDeviceDisplayPlanePropertiesKHR", out addr)) { _vkGetPhysicalDeviceDisplayPlanePropertiesKHR = (delegate* unmanaged<VulkanHandle<VkPhysicalDevice>, uint*, VkDisplayPlanePropertiesKHR*, VkResult>)addr; } if (TryLoadFunc(dev, "vkGetDisplayPlaneSupportedDisplaysKHR", out addr)) { _vkGetDisplayPlaneSupportedDisplaysKHR = (delegate* unmanaged<VulkanHandle<VkPhysicalDevice>, uint, uint*, VulkanHandle<VkDisplayKHR>*, VkResult>)addr; } if (TryLoadFunc(dev, "vkGetDisplayModePropertiesKHR", out addr)) { _vkGetDisplayModePropertiesKHR = (delegate* unmanaged<VulkanHandle<VkPhysicalDevice>, VulkanHandle<VkDisplayKHR>, uint*, VkDisplayModePropertiesKHR*, VkResult>)addr; } if (TryLoadFunc(dev, "vkCreateDisplayModeKHR", out addr)) { _vkCreateDisplayModeKHR = (delegate* unmanaged<VulkanHandle<VkPhysicalDevice>, VulkanHandle<VkDisplayKHR>, VkDisplayModeCreateInfoKHR*, VkAllocationCallbacks*, VulkanHandle<VkDisplayModeKHR>*, VkResult>)addr; } if (TryLoadFunc(dev, "vkGetDisplayPlaneCapabilitiesKHR", out addr)) { _vkGetDisplayPlaneCapabilitiesKHR = (delegate* unmanaged<VulkanHandle<VkPhysicalDevice>, VulkanHandle<VkDisplayModeKHR>, uint, VkDisplayPlaneCapabilitiesKHR*, VkResult>)addr; } if (TryLoadFunc(dev, "vkCreateDisplayPlaneSurfaceKHR", out addr)) { _vkCreateDisplayPlaneSurfaceKHR = (delegate* unmanaged<VulkanHandle<VkInstance>, VkDisplaySurfaceCreateInfoKHR*, VkAllocationCallbacks*, VulkanHandle<VkSurfaceKHR>*, VkResult>)addr; } if (TryLoadFunc(dev, "vkDestroySurfaceKHR", out addr)) { _vkDestroySurfaceKHR = (delegate* unmanaged<VulkanHandle<VkInstance>, VulkanHandle<VkSurfaceKHR>, VkAllocationCallbacks*, void>)addr; } if (TryLoadFunc(dev, "vkGetPhysicalDeviceSurfaceSupportKHR", out addr)) { _vkGetPhysicalDeviceSurfaceSupportKHR = (delegate* unmanaged<VulkanHandle<VkPhysicalDevice>, uint, VulkanHandle<VkSurfaceKHR>, VkBool32*, VkResult>)addr; } if (TryLoadFunc(dev, "vkGetPhysicalDeviceSurfaceCapabilitiesKHR", out addr)) { _vkGetPhysicalDeviceSurfaceCapabilitiesKHR = (delegate* unmanaged<VulkanHandle<VkPhysicalDevice>, VulkanHandle<VkSurfaceKHR>, VkSurfaceCapabilitiesKHR*, VkResult>)addr; } if (TryLoadFunc(dev, "vkGetPhysicalDeviceSurfaceFormatsKHR", out addr)) { _vkGetPhysicalDeviceSurfaceFormatsKHR = (delegate* unmanaged<VulkanHandle<VkPhysicalDevice>, VulkanHandle<VkSurfaceKHR>, uint*, VkSurfaceFormatKHR*, VkResult>)addr; } if (TryLoadFunc(dev, "vkGetPhysicalDeviceSurfacePresentModesKHR", out addr)) { _vkGetPhysicalDeviceSurfacePresentModesKHR = (delegate* unmanaged<VulkanHandle<VkPhysicalDevice>, VulkanHandle<VkSurfaceKHR>, uint*, VkPresentModeKHR*, VkResult>)addr; } if (TryLoadFunc(dev, "vkCreateViSurfaceNN", out addr)) { _vkCreateViSurfaceNN = (delegate* unmanaged<VulkanHandle<VkInstance>, VkViSurfaceCreateInfoNN*, VkAllocationCallbacks*, VulkanHandle<VkSurfaceKHR>*, VkResult>)addr; } if (TryLoadFunc(dev, "vkCreateWaylandSurfaceKHR", out addr)) { _vkCreateWaylandSurfaceKHR = (delegate* unmanaged<VulkanHandle<VkInstance>, VkWaylandSurfaceCreateInfoKHR*, VkAllocationCallbacks*, VulkanHandle<VkSurfaceKHR>*, VkResult>)addr; } if (TryLoadFunc(dev, "vkGetPhysicalDeviceWaylandPresentationSupportKHR", out addr)) { _vkGetPhysicalDeviceWaylandPresentationSupportKHR = (delegate* unmanaged<VulkanHandle<VkPhysicalDevice>, uint, void*, VkBool32>)addr; } if (TryLoadFunc(dev, "vkCreateWin32SurfaceKHR", out addr)) { _vkCreateWin32SurfaceKHR = (delegate* unmanaged<VulkanHandle<VkInstance>, VkWin32SurfaceCreateInfoKHR*, VkAllocationCallbacks*, VulkanHandle<VkSurfaceKHR>*, VkResult>)addr; } if (TryLoadFunc(dev, "vkGetPhysicalDeviceWin32PresentationSupportKHR", out addr)) { _vkGetPhysicalDeviceWin32PresentationSupportKHR = (delegate* unmanaged<VulkanHandle<VkPhysicalDevice>, uint, VkBool32>)addr; } if (TryLoadFunc(dev, "vkCreateXlibSurfaceKHR", out addr)) { _vkCreateXlibSurfaceKHR = (delegate* unmanaged<VulkanHandle<VkInstance>, VkXlibSurfaceCreateInfoKHR*, VkAllocationCallbacks*, VulkanHandle<VkSurfaceKHR>*, VkResult>)addr; } if (TryLoadFunc(dev, "vkGetPhysicalDeviceXlibPresentationSupportKHR", out addr)) { _vkGetPhysicalDeviceXlibPresentationSupportKHR = (delegate* unmanaged<VulkanHandle<VkPhysicalDevice>, uint, void*, ulong, VkBool32>)addr; } if (TryLoadFunc(dev, "vkCreateXcbSurfaceKHR", out addr)) { _vkCreateXcbSurfaceKHR = (delegate* unmanaged<VulkanHandle<VkInstance>, VkXcbSurfaceCreateInfoKHR*, VkAllocationCallbacks*, VulkanHandle<VkSurfaceKHR>*, VkResult>)addr; } if (TryLoadFunc(dev, "vkGetPhysicalDeviceXcbPresentationSupportKHR", out addr)) { _vkGetPhysicalDeviceXcbPresentationSupportKHR = (delegate* unmanaged<VulkanHandle<VkPhysicalDevice>, uint, void*, uint, VkBool32>)addr; } if (TryLoadFunc(dev, "vkCreateDirectFBSurfaceEXT", out addr)) { _vkCreateDirectFBSurfaceEXT = (delegate* unmanaged<VulkanHandle<VkInstance>, VkDirectFBSurfaceCreateInfoEXT*, VkAllocationCallbacks*, VulkanHandle<VkSurfaceKHR>*, VkResult>)addr; } if (TryLoadFunc(dev, "vkGetPhysicalDeviceDirectFBPresentationSupportEXT", out addr)) { _vkGetPhysicalDeviceDirectFBPresentationSupportEXT = (delegate* unmanaged<VulkanHandle<VkPhysicalDevice>, uint, void*, VkBool32>)addr; } if (TryLoadFunc(dev, "vkCreateImagePipeSurfaceFUCHSIA", out addr)) { _vkCreateImagePipeSurfaceFUCHSIA = (delegate* unmanaged<VulkanHandle<VkInstance>, VkImagePipeSurfaceCreateInfoFUCHSIA*, VkAllocationCallbacks*, VulkanHandle<VkSurfaceKHR>*, VkResult>)addr; } if (TryLoadFunc(dev, "vkCreateStreamDescriptorSurfaceGGP", out addr)) { _vkCreateStreamDescriptorSurfaceGGP = (delegate* unmanaged<VulkanHandle<VkInstance>, VkStreamDescriptorSurfaceCreateInfoGGP*, VkAllocationCallbacks*, VulkanHandle<VkSurfaceKHR>*, VkResult>)addr; } if (TryLoadFunc(dev, "vkCreateDebugReportCallbackEXT", out addr)) { _vkCreateDebugReportCallbackEXT = (delegate* unmanaged<VulkanHandle<VkInstance>, VkDebugReportCallbackCreateInfoEXT*, VkAllocationCallbacks*, VulkanHandle<VkDebugReportCallbackEXT>*, VkResult>)addr; } if (TryLoadFunc(dev, "vkDestroyDebugReportCallbackEXT", out addr)) { _vkDestroyDebugReportCallbackEXT = (delegate* unmanaged<VulkanHandle<VkInstance>, VulkanHandle<VkDebugReportCallbackEXT>, VkAllocationCallbacks*, void>)addr; } if (TryLoadFunc(dev, "vkDebugReportMessageEXT", out addr)) { _vkDebugReportMessageEXT = (delegate* unmanaged<VulkanHandle<VkInstance>, VkDebugReportFlagsEXT, VkDebugReportObjectTypeEXT, ulong, ulong, int, byte*, byte*, void>)addr; } if (TryLoadFunc(dev, "vkGetPhysicalDeviceExternalImageFormatPropertiesNV", out addr)) { _vkGetPhysicalDeviceExternalImageFormatPropertiesNV = (delegate* unmanaged<VulkanHandle<VkPhysicalDevice>, VkFormat, VkImageType, VkImageTiling, VkImageUsageFlags, VkImageCreateFlags, VkExternalMemoryHandleTypeFlagsNV, VkExternalImageFormatPropertiesNV*, VkResult>)addr; } if (version >= VkVersion.VK_VERSION_1_1) { _vkGetPhysicalDeviceFeatures2 = (delegate* unmanaged<VulkanHandle<VkPhysicalDevice>, VkPhysicalDeviceFeatures2*, void>)LoadFunc(dev, "vkGetPhysicalDeviceFeatures2"); } _vkGetPhysicalDeviceFeatures2KHR = _vkGetPhysicalDeviceFeatures2; if ((_vkGetPhysicalDeviceFeatures2KHR == null) && TryLoadFunc(dev, "vkGetPhysicalDeviceFeatures2KHR", out addr)) { _vkGetPhysicalDeviceFeatures2KHR = (delegate* unmanaged<VulkanHandle<VkPhysicalDevice>, VkPhysicalDeviceFeatures2*, void>)addr; } if (version >= VkVersion.VK_VERSION_1_1) { _vkGetPhysicalDeviceProperties2 = (delegate* unmanaged<VulkanHandle<VkPhysicalDevice>, VkPhysicalDeviceProperties2*, void>)LoadFunc(dev, "vkGetPhysicalDeviceProperties2"); } _vkGetPhysicalDeviceProperties2KHR = _vkGetPhysicalDeviceProperties2; if ((_vkGetPhysicalDeviceProperties2KHR == null) && TryLoadFunc(dev, "vkGetPhysicalDeviceProperties2KHR", out addr)) { _vkGetPhysicalDeviceProperties2KHR = (delegate* unmanaged<VulkanHandle<VkPhysicalDevice>, VkPhysicalDeviceProperties2*, void>)addr; } if (version >= VkVersion.VK_VERSION_1_1) { _vkGetPhysicalDeviceFormatProperties2 = (delegate* unmanaged<VulkanHandle<VkPhysicalDevice>, VkFormat, VkFormatProperties2*, void>)LoadFunc(dev, "vkGetPhysicalDeviceFormatProperties2"); } _vkGetPhysicalDeviceFormatProperties2KHR = _vkGetPhysicalDeviceFormatProperties2; if ((_vkGetPhysicalDeviceFormatProperties2KHR == null) && TryLoadFunc(dev, "vkGetPhysicalDeviceFormatProperties2KHR", out addr)) { _vkGetPhysicalDeviceFormatProperties2KHR = (delegate* unmanaged<VulkanHandle<VkPhysicalDevice>, VkFormat, VkFormatProperties2*, void>)addr; } if (version >= VkVersion.VK_VERSION_1_1) { _vkGetPhysicalDeviceImageFormatProperties2 = (delegate* unmanaged<VulkanHandle<VkPhysicalDevice>, VkPhysicalDeviceImageFormatInfo2*, VkImageFormatProperties2*, VkResult>)LoadFunc(dev, "vkGetPhysicalDeviceImageFormatProperties2"); } _vkGetPhysicalDeviceImageFormatProperties2KHR = _vkGetPhysicalDeviceImageFormatProperties2; if ((_vkGetPhysicalDeviceImageFormatProperties2KHR == null) && TryLoadFunc(dev, "vkGetPhysicalDeviceImageFormatProperties2KHR", out addr)) { _vkGetPhysicalDeviceImageFormatProperties2KHR = (delegate* unmanaged<VulkanHandle<VkPhysicalDevice>, VkPhysicalDeviceImageFormatInfo2*, VkImageFormatProperties2*, VkResult>)addr; } if (version >= VkVersion.VK_VERSION_1_1) { _vkGetPhysicalDeviceQueueFamilyProperties2 = (delegate* unmanaged<VulkanHandle<VkPhysicalDevice>, uint*, VkQueueFamilyProperties2*, void>)LoadFunc(dev, "vkGetPhysicalDeviceQueueFamilyProperties2"); } _vkGetPhysicalDeviceQueueFamilyProperties2KHR = _vkGetPhysicalDeviceQueueFamilyProperties2; if ((_vkGetPhysicalDeviceQueueFamilyProperties2KHR == null) && TryLoadFunc(dev, "vkGetPhysicalDeviceQueueFamilyProperties2KHR", out addr)) { _vkGetPhysicalDeviceQueueFamilyProperties2KHR = (delegate* unmanaged<VulkanHandle<VkPhysicalDevice>, uint*, VkQueueFamilyProperties2*, void>)addr; } if (version >= VkVersion.VK_VERSION_1_1) { _vkGetPhysicalDeviceMemoryProperties2 = (delegate* unmanaged<VulkanHandle<VkPhysicalDevice>, VkPhysicalDeviceMemoryProperties2*, void>)LoadFunc(dev, "vkGetPhysicalDeviceMemoryProperties2"); } _vkGetPhysicalDeviceMemoryProperties2KHR = _vkGetPhysicalDeviceMemoryProperties2; if ((_vkGetPhysicalDeviceMemoryProperties2KHR == null) && TryLoadFunc(dev, "vkGetPhysicalDeviceMemoryProperties2KHR", out addr)) { _vkGetPhysicalDeviceMemoryProperties2KHR = (delegate* unmanaged<VulkanHandle<VkPhysicalDevice>, VkPhysicalDeviceMemoryProperties2*, void>)addr; } if (version >= VkVersion.VK_VERSION_1_1) { _vkGetPhysicalDeviceSparseImageFormatProperties2 = (delegate* unmanaged<VulkanHandle<VkPhysicalDevice>, VkPhysicalDeviceSparseImageFormatInfo2*, uint*, VkSparseImageFormatProperties2*, void>)LoadFunc(dev, "vkGetPhysicalDeviceSparseImageFormatProperties2"); } _vkGetPhysicalDeviceSparseImageFormatProperties2KHR = _vkGetPhysicalDeviceSparseImageFormatProperties2; if ((_vkGetPhysicalDeviceSparseImageFormatProperties2KHR == null) && TryLoadFunc(dev, "vkGetPhysicalDeviceSparseImageFormatProperties2KHR", out addr)) { _vkGetPhysicalDeviceSparseImageFormatProperties2KHR = (delegate* unmanaged<VulkanHandle<VkPhysicalDevice>, VkPhysicalDeviceSparseImageFormatInfo2*, uint*, VkSparseImageFormatProperties2*, void>)addr; } if (version >= VkVersion.VK_VERSION_1_1) { _vkGetPhysicalDeviceExternalBufferProperties = (delegate* unmanaged<VulkanHandle<VkPhysicalDevice>, VkPhysicalDeviceExternalBufferInfo*, VkExternalBufferProperties*, void>)LoadFunc(dev, "vkGetPhysicalDeviceExternalBufferProperties"); } _vkGetPhysicalDeviceExternalBufferPropertiesKHR = _vkGetPhysicalDeviceExternalBufferProperties; if ((_vkGetPhysicalDeviceExternalBufferPropertiesKHR == null) && TryLoadFunc(dev, "vkGetPhysicalDeviceExternalBufferPropertiesKHR", out addr)) { _vkGetPhysicalDeviceExternalBufferPropertiesKHR = (delegate* unmanaged<VulkanHandle<VkPhysicalDevice>, VkPhysicalDeviceExternalBufferInfo*, VkExternalBufferProperties*, void>)addr; } if (version >= VkVersion.VK_VERSION_1_1) { _vkGetPhysicalDeviceExternalSemaphoreProperties = (delegate* unmanaged<VulkanHandle<VkPhysicalDevice>, VkPhysicalDeviceExternalSemaphoreInfo*, VkExternalSemaphoreProperties*, void>)LoadFunc(dev, "vkGetPhysicalDeviceExternalSemaphoreProperties"); } _vkGetPhysicalDeviceExternalSemaphorePropertiesKHR = _vkGetPhysicalDeviceExternalSemaphoreProperties; if ((_vkGetPhysicalDeviceExternalSemaphorePropertiesKHR == null) && TryLoadFunc(dev, "vkGetPhysicalDeviceExternalSemaphorePropertiesKHR", out addr)) { _vkGetPhysicalDeviceExternalSemaphorePropertiesKHR = (delegate* unmanaged<VulkanHandle<VkPhysicalDevice>, VkPhysicalDeviceExternalSemaphoreInfo*, VkExternalSemaphoreProperties*, void>)addr; } if (version >= VkVersion.VK_VERSION_1_1) { _vkGetPhysicalDeviceExternalFenceProperties = (delegate* unmanaged<VulkanHandle<VkPhysicalDevice>, VkPhysicalDeviceExternalFenceInfo*, VkExternalFenceProperties*, void>)LoadFunc(dev, "vkGetPhysicalDeviceExternalFenceProperties"); } _vkGetPhysicalDeviceExternalFencePropertiesKHR = _vkGetPhysicalDeviceExternalFenceProperties; if ((_vkGetPhysicalDeviceExternalFencePropertiesKHR == null) && TryLoadFunc(dev, "vkGetPhysicalDeviceExternalFencePropertiesKHR", out addr)) { _vkGetPhysicalDeviceExternalFencePropertiesKHR = (delegate* unmanaged<VulkanHandle<VkPhysicalDevice>, VkPhysicalDeviceExternalFenceInfo*, VkExternalFenceProperties*, void>)addr; } if (TryLoadFunc(dev, "vkReleaseDisplayEXT", out addr)) { _vkReleaseDisplayEXT = (delegate* unmanaged<VulkanHandle<VkPhysicalDevice>, VulkanHandle<VkDisplayKHR>, VkResult>)addr; } if (TryLoadFunc(dev, "vkAcquireXlibDisplayEXT", out addr)) { _vkAcquireXlibDisplayEXT = (delegate* unmanaged<VulkanHandle<VkPhysicalDevice>, void*, VulkanHandle<VkDisplayKHR>, VkResult>)addr; } if (TryLoadFunc(dev, "vkGetRandROutputDisplayEXT", out addr)) { _vkGetRandROutputDisplayEXT = (delegate* unmanaged<VulkanHandle<VkPhysicalDevice>, void*, ulong, VulkanHandle<VkDisplayKHR>*, VkResult>)addr; } if (TryLoadFunc(dev, "vkAcquireWinrtDisplayNV", out addr)) { _vkAcquireWinrtDisplayNV = (delegate* unmanaged<VulkanHandle<VkPhysicalDevice>, VulkanHandle<VkDisplayKHR>, VkResult>)addr; } if (TryLoadFunc(dev, "vkGetWinrtDisplayNV", out addr)) { _vkGetWinrtDisplayNV = (delegate* unmanaged<VulkanHandle<VkPhysicalDevice>, uint, VulkanHandle<VkDisplayKHR>*, VkResult>)addr; } if (TryLoadFunc(dev, "vkGetPhysicalDeviceSurfaceCapabilities2EXT", out addr)) { _vkGetPhysicalDeviceSurfaceCapabilities2EXT = (delegate* unmanaged<VulkanHandle<VkPhysicalDevice>, VulkanHandle<VkSurfaceKHR>, VkSurfaceCapabilities2EXT*, VkResult>)addr; } if (version >= VkVersion.VK_VERSION_1_1) { _vkEnumeratePhysicalDeviceGroups = (delegate* unmanaged<VulkanHandle<VkInstance>, uint*, VkPhysicalDeviceGroupProperties*, VkResult>)LoadFunc(dev, "vkEnumeratePhysicalDeviceGroups"); } _vkEnumeratePhysicalDeviceGroupsKHR = _vkEnumeratePhysicalDeviceGroups; if ((_vkEnumeratePhysicalDeviceGroupsKHR == null) && TryLoadFunc(dev, "vkEnumeratePhysicalDeviceGroupsKHR", out addr)) { _vkEnumeratePhysicalDeviceGroupsKHR = (delegate* unmanaged<VulkanHandle<VkInstance>, uint*, VkPhysicalDeviceGroupProperties*, VkResult>)addr; } if (TryLoadFunc(dev, "vkGetPhysicalDevicePresentRectanglesKHR", out addr)) { _vkGetPhysicalDevicePresentRectanglesKHR = (delegate* unmanaged<VulkanHandle<VkPhysicalDevice>, VulkanHandle<VkSurfaceKHR>, uint*, VkRect2D*, VkResult>)addr; } if (TryLoadFunc(dev, "vkCreateIOSSurfaceMVK", out addr)) { _vkCreateIOSSurfaceMVK = (delegate* unmanaged<VulkanHandle<VkInstance>, VkIOSSurfaceCreateInfoMVK*, VkAllocationCallbacks*, VulkanHandle<VkSurfaceKHR>*, VkResult>)addr; } if (TryLoadFunc(dev, "vkCreateMacOSSurfaceMVK", out addr)) { _vkCreateMacOSSurfaceMVK = (delegate* unmanaged<VulkanHandle<VkInstance>, VkMacOSSurfaceCreateInfoMVK*, VkAllocationCallbacks*, VulkanHandle<VkSurfaceKHR>*, VkResult>)addr; } if (TryLoadFunc(dev, "vkCreateMetalSurfaceEXT", out addr)) { _vkCreateMetalSurfaceEXT = (delegate* unmanaged<VulkanHandle<VkInstance>, VkMetalSurfaceCreateInfoEXT*, VkAllocationCallbacks*, VulkanHandle<VkSurfaceKHR>*, VkResult>)addr; } if (TryLoadFunc(dev, "vkGetPhysicalDeviceMultisamplePropertiesEXT", out addr)) { _vkGetPhysicalDeviceMultisamplePropertiesEXT = (delegate* unmanaged<VulkanHandle<VkPhysicalDevice>, VkSampleCountFlags, VkMultisamplePropertiesEXT*, void>)addr; } if (TryLoadFunc(dev, "vkGetPhysicalDeviceSurfaceCapabilities2KHR", out addr)) { _vkGetPhysicalDeviceSurfaceCapabilities2KHR = (delegate* unmanaged<VulkanHandle<VkPhysicalDevice>, VkPhysicalDeviceSurfaceInfo2KHR*, VkSurfaceCapabilities2KHR*, VkResult>)addr; } if (TryLoadFunc(dev, "vkGetPhysicalDeviceSurfaceFormats2KHR", out addr)) { _vkGetPhysicalDeviceSurfaceFormats2KHR = (delegate* unmanaged<VulkanHandle<VkPhysicalDevice>, VkPhysicalDeviceSurfaceInfo2KHR*, uint*, VkSurfaceFormat2KHR*, VkResult>)addr; } if (TryLoadFunc(dev, "vkGetPhysicalDeviceDisplayProperties2KHR", out addr)) { _vkGetPhysicalDeviceDisplayProperties2KHR = (delegate* unmanaged<VulkanHandle<VkPhysicalDevice>, uint*, VkDisplayProperties2KHR*, VkResult>)addr; } if (TryLoadFunc(dev, "vkGetPhysicalDeviceDisplayPlaneProperties2KHR", out addr)) { _vkGetPhysicalDeviceDisplayPlaneProperties2KHR = (delegate* unmanaged<VulkanHandle<VkPhysicalDevice>, uint*, VkDisplayPlaneProperties2KHR*, VkResult>)addr; } if (TryLoadFunc(dev, "vkGetDisplayModeProperties2KHR", out addr)) { _vkGetDisplayModeProperties2KHR = (delegate* unmanaged<VulkanHandle<VkPhysicalDevice>, VulkanHandle<VkDisplayKHR>, uint*, VkDisplayModeProperties2KHR*, VkResult>)addr; } if (TryLoadFunc(dev, "vkGetDisplayPlaneCapabilities2KHR", out addr)) { _vkGetDisplayPlaneCapabilities2KHR = (delegate* unmanaged<VulkanHandle<VkPhysicalDevice>, VkDisplayPlaneInfo2KHR*, VkDisplayPlaneCapabilities2KHR*, VkResult>)addr; } if (TryLoadFunc(dev, "vkGetPhysicalDeviceCalibrateableTimeDomainsEXT", out addr)) { _vkGetPhysicalDeviceCalibrateableTimeDomainsEXT = (delegate* unmanaged<VulkanHandle<VkPhysicalDevice>, uint*, VkTimeDomainEXT*, VkResult>)addr; } if (TryLoadFunc(dev, "vkCreateDebugUtilsMessengerEXT", out addr)) { _vkCreateDebugUtilsMessengerEXT = (delegate* unmanaged<VulkanHandle<VkInstance>, VkDebugUtilsMessengerCreateInfoEXT*, VkAllocationCallbacks*, VulkanHandle<VkDebugUtilsMessengerEXT>*, VkResult>)addr; } if (TryLoadFunc(dev, "vkDestroyDebugUtilsMessengerEXT", out addr)) { _vkDestroyDebugUtilsMessengerEXT = (delegate* unmanaged<VulkanHandle<VkInstance>, VulkanHandle<VkDebugUtilsMessengerEXT>, VkAllocationCallbacks*, void>)addr; } if (TryLoadFunc(dev, "vkSubmitDebugUtilsMessageEXT", out addr)) { _vkSubmitDebugUtilsMessageEXT = (delegate* unmanaged<VulkanHandle<VkInstance>, VkDebugUtilsMessageSeverityFlagsEXT, VkDebugUtilsMessageTypeFlagsEXT, VkDebugUtilsMessengerCallbackDataEXT*, void>)addr; } if (TryLoadFunc(dev, "vkGetPhysicalDeviceCooperativeMatrixPropertiesNV", out addr)) { _vkGetPhysicalDeviceCooperativeMatrixPropertiesNV = (delegate* unmanaged<VulkanHandle<VkPhysicalDevice>, uint*, VkCooperativeMatrixPropertiesNV*, VkResult>)addr; } if (TryLoadFunc(dev, "vkGetPhysicalDeviceSurfacePresentModes2EXT", out addr)) { _vkGetPhysicalDeviceSurfacePresentModes2EXT = (delegate* unmanaged<VulkanHandle<VkPhysicalDevice>, VkPhysicalDeviceSurfaceInfo2KHR*, uint*, VkPresentModeKHR*, VkResult>)addr; } if (TryLoadFunc(dev, "vkEnumeratePhysicalDeviceQueueFamilyPerformanceQueryCountersKHR", out addr)) { _vkEnumeratePhysicalDeviceQueueFamilyPerformanceQueryCountersKHR = (delegate* unmanaged<VulkanHandle<VkPhysicalDevice>, uint, uint*, VkPerformanceCounterKHR*, VkPerformanceCounterDescriptionKHR*, VkResult>)addr; } if (TryLoadFunc(dev, "vkGetPhysicalDeviceQueueFamilyPerformanceQueryPassesKHR", out addr)) { _vkGetPhysicalDeviceQueueFamilyPerformanceQueryPassesKHR = (delegate* unmanaged<VulkanHandle<VkPhysicalDevice>, VkQueryPoolPerformanceCreateInfoKHR*, uint*, void>)addr; } if (TryLoadFunc(dev, "vkCreateHeadlessSurfaceEXT", out addr)) { _vkCreateHeadlessSurfaceEXT = (delegate* unmanaged<VulkanHandle<VkInstance>, VkHeadlessSurfaceCreateInfoEXT*, VkAllocationCallbacks*, VulkanHandle<VkSurfaceKHR>*, VkResult>)addr; } if (TryLoadFunc(dev, "vkGetPhysicalDeviceSupportedFramebufferMixedSamplesCombinationsNV", out addr)) { _vkGetPhysicalDeviceSupportedFramebufferMixedSamplesCombinationsNV = (delegate* unmanaged<VulkanHandle<VkPhysicalDevice>, uint*, VkFramebufferMixedSamplesCombinationNV*, VkResult>)addr; } if (TryLoadFunc(dev, "vkGetPhysicalDeviceToolPropertiesEXT", out addr)) { _vkGetPhysicalDeviceToolPropertiesEXT = (delegate* unmanaged<VulkanHandle<VkPhysicalDevice>, uint*, VkPhysicalDeviceToolPropertiesEXT*, VkResult>)addr; } if (TryLoadFunc(dev, "vkGetPhysicalDeviceFragmentShadingRatesKHR", out addr)) { _vkGetPhysicalDeviceFragmentShadingRatesKHR = (delegate* unmanaged<VulkanHandle<VkPhysicalDevice>, uint*, VkPhysicalDeviceFragmentShadingRateKHR*, VkResult>)addr; } } static StaticFunctionTable() { _vkCreateInstance = (delegate* unmanaged<VkInstanceCreateInfo*, VkAllocationCallbacks*, VulkanHandle<VkInstance>*, VkResult>)VulkanLibrary.GetExport("vkCreateInstance").ToPointer(); _vkGetDeviceProcAddr = (delegate* unmanaged<VulkanHandle<VkDevice>, byte*, delegate* unmanaged<void>>)VulkanLibrary.GetExport("vkGetDeviceProcAddr").ToPointer(); _vkGetInstanceProcAddr = (delegate* unmanaged<VulkanHandle<VkInstance>, byte*, delegate* unmanaged<void>>)VulkanLibrary.GetExport("vkGetInstanceProcAddr").ToPointer(); _vkEnumerateInstanceVersion = (delegate* unmanaged<uint*, VkResult>)VulkanLibrary.GetExport("vkEnumerateInstanceVersion").ToPointer(); _vkEnumerateInstanceLayerProperties = (delegate* unmanaged<uint*, VkLayerProperties*, VkResult>)VulkanLibrary.GetExport("vkEnumerateInstanceLayerProperties").ToPointer(); _vkEnumerateInstanceExtensionProperties = (delegate* unmanaged<byte*, uint*, VkExtensionProperties*, VkResult>)VulkanLibrary.GetExport("vkEnumerateInstanceExtensionProperties").ToPointer(); } } } // namespace Vulkan
119.305263
302
0.828072
[ "MIT" ]
LibVega/VVK
VVK/Generated/StaticFunctionTable.cs
124,676
C#
namespace PlanEatSave.Utils { public class LoggingEvents { public const int ACCOUNT_REGISTER = 1000; public const int ACCOUNT_LOGIN = 1001; public const int PANTRY_ADD_ITEM = 2000; public const int PANTRY_EDIT_ITEM = 2001; public const int PANTRY_RETRIEVE_ITEM = 2002; public const int PANTRY_REMOVE_ITEM = 2003; public const int PANTRY_RETRIEVE_USER_PANTRY = 2004; public const int RECIPES_ADD_RECIPE = 3000; public const int RECIPES_EDIT_RECIPE = 3001; public const int RECIPES_RETRIEVE_ALL = 3002; public const int RECIPES_REMOVE_RECIPE = 3003; public const int RECIPES_RETRIEVE_RECIPE = 3004; public const int MEALS_ADD_MEAL_FROM_EXISTING_RECIPE = 4001; public const int MEALS_RETRIEVE_MEALS = 4002; public const int MEALS_REMOVE_MEAL = 4002; } }
42
68
0.699546
[ "MIT" ]
AlinCiocan/FoodPlan-Prototype
Utils/LoggingEvents.cs
882
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class TimeUpgrade : UpgradeBase { private IntSO maxModules; public TimeUpgrade(string upgradeName, int level, int maxlevel, IntSO maxModules) : base(upgradeName, level, maxlevel) { this.maxModules = maxModules; } public override bool Upgrade() { maxModules.Value += 4; return false; } }
21.45
122
0.685315
[ "MIT" ]
Delunado/Keeping-IT-Alive-LudumDare46
Source/Assets/Scripts/Upgrades/TimeUpgrade.cs
431
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Buffers; using System.Diagnostics; using System.IO.Pipelines; using System.Threading.Tasks.Sources; using Microsoft.AspNetCore.Connections; using Microsoft.AspNetCore.Internal; using Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http; using Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http2.FlowControl; using Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Infrastructure; using Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Infrastructure.PipeWriterHelpers; using Microsoft.Extensions.Logging; namespace Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http2; internal class Http2OutputProducer : IHttpOutputProducer, IHttpOutputAborter, IValueTaskSource<FlushResult>, IDisposable { private int StreamId => _stream.StreamId; private readonly Http2FrameWriter _frameWriter; private readonly TimingPipeFlusher _flusher; private readonly KestrelTrace _log; // This should only be accessed via the FrameWriter. The connection-level output flow control is protected by the // FrameWriter's connection-level write lock. private readonly StreamOutputFlowControl _flowControl; private readonly MemoryPool<byte> _memoryPool; private readonly Http2Stream _stream; private readonly object _dataWriterLock = new object(); private readonly Pipe _pipe; private readonly ConcurrentPipeWriter _pipeWriter; private readonly PipeReader _pipeReader; private readonly ManualResetValueTaskSource<object?> _resetAwaitable = new ManualResetValueTaskSource<object?>(); private IMemoryOwner<byte>? _fakeMemoryOwner; private byte[]? _fakeMemory; private bool _startedWritingDataFrames; private bool _streamCompleted; private bool _suffixSent; private bool _streamEnded; private bool _writerComplete; // Internal for testing internal Task _dataWriteProcessingTask; internal bool _disposed; /// <summary>The core logic for the IValueTaskSource implementation.</summary> private ManualResetValueTaskSourceCore<FlushResult> _responseCompleteTaskSource = new ManualResetValueTaskSourceCore<FlushResult> { RunContinuationsAsynchronously = true }; // mutable struct, do not make this readonly // This object is itself usable as a backing source for ValueTask. Since there's only ever one awaiter // for this object's state transitions at a time, we allow the object to be awaited directly. All functionality // associated with the implementation is just delegated to the ManualResetValueTaskSourceCore. private ValueTask<FlushResult> GetWaiterTask() => new ValueTask<FlushResult>(this, _responseCompleteTaskSource.Version); ValueTaskSourceStatus IValueTaskSource<FlushResult>.GetStatus(short token) => _responseCompleteTaskSource.GetStatus(token); void IValueTaskSource<FlushResult>.OnCompleted(Action<object?> continuation, object? state, short token, ValueTaskSourceOnCompletedFlags flags) => _responseCompleteTaskSource.OnCompleted(continuation, state, token, flags); FlushResult IValueTaskSource<FlushResult>.GetResult(short token) => _responseCompleteTaskSource.GetResult(token); public Http2OutputProducer(Http2Stream stream, Http2StreamContext context, StreamOutputFlowControl flowControl) { _stream = stream; _frameWriter = context.FrameWriter; _flowControl = flowControl; _memoryPool = context.MemoryPool; _log = context.ServiceContext.Log; _pipe = CreateDataPipe(_memoryPool); _pipeWriter = new ConcurrentPipeWriter(_pipe.Writer, _memoryPool, _dataWriterLock); _pipeReader = _pipe.Reader; // No need to pass in timeoutControl here, since no minDataRates are passed to the TimingPipeFlusher. // The minimum output data rate is enforced at the connection level by Http2FrameWriter. _flusher = new TimingPipeFlusher(timeoutControl: null, _log); _flusher.Initialize(_pipeWriter); _dataWriteProcessingTask = ProcessDataWrites(); } public void StreamReset() { // Data background task must still be running. Debug.Assert(!_dataWriteProcessingTask.IsCompleted); // Response should have been completed. Debug.Assert(_responseCompleteTaskSource.GetStatus(_responseCompleteTaskSource.Version) == ValueTaskSourceStatus.Succeeded); _streamEnded = false; _suffixSent = false; _startedWritingDataFrames = false; _streamCompleted = false; _writerComplete = false; _pipe.Reset(); _pipeWriter.Reset(); _responseCompleteTaskSource.Reset(); // Trigger the data process task to resume _resetAwaitable.SetResult(null); } public void Complete() { lock (_dataWriterLock) { if (_writerComplete) { return; } _writerComplete = true; Stop(); // Make sure the writing side is completed. _pipeWriter.Complete(); if (_fakeMemoryOwner != null) { _fakeMemoryOwner.Dispose(); _fakeMemoryOwner = null; } if (_fakeMemory != null) { ArrayPool<byte>.Shared.Return(_fakeMemory); _fakeMemory = null; } } } // This is called when a CancellationToken fires mid-write. In HTTP/1.x, this aborts the entire connection. // For HTTP/2 we abort the stream. void IHttpOutputAborter.Abort(ConnectionAbortedException abortReason) { _stream.ResetAndAbort(abortReason, Http2ErrorCode.INTERNAL_ERROR); } void IHttpOutputAborter.OnInputOrOutputCompleted() { _stream.ResetAndAbort(new ConnectionAbortedException($"{nameof(Http2OutputProducer)}.{nameof(ProcessDataWrites)} has completed."), Http2ErrorCode.INTERNAL_ERROR); } public ValueTask<FlushResult> FlushAsync(CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) { return new ValueTask<FlushResult>(Task.FromCanceled<FlushResult>(cancellationToken)); } lock (_dataWriterLock) { ThrowIfSuffixSentOrCompleted(); if (_streamCompleted) { return default; } if (_startedWritingDataFrames) { // If there's already been response data written to the stream, just wait for that. Any header // should be in front of the data frames in the connection pipe. Trailers could change things. return _flusher.FlushAsync(this, cancellationToken); } else { // Flushing the connection pipe ensures headers already in the pipe are flushed even if no data // frames have been written. return _frameWriter.FlushAsync(this, cancellationToken); } } } public ValueTask<FlushResult> Write100ContinueAsync() { lock (_dataWriterLock) { ThrowIfSuffixSentOrCompleted(); if (_streamCompleted) { return default; } return _frameWriter.Write100ContinueAsync(StreamId); } } public void WriteResponseHeaders(int statusCode, string? reasonPhrase, HttpResponseHeaders responseHeaders, bool autoChunk, bool appCompleted) { lock (_dataWriterLock) { // The HPACK header compressor is stateful, if we compress headers for an aborted stream we must send them. // Optimize for not compressing or sending them. if (_streamCompleted) { return; } // If the responseHeaders will be written as the final HEADERS frame then // set END_STREAM on the HEADERS frame. This avoids the need to write an // empty DATA frame with END_STREAM. // // The headers will be the final frame if: // 1. There is no content // 2. There is no trailing HEADERS frame. Http2HeadersFrameFlags http2HeadersFrame; if (appCompleted && !_startedWritingDataFrames && (_stream.ResponseTrailers == null || _stream.ResponseTrailers.Count == 0)) { _streamEnded = true; _stream.DecrementActiveClientStreamCount(); http2HeadersFrame = Http2HeadersFrameFlags.END_STREAM; } else { http2HeadersFrame = Http2HeadersFrameFlags.NONE; } _frameWriter.WriteResponseHeaders(StreamId, statusCode, http2HeadersFrame, responseHeaders); } } public Task WriteDataAsync(ReadOnlySpan<byte> data, CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) { return Task.FromCanceled(cancellationToken); } lock (_dataWriterLock) { ThrowIfSuffixSentOrCompleted(); // This length check is important because we don't want to set _startedWritingDataFrames unless a data // frame will actually be written causing the headers to be flushed. if (_streamCompleted || data.Length == 0) { return Task.CompletedTask; } _startedWritingDataFrames = true; _pipeWriter.Write(data); return _flusher.FlushAsync(this, cancellationToken).GetAsTask(); } } public ValueTask<FlushResult> WriteStreamSuffixAsync() { lock (_dataWriterLock) { if (_streamCompleted) { return GetWaiterTask(); } _streamCompleted = true; _suffixSent = true; _pipeWriter.Complete(); return GetWaiterTask(); } } public ValueTask<FlushResult> WriteRstStreamAsync(Http2ErrorCode error) { lock (_dataWriterLock) { // Always send the reset even if the response body is _completed. The request body may not have completed yet. Stop(); return _frameWriter.WriteRstStreamAsync(StreamId, error); } } public void Advance(int bytes) { lock (_dataWriterLock) { ThrowIfSuffixSentOrCompleted(); if (_streamCompleted) { return; } _startedWritingDataFrames = true; _pipeWriter.Advance(bytes); } } public Span<byte> GetSpan(int sizeHint = 0) { lock (_dataWriterLock) { ThrowIfSuffixSentOrCompleted(); if (_streamCompleted) { return GetFakeMemory(sizeHint).Span; } return _pipeWriter.GetSpan(sizeHint); } } public Memory<byte> GetMemory(int sizeHint = 0) { lock (_dataWriterLock) { ThrowIfSuffixSentOrCompleted(); if (_streamCompleted) { return GetFakeMemory(sizeHint); } return _pipeWriter.GetMemory(sizeHint); } } public void CancelPendingFlush() { lock (_dataWriterLock) { if (_streamCompleted) { return; } _pipeWriter.CancelPendingFlush(); } } public ValueTask<FlushResult> WriteDataToPipeAsync(ReadOnlySpan<byte> data, CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) { return new ValueTask<FlushResult>(Task.FromCanceled<FlushResult>(cancellationToken)); } lock (_dataWriterLock) { ThrowIfSuffixSentOrCompleted(); // This length check is important because we don't want to set _startedWritingDataFrames unless a data // frame will actually be written causing the headers to be flushed. if (_streamCompleted || data.Length == 0) { return default; } _startedWritingDataFrames = true; _pipeWriter.Write(data); return _flusher.FlushAsync(this, cancellationToken); } } public ValueTask<FlushResult> FirstWriteAsync(int statusCode, string? reasonPhrase, HttpResponseHeaders responseHeaders, bool autoChunk, ReadOnlySpan<byte> data, CancellationToken cancellationToken) { lock (_dataWriterLock) { WriteResponseHeaders(statusCode, reasonPhrase, responseHeaders, autoChunk, appCompleted: false); return WriteDataToPipeAsync(data, cancellationToken); } } ValueTask<FlushResult> IHttpOutputProducer.WriteChunkAsync(ReadOnlySpan<byte> data, CancellationToken cancellationToken) { throw new NotImplementedException(); } public ValueTask<FlushResult> FirstWriteChunkedAsync(int statusCode, string? reasonPhrase, HttpResponseHeaders responseHeaders, bool autoChunk, ReadOnlySpan<byte> data, CancellationToken cancellationToken) { throw new NotImplementedException(); } public void Stop() { lock (_dataWriterLock) { if (_streamCompleted) { return; } _streamCompleted = true; _pipeReader.CancelPendingRead(); _frameWriter.AbortPendingStreamDataWrites(_flowControl); } } public void Reset() { } private async Task ProcessDataWrites() { // ProcessDataWrites runs for the lifetime of the Http2OutputProducer, and is designed to be reused by multiple streams. // When Http2OutputProducer is no longer used (e.g. a stream is aborted and will no longer be used, or the connection is closed) // it should be disposed so ProcessDataWrites exits. Not disposing won't cause a memory leak in release builds, but in debug // builds active tasks are rooted on Task.s_currentActiveTasks. Dispose could be removed in the future when active tasks are // tracked by a weak reference. See https://github.com/dotnet/runtime/issues/26565 do { FlushResult flushResult = default; ReadResult readResult = default; try { do { var firstWrite = true; readResult = await _pipeReader.ReadAsync(); if (readResult.IsCanceled) { // Response body is aborted, break and complete reader. break; } else if (readResult.IsCompleted && _stream.ResponseTrailers?.Count > 0) { // Output is ending and there are trailers to write // Write any remaining content then write trailers _stream.ResponseTrailers.SetReadOnly(); _stream.DecrementActiveClientStreamCount(); if (readResult.Buffer.Length > 0) { // It is faster to write data and trailers together. Locking once reduces lock contention. flushResult = await _frameWriter.WriteDataAndTrailersAsync(StreamId, _flowControl, readResult.Buffer, firstWrite, _stream.ResponseTrailers); } else { flushResult = await _frameWriter.WriteResponseTrailersAsync(StreamId, _stream.ResponseTrailers); } } else if (readResult.IsCompleted && _streamEnded) { if (readResult.Buffer.Length != 0) { ThrowUnexpectedState(); } // Headers have already been written and there is no other content to write flushResult = await _frameWriter.FlushAsync(outputAborter: null, cancellationToken: default); } else { var endStream = readResult.IsCompleted; if (endStream) { _stream.DecrementActiveClientStreamCount(); } flushResult = await _frameWriter.WriteDataAsync(StreamId, _flowControl, readResult.Buffer, endStream, firstWrite, forceFlush: true); } firstWrite = false; _pipeReader.AdvanceTo(readResult.Buffer.End); } while (!readResult.IsCompleted); } catch (Exception ex) { _log.LogCritical(ex, nameof(Http2OutputProducer) + "." + nameof(ProcessDataWrites) + " observed an unexpected exception."); } await _pipeReader.CompleteAsync(); // Signal via WriteStreamSuffixAsync to the stream that output has finished. // Stream state will move to RequestProcessingStatus.ResponseCompleted _responseCompleteTaskSource.SetResult(flushResult); // Wait here for the stream to be reset or disposed. await new ValueTask(_resetAwaitable, _resetAwaitable.Version); _resetAwaitable.Reset(); } while (!_disposed); static void ThrowUnexpectedState() { throw new InvalidOperationException(nameof(Http2OutputProducer) + "." + nameof(ProcessDataWrites) + " observed an unexpected state where the streams output ended with data still remaining in the pipe."); } } internal Memory<byte> GetFakeMemory(int minSize) { // Try to reuse _fakeMemoryOwner if (_fakeMemoryOwner != null) { if (_fakeMemoryOwner.Memory.Length < minSize) { _fakeMemoryOwner.Dispose(); _fakeMemoryOwner = null; } else { return _fakeMemoryOwner.Memory; } } // Try to reuse _fakeMemory if (_fakeMemory != null) { if (_fakeMemory.Length < minSize) { ArrayPool<byte>.Shared.Return(_fakeMemory); _fakeMemory = null; } else { return _fakeMemory; } } // Requesting a bigger buffer could throw. if (minSize <= _memoryPool.MaxBufferSize) { // Use the specified pool as it fits. _fakeMemoryOwner = _memoryPool.Rent(minSize); return _fakeMemoryOwner.Memory; } else { // Use the array pool. Its MaxBufferSize is int.MaxValue. return _fakeMemory = ArrayPool<byte>.Shared.Rent(minSize); } } [StackTraceHidden] private void ThrowIfSuffixSentOrCompleted() { if (_suffixSent) { ThrowSuffixSent(); } if (_writerComplete) { ThrowWriterComplete(); } } [StackTraceHidden] private static void ThrowSuffixSent() { throw new InvalidOperationException("Writing is not allowed after writer was completed."); } [StackTraceHidden] private static void ThrowWriterComplete() { throw new InvalidOperationException("Cannot write to response after the request has completed."); } private static Pipe CreateDataPipe(MemoryPool<byte> pool) => new Pipe(new PipeOptions ( pool: pool, readerScheduler: PipeScheduler.Inline, writerScheduler: PipeScheduler.ThreadPool, pauseWriterThreshold: 1, resumeWriterThreshold: 1, useSynchronizationContext: false, minimumSegmentSize: pool.GetMinimumSegmentSize() )); public void Dispose() { if (_disposed) { return; } _disposed = true; // Set awaitable after disposed is true to ensure ProcessDataWrites exits successfully. _resetAwaitable.SetResult(null); } }
35.09029
226
0.61404
[ "MIT" ]
Aezura/aspnetcore
src/Servers/Kestrel/Core/src/Internal/Http2/Http2OutputProducer.cs
20,598
C#
using System; using System.Collections.Generic; using System.Net.Http; using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Xunit; using Shouldly; namespace MhLabs.AwsSignedHttpClient.Tests { public interface IBingService { Task Get(string query, CancellationToken cancellationToken = default(CancellationToken)); } }
23.888889
97
0.795349
[ "MIT" ]
mhlabs/MhLabs.AwsSignedHttpClient
MhLabs.AwsSignedHttpClient.Tests/LoggingTests/IBingService.cs
430
C#