content
stringlengths
5
1.04M
avg_line_length
float64
1.75
12.9k
max_line_length
int64
2
244k
alphanum_fraction
float64
0
0.98
licenses
list
repository_name
stringlengths
7
92
path
stringlengths
3
249
size
int64
5
1.04M
lang
stringclasses
2 values
using System.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("Compare char arrays")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Compare char arrays")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("f3afeb85-0115-4aeb-b7fd-ac8583aa2f79")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
38.135135
84
0.744862
[ "MIT" ]
bun2fun/CSharp2
1st Arrays/Compare char arrays/Properties/AssemblyInfo.cs
1,414
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. // // // This file was generated, please do not edit it directly. // // Please see MilCodeGen.html for more information. // using MS.Internal; using MS.Internal.KnownBoxes; using MS.Internal.Collections; using MS.Internal.PresentationCore; using MS.Utility; using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Globalization; using System.Reflection; using System.Runtime.InteropServices; using System.ComponentModel.Design.Serialization; using System.Text; using System.Windows; using System.Windows.Media; using System.Windows.Media.Effects; using System.Windows.Media.Media3D; using System.Windows.Media.Animation; using System.Windows.Media.Composition; using System.Windows.Media.Imaging; using System.Windows.Markup; using System.Windows.Media.Converters; using System.Security; using SR=MS.Internal.PresentationCore.SR; using SRID=MS.Internal.PresentationCore.SRID; // These types are aliased to match the unamanaged names used in interop using BOOL = System.UInt32; using WORD = System.UInt16; using Float = System.Single; namespace System.Windows.Media { sealed partial class RotateTransform : Transform { //------------------------------------------------------ // // Public Methods // //------------------------------------------------------ #region Public Methods /// <summary> /// Shadows inherited Clone() with a strongly typed /// version for convenience. /// </summary> public new RotateTransform Clone() { return (RotateTransform)base.Clone(); } /// <summary> /// Shadows inherited CloneCurrentValue() with a strongly typed /// version for convenience. /// </summary> public new RotateTransform CloneCurrentValue() { return (RotateTransform)base.CloneCurrentValue(); } #endregion Public Methods //------------------------------------------------------ // // Public Properties // //------------------------------------------------------ private static void AnglePropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { RotateTransform target = ((RotateTransform) d); target.PropertyChanged(AngleProperty); } private static void CenterXPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { RotateTransform target = ((RotateTransform) d); target.PropertyChanged(CenterXProperty); } private static void CenterYPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { RotateTransform target = ((RotateTransform) d); target.PropertyChanged(CenterYProperty); } #region Public Properties /// <summary> /// Angle - double. Default value is 0.0. /// </summary> public double Angle { get { return (double) GetValue(AngleProperty); } set { SetValueInternal(AngleProperty, value); } } /// <summary> /// CenterX - double. Default value is 0.0. /// </summary> public double CenterX { get { return (double) GetValue(CenterXProperty); } set { SetValueInternal(CenterXProperty, value); } } /// <summary> /// CenterY - double. Default value is 0.0. /// </summary> public double CenterY { get { return (double) GetValue(CenterYProperty); } set { SetValueInternal(CenterYProperty, value); } } #endregion Public Properties //------------------------------------------------------ // // Protected Methods // //------------------------------------------------------ #region Protected Methods /// <summary> /// Implementation of <see cref="System.Windows.Freezable.CreateInstanceCore">Freezable.CreateInstanceCore</see>. /// </summary> /// <returns>The new Freezable.</returns> protected override Freezable CreateInstanceCore() { return new RotateTransform(); } #endregion ProtectedMethods //------------------------------------------------------ // // Internal Methods // //------------------------------------------------------ #region Internal Methods internal override void UpdateResource(DUCE.Channel channel, bool skipOnChannelCheck) { // If we're told we can skip the channel check, then we must be on channel Debug.Assert(!skipOnChannelCheck || _duceResource.IsOnChannel(channel)); if (skipOnChannelCheck || _duceResource.IsOnChannel(channel)) { base.UpdateResource(channel, skipOnChannelCheck); // Obtain handles for animated properties DUCE.ResourceHandle hAngleAnimations = GetAnimationResourceHandle(AngleProperty, channel); DUCE.ResourceHandle hCenterXAnimations = GetAnimationResourceHandle(CenterXProperty, channel); DUCE.ResourceHandle hCenterYAnimations = GetAnimationResourceHandle(CenterYProperty, channel); // Pack & send command packet DUCE.MILCMD_ROTATETRANSFORM data; unsafe { data.Type = MILCMD.MilCmdRotateTransform; data.Handle = _duceResource.GetHandle(channel); if (hAngleAnimations.IsNull) { data.Angle = Angle; } data.hAngleAnimations = hAngleAnimations; if (hCenterXAnimations.IsNull) { data.CenterX = CenterX; } data.hCenterXAnimations = hCenterXAnimations; if (hCenterYAnimations.IsNull) { data.CenterY = CenterY; } data.hCenterYAnimations = hCenterYAnimations; // Send packed command structure channel.SendCommand( (byte*)&data, sizeof(DUCE.MILCMD_ROTATETRANSFORM)); } } } internal override DUCE.ResourceHandle AddRefOnChannelCore(DUCE.Channel channel) { if (_duceResource.CreateOrAddRefOnChannel(this, channel, System.Windows.Media.Composition.DUCE.ResourceType.TYPE_ROTATETRANSFORM)) { AddRefOnChannelAnimations(channel); UpdateResource(channel, true /* skip "on channel" check - we already know that we're on channel */ ); } return _duceResource.GetHandle(channel); } internal override void ReleaseOnChannelCore(DUCE.Channel channel) { Debug.Assert(_duceResource.IsOnChannel(channel)); if (_duceResource.ReleaseOnChannel(channel)) { ReleaseOnChannelAnimations(channel); } } internal override DUCE.ResourceHandle GetHandleCore(DUCE.Channel channel) { // Note that we are in a lock here already. return _duceResource.GetHandle(channel); } internal override int GetChannelCountCore() { // must already be in composition lock here return _duceResource.GetChannelCount(); } internal override DUCE.Channel GetChannelCore(int index) { // Note that we are in a lock here already. return _duceResource.GetChannel(index); } #endregion Internal Methods //------------------------------------------------------ // // Internal Properties // //------------------------------------------------------ #region Internal Properties #endregion Internal Properties //------------------------------------------------------ // // Dependency Properties // //------------------------------------------------------ #region Dependency Properties /// <summary> /// The DependencyProperty for the RotateTransform.Angle property. /// </summary> public static readonly DependencyProperty AngleProperty; /// <summary> /// The DependencyProperty for the RotateTransform.CenterX property. /// </summary> public static readonly DependencyProperty CenterXProperty; /// <summary> /// The DependencyProperty for the RotateTransform.CenterY property. /// </summary> public static readonly DependencyProperty CenterYProperty; #endregion Dependency Properties //------------------------------------------------------ // // Internal Fields // //------------------------------------------------------ #region Internal Fields internal System.Windows.Media.Composition.DUCE.MultiChannelResource _duceResource = new System.Windows.Media.Composition.DUCE.MultiChannelResource(); internal const double c_Angle = 0.0; internal const double c_CenterX = 0.0; internal const double c_CenterY = 0.0; #endregion Internal Fields #region Constructors //------------------------------------------------------ // // Constructors // //------------------------------------------------------ static RotateTransform() { // We check our static default fields which are of type Freezable // to make sure that they are not mutable, otherwise we will throw // if these get touched by more than one thread in the lifetime // of your app // Initializations Type typeofThis = typeof(RotateTransform); AngleProperty = RegisterProperty("Angle", typeof(double), typeofThis, 0.0, new PropertyChangedCallback(AnglePropertyChanged), null, /* isIndependentlyAnimated = */ true, /* coerceValueCallback */ null); CenterXProperty = RegisterProperty("CenterX", typeof(double), typeofThis, 0.0, new PropertyChangedCallback(CenterXPropertyChanged), null, /* isIndependentlyAnimated = */ true, /* coerceValueCallback */ null); CenterYProperty = RegisterProperty("CenterY", typeof(double), typeofThis, 0.0, new PropertyChangedCallback(CenterYPropertyChanged), null, /* isIndependentlyAnimated = */ true, /* coerceValueCallback */ null); } #endregion Constructors } }
32.448276
157
0.507235
[ "MIT" ]
00mjk/wpf
src/Microsoft.DotNet.Wpf/src/PresentationCore/System/Windows/Media/Generated/RotateTransform.cs
12,233
C#
using UnityEngine; using zapnet; public interface IProjectileTarget { bool OnProjectileHit(BaseProjectile projectile, NetworkRaycastHit hitbox); }
19.125
78
0.816993
[ "MIT" ]
BlackPhoenix134/zapnet
Demo/Zapnet/Assets/Zapnet/Demo/Entities/Tags/IProjectileTarget.cs
155
C#
using System; using System.Threading.Tasks; #if UWP using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; #else using System.Windows; using System.Windows.Controls; #endif namespace Xamarin.CommunityToolkit.UI.Views.Helpers { class SnackbarLayout : Grid { public SnackbarLayout(string message, string actionButtonText, Func<Task> action) { RowDefinitions.Add(new RowDefinition()); ColumnDefinitions.Add(new ColumnDefinition()); ColumnDefinitions.Add(new ColumnDefinition() { Width = GridLength.Auto }); #if UWP var messageLabel = new TextBlock() { Text = message }; #else var messageLabel = new Label() { Content = message }; #endif Children.Add(messageLabel); SetRow(messageLabel, 0); SetColumn(messageLabel, 0); if (!string.IsNullOrEmpty(actionButtonText) && action != null) { var button = new Button { Content = actionButtonText, Command = new Forms.Command(async () => { OnSnackbarActionExecuted?.Invoke(); await action(); }) }; Children.Add(button); SetRow(button, 0); SetColumn(button, 1); } } public Action OnSnackbarActionExecuted; } }
24.404255
83
0.694856
[ "MIT" ]
AbuMandour/XamarinCommunityToolkit
XamarinCommunityToolkit/Views/Snackbar/Helpers/SnackbarLayout.uwp.wpf.cs
1,149
C#
using Amazon.JSII.Runtime.Deputy; #pragma warning disable CS0672,CS0809,CS1591 namespace aws { [JsiiInterface(nativeType: typeof(IWafv2WebAclRuleStatementAndStatementStatementNotStatementStatementNotStatementStatementByteMatchStatementFieldToMatchQueryString), fullyQualifiedName: "aws.Wafv2WebAclRuleStatementAndStatementStatementNotStatementStatementNotStatementStatementByteMatchStatementFieldToMatchQueryString")] public interface IWafv2WebAclRuleStatementAndStatementStatementNotStatementStatementNotStatementStatementByteMatchStatementFieldToMatchQueryString { [JsiiTypeProxy(nativeType: typeof(IWafv2WebAclRuleStatementAndStatementStatementNotStatementStatementNotStatementStatementByteMatchStatementFieldToMatchQueryString), fullyQualifiedName: "aws.Wafv2WebAclRuleStatementAndStatementStatementNotStatementStatementNotStatementStatementByteMatchStatementFieldToMatchQueryString")] internal sealed class _Proxy : DeputyBase, aws.IWafv2WebAclRuleStatementAndStatementStatementNotStatementStatementNotStatementStatementByteMatchStatementFieldToMatchQueryString { private _Proxy(ByRefValue reference): base(reference) { } } } }
61
330
0.859016
[ "MIT" ]
scottenriquez/cdktf-alpha-csharp-testing
resources/.gen/aws/aws/IWafv2WebAclRuleStatementAndStatementStatementNotStatementStatementNotStatementStatementByteMatchStatementFieldToMatchQueryString.cs
1,220
C#
using System; using System.Collections.Generic; using System.Threading.Tasks; using System.Windows.Forms; namespace RimworldConflictChecker { public class Program { public static int Formrc { get; set; } public static string[] Allargs { get; set; } //public static bool incdisabled = false; public static bool Dps; public static DateTime Starttime; //Win10 Insider fix 07/19/17 //Tools -> Options -> Debugging -> General ->Uncheck: Enable UI Debugging Tools for XAML // Satisfies rule: MarkWindowsFormsEntryPointsWithStaThread. [STAThread] private static int Main(string[] args) { Allargs = args; var rimworldfolder = ""; var modfolder1 = ""; var modfolder2 = ""; var modsconfigfolder = ""; var incdisabled = false; var showdetails = false; Starttime = DateTime.Now; // Replace NBUG with https://github.com/google/breakpad one day? // Uncomment the following after testing to see that NBug is working as configured NBug.Settings.ReleaseMode = true; #if DEBUG NBug.Settings.WriteLogToDisk = true; #endif var list = new List<NBug.Core.Util.Storage.FileMask> {"RCC.txt"}; NBug.Settings.AdditionalReportFiles = list; //NBug.Exceptions.Dispatch(); // Sample NBug configuration for console applications AppDomain.CurrentDomain.UnhandledException += NBug.Handler.UnhandledException; TaskScheduler.UnobservedTaskException += NBug.Handler.UnobservedTaskException; // Add the event handler for handling UI thread exceptions to the event. Application.ThreadException += NBug.Handler.ThreadException; // Sample NBug configuration for WinForms applications // all set above //AppDomain.CurrentDomain.UnhandledException += NBug.Handler.UnhandledException; //Application.ThreadException += NBug.Handler.ThreadException; //TaskScheduler.UnobservedTaskException += NBug.Handler.UnobservedTaskException; if (args.Length == 1) { if (args[0] == "--help" || args[0] == "-help" || args[0] == "-h" || args[0] == "--h" || args[0] == "/?") { Console.WriteLine("Rimworld Conflict Checker"); Console.WriteLine(); Console.WriteLine("Usage:"); Console.WriteLine(" RCC.exe [-all] [path(s)]"); Console.WriteLine(); Console.WriteLine(" -all : Run as if all mods are enabled (ignoring what is set in ModsConfig.xml)"); Console.WriteLine(" [path] : Path(s) (each within quotes) seperated by spaces"); Console.WriteLine(" Where paths are : (required) Rimworld.exe location "); Console.WriteLine(" (optional) Rimworld Game Mod Folder"); Console.WriteLine(" (optional) Steam Mod Folder"); Console.WriteLine(" (optional) ModsConfig.xml location"); //Console.WriteLine(); Console.WriteLine("Example:"); Console.WriteLine(" RCC.exe \"D:\\SteamLibrary\\steamapps\\common\\RimWorld\" \"D:\\SteamLibrary\\steamapps\\workshop\\content\\294100\""); Console.WriteLine(); Console.WriteLine("or just run RCC.exe without parameters to get a folder chooser"); return 1; } } Console.WriteLine("Rimworld Conflict Checker Starting"); Formrc = 2; if (args.Length != 0) { foreach (string arg in args) { if (Utils.FileOrDirectoryExists(arg + "\\RimWorldWin.exe") || Utils.FileOrDirectoryExists(arg + "\\RimWorldWin64.exe")) { rimworldfolder = arg; Formrc = 0; continue; } if (Utils.FileOrDirectoryExists(arg + "\\Core")) { modfolder1 = arg + "\\Mods"; Formrc = 0; continue; } if (Utils.FileOrDirectoryExists(arg + "\\ModsConfig.xml")) { modsconfigfolder = arg; Formrc = 0; continue; } if (arg == "-all") { incdisabled = true; Settings.Default.incDisabled = true; } if (arg == "-details") { showdetails = true; Settings.Default.showDetails = true; } Dps |= arg == "-dps"; modfolder2 = arg; Formrc = 0; } } //if (args.Length == 0 || ((incdisabled) && (args.Length == 1))) if (args.Length == 0) { //run folder picker if (Settings.Default.UpgradeRequired) { Settings.Default.Upgrade(); Settings.Default.UpgradeRequired = false; Settings.Default.Save(); } Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); using (var optionsForm = new OptionsForm()) { Application.Run(optionsForm); } //set folder locations based on settings rimworldfolder = (string)Settings.Default["RimWorldFolder"]; modfolder1 = (string)Settings.Default["ModFolder1"]; modfolder2 = (string)Settings.Default["ModFolder2"]; modsconfigfolder = (string)Settings.Default["ModsConfigFolder"]; incdisabled = (bool)Settings.Default["incDisabled"]; showdetails = (bool)Settings.Default["showDetails"]; Formrc = OptionsForm.ReturnValue1; //Settings.Default.Upgrade(); } //testing throwing exception //throw new ArgumentException("ha-ha"); //this is terrible code. //TODO: Put all this into the RimWorld object var mainprogram = new RimworldXmlLoader(showdetails, incdisabled, rimworldfolder, modsconfigfolder, modfolder1, modfolder2); Logger.Instance.WriteToFile(); if (mainprogram.Rc == 0) { RunWpf(); } //testing throwing exception //throw new ArgumentException("ha-ha"); #if DEBUG //Process.Start(@"RCC.txt"); #endif return mainprogram.Rc; } // All WPF applications should execute on a single-threaded apartment (STA) thread [STAThread] public static void RunWpf() { //Windows forms: //Application.Run(new ResultsForm()); //System.Windows.Forms.Application.Run(new ResultsForm()); //WPF var form = new System.Windows.Application(); form.Run(new ResultsWpf()); } } }
42.087912
163
0.507572
[ "MIT" ]
Slayd7/RimworldConflictChecker
RimworldConflictChecker/Program.cs
7,662
C#
using CadastroPessoa.DATA.Interfaces; using CadastroPessoa.DATA.Models; using System; using System.Collections.Generic; using System.Text; namespace CadastroPessoa.DATA.Repositories { public class RepositoryPessoaTelefone : RepositoryBase<PessoaTelefone>, IRepositoryPessoaTelefone { public RepositoryPessoaTelefone(bool SaveChanges = true) : base(SaveChanges) { } } }
22.722222
101
0.753056
[ "MIT" ]
DanSmithh/ProjetoCrudCadastroDeUsuariosWeb
CadastroPessoa.DATA/Repositories/RepositoryPessoaTelefone.cs
411
C#
using Newtonsoft.Json; using JsonMasking; using System; using Xunit; namespace JsonMasking.Tests { public static class JsonMaskingTests { [Fact] public static void MaskFields_Should_Mask_No_Field_With_Empty_Blacklist() { // arrange var obj = new { Test = "1", Password = "somepass#here" }; var json = JsonConvert.SerializeObject(obj, Formatting.Indented); string[] blacklist = {}; var mask = "*******"; // act var result = json.MaskFields(blacklist, mask); // assert Assert.Equal("{\n \"Test\": \"1\",\n \"Password\": \"somepass#here\"\n}", result.Replace("\r\n","\n")); } [Fact] public static void MaskFields_Should_Mask_No_Field_With_Json_Without_Property() { // arrange var obj = new { Test = "1", OtherField = "somepass#here" }; var json = JsonConvert.SerializeObject(obj, Formatting.Indented); string[] blacklist = { "password" }; var mask = "*******"; // act var result = json.MaskFields(blacklist, mask); // assert Assert.Equal("{\n \"Test\": \"1\",\n \"OtherField\": \"somepass#here\"\n}", result.Replace("\r\n","\n")); } [Fact] public static void MaskFields_Should_Mask_Single_Field() { // arrange var obj = new { Test = "1", Password = "somepass#here" }; var json = JsonConvert.SerializeObject(obj, Formatting.Indented); string[] blacklist = { "password" }; var mask = "----"; // act var result = json.MaskFields(blacklist, mask); // assert Assert.Equal("{\n \"Test\": \"1\",\n \"Password\": \"----\"\n}", result.Replace("\r\n","\n")); } [Fact] public static void MaskFields_Should_Mask_Integer_Field() { // arrange var obj = new { Test = 1, Password = 123456 }; var json = JsonConvert.SerializeObject(obj, Formatting.Indented); string[] blacklist = { "*password" }; var mask = "*******"; // act var result = json.MaskFields(blacklist, mask); // assert Assert.Equal("{\n \"Test\": 1,\n \"Password\": \"*******\"\n}", result.Replace("\r\n","\n")); } [Fact] public static void MaskFields_Should_Mask_Depth_Field() { // arrange var obj = new { DepthObject = new { Test = "1", Password = "somepass#here" } }; var json = JsonConvert.SerializeObject(obj, Formatting.Indented); string[] blacklist = { "*.password" }; var mask = "*******"; // act var result = json.MaskFields(blacklist, mask); // assert Assert.Equal("{\n \"DepthObject\": {\n \"Test\": \"1\",\n \"Password\": \"*******\"\n }\n}", result.Replace("\r\n","\n")); } [Fact] public static void MaskFields_Should_Mask_Multiple_Fields() { // arrange var obj = new { Password = "somepass#here", DepthObject = new { Test = "1", Password = "somepass#here2" } }; var json = JsonConvert.SerializeObject(obj, Formatting.Indented); string[] blacklist = { "*password" }; var mask = "*******"; // act var result = json.MaskFields(blacklist, mask); // assert Assert.Equal("{\n \"Password\": \"*******\",\n \"DepthObject\": {\n \"Test\": \"1\",\n \"Password\": \"*******\"\n }\n}", result.Replace("\r\n","\n")); } [Fact] public static void MaskFields_Should_Mask_Multiple_Fields_With_Multiple_Blacklist() { // arrange var obj = new { Password = "somepass#here", DepthObject = new { Test = "1", CreditCardNumber = "5555000011112222" } }; var json = JsonConvert.SerializeObject(obj, Formatting.Indented); string[] blacklist = { "password", "*creditcardnumber" }; var mask = "*******"; // act var result = json.MaskFields(blacklist, mask); // assert Assert.Equal("{\n \"Password\": \"*******\",\n \"DepthObject\": {\n \"Test\": \"1\",\n \"CreditCardNumber\": \"*******\"\n }\n}", result.Replace("\r\n","\n")); } [Fact] public static void MaskFields_Should_Mask_With_Null_Property() { // arrange var obj = new { DepthObject = new { Test = "1", Password = (string)null, } }; var json = JsonConvert.SerializeObject(obj, Formatting.Indented); string[] blacklist = { "*password" }; var mask = "*******"; // act var result = json.MaskFields(blacklist, mask); // assert Assert.Equal("{\n \"DepthObject\": {\n \"Test\": \"1\",\n \"Password\": \"*******\"\n }\n}", result.Replace("\r\n","\n")); } [Fact] public static void MaskFields_Should_Throw_Exception_When_Blacklist_Is_Null() { // arrange var obj = new { Test = "1", Password = "somepass#here" }; var json = JsonConvert.SerializeObject(obj, Formatting.Indented); string[] blacklist = null; var mask = "*******"; // act Exception ex = Assert.Throws<ArgumentNullException>(() => json.MaskFields(blacklist, mask)); // assert Assert.Equal("Value cannot be null.\nParameter name: blacklist", ex.Message.Replace("\r\n","\n")); } [Fact] public static void MaskFields_Should_Throw_Exception_When_Json_Is_Null() { // arrange string json = null; string[] blacklist = { "password" }; var mask = "*******"; // act Exception ex = Assert.Throws<ArgumentNullException>(() => json.MaskFields(blacklist, mask)); // assert Assert.Equal("Value cannot be null.\nParameter name: json", ex.Message.Replace("\r\n", "\n")); } [Fact] public static void MaskFields_Should_Throw_Exception_When_Json_String_Is_Empty() { // arrange string json = ""; string[] blacklist = { "password" }; var mask = "*******"; // act Exception ex = Assert.Throws<ArgumentNullException>(() => json.MaskFields(blacklist, mask)); // assert Assert.Equal("Value cannot be null.\nParameter name: json", ex.Message.Replace("\r\n", "\n")); } [Fact] public static void MaskFields_Should_Throw_Exception_When_Json_String_Is_Invalid() { // arrange var json = "invalid json"; string[] blacklist = { "password" }; string mask = "------"; // act Exception ex = Assert.Throws<JsonReaderException>(() => json.MaskFields(blacklist, mask)); // assert Assert.StartsWith("Unexpected character encountered while parsing value", ex.Message); } [Fact] public static void MaskFields_Should_Mask_With_Wildcard() { // arrange var obj = new { DepthObject = new { Test = "1", Password = "somepass#here", DepthObject = new { Test = "1", Password = "somepass#here" } }, DepthObject2 = new { Test = "1", Password = "somepass#here", DepthObject = new { Test = "1", Password = "somepass#here", DepthObject = new { Test = "1", Password = new { Test1 = "1", Password2 = "somepass#here" } } } }, Password = "somepass#here" }; var json = JsonConvert.SerializeObject(obj, Formatting.Indented); string[] blacklist = { "*.DepthObject*.Password" }; var mask = "*******"; // act var result = json.MaskFields(blacklist, mask); // assert Assert.Equal("{\n \"DepthObject\": {\n \"Test\": \"1\",\n \"Password\": \"somepass#here\",\n \"DepthObject\": {\n \"Test\": \"1\",\n \"Password\": \"*******\"\n }\n },\n \"DepthObject2\": {\n \"Test\": \"1\",\n \"Password\": \"somepass#here\",\n \"DepthObject\": {\n \"Test\": \"1\",\n \"Password\": \"*******\",\n \"DepthObject\": {\n \"Test\": \"1\",\n \"Password\": \"*******\"\n }\n }\n },\n \"Password\": \"somepass#here\"\n}", result.Replace("\r\n","\n")); } } }
33.547855
547
0.431185
[ "MIT" ]
SenirSales/jsonmasking
JsonMasking.Tests/JsonMaskingTests.cs
10,165
C#
using Newtonsoft.Json; namespace ImageDL.Classes.ImageDownloading.Instagram.Models { /// <summary> /// Information about where a post was taken. /// </summary> public sealed class InstagramLocation { /// <summary> /// Whether the location has a page dedicated to it. /// </summary> [JsonProperty("has_public_page")] public bool HasPublicPage { get; private set; } /// <summary> /// The id of the location. /// </summary> [JsonProperty("id")] public string Id { get; private set; } /// <summary> /// The name of the location. /// </summary> [JsonProperty("name")] public string Name { get; private set; } /// <summary> /// The part of the url used to get to the page dedicated to this location. /// </summary> [JsonProperty("slug")] public string Slug { get; private set; } /// <summary> /// Returns the name and id. /// </summary> /// <returns></returns> public override string ToString() => $"{Name} ({Id})"; } }
24.375
77
0.634872
[ "MIT" ]
advorange/ImageDL
src/ImageDL.Core/Classes/ImageDownloading/Instagram/Models/InstagramLocation.cs
977
C#
// ---------------------------------------------------------------------------------- // // Copyright Microsoft Corporation // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ---------------------------------------------------------------------------------- using System.Configuration; using System.Reflection; using Microsoft.Azure.Commands.Common.Authentication.Models; using RecoveryServicesNS = Microsoft.Azure.Management.RecoveryServices.Backup; using Microsoft.Azure.Commands.Common.Authentication.Abstractions; namespace Microsoft.Azure.Commands.RecoveryServices.Backup.Cmdlets.ServiceClientAdapterNS { /// <summary> /// Adapter for service client to communicate with the backend service /// </summary> public partial class ServiceClientAdapter { const string AppSettingsSectionName = "appSettings"; const string ProviderNamespaceKey = "ProviderNamespace"; const string AzureFabricName = "Azure"; public const string ResourceProviderProductionNamespace = "Microsoft.RecoveryServices"; ClientProxy<RecoveryServicesNS.RecoveryServicesBackupClient> BmsAdapter; /// <summary> /// Resource provider namespace that this adapter uses to /// communicate with the backend service. /// This value depends on the value given in the /// exe config file of the service client DLL. /// </summary> public static string ResourceProviderNamespace { get { Configuration exeConfiguration = ConfigurationManager.OpenExeConfiguration( Assembly.GetExecutingAssembly().Location); AppSettingsSection appSettings = (AppSettingsSection)exeConfiguration.GetSection( AppSettingsSectionName); string resourceProviderNamespace = ResourceProviderProductionNamespace; if (appSettings.Settings[ProviderNamespaceKey] != null) { resourceProviderNamespace = appSettings.Settings[ProviderNamespaceKey].Value; } return resourceProviderNamespace; } } /// <summary> /// AzureContext based ctor /// </summary> /// <param name="context">Azure context</param> public ServiceClientAdapter(IAzureContext context) { BmsAdapter = new ClientProxy<RecoveryServicesNS.RecoveryServicesBackupClient>(context); } } }
44.318841
100
0.634075
[ "MIT" ]
SpillChek2/azure-powershell
src/ResourceManager/RecoveryServices.Backup/Commands.RecoveryServices.Backup.ServiceClientAdapter/ServiceClientAdapter.cs
2,992
C#
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Filters; using UserManager.Implementation.Exception; namespace Web.Tools { public class BusinessExceptionFilter : ExceptionFilterAttribute { public override void OnException(ExceptionContext context) { var exception = context.Exception as BusinessException; if (exception != null) { var result = new ObjectResult(exception.Content); context.ExceptionHandled = true; context.Result = result; result.StatusCode = 400; } } } }
28.954545
67
0.618524
[ "MIT" ]
kleevs/user-manager-api
src/Web/Tools/BusinessExceptionFilter.cs
639
C#
namespace FuncSharp { public static class NullableExtensions { /// <summary> /// Turns the specified value into an option. /// </summary> public static Option<A> ToOption<A>(this A? value) where A : struct { return Option.Create(value); } } }
21.866667
58
0.530488
[ "MIT" ]
JakubLinhart/FuncSharp
src/FuncSharp/Extensions/NullableExtensions.cs
330
C#
using System; using System.Collections.Generic; using Avalonia.VisualTree; namespace Avalonia.Rendering { public class ZIndexComparer : IComparer<IVisual> { public static readonly ZIndexComparer Instance = new ZIndexComparer(); public int Compare(IVisual x, IVisual y) => (x?.ZIndex ?? 0).CompareTo(y?.ZIndex ?? 0); } }
25.071429
95
0.700855
[ "MIT" ]
BOBO41/Avalonia
src/Avalonia.Visuals/Rendering/ZIndexComparer.cs
353
C#
namespace AptTool.Workspace { public class InstallScript { public InstallScript() { Name = "script.sh"; } public string Directory { get; set; } public string Name { get; set; } } }
18.714286
45
0.492366
[ "MIT" ]
adfernandes/apt-tool
src/AptTool/Workspace/InstallScript.cs
262
C#
using UnityEngine; using System; public abstract class BossPattern { protected Action OnPatternFinished; protected PhaseAI boss; public virtual void SetBoss(PhaseAI boss) { this.boss = boss; } public void ExecutePattern(Action action) { OnPatternFinished = action; ExecutePattern(); // Call OnPaternFinished when the patern is finished. } protected abstract void ExecutePattern(); protected abstract void OnStopPattern(); public void StopPattern() { OnStopPattern(); } }
16.323529
61
0.675676
[ "Apache-2.0" ]
Eresia/Harpooneers
Assets/Scripts/Gameplay/Boss/BossPattern.cs
557
C#
var builder = WebApplication.CreateBuilder(); builder.Services.AddRazorPages(); var app = builder.Build(); app.MapRazorPages(); app.Run();
17.625
45
0.744681
[ "MIT" ]
BearerPipelineTest/practical-aspnetcore
projects/razor-pages/razor/razor-1/Program.cs
141
C#
using CS.Hardware.BooleanLogic.Gates; using CS.Hardware.BooleanLogic.Multiplexers; using System; using System.Collections.Generic; using System.Text; namespace CS.Hardware.SequentialLogic { public class RAM8 { private const int BITS = 16; private const int SIZE = 8; private const int SEL_SIZE = 3; public bool Load { get; set; } private List<Register> _registers; private Mux8Way16 _mux; private DMux8Way _dmux; private bool[] _address = new bool[SEL_SIZE]; public bool[] Address { get { return _address; } } private bool[] _out = new bool[BITS]; public bool[] Out { get { return _out; } } public bool[] In { get; set; } = new bool[BITS]; public void SetAddress(bool s1 = false, bool s2 = false, bool s3 = false, bool update = true) => SetAddress(new bool[] { s1, s2, s3 }, update); public void SetAddress(bool[] address, bool update = true) { _address = address; if(update) { Update(); } } private void Update() { _mux.A = _registers[0].Out; _mux.B = _registers[1].Out; _mux.C = _registers[2].Out; _mux.D = _registers[3].Out; _mux.E = _registers[4].Out; _mux.F = _registers[5].Out; _mux.G = _registers[6].Out; _mux.H = _registers[7].Out; _mux.Sel = Address; _out = _mux.Out; } public void Tick(bool pulse) { if (!Load) return; _dmux.Sel = Address; _dmux.In = Load; _registers[0].Load = _dmux.A; _registers[1].Load = _dmux.B; _registers[2].Load = _dmux.C; _registers[3].Load = _dmux.D; _registers[4].Load = _dmux.E; _registers[5].Load = _dmux.F; _registers[6].Load = _dmux.G; _registers[7].Load = _dmux.H; for(int i = 0; i < SIZE; i++) { if(_registers[i].Load) { _registers[i].In = In; _registers[i].Tick(pulse); } } Update(); Load = false; } public RAM8() { _mux = new Mux8Way16(); _dmux = new DMux8Way(); _registers = new List<Register>(); for(int i = 0; i < SIZE; i++) { _registers.Add(new Register()); } } //public List<Register> DebugRegister { get { return _registers; } } public void ReadAllBlocks(ref int address, StringBuilder sb) { for (int i = 0; i < SIZE; i++) { _registers[i].ReadAllBlocks(ref address, sb); } } } }
29.191919
151
0.487197
[ "MIT" ]
larsrotgers/computing-system
CS.Hardware/SequentialLogic/RAM8.cs
2,892
C#
using System.Collections.Generic; using Microsoft.AspNetCore.Mvc; using DotNetNote.Models; namespace DotNetNote.Controllers { [Route("api/[controller]")] public class NoteCommentServiceController : Controller { private INoteCommentRepository _repository; public NoteCommentServiceController(INoteCommentRepository repository) { _repository = repository; } [HttpGet] public IEnumerable<NoteComment> Get() { // 최근 댓글 리스트 반환 return _repository.GetRecentComments(); } } }
23.52
78
0.64966
[ "MIT" ]
VisualAcademy/AspNetCoreBook
DotNetNote/src/DotNetNote/Controllers/NoteCommentServiceController.cs
608
C#
using System.Collections.Generic; namespace Tx.DataStructureExersises.Stack { interface ISimpleStack<T> : IEnumerable<T> { T Peek(); T Pop(); void Push(T item); void Clear(); int Count { get; } } }
18
46
0.56746
[ "MIT" ]
Telliax/Tx.DataStructureExercises
Stack/ISimpleStack.cs
254
C#
// ---------------------------------------------------------------------------------- // // Copyright Microsoft Corporation // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ---------------------------------------------------------------------------------- using System; using Microsoft.Azure.Commands.Automation.Common; using Microsoft.Azure.Commands.Automation.Properties; using System.Management.Automation; using System.Security.Permissions; namespace Microsoft.Azure.Commands.Automation.Cmdlet { /// <summary> /// Removes a Certificate for automation. /// </summary> [Cmdlet("Remove", ResourceManager.Common.AzureRMConstants.AzureRMPrefix + "AutomationCertificate", SupportsShouldProcess = true,DefaultParameterSetName = AutomationCmdletParameterSets.ByCertificateName), OutputType(typeof(void))] public class RemoveAzureAutomationCertificate : AzureAutomationBaseCmdlet { /// <summary> /// Gets or sets the certificate name. /// </summary> [Parameter(ParameterSetName = AutomationCmdletParameterSets.ByCertificateName, Position = 2, Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "The certificate name.")] [ValidateNotNullOrEmpty] public string Name { get; set; } /// <summary> /// Execute this cmdlet. /// </summary> [PermissionSet(SecurityAction.Demand, Name = "FullTrust")] protected override void AutomationProcessRecord() { ConfirmAction( string.Format(Resources.RemoveAzureAutomationResourceDescription, "Certificate"), Name, () => { this.AutomationClient.DeleteCertificate(this.ResourceGroupName, this.AutomationAccountName, Name); }); } } }
46.519231
234
0.622158
[ "MIT" ]
3quanfeng/azure-powershell
src/Automation/Automation/Cmdlet/RemoveAzureAutomationCertificate.cs
2,370
C#
using System; using Aop.Api.Domain; using System.Collections.Generic; using Aop.Api.Response; namespace Aop.Api.Request { /// <summary> /// AOP API: alipay.eco.eprint.order.cancel /// </summary> public class AlipayEcoEprintOrderCancelRequest : IAopRequest<AlipayEcoEprintOrderCancelResponse> { /// <summary> /// 易联云取消单条未打印订单对外接口服务 /// </summary> public string BizContent { get; set; } #region IAopRequest Members private bool needEncrypt=false; private string apiVersion = "1.0"; private string terminalType; private string terminalInfo; private string prodCode; private string notifyUrl; private string returnUrl; private AopObject bizModel; private Dictionary<string, string> udfParams; //add user-defined text parameters public void SetNeedEncrypt(bool needEncrypt){ this.needEncrypt=needEncrypt; } public bool GetNeedEncrypt(){ return this.needEncrypt; } public void SetNotifyUrl(string notifyUrl){ this.notifyUrl = notifyUrl; } public string GetNotifyUrl(){ return this.notifyUrl; } public void SetReturnUrl(string returnUrl){ this.returnUrl = returnUrl; } public string GetReturnUrl(){ return this.returnUrl; } public void SetTerminalType(String terminalType){ this.terminalType=terminalType; } public string GetTerminalType(){ return this.terminalType; } public void SetTerminalInfo(String terminalInfo){ this.terminalInfo=terminalInfo; } public string GetTerminalInfo(){ return this.terminalInfo; } public void SetProdCode(String prodCode){ this.prodCode=prodCode; } public string GetProdCode(){ return this.prodCode; } public string GetApiName() { return "alipay.eco.eprint.order.cancel"; } public void SetApiVersion(string apiVersion){ this.apiVersion=apiVersion; } public string GetApiVersion(){ return this.apiVersion; } public void PutOtherTextParam(string key, string value) { if(this.udfParams == null) { this.udfParams = new Dictionary<string, string>(); } this.udfParams.Add(key, value); } public IDictionary<string, string> GetParameters() { AopDictionary parameters = new AopDictionary(); parameters.Add("biz_content", this.BizContent); if(udfParams != null) { parameters.AddAll(this.udfParams); } return parameters; } public AopObject GetBizModel() { return this.bizModel; } public void SetBizModel(AopObject bizModel) { this.bizModel = bizModel; } #endregion } }
25.790323
101
0.564103
[ "Apache-2.0" ]
554393109/alipay-sdk-net-all
AlipaySDKNet.Standard/Request/AlipayEcoEprintOrderCancelRequest.cs
3,234
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using NBitcoin.DataEncoders; using Newtonsoft.Json; using UnKnownKVMap = System.Collections.Generic.SortedDictionary<byte[], byte[]>; using NBitcoin.BuilderExtensions; namespace NBitcoin { static class PSBTConstants { public static byte[] PSBT_GLOBAL_ALL { get; } public static byte[] PSBT_IN_ALL { get; } public static byte[] PSBT_OUT_ALL { get; } static PSBTConstants() { PSBT_GLOBAL_ALL = new byte[] { PSBT_GLOBAL_UNSIGNED_TX, PSBT_GLOBAL_XPUB }; PSBT_IN_ALL = new byte[] { PSBT_IN_NON_WITNESS_UTXO, PSBT_IN_WITNESS_UTXO, PSBT_IN_PARTIAL_SIG, PSBT_IN_SIGHASH, PSBT_IN_REDEEMSCRIPT, PSBT_IN_WITNESSSCRIPT, PSBT_IN_SCRIPTSIG, PSBT_IN_SCRIPTWITNESS, PSBT_IN_BIP32_DERIVATION }; PSBT_OUT_ALL = new byte[] { PSBT_OUT_REDEEMSCRIPT, PSBT_OUT_WITNESSSCRIPT, PSBT_OUT_BIP32_DERIVATION }; } // Note: These constants are in reverse byte order because serialization uses LSB // Global types public const byte PSBT_GLOBAL_UNSIGNED_TX = 0x00; public const byte PSBT_GLOBAL_XPUB = 0x01; // Input types public const byte PSBT_IN_NON_WITNESS_UTXO = 0x00; public const byte PSBT_IN_WITNESS_UTXO = 0x01; public const byte PSBT_IN_PARTIAL_SIG = 0x02; public const byte PSBT_IN_SIGHASH = 0x03; public const byte PSBT_IN_REDEEMSCRIPT = 0x04; public const byte PSBT_IN_WITNESSSCRIPT = 0x05; public const byte PSBT_IN_BIP32_DERIVATION = 0x06; public const byte PSBT_IN_SCRIPTSIG = 0x07; public const byte PSBT_IN_SCRIPTWITNESS = 0x08; // Output types public const byte PSBT_OUT_REDEEMSCRIPT = 0x00; public const byte PSBT_OUT_WITNESSSCRIPT = 0x01; public const byte PSBT_OUT_BIP32_DERIVATION = 0x02; // The separator is 0x00. Reading this in means that the unserializer can interpret it // as a 0 length key which indicates that this is the separator. The separator has no value. public const byte PSBT_SEPARATOR = 0x00; } public class PSBTSettings { /// <summary> /// Test vector in the bip174 specify to use a signer which follows RFC 6979. /// So we must sign without [LowR value assured way](https://github.com/MetacoSA/NBitcoin/pull/510) /// This should be turned false only in the test. /// ref: https://github.com/bitcoin/bitcoin/pull/13666 /// </summary> public bool UseLowR { get; set; } = true; /// <summary> /// Use custom builder extensions to customize finalization /// </summary> public IEnumerable<BuilderExtension> CustomBuilderExtensions { get; set; } /// <summary> /// Try to do anything that is possible to deduce PSBT information from input information /// </summary> public bool IsSmart { get; set; } = true; public PSBTSettings Clone() { return new PSBTSettings() { UseLowR = UseLowR, CustomBuilderExtensions = CustomBuilderExtensions?.ToArray(), IsSmart = IsSmart }; } } public class PSBT : IEquatable<PSBT> { // Magic bytes readonly static byte[] PSBT_MAGIC_BYTES = Encoders.ASCII.DecodeData("psbt\xff"); internal byte[] _XPubVersionBytes; byte[] XPubVersionBytes => _XPubVersionBytes = _XPubVersionBytes ?? Network.GetVersionBytes(Base58Type.EXT_PUBLIC_KEY, false); internal Transaction tx; public SortedDictionary<BitcoinExtPubKey, RootedKeyPath> GlobalXPubs { get; } = new SortedDictionary<BitcoinExtPubKey, RootedKeyPath>(BitcoinExtPubKeyComparer.Instance); internal class BitcoinExtPubKeyComparer : IComparer<BitcoinExtPubKey> { BitcoinExtPubKeyComparer() { } public static BitcoinExtPubKeyComparer Instance { get; } = new BitcoinExtPubKeyComparer(); public int Compare(BitcoinExtPubKey x, BitcoinExtPubKey y) { return BytesComparer.Instance.Compare(x.ExtPubKey.ToBytes(), y.ExtPubKey.ToBytes()); } } public PSBTInputList Inputs { get; } public PSBTOutputList Outputs { get; } internal UnKnownKVMap unknown = new UnKnownKVMap(BytesComparer.Instance); public static PSBT Parse(string hexOrBase64, Network network) { if (network == null) throw new ArgumentNullException(nameof(network)); if (hexOrBase64 == null) throw new ArgumentNullException(nameof(hexOrBase64)); if (network == null) throw new ArgumentNullException(nameof(network)); byte[] raw; if (HexEncoder.IsWellFormed(hexOrBase64)) raw = Encoders.Hex.DecodeData(hexOrBase64); else raw = Encoders.Base64.DecodeData(hexOrBase64); return Load(raw, network); } public static bool TryParse(string hexOrBase64, Network network, out PSBT psbt) { if (hexOrBase64 == null) throw new ArgumentNullException(nameof(hexOrBase64)); if (network == null) throw new ArgumentNullException(nameof(network)); try { psbt = Parse(hexOrBase64, network); return true; } catch { psbt = null; return false; } } public static PSBT Load(byte[] rawBytes, Network network) { if (network == null) throw new ArgumentNullException(nameof(network)); var stream = new BitcoinStream(rawBytes); stream.ConsensusFactory = network.Consensus.ConsensusFactory; var ret = new PSBT(stream, network); return ret; } public Network Network { get; } private PSBT(Transaction transaction, Network network) { if (transaction == null) throw new ArgumentNullException(nameof(transaction)); if (network == null) throw new ArgumentNullException(nameof(network)); Network = network; tx = transaction.Clone(); Inputs = new PSBTInputList(); Outputs = new PSBTOutputList(); for (var i = 0; i < tx.Inputs.Count; i++) this.Inputs.Add(new PSBTInput(this, (uint)i, tx.Inputs[i])); for (var i = 0; i < tx.Outputs.Count; i++) this.Outputs.Add(new PSBTOutput(this, (uint)i, tx.Outputs[i])); foreach (var input in tx.Inputs) { input.ScriptSig = Script.Empty; input.WitScript = WitScript.Empty; } } internal PSBT(BitcoinStream stream, Network network) { if (network == null) throw new ArgumentNullException(nameof(network)); Network = network; Inputs = new PSBTInputList(); Outputs = new PSBTOutputList(); var magicBytes = stream.Inner.ReadBytes(PSBT_MAGIC_BYTES.Length); if (!magicBytes.SequenceEqual(PSBT_MAGIC_BYTES)) { throw new FormatException("Invalid PSBT magic bytes"); } // It will be reassigned in `ReadWriteAsVarString` so no worry to assign 0 length array here. byte[] k = new byte[0]; byte[] v = new byte[0]; var txFound = false; stream.ReadWriteAsVarString(ref k); while (k.Length != 0) { switch (k[0]) { case PSBTConstants.PSBT_GLOBAL_UNSIGNED_TX: if (k.Length != 1) throw new FormatException("Invalid PSBT. Contains illegal value in key global tx"); if (tx != null) throw new FormatException("Duplicate Key, unsigned tx already provided"); tx = stream.ConsensusFactory.CreateTransaction(); uint size = 0; stream.ReadWriteAsVarInt(ref size); var pos = stream.Counter.ReadenBytes; tx.ReadWrite(stream); if (stream.Counter.ReadenBytes - pos != size) throw new FormatException("Malformed global tx. Unexpected size."); if (tx.Inputs.Any(txin => txin.ScriptSig != Script.Empty || txin.WitScript != WitScript.Empty)) throw new FormatException("Malformed global tx. It should not contain any scriptsig or witness by itself"); txFound = true; break; case PSBTConstants.PSBT_GLOBAL_XPUB when XPubVersionBytes != null: if (k.Length != 1 + XPubVersionBytes.Length + 74) throw new FormatException("Malformed global xpub."); for (int ii = 0; ii < XPubVersionBytes.Length; ii++) { if (k[1 + ii] != XPubVersionBytes[ii]) throw new FormatException("Malformed global xpub."); } stream.ReadWriteAsVarString(ref v); KeyPath path = KeyPath.FromBytes(v.Skip(4).ToArray()); var rootedKeyPath = new RootedKeyPath(new HDFingerprint(v.Take(4).ToArray()), path); GlobalXPubs.Add(new ExtPubKey(k, 1 + XPubVersionBytes.Length, 74).GetWif(Network), rootedKeyPath); break; default: if (unknown.ContainsKey(k)) throw new FormatException("Invalid PSBTInput, duplicate key for unknown value"); stream.ReadWriteAsVarString(ref v); unknown.Add(k, v); break; } stream.ReadWriteAsVarString(ref k); } if (!txFound) throw new FormatException("Invalid PSBT. No global TX"); int i = 0; while (stream.Inner.CanRead && i < tx.Inputs.Count) { var psbtin = new PSBTInput(stream, this, (uint)i, tx.Inputs[i]); Inputs.Add(psbtin); i++; } if (i != tx.Inputs.Count) throw new FormatException("Invalid PSBT. Number of input does not match to the global tx"); i = 0; while (stream.Inner.CanRead && i < tx.Outputs.Count) { var psbtout = new PSBTOutput(stream, this, (uint)i, tx.Outputs[i]); Outputs.Add(psbtout); i++; } if (i != tx.Outputs.Count) throw new FormatException("Invalid PSBT. Number of outputs does not match to the global tx"); } public PSBT AddCoins(params ICoin[] coins) { if (coins == null) return this; if (IsAllFinalized()) return this; foreach (var coin in coins) { var indexedInput = this.Inputs.FindIndexedInput(coin.Outpoint); if (indexedInput == null) continue; indexedInput.UpdateFromCoin(coin); } foreach (var coin in coins) { foreach (var output in this.Outputs) { if (output.ScriptPubKey == coin.TxOut.ScriptPubKey) { output.UpdateFromCoin(coin); } } } return this; } public PSBT AddCoins(params Transaction[] transactions) { if (transactions == null) throw new ArgumentNullException(nameof(transactions)); return AddTransactions(transactions).AddCoins(transactions.SelectMany(t => t.Outputs.AsCoins()).ToArray()); } /// <summary> /// Add transactions to non segwit outputs /// </summary> /// <param name="parentTransactions">Parent transactions</param> /// <returns>This PSBT</returns> public PSBT AddTransactions(params Transaction[] parentTransactions) { if (parentTransactions == null) return this; Dictionary<uint256, Transaction> txsById = new Dictionary<uint256, Transaction>(); foreach (var tx in parentTransactions) txsById.TryAdd(tx.GetHash(), tx); foreach (var input in Inputs) { if (input.IsFinalized()) continue; if (input.WitnessUtxo == null && txsById.TryGetValue(input.TxIn.PrevOut.Hash, out var tx)) { if (input.TxIn.PrevOut.N >= tx.Outputs.Count) continue; var output = tx.Outputs[input.TxIn.PrevOut.N]; if (output.ScriptPubKey.IsScriptType(ScriptType.Witness) || input.RedeemScript?.IsScriptType(ScriptType.Witness) is true) { input.WitnessUtxo = output; input.NonWitnessUtxo = null; } else { input.WitnessUtxo = null; input.NonWitnessUtxo = tx; } } } return this; } /// <summary> /// If an other PSBT has a specific field and this does not have it, then inject that field to this. /// otherwise leave it as it is. /// /// If you need to call this on transactions with different global transaction, use <see cref="PSBT.UpdateFrom(PSBT)"/> instead. /// </summary> /// <param name="other">Another PSBT to takes information from</param> /// <exception cref="System.ArgumentException">Can not Combine PSBT with different global tx.</exception> /// <returns>This instance</returns> public PSBT Combine(PSBT other) { if (other == null) { throw new ArgumentNullException(nameof(other)); } if (other.tx.GetHash() != this.tx.GetHash()) throw new ArgumentException(paramName: nameof(other), message: "Can not Combine PSBT with different global tx."); foreach (var xpub in other.GlobalXPubs) this.GlobalXPubs.TryAdd(xpub.Key, xpub.Value); for (int i = 0; i < Inputs.Count; i++) this.Inputs[i].UpdateFrom(other.Inputs[i]); for (int i = 0; i < Outputs.Count; i++) this.Outputs[i].UpdateFrom(other.Outputs[i]); foreach (var uk in other.unknown) this.unknown.TryAdd(uk.Key, uk.Value); return this; } /// <summary> /// If an other PSBT has a specific field and this does not have it, then inject that field to this. /// otherwise leave it as it is. /// /// Contrary to <see cref="PSBT.Combine(PSBT)"/>, it can be called on PSBT with a different global transaction. /// </summary> /// <param name="other">Another PSBT to takes information from</param> /// <returns>This instance</returns> public PSBT UpdateFrom(PSBT other) { if (other == null) { throw new ArgumentNullException(nameof(other)); } foreach (var xpub in other.GlobalXPubs) this.GlobalXPubs.TryAdd(xpub.Key, xpub.Value); foreach (var otherInput in other.Inputs) this.Inputs.FindIndexedInput(otherInput.PrevOut)?.UpdateFrom(otherInput); foreach (var otherOutput in other.Outputs) foreach (var thisOutput in this.Outputs.Where(o => o.ScriptPubKey == otherOutput.ScriptPubKey)) thisOutput.UpdateFrom(otherOutput); foreach (var uk in other.unknown) this.unknown.TryAdd(uk.Key, uk.Value); return this; } /// <summary> /// Join two PSBT into one CoinJoin PSBT. /// This is an immutable method. /// TODO: May need assertion for sighash type? /// </summary> /// <param name="other"></param> /// <returns></returns> public PSBT CoinJoin(PSBT other) { if (other == null) throw new ArgumentNullException(nameof(other)); other.AssertSanity(); var result = this.Clone(); for (int i = 0; i < other.Inputs.Count; i++) { result.tx.Inputs.Add(other.tx.Inputs[i]); result.Inputs.Add(other.Inputs[i]); } for (int i = 0; i < other.Outputs.Count; i++) { result.tx.Outputs.Add(other.tx.Outputs[i]); result.Outputs.Add(other.Outputs[i]); } return result; } public PSBT Finalize() { if (!TryFinalize(out var errors)) throw new PSBTException(errors); return this; } public bool TryFinalize(out IList<PSBTError> errors) { var localErrors = new List<PSBTError>(); foreach (var input in Inputs) { if (!input.TryFinalizeInput(out var e)) { localErrors.AddRange(e); } } if (localErrors.Count != 0) { errors = localErrors; return false; } errors = null; return true; } public bool IsReadyToSign() { return IsReadyToSign(out _); } public bool IsReadyToSign(out PSBTError[] errors) { var errorList = new List<PSBTError>(); foreach (var input in Inputs) { var localErrors = input.CheckSanity(); if (localErrors.Count != 0) { errorList.AddRange(localErrors); } else { if (input.GetSignableCoin(out var err) == null) errorList.Add(new PSBTError(input.Index, err)); } } if (errorList.Count != 0) { errors = errorList.ToArray(); return false; } errors = null; return true; } public PSBTSettings Settings { get; set; } = new PSBTSettings(); /// <summary> /// Sign all inputs which derive <paramref name="accountKey"/> of type <paramref name="scriptPubKeyType"/>. /// </summary> /// <param name="scriptPubKeyType">The way to derive addresses from the accountKey</param> /// <param name="accountKey">The account key with which to sign</param> /// <param name="accountKeyPath">The account key path (eg. [masterFP]/49'/0'/0')</param> /// <param name="sigHash">The SigHash</param> /// <returns>This PSBT</returns> public PSBT SignAll(ScriptPubKeyType scriptPubKeyType, IHDKey accountKey, RootedKeyPath accountKeyPath, SigHash sigHash = SigHash.All) { if (accountKey == null) throw new ArgumentNullException(nameof(accountKey)); return SignAll(new HDKeyScriptPubKey(accountKey, scriptPubKeyType), accountKey, accountKeyPath, sigHash); } /// <summary> /// Sign all inputs which derive <paramref name="accountKey"/> of type <paramref name="scriptPubKeyType"/>. /// </summary> /// <param name="scriptPubKeyType">The way to derive addresses from the accountKey</param> /// <param name="accountKey">The account key with which to sign</param> /// <param name="sigHash">The SigHash</param> /// <returns>This PSBT</returns> public PSBT SignAll(ScriptPubKeyType scriptPubKeyType, IHDKey accountKey, SigHash sigHash = SigHash.All) { if (accountKey == null) throw new ArgumentNullException(nameof(accountKey)); return SignAll(new HDKeyScriptPubKey(accountKey, scriptPubKeyType), accountKey, sigHash); } /// <summary> /// Sign all inputs which derive addresses from <paramref name="accountHDScriptPubKey"/> and that need to be signed by <paramref name="accountKey"/>. /// </summary> /// <param name="accountHDScriptPubKey">The address generator</param> /// <param name="accountKey">The account key with which to sign</param> /// <param name="sigHash">The SigHash</param> /// <returns>This PSBT</returns> public PSBT SignAll(IHDScriptPubKey accountHDScriptPubKey, IHDKey accountKey, SigHash sigHash = SigHash.All) { return SignAll(accountHDScriptPubKey, accountKey, null, sigHash); } /// <summary> /// Sign all inputs which derive addresses from <paramref name="accountHDScriptPubKey"/> and that need to be signed by <paramref name="accountKey"/>. /// </summary> /// <param name="accountHDScriptPubKey">The address generator</param> /// <param name="accountKey">The account key with which to sign</param> /// <param name="accountKeyPath">The account key path (eg. [masterFP]/49'/0'/0')</param> /// <param name="sigHash">The SigHash</param> /// <returns>This PSBT</returns> public PSBT SignAll(IHDScriptPubKey accountHDScriptPubKey, IHDKey accountKey, RootedKeyPath accountKeyPath, SigHash sigHash = SigHash.All) { if (accountKey == null) throw new ArgumentNullException(nameof(accountKey)); if (accountHDScriptPubKey == null) throw new ArgumentNullException(nameof(accountHDScriptPubKey)); accountHDScriptPubKey = accountHDScriptPubKey.AsHDKeyCache(); accountKey = accountKey.AsHDKeyCache(); Money total = Money.Zero; foreach (var o in Inputs.CoinsFor(accountHDScriptPubKey, accountKey, accountKeyPath)) { o.TrySign(accountHDScriptPubKey, accountKey, accountKeyPath, sigHash); } return this; } /// <summary> /// Returns the fee of the transaction being signed /// </summary> /// <param name="fee"></param> /// <returns></returns> public bool TryGetFee(out Money fee) { fee = tx.GetFee(GetAllCoins().ToArray()); return fee != null; } /// <summary> /// Returns the fee of the transaction being signed /// </summary> /// <returns>The fees</returns> /// <exception cref="System.InvalidOperationException">Not enough information to know about the fee</exception> public Money GetFee() { if (!TryGetFee(out var fee)) throw new InvalidOperationException("Not enough information to know about the fee"); return fee; } /// <summary> /// Returns the fee rate of the transaction. If the PSBT is finalized, then the exact rate is returned, else an estimation is made. /// </summary> /// <param name="estimatedFeeRate"></param> /// <returns>True if could get the estimated fee rate</returns> public bool TryGetEstimatedFeeRate(out FeeRate estimatedFeeRate) { if (IsAllFinalized()) { estimatedFeeRate = ExtractTransaction().GetFeeRate(GetAllCoins().ToArray()); return estimatedFeeRate != null; } if (!TryGetFee(out var fee)) { estimatedFeeRate = null; return false; } var transactionBuilder = CreateTransactionBuilder(); transactionBuilder.AddCoins(GetAllCoins()); try { var vsize = transactionBuilder.EstimateSize(this.tx, true); estimatedFeeRate = new FeeRate(fee, vsize); return true; } catch { estimatedFeeRate = null; return false; } } /// <summary> /// Returns the virtual transaction size of the transaction. If the PSBT is finalized, then the exact virtual size. /// </summary> /// <param name="vsize">The calculated virtual size</param> /// <returns>True if could get the virtual size could get estimated</returns> public bool TryGetVirtualSize(out int vsize) { if (IsAllFinalized()) { vsize = ExtractTransaction().GetVirtualSize(); return true; } var transactionBuilder = CreateTransactionBuilder(); transactionBuilder.AddCoins(GetAllCoins()); try { vsize = transactionBuilder.EstimateSize(this.tx, true); return true; } catch { vsize = -1; return false; } } /// <summary> /// Returns the fee rate of the transaction. If the PSBT is finalized, then the exact rate is returned, else an estimation is made. /// </summary> /// <returns>The estimated fee</returns> /// <exception cref="System.InvalidOperationException">Not enough information to know about the fee rate</exception> public FeeRate GetEstimatedFeeRate() { if (!TryGetEstimatedFeeRate(out var feeRate)) throw new InvalidOperationException("Not enough information to know about the fee rate"); return feeRate; } public PSBT SignWithKeys(params Key[] keys) { return SignWithKeys(SigHash.All, keys); } public PSBT SignWithKeys(params ISecret[] keys) { return SignWithKeys(SigHash.All, keys.Select(k => k.PrivateKey).ToArray()); } public PSBT SignWithKeys(SigHash sigHash, params Key[] keys) { AssertSanity(); foreach (var key in keys) { foreach (var input in this.Inputs) { input.Sign(key, sigHash); } } return this; } internal TransactionBuilder CreateTransactionBuilder() { var transactionBuilder = Network.CreateTransactionBuilder(); if (Settings.CustomBuilderExtensions != null) { transactionBuilder.Extensions.Clear(); transactionBuilder.Extensions.AddRange(Settings.CustomBuilderExtensions); } transactionBuilder.UseLowR = Settings.UseLowR; return transactionBuilder; } private IEnumerable<ICoin> GetAllCoins() { return this.Inputs.Select(i => i.GetSignableCoin() ?? i.GetCoin()).Where(c => c != null).ToArray(); } public Transaction ExtractTransaction() { if (!this.CanExtractTransaction()) throw new InvalidOperationException("PSBTInputs are not all finalized!"); var copy = tx.Clone(); for (var i = 0; i < tx.Inputs.Count; i++) { copy.Inputs[i].ScriptSig = Inputs[i].FinalScriptSig ?? Script.Empty; copy.Inputs[i].WitScript = Inputs[i].FinalScriptWitness ?? WitScript.Empty; } return copy; } public bool CanExtractTransaction() => IsAllFinalized(); public bool IsAllFinalized() => this.Inputs.All(i => i.IsFinalized()); public IList<PSBTError> CheckSanity() { List<PSBTError> errors = new List<PSBTError>(); foreach (var input in Inputs) { errors.AddRange(input.CheckSanity()); } return errors; } public void AssertSanity() { var errors = CheckSanity(); if (errors.Count != 0) throw new PSBTException(errors); } /// <summary> /// Get the expected hash once the transaction is fully signed /// </summary> /// <param name="hash">The hash once fully signed</param> /// <returns>True if we can know the expected hash. False if we can't (unsigned non-segwit).</returns> public bool TryGetFinalizedHash(out uint256 hash) { var tx = GetGlobalTransaction(); for (int i = 0; i < Inputs.Count; i++) { if (Inputs[i].IsFinalized()) { tx.Inputs[i].ScriptSig = Inputs[i].FinalScriptSig ?? Script.Empty; tx.Inputs[i].WitScript = Inputs[i].WitnessScript ?? Script.Empty; } else if (Inputs[i].NonWitnessUtxo != null) { hash = null; return false; } else if (Network.Consensus.SupportSegwit && Inputs[i].WitnessUtxo is TxOut utxo && utxo.ScriptPubKey.IsScriptType(ScriptType.P2SH) && Inputs[i].GetSignableCoin() is ScriptCoin sc && sc.GetP2SHRedeem() is Script p2shRedeem) { tx.Inputs[i].ScriptSig = PayToScriptHashTemplate.Instance.GenerateScriptSig(null as byte[][], p2shRedeem); } else if (Network.Consensus.SupportSegwit && Inputs[i].WitnessUtxo is TxOut utxo2 && !utxo2.ScriptPubKey.IsScriptType(ScriptType.P2SH)) { } else { hash = null; return false; } } hash = tx.GetHash(); return true; } #region IBitcoinSerializable Members private static uint defaultKeyLen = 1; public void Serialize(BitcoinStream stream) { // magic bytes stream.Inner.Write(PSBT_MAGIC_BYTES, 0, PSBT_MAGIC_BYTES.Length); // unsigned tx flag stream.ReadWriteAsVarInt(ref defaultKeyLen); stream.ReadWrite(PSBTConstants.PSBT_GLOBAL_UNSIGNED_TX); // Write serialized tx to a stream stream.TransactionOptions &= TransactionOptions.None; uint txLength = (uint)tx.GetSerializedSize(TransactionOptions.None); stream.ReadWriteAsVarInt(ref txLength); stream.ReadWrite(tx); foreach (var xpub in GlobalXPubs) { if (xpub.Key.Network != Network) throw new InvalidOperationException("Invalid key inside the global xpub collection"); var len = (uint)(1 + XPubVersionBytes.Length + 74); stream.ReadWriteAsVarInt(ref len); stream.ReadWrite(PSBTConstants.PSBT_GLOBAL_XPUB); var vb = XPubVersionBytes; stream.ReadWrite(ref vb); xpub.Key.ExtPubKey.ReadWrite(stream); var path = xpub.Value.KeyPath.ToBytes(); var pathInfo = xpub.Value.MasterFingerprint.ToBytes().Concat(path); stream.ReadWriteAsVarString(ref pathInfo); } // Write the unknown things foreach (var kv in unknown) { byte[] k = kv.Key; byte[] v = kv.Value; stream.ReadWriteAsVarString(ref k); stream.ReadWriteAsVarString(ref v); } // Separator var sep = PSBTConstants.PSBT_SEPARATOR; stream.ReadWrite(ref sep); // Write inputs foreach (var psbtin in Inputs) { psbtin.Serialize(stream); } // Write outputs foreach (var psbtout in Outputs) { psbtout.Serialize(stream); } } #endregion public override string ToString() { var strWriter = new StringWriter(); var jsonWriter = new JsonTextWriter(strWriter); jsonWriter.Formatting = Formatting.Indented; jsonWriter.WriteStartObject(); if (TryGetFee(out var fee)) { jsonWriter.WritePropertyValue("fee", $"{fee} BTC"); } else { jsonWriter.WritePropertyName("fee"); jsonWriter.WriteToken(JsonToken.Null); } if (TryGetEstimatedFeeRate(out var feeRate)) { jsonWriter.WritePropertyValue("feeRate", $"{feeRate}"); } else { jsonWriter.WritePropertyName("feeRate"); jsonWriter.WriteToken(JsonToken.Null); } jsonWriter.WritePropertyName("tx"); jsonWriter.WriteStartObject(); var formatter = new RPC.BlockExplorerFormatter(); formatter.WriteTransaction2(jsonWriter, tx); jsonWriter.WriteEndObject(); if (GlobalXPubs.Count != 0) { jsonWriter.WritePropertyName("xpubs"); jsonWriter.WriteStartArray(); foreach (var xpub in GlobalXPubs) { jsonWriter.WriteStartObject(); jsonWriter.WritePropertyValue("key", xpub.Key.ToString()); jsonWriter.WritePropertyValue("value", xpub.Value.ToString()); jsonWriter.WriteEndObject(); } jsonWriter.WriteEndArray(); } if (unknown.Count != 0) { jsonWriter.WritePropertyName("unknown"); jsonWriter.WriteStartObject(); foreach (var el in unknown) { jsonWriter.WritePropertyValue(Encoders.Hex.EncodeData(el.Key), Encoders.Hex.EncodeData(el.Value)); } jsonWriter.WriteEndObject(); } jsonWriter.WritePropertyName("inputs"); jsonWriter.WriteStartArray(); foreach (var input in this.Inputs) { input.Write(jsonWriter); } jsonWriter.WriteEndArray(); jsonWriter.WritePropertyName("outputs"); jsonWriter.WriteStartArray(); foreach (var output in this.Outputs) { output.Write(jsonWriter); } jsonWriter.WriteEndArray(); jsonWriter.WriteEndObject(); jsonWriter.Flush(); return strWriter.ToString(); } public byte[] ToBytes() { MemoryStream ms = new MemoryStream(); var bs = new BitcoinStream(ms, true); bs.ConsensusFactory = tx.GetConsensusFactory(); this.Serialize(bs); return ms.ToArrayEfficient(); } /// <summary> /// Clone this PSBT /// </summary> /// <returns>A cloned PSBT</returns> public PSBT Clone() { return Clone(true); } /// <summary> /// Clone this PSBT /// </summary> /// <param name="keepOriginalTransactionInformation">Whether the original scriptSig and witScript or inputs is saved</param> /// <returns>A cloned PSBT</returns> public PSBT Clone(bool keepOriginalTransactionInformation) { var bytes = ToBytes(); var psbt = PSBT.Load(bytes, Network); if (keepOriginalTransactionInformation) { for (int i = 0; i < Inputs.Count; i++) { psbt.Inputs[i].originalScriptSig = this.Inputs[i].originalScriptSig; psbt.Inputs[i].originalWitScript = this.Inputs[i].originalWitScript; psbt.Inputs[i].orphanTxOut = this.Inputs[i].orphanTxOut; } } psbt.Settings = Settings.Clone(); return psbt; } public string ToBase64() => Encoders.Base64.EncodeData(this.ToBytes()); public string ToHex() => Encoders.Hex.EncodeData(this.ToBytes()); public override bool Equals(object obj) { var item = obj as PSBT; if (item == null) return false; return item.Equals(this); } public bool Equals(PSBT b) { if (b is null) return false; return this.ToBytes().SequenceEqual(b.ToBytes()); } public override int GetHashCode() => Utils.GetHashCode(this.ToBytes()); public static PSBT FromTransaction(Transaction transaction, Network network) { if (transaction == null) throw new ArgumentNullException(nameof(transaction)); if (network == null) throw new ArgumentNullException(nameof(network)); return new PSBT(transaction, network); } public PSBT AddScripts(params Script[] redeems) { if (redeems == null) throw new ArgumentNullException(nameof(redeems)); var unused = new OutPoint(uint256.Zero, 0); foreach (var redeem in redeems) { var p2sh = redeem.Hash.ScriptPubKey; var p2wsh = redeem.WitHash.ScriptPubKey; var p2shp2wsh = redeem.WitHash.ScriptPubKey.Hash.ScriptPubKey; foreach (var o in this.Inputs.OfType<PSBTCoin>().Concat(this.Outputs)) { if (o is PSBTInput ii && ii.IsFinalized()) continue; var txout = o.GetCoin()?.TxOut; if (txout == null) continue; if (txout.ScriptPubKey == p2sh) { o.RedeemScript = redeem; } else if (txout.ScriptPubKey == p2wsh) { o.WitnessScript = redeem; if (o is PSBTInput i) i.TrySlimUTXO(); } else if (txout.ScriptPubKey == p2shp2wsh) { o.WitnessScript = redeem; o.RedeemScript = redeem.WitHash.ScriptPubKey; if (o is PSBTInput i) i.TrySlimUTXO(); } } } return this; } /// <summary> /// Get the balance change if you were signing this transaction. /// </summary> /// <param name="accountHDScriptPubKey">The hdScriptPubKey used to generate addresses</param> /// <param name="accountKey">The account key that will be used to sign (ie. 49'/0'/0')</param> /// <param name="accountKeyPath">The account key path</param> /// <returns>The balance change</returns> public Money GetBalance(ScriptPubKeyType scriptPubKeyType, IHDKey accountKey, RootedKeyPath accountKeyPath = null) { if (accountKey == null) throw new ArgumentNullException(nameof(accountKey)); return GetBalance(new HDKeyScriptPubKey(accountKey, scriptPubKeyType), accountKey, accountKeyPath); } /// <summary> /// Get the balance change if you were signing this transaction. /// </summary> /// <param name="accountHDScriptPubKey">The hdScriptPubKey used to generate addresses</param> /// <param name="accountKey">The account key that will be used to sign (ie. 49'/0'/0')</param> /// <param name="accountKeyPath">The account key path</param> /// <returns>The balance change</returns> public Money GetBalance(IHDScriptPubKey accountHDScriptPubKey, IHDKey accountKey, RootedKeyPath accountKeyPath = null) { if (accountHDScriptPubKey == null) throw new ArgumentNullException(nameof(accountHDScriptPubKey)); Money total = Money.Zero; foreach (var o in CoinsFor(accountHDScriptPubKey, accountKey, accountKeyPath)) { var amount = o.GetCoin()?.Amount; if (amount == null) continue; total += o is PSBTInput ? -amount : amount; } return total; } /// <summary> /// Filter the coins which contains the <paramref name="accountKey"/> and <paramref name="accountKeyPath"/> in the HDKeys and derive /// the same scriptPubKeys as <paramref name="accountHDScriptPubKey"/>. /// </summary> /// <param name="accountHDScriptPubKey">The hdScriptPubKey used to generate addresses</param> /// <param name="accountKey">The account key that will be used to sign (ie. 49'/0'/0')</param> /// <param name="accountKeyPath">The account key path</param> /// <returns>Inputs with HD keys matching masterFingerprint and account key</returns> public IEnumerable<PSBTCoin> CoinsFor(IHDScriptPubKey accountHDScriptPubKey, IHDKey accountKey, RootedKeyPath accountKeyPath = null) { if (accountKey == null) throw new ArgumentNullException(nameof(accountKey)); if (accountHDScriptPubKey == null) throw new ArgumentNullException(nameof(accountHDScriptPubKey)); accountHDScriptPubKey = accountHDScriptPubKey.AsHDKeyCache(); accountKey = accountKey.AsHDKeyCache(); return Inputs.CoinsFor(accountHDScriptPubKey, accountKey, accountKeyPath).OfType<PSBTCoin>().Concat(Outputs.CoinsFor(accountHDScriptPubKey, accountKey, accountKeyPath).OfType<PSBTCoin>()); } /// <summary> /// Filter the keys which contains the <paramref name="accountKey"/> and <paramref name="accountKeyPath"/> in the HDKeys and whose input/output /// the same scriptPubKeys as <paramref name="accountHDScriptPubKey"/>. /// </summary> /// <param name="accountHDScriptPubKey">The hdScriptPubKey used to generate addresses</param> /// <param name="accountKey">The account key that will be used to sign (ie. 49'/0'/0')</param> /// <param name="accountKeyPath">The account key path</param> /// <returns>HD Keys matching master root key</returns> public IEnumerable<PSBTHDKeyMatch> HDKeysFor(IHDScriptPubKey accountHDScriptPubKey, IHDKey accountKey, RootedKeyPath accountKeyPath = null) { if (accountKey == null) throw new ArgumentNullException(nameof(accountKey)); if (accountHDScriptPubKey == null) throw new ArgumentNullException(nameof(accountHDScriptPubKey)); accountHDScriptPubKey = accountHDScriptPubKey.AsHDKeyCache(); accountKey = accountKey.AsHDKeyCache(); return Inputs.HDKeysFor(accountHDScriptPubKey, accountKey, accountKeyPath).OfType<PSBTHDKeyMatch>().Concat(Outputs.HDKeysFor(accountHDScriptPubKey, accountKey, accountKeyPath)); } /// <summary> /// Filter the keys which contains the <paramref name="accountKey"/> and <paramref name="accountKeyPath"/>. /// </summary> /// <param name="accountKey">The account key that will be used to sign (ie. 49'/0'/0')</param> /// <param name="accountKeyPath">The account key path</param> /// <returns>HD Keys matching master root key</returns> public IEnumerable<PSBTHDKeyMatch> HDKeysFor(IHDKey accountKey, RootedKeyPath accountKeyPath = null) { if (accountKey == null) throw new ArgumentNullException(nameof(accountKey)); accountKey = accountKey.AsHDKeyCache(); return Inputs.HDKeysFor(accountKey, accountKeyPath).OfType<PSBTHDKeyMatch>().Concat(Outputs.HDKeysFor(accountKey, accountKeyPath)); } /// <summary> /// Add keypath information to this PSBT for each input or output involving it /// </summary> /// <param name="masterKey">The master key of the keypaths</param> /// <param name="paths">The path of the public keys</param> /// <returns>This PSBT</returns> public PSBT AddKeyPath(IHDKey masterKey, params KeyPath[] paths) { return AddKeyPath(masterKey, paths.Select(p => Tuple.Create(p, null as Script)).ToArray()); } /// <summary> /// Add keypath information to this PSBT for each input or output involving it /// </summary> /// <param name="masterKey">The master key of the keypaths</param> /// <param name="paths">The path of the public keys with their expected scriptPubKey</param> /// <returns>This PSBT</returns> public PSBT AddKeyPath(IHDKey masterKey, params Tuple<KeyPath, Script>[] paths) { if (masterKey == null) throw new ArgumentNullException(nameof(masterKey)); if (paths == null) throw new ArgumentNullException(nameof(paths)); masterKey = masterKey.AsHDKeyCache(); var masterKeyFP = masterKey.GetPublicKey().GetHDFingerPrint(); foreach (var path in paths) { var key = masterKey.Derive(path.Item1); AddKeyPath(key.GetPublicKey(), new RootedKeyPath(masterKeyFP, path.Item1), path.Item2); } return this; } /// <summary> /// Add keypath information to this PSBT for each input or output involving it /// </summary> /// <param name="pubkey">The public key which need to sign</param> /// <param name="rootedKeyPath">The keypath to this public key</param> /// <returns>This PSBT</returns> public PSBT AddKeyPath(PubKey pubkey, RootedKeyPath rootedKeyPath) { return AddKeyPath(pubkey, rootedKeyPath, null); } /// <summary> /// Add keypath information to this PSBT, if the PSBT all finalized this operation is a no-op /// </summary> /// <param name="pubkey">The public key which need to sign</param> /// <param name="rootedKeyPath">The keypath to this public key</param> /// <param name="scriptPubKey">A specific scriptPubKey this pubkey is involved with</param> /// <returns>This PSBT</returns> public PSBT AddKeyPath(PubKey pubkey, RootedKeyPath rootedKeyPath, Script scriptPubKey) { if (pubkey == null) throw new ArgumentNullException(nameof(pubkey)); if (rootedKeyPath == null) throw new ArgumentNullException(nameof(rootedKeyPath)); if (IsAllFinalized()) return this; var txBuilder = CreateTransactionBuilder(); foreach (var o in this.Inputs.OfType<PSBTCoin>().Concat(this.Outputs)) { if (o is PSBTInput i && i.IsFinalized()) continue; var coin = o.GetCoin(); if (coin == null) continue; if ((scriptPubKey != null && coin.ScriptPubKey == scriptPubKey) || ((o.GetSignableCoin() ?? coin.TryToScriptCoin(pubkey)) is Coin c && txBuilder.IsCompatibleKeyFromScriptCode(pubkey, c.GetScriptCode())) || txBuilder.IsCompatibleKeyFromScriptCode(pubkey, coin.ScriptPubKey)) { o.AddKeyPath(pubkey, rootedKeyPath); } } return this; } /// <summary> /// Rebase the keypaths. /// If a PSBT updater only know the child HD public key but not the root one, another updater knowing the parent master key it is based on /// can rebase the paths. If the PSBT is all finalized this operation is a no-op /// </summary> /// <param name="accountKey">The current account key</param> /// <param name="newRoot">The KeyPath with the fingerprint of the new root key</param> /// <returns>This PSBT</returns> public PSBT RebaseKeyPaths(IHDKey accountKey, RootedKeyPath newRoot) { if (accountKey == null) throw new ArgumentNullException(nameof(accountKey)); if (newRoot == null) throw new ArgumentNullException(nameof(newRoot)); if (IsAllFinalized()) return this; accountKey = accountKey.AsHDKeyCache(); var accountKeyFP = accountKey.GetPublicKey().GetHDFingerPrint(); foreach (var o in HDKeysFor(accountKey).GroupBy(c => c.Coin)) { if (o.Key is PSBTInput i && i.IsFinalized()) continue; foreach (var keyPath in o) { if (keyPath.RootedKeyPath.MasterFingerprint != newRoot.MasterFingerprint) { o.Key.HDKeyPaths.Remove(keyPath.PubKey); o.Key.HDKeyPaths.Add(keyPath.PubKey, newRoot.Derive(keyPath.RootedKeyPath.KeyPath)); } } } foreach (var xpub in GlobalXPubs.ToList()) { if (xpub.Key.ExtPubKey.PubKey == accountKey.GetPublicKey()) { if (xpub.Value.MasterFingerprint != newRoot.MasterFingerprint) { GlobalXPubs.Remove(xpub.Key); GlobalXPubs.Add(xpub.Key, newRoot.Derive(xpub.Value.KeyPath)); } } } return this; } public Transaction GetOriginalTransaction() { var clone = tx.Clone(); for (int i = 0; i < Inputs.Count; i++) { clone.Inputs[i].ScriptSig = Inputs[i].originalScriptSig; clone.Inputs[i].WitScript = Inputs[i].originalWitScript; } return clone; } public Transaction GetGlobalTransaction() { return tx.Clone(); } } }
32.89533
191
0.690523
[ "MIT" ]
Soho-Rab/NBitcoin
NBitcoin/BIP174/PartiallySignedTransaction.cs
40,856
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; using System.Collections.Generic; using System.Collections.Immutable; using System.IO; using System.Linq; using System.Reflection.PortableExecutable; using System.Xml.Linq; using Microsoft.CodeAnalysis.CodeGen; using Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.Operations; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Test.Utilities { public enum Verification { Passes = 0, Fails, Skipped } /// <summary> /// Base class for all language specific tests. /// </summary> public abstract partial class CommonTestBase : TestBase { #region Emit internal CompilationVerifier CompileAndVerifyCommon( Compilation compilation, IEnumerable<ResourceDescription> manifestResources = null, IEnumerable<ModuleData> dependencies = null, Action<IModuleSymbol> sourceSymbolValidator = null, Action<PEAssembly> assemblyValidator = null, Action<IModuleSymbol> symbolValidator = null, SignatureDescription[] expectedSignatures = null, string expectedOutput = null, int? expectedReturnCode = null, string[] args = null, EmitOptions emitOptions = null, Verification verify = Verification.Passes) { Assert.NotNull(compilation); Assert.True(expectedOutput == null || (compilation.Options.OutputKind == OutputKind.ConsoleApplication || compilation.Options.OutputKind == OutputKind.WindowsApplication), "Compilation must be executable if output is expected."); if (sourceSymbolValidator != null) { var module = compilation.Assembly.Modules.First(); sourceSymbolValidator(module); } CompilationVerifier result = null; var verifier = Emit(compilation, dependencies, manifestResources, expectedSignatures, expectedOutput, expectedReturnCode, args ?? Array.Empty<string>(), assemblyValidator, symbolValidator, emitOptions, verify); if (result == null) { result = verifier; } else { // only one emitter should return a verifier Assert.Null(verifier); } // If this fails, it means that more that all emitters failed to return a validator // (i.e. none thought that they were applicable for the given input parameters). Assert.NotNull(result); return result; } internal CompilationVerifier CompileAndVerifyFieldMarshalCommon(Compilation compilation, Dictionary<string, byte[]> expectedBlobs, bool isField = true) { return CompileAndVerifyFieldMarshalCommon( compilation, (s, _omitted1) => { Assert.True(expectedBlobs.ContainsKey(s), "Expecting marshalling blob for " + (isField ? "field " : "parameter ") + s); return expectedBlobs[s]; }, isField); } internal CompilationVerifier CompileAndVerifyFieldMarshalCommon(Compilation compilation, Func<string, PEAssembly, byte[]> getExpectedBlob, bool isField = true) { return CompileAndVerifyCommon(compilation, assemblyValidator: (assembly) => MetadataValidation.MarshalAsMetadataValidator(assembly, getExpectedBlob, isField)); } static internal void RunValidators(CompilationVerifier verifier, Action<PEAssembly> assemblyValidator, Action<IModuleSymbol> symbolValidator) { Assert.True(assemblyValidator != null || symbolValidator != null); var emittedMetadata = verifier.GetMetadata(); if (assemblyValidator != null) { Assert.Equal(MetadataImageKind.Assembly, emittedMetadata.Kind); var assembly = ((AssemblyMetadata)emittedMetadata).GetAssembly(); assemblyValidator(assembly); } if (symbolValidator != null) { var reference = emittedMetadata.Kind == MetadataImageKind.Assembly ? ((AssemblyMetadata)emittedMetadata).GetReference() : ((ModuleMetadata)emittedMetadata).GetReference(); var moduleSymbol = verifier.GetSymbolFromMetadata(reference, verifier.Compilation.Options.MetadataImportOptions); symbolValidator(moduleSymbol); } } internal CompilationVerifier Emit( Compilation compilation, IEnumerable<ModuleData> dependencies, IEnumerable<ResourceDescription> manifestResources, SignatureDescription[] expectedSignatures, string expectedOutput, int? expectedReturnCode, string[] args, Action<PEAssembly> assemblyValidator, Action<IModuleSymbol> symbolValidator, EmitOptions emitOptions, Verification verify) { var verifier = new CompilationVerifier(compilation, VisualizeRealIL, dependencies); verifier.Emit(expectedOutput, expectedReturnCode, args, manifestResources, emitOptions, verify, expectedSignatures); if (assemblyValidator != null || symbolValidator != null) { // We're dual-purposing emitters here. In this context, it // tells the validator the version of Emit that is calling it. RunValidators(verifier, assemblyValidator, symbolValidator); } return verifier; } /// <summary> /// Reads content of the specified file. /// </summary> /// <param name="path">The path to the file.</param> /// <returns>Read-only binary data read from the file.</returns> public static ImmutableArray<byte> ReadFromFile(string path) { return ImmutableArray.Create<byte>(File.ReadAllBytes(path)); } internal static void EmitILToArray( string ilSource, bool appendDefaultHeader, bool includePdb, out ImmutableArray<byte> assemblyBytes, out ImmutableArray<byte> pdbBytes, bool autoInherit = true) { IlasmUtilities.IlasmTempAssembly(ilSource, appendDefaultHeader, includePdb, autoInherit, out var assemblyPath, out var pdbPath); Assert.NotNull(assemblyPath); Assert.Equal(pdbPath != null, includePdb); using (new DisposableFile(assemblyPath)) { assemblyBytes = ReadFromFile(assemblyPath); } if (pdbPath != null) { using (new DisposableFile(pdbPath)) { pdbBytes = ReadFromFile(pdbPath); } } else { pdbBytes = default(ImmutableArray<byte>); } } internal static MetadataReference CompileIL(string ilSource, bool prependDefaultHeader = true, bool embedInteropTypes = false, bool autoInherit = true) { EmitILToArray(ilSource, prependDefaultHeader, includePdb: false, assemblyBytes: out var assemblyBytes, pdbBytes: out var pdbBytes, autoInherit: autoInherit); return AssemblyMetadata.CreateFromImage(assemblyBytes).GetReference(embedInteropTypes: embedInteropTypes); } internal static MetadataReference GetILModuleReference(string ilSource, bool prependDefaultHeader = true) { EmitILToArray(ilSource, prependDefaultHeader, includePdb: false, assemblyBytes: out var assemblyBytes, pdbBytes: out var pdbBytes); return ModuleMetadata.CreateFromImage(assemblyBytes).GetReference(); } #endregion #region Compilation Creation Helpers protected CSharp.CSharpCompilation CreateCSharpCompilation( XCData code, CSharp.CSharpParseOptions parseOptions = null, CSharp.CSharpCompilationOptions compilationOptions = null, string assemblyName = null, IEnumerable<MetadataReference> referencedAssemblies = null) { return CreateCSharpCompilation(assemblyName, code, parseOptions, compilationOptions, referencedAssemblies, referencedCompilations: null); } protected CSharp.CSharpCompilation CreateCSharpCompilation( string assemblyName, XCData code, CSharp.CSharpParseOptions parseOptions = null, CSharp.CSharpCompilationOptions compilationOptions = null, IEnumerable<MetadataReference> referencedAssemblies = null, IEnumerable<Compilation> referencedCompilations = null) { return CreateCSharpCompilation( assemblyName, code.Value, parseOptions, compilationOptions, referencedAssemblies, referencedCompilations); } protected CSharp.CSharpCompilation CreateCSharpCompilation( string code, CSharp.CSharpParseOptions parseOptions = null, CSharp.CSharpCompilationOptions compilationOptions = null, string assemblyName = null, IEnumerable<MetadataReference> referencedAssemblies = null) { return CreateCSharpCompilation(assemblyName, code, parseOptions, compilationOptions, referencedAssemblies, referencedCompilations: null); } protected CSharp.CSharpCompilation CreateCSharpCompilation( string assemblyName, string code, CSharp.CSharpParseOptions parseOptions = null, CSharp.CSharpCompilationOptions compilationOptions = null, IEnumerable<MetadataReference> referencedAssemblies = null, IEnumerable<Compilation> referencedCompilations = null) { if (assemblyName == null) { assemblyName = GetUniqueName(); } if (parseOptions == null) { parseOptions = CSharp.CSharpParseOptions.Default.WithLanguageVersion(CSharp.LanguageVersion.Default).WithDocumentationMode(DocumentationMode.None); } if (compilationOptions == null) { compilationOptions = new CSharp.CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary); } var references = new List<MetadataReference>(); if (referencedAssemblies == null) { references.Add(MscorlibRef); references.Add(SystemRef); references.Add(SystemCoreRef); //TODO: references.Add(MsCSRef); references.Add(SystemXmlRef); references.Add(SystemXmlLinqRef); } else { references.AddRange(referencedAssemblies); } AddReferencedCompilations(referencedCompilations, references); var tree = CSharp.SyntaxFactory.ParseSyntaxTree(code, options: parseOptions); return CSharp.CSharpCompilation.Create(assemblyName, new[] { tree }, references, compilationOptions); } private void AddReferencedCompilations(IEnumerable<Compilation> referencedCompilations, List<MetadataReference> references) { if (referencedCompilations != null) { foreach (var referencedCompilation in referencedCompilations) { references.Add(referencedCompilation.EmitToImageReference()); } } } public static string WithWindowsLineBreaks(string source) => source.Replace(Environment.NewLine, "\r\n"); #endregion #region IL Verification internal abstract string VisualizeRealIL(IModuleSymbol peModule, CompilationTestData.MethodData methodData, IReadOnlyDictionary<int, string> markers, bool areLocalsZeroed); #endregion #region Other Helpers internal static Cci.ModulePropertiesForSerialization GetDefaultModulePropertiesForSerialization() { return new Cci.ModulePropertiesForSerialization( persistentIdentifier: default(Guid), corFlags: CorFlags.ILOnly, fileAlignment: Cci.ModulePropertiesForSerialization.DefaultFileAlignment32Bit, sectionAlignment: Cci.ModulePropertiesForSerialization.DefaultSectionAlignment, targetRuntimeVersion: "v4.0.30319", machine: 0, baseAddress: Cci.ModulePropertiesForSerialization.DefaultExeBaseAddress32Bit, sizeOfHeapReserve: Cci.ModulePropertiesForSerialization.DefaultSizeOfHeapReserve32Bit, sizeOfHeapCommit: Cci.ModulePropertiesForSerialization.DefaultSizeOfHeapCommit32Bit, sizeOfStackReserve: Cci.ModulePropertiesForSerialization.DefaultSizeOfStackReserve32Bit, sizeOfStackCommit: Cci.ModulePropertiesForSerialization.DefaultSizeOfStackCommit32Bit, dllCharacteristics: Compilation.GetDllCharacteristics(enableHighEntropyVA: true, configureToExecuteInAppContainer: false), subsystem: Subsystem.WindowsCui, imageCharacteristics: Characteristics.Dll, majorSubsystemVersion: 0, minorSubsystemVersion: 0, linkerMajorVersion: 0, linkerMinorVersion: 0); } internal void AssertDeclaresType(PEModuleSymbol peModule, WellKnownType type, Accessibility expectedAccessibility) { var name = MetadataTypeName.FromFullName(type.GetMetadataName()); Assert.Equal(expectedAccessibility, peModule.LookupTopLevelMetadataType(ref name).DeclaredAccessibility); } #endregion #region Metadata Validation /// <summary> /// Creates instance of SignatureDescription for a specified member /// </summary> /// <param name="fullyQualifiedTypeName"> /// Fully qualified type name for member /// Names must be in format recognized by reflection /// e.g. MyType{T}.MyNestedType{T, U} => MyType`1+MyNestedType`2 /// </param> /// <param name="memberName"> /// Name of member on specified type whose signature needs to be verified /// Names must be in format recognized by reflection /// e.g. For explicitly implemented member - I1{string}.Method => I1{System.String}.Method /// </param> /// <param name="expectedSignature"> /// Baseline string for signature of specified member /// Skip this argument to get an error message that shows all available signatures for specified member /// </param> /// <returns>Instance of SignatureDescription for specified member</returns> internal static SignatureDescription Signature(string fullyQualifiedTypeName, string memberName, string expectedSignature = "") { return new SignatureDescription() { FullyQualifiedTypeName = fullyQualifiedTypeName, MemberName = memberName, ExpectedSignature = expectedSignature }; } #endregion #region Operation Test Helpers internal static void VerifyParentOperations(SemanticModel model) { var parentMap = GetParentOperationsMap(model); // check parent for each child foreach (var (child, parent) in parentMap) { // check parent property returns same parent we gathered by walking down operation tree Assert.Equal(child.Parent, parent); // check SearchparentOperation return same parent Assert.Equal(((Operation)child).SearchParentOperation(), parent); if (parent == null) { // this is root of operation tree VerifyOperationTreeContracts(child); } } } private static Dictionary<IOperation, IOperation> GetParentOperationsMap(SemanticModel model) { // get top operations first var topOperations = new HashSet<IOperation>(); var root = model.SyntaxTree.GetRoot(); CollectTopOperations(model, root, topOperations); // dig down the each operation tree to create the parent operation map var map = new Dictionary<IOperation, IOperation>(); foreach (var topOperation in topOperations) { // this is top of the operation tree map.Add(topOperation, null); CollectParentOperations(topOperation, map); } return map; } private static void CollectParentOperations(IOperation operation, Dictionary<IOperation, IOperation> map) { // walk down to collect all parent operation map for this tree foreach (var child in operation.Children.WhereNotNull()) { map.Add(child, operation); CollectParentOperations(child, map); } } private static void CollectTopOperations(SemanticModel model, SyntaxNode node, HashSet<IOperation> topOperations) { foreach (var child in node.ChildNodes()) { var operation = model.GetOperation(child); if (operation != null) { // found top operation topOperations.Add(operation); // don't dig down anymore continue; } // sub tree might have the top operation CollectTopOperations(model, child, topOperations); } } internal static void VerifyClone(SemanticModel model) { foreach (var node in model.SyntaxTree.GetRoot().DescendantNodes()) { var operation = model.GetOperation(node); if (operation == null) { continue; } var clonedOperation = OperationCloner.CloneOperation(operation); Assert.Same(model, operation.SemanticModel); Assert.Same(model, clonedOperation.SemanticModel); Assert.NotSame(model, ((Operation)operation).OwningSemanticModel); Assert.Same(((Operation)operation).OwningSemanticModel, ((Operation)clonedOperation).OwningSemanticModel); // check whether cloned IOperation is same as original one var original = OperationTreeVerifier.GetOperationTree(model.Compilation, operation); var cloned = OperationTreeVerifier.GetOperationTree(model.Compilation, clonedOperation); Assert.Equal(original, cloned); // make sure cloned operation is value equal but doesn't share any IOperations var originalSet = new HashSet<IOperation>(operation.DescendantsAndSelf()); var clonedSet = new HashSet<IOperation>(clonedOperation.DescendantsAndSelf()); Assert.Equal(originalSet.Count, clonedSet.Count); Assert.Equal(0, originalSet.Intersect(clonedSet).Count()); } } private static void VerifyOperationTreeContracts(IOperation root) { var semanticModel = ((Operation)root).OwningSemanticModel; var set = new HashSet<IOperation>(root.DescendantsAndSelf()); foreach (var child in root.DescendantsAndSelf()) { // all operations from spine should belong to the operation tree set VerifyOperationTreeSpine(semanticModel, set, child.Syntax); // operation tree's node must be part of root of semantic model which is // owner of operation's lifetime Assert.True(semanticModel.Root.FullSpan.Contains(child.Syntax.FullSpan)); } } private static void VerifyOperationTreeSpine( SemanticModel semanticModel, HashSet<IOperation> set, SyntaxNode node) { while (node != semanticModel.Root) { var operation = semanticModel.GetOperation(node); if (operation != null) { Assert.True(set.Contains(operation)); } node = node.Parent; } } #endregion #region Theory Helpers public static IEnumerable<object[]> ExternalPdbFormats { get { if (ExecutionConditionUtil.IsWindows) { return new List<object[]>() { new object[] { DebugInformationFormat.Pdb }, new object[] { DebugInformationFormat.PortablePdb } }; } else { return new List<object[]>() { new object[] { DebugInformationFormat.PortablePdb } }; } } } public static IEnumerable<object[]> PdbFormats => new List<object[]>(ExternalPdbFormats) { new object[] { DebugInformationFormat.Embedded } }; #endregion } }
40.182469
180
0.601905
[ "MIT" ]
nikitaodnorob/pl-roslyn
src/Test/Utilities/Portable/CommonTestBase.cs
22,464
C#
/* Copyright (c) 2017, Nokia 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 the copyright holder 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. */ using System; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using Newtonsoft.Json.Converters; using net.nuagenetworks.bambou; using net.nuagenetworks.vspk.v6.fetchers; namespace net.nuagenetworks.vspk.v6 { public class NetconfManager: RestObject { private const long serialVersionUID = 1L; public enum EEntityScope {ENTERPRISE,GLOBAL }; public enum EStatus {CONNECTED,DISCONNECTED,INIT,JMS_DISCONNECTED }; [JsonProperty("assocEntityType")] protected String _assocEntityType; [JsonProperty("creationDate")] protected String _creationDate; [JsonProperty("embeddedMetadata")] protected System.Collections.Generic.List<Metadata> _embeddedMetadata; [JsonConverter(typeof(StringEnumConverter))] [JsonProperty("entityScope")] protected EEntityScope? _entityScope; [JsonProperty("eventProcessingEnabled")] protected bool _eventProcessingEnabled; [JsonProperty("externalID")] protected String _externalID; [JsonProperty("lastUpdatedBy")] protected String _lastUpdatedBy; [JsonProperty("lastUpdatedDate")] protected String _lastUpdatedDate; [JsonProperty("name")] protected String _name; [JsonProperty("owner")] protected String _owner; [JsonProperty("release")] protected String _release; [JsonConverter(typeof(StringEnumConverter))] [JsonProperty("status")] protected EStatus? _status; [JsonIgnore] private AlarmsFetcher _alarms; [JsonIgnore] private GlobalMetadatasFetcher _globalMetadatas; [JsonIgnore] private GNMISessionsFetcher _gNMISessions; [JsonIgnore] private MetadatasFetcher _metadatas; [JsonIgnore] private NetconfSessionsFetcher _netconfSessions; [JsonIgnore] private PermissionsFetcher _permissions; public NetconfManager() { _alarms = new AlarmsFetcher(this); _globalMetadatas = new GlobalMetadatasFetcher(this); _gNMISessions = new GNMISessionsFetcher(this); _metadatas = new MetadatasFetcher(this); _netconfSessions = new NetconfSessionsFetcher(this); _permissions = new PermissionsFetcher(this); } [JsonIgnore] public String NUAssocEntityType { get { return _assocEntityType; } set { this._assocEntityType = value; } } [JsonIgnore] public String NUCreationDate { get { return _creationDate; } set { this._creationDate = value; } } [JsonIgnore] public System.Collections.Generic.List<Metadata> NUEmbeddedMetadata { get { return _embeddedMetadata; } set { this._embeddedMetadata = value; } } [JsonIgnore] public EEntityScope? NUEntityScope { get { return _entityScope; } set { this._entityScope = value; } } [JsonIgnore] public bool NUEventProcessingEnabled { get { return _eventProcessingEnabled; } set { this._eventProcessingEnabled = value; } } [JsonIgnore] public String NUExternalID { get { return _externalID; } set { this._externalID = value; } } [JsonIgnore] public String NULastUpdatedBy { get { return _lastUpdatedBy; } set { this._lastUpdatedBy = value; } } [JsonIgnore] public String NULastUpdatedDate { get { return _lastUpdatedDate; } set { this._lastUpdatedDate = value; } } [JsonIgnore] public String NUName { get { return _name; } set { this._name = value; } } [JsonIgnore] public String NUOwner { get { return _owner; } set { this._owner = value; } } [JsonIgnore] public String NURelease { get { return _release; } set { this._release = value; } } [JsonIgnore] public EStatus? NUStatus { get { return _status; } set { this._status = value; } } public AlarmsFetcher getAlarms() { return _alarms; } public GlobalMetadatasFetcher getGlobalMetadatas() { return _globalMetadatas; } public GNMISessionsFetcher getGNMISessions() { return _gNMISessions; } public MetadatasFetcher getMetadatas() { return _metadatas; } public NetconfSessionsFetcher getNetconfSessions() { return _netconfSessions; } public PermissionsFetcher getPermissions() { return _permissions; } public String toString() { return "NetconfManager [" + "assocEntityType=" + _assocEntityType + ", creationDate=" + _creationDate + ", embeddedMetadata=" + _embeddedMetadata + ", entityScope=" + _entityScope + ", eventProcessingEnabled=" + _eventProcessingEnabled + ", externalID=" + _externalID + ", lastUpdatedBy=" + _lastUpdatedBy + ", lastUpdatedDate=" + _lastUpdatedDate + ", name=" + _name + ", owner=" + _owner + ", release=" + _release + ", status=" + _status + ", id=" + NUId + ", parentId=" + NUParentId + ", parentType=" + NUParentType + "]"; } public static String getResourceName() { return "netconfmanagers"; } public static String getRestName() { return "netconfmanager"; } } }
23.781145
532
0.653547
[ "BSD-3-Clause" ]
nuagenetworks/vspk-csharp
vspk/vspk/NetconfManager.cs
7,063
C#
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gcrv = Google.Cloud.RecommendationEngine.V1Beta1; namespace Google.Cloud.RecommendationEngine.V1Beta1 { public partial class PredictRequest { /// <summary> /// <see cref="gcrv::PlacementName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gcrv::PlacementName PlacementName { get => string.IsNullOrEmpty(Name) ? null : gcrv::PlacementName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } } }
35.454545
108
0.684615
[ "Apache-2.0" ]
Mattlk13/google-cloud-dotnet
apis/Google.Cloud.RecommendationEngine.V1Beta1/Google.Cloud.RecommendationEngine.V1Beta1/PredictionServiceResourceNames.g.cs
1,170
C#
using System; namespace NSubstitute.Core { class ParameterInfoFromType : IParameterInfo { private readonly Type _parameterType; public ParameterInfoFromType(Type parameterType) { _parameterType = parameterType; } public Type ParameterType { get { return _parameterType; } } public bool IsParams { get { return false; } } public bool IsOptional { get { return false; } } public bool IsOut { get { return false; } } } }
18.352941
56
0.512821
[ "BSD-3-Clause" ]
Erwinvandervalk/NSubstitute
Source/NSubstitute/Core/ParameterInfoFromType.cs
626
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 Microsoft.Win32.SafeHandles; using System.ComponentModel; using System.Diagnostics; using System.Runtime.InteropServices; namespace System.Security.Principal { [Flags] internal enum PolicyRights { POLICY_VIEW_LOCAL_INFORMATION = 0x00000001, POLICY_VIEW_AUDIT_INFORMATION = 0x00000002, POLICY_GET_PRIVATE_INFORMATION = 0x00000004, POLICY_TRUST_ADMIN = 0x00000008, POLICY_CREATE_ACCOUNT = 0x00000010, POLICY_CREATE_SECRET = 0x00000020, POLICY_CREATE_PRIVILEGE = 0x00000040, POLICY_SET_DEFAULT_QUOTA_LIMITS = 0x00000080, POLICY_SET_AUDIT_REQUIREMENTS = 0x00000100, POLICY_AUDIT_LOG_ADMIN = 0x00000200, POLICY_SERVER_ADMIN = 0x00000400, POLICY_LOOKUP_NAMES = 0x00000800, POLICY_NOTIFICATION = 0x00001000, } internal static class Win32 { internal const int FALSE = 0; // // Wrapper around advapi32.LsaOpenPolicy // internal static SafeLsaPolicyHandle LsaOpenPolicy( string systemName, PolicyRights rights) { SafeLsaPolicyHandle policyHandle; Interop.OBJECT_ATTRIBUTES attributes = default; uint error = Interop.Advapi32.LsaOpenPolicy(systemName, ref attributes, (int)rights, out policyHandle); if (error == 0) { return policyHandle; } else if (error == Interop.StatusOptions.STATUS_ACCESS_DENIED) { throw new UnauthorizedAccessException(); } else if (error == Interop.StatusOptions.STATUS_INSUFFICIENT_RESOURCES || error == Interop.StatusOptions.STATUS_NO_MEMORY) { throw new OutOfMemoryException(); } else { uint win32ErrorCode = Interop.Advapi32.LsaNtStatusToWinError(error); throw new Win32Exception(unchecked((int)win32ErrorCode)); } } internal static byte[] ConvertIntPtrSidToByteArraySid(IntPtr binaryForm) { byte[] ResultSid; // // Verify the revision (just sanity, should never fail to be 1) // byte Revision = Marshal.ReadByte(binaryForm, 0); if (Revision != SecurityIdentifier.Revision) { throw new ArgumentException(SR.IdentityReference_InvalidSidRevision, nameof(binaryForm)); } // // Need the subauthority count in order to figure out how many bytes to read // byte SubAuthorityCount = Marshal.ReadByte(binaryForm, 1); if (SubAuthorityCount < 0 || SubAuthorityCount > SecurityIdentifier.MaxSubAuthorities) { throw new ArgumentException(SR.Format(SR.IdentityReference_InvalidNumberOfSubauthorities, SecurityIdentifier.MaxSubAuthorities), nameof(binaryForm)); } // // Compute the size of the binary form of this SID and allocate the memory // int BinaryLength = 1 + 1 + 6 + SubAuthorityCount * 4; ResultSid = new byte[BinaryLength]; // // Extract the data from the returned pointer // Marshal.Copy(binaryForm, ResultSid, 0, BinaryLength); return ResultSid; } // // Wrapper around advapi32.ConvertStringSidToSidW // internal static int CreateSidFromString( string stringSid, out byte[] resultSid ) { int ErrorCode; IntPtr ByteArray = IntPtr.Zero; try { if (FALSE == Interop.Advapi32.ConvertStringSidToSid(stringSid, out ByteArray)) { ErrorCode = Marshal.GetLastWin32Error(); goto Error; } resultSid = ConvertIntPtrSidToByteArraySid(ByteArray); } finally { // // Now is a good time to get rid of the returned pointer // Interop.Kernel32.LocalFree(ByteArray); } // // Now invoke the SecurityIdentifier factory method to create the result // return Interop.Errors.ERROR_SUCCESS; Error: resultSid = null; return ErrorCode; } // // Wrapper around advapi32.CreateWellKnownSid // internal static int CreateWellKnownSid( WellKnownSidType sidType, SecurityIdentifier domainSid, out byte[] resultSid ) { // // Passing an array as big as it can ever be is a small price to pay for // not having to P/Invoke twice (once to get the buffer, once to get the data) // uint length = (uint)SecurityIdentifier.MaxBinaryLength; resultSid = new byte[length]; if (FALSE != Interop.Advapi32.CreateWellKnownSid((int)sidType, domainSid == null ? null : domainSid.BinaryForm, resultSid, ref length)) { return Interop.Errors.ERROR_SUCCESS; } else { resultSid = null; return Marshal.GetLastWin32Error(); } } // // Wrapper around advapi32.EqualDomainSid // internal static bool IsEqualDomainSid(SecurityIdentifier sid1, SecurityIdentifier sid2) { if (sid1 == null || sid2 == null) { return false; } else { bool result; byte[] BinaryForm1 = new byte[sid1.BinaryLength]; sid1.GetBinaryForm(BinaryForm1, 0); byte[] BinaryForm2 = new byte[sid2.BinaryLength]; sid2.GetBinaryForm(BinaryForm2, 0); return (Interop.Advapi32.IsEqualDomainSid(BinaryForm1, BinaryForm2, out result) == FALSE ? false : result); } } /// <summary> /// Setup the size of the buffer Windows provides for an LSA_REFERENCED_DOMAIN_LIST /// </summary> internal static void InitializeReferencedDomainsPointer(SafeLsaMemoryHandle referencedDomains) { Debug.Assert(referencedDomains != null, "referencedDomains != null"); // We don't know the real size of the referenced domains yet, so we need to set an initial // size based on the LSA_REFERENCED_DOMAIN_LIST structure, then resize it to include all of // the domains. referencedDomains.Initialize((uint)Marshal.SizeOf<Interop.LSA_REFERENCED_DOMAIN_LIST>()); Interop.LSA_REFERENCED_DOMAIN_LIST domainList = referencedDomains.Read<Interop.LSA_REFERENCED_DOMAIN_LIST>(0); unsafe { byte* pRdl = null; try { referencedDomains.AcquirePointer(ref pRdl); // If there is a trust information list, then the buffer size is the end of that list minus // the beginning of the domain list. Otherwise, then the buffer is just the size of the // referenced domain list structure, which is what we defaulted to. if (domainList.Domains != IntPtr.Zero) { Interop.LSA_TRUST_INFORMATION* pTrustInformation = (Interop.LSA_TRUST_INFORMATION*)domainList.Domains; pTrustInformation = pTrustInformation + domainList.Entries; long bufferSize = (byte*)pTrustInformation - pRdl; Debug.Assert(bufferSize > 0, "bufferSize > 0"); referencedDomains.Initialize((ulong)bufferSize); } } finally { if (pRdl != null) referencedDomains.ReleasePointer(); } } } // // Wrapper around avdapi32.GetWindowsAccountDomainSid // internal static int GetWindowsAccountDomainSid( SecurityIdentifier sid, out SecurityIdentifier resultSid ) { // // Passing an array as big as it can ever be is a small price to pay for // not having to P/Invoke twice (once to get the buffer, once to get the data) // byte[] BinaryForm = new byte[sid.BinaryLength]; sid.GetBinaryForm(BinaryForm, 0); uint sidLength = (uint)SecurityIdentifier.MaxBinaryLength; byte[] resultSidBinary = new byte[sidLength]; if (FALSE != Interop.Advapi32.GetWindowsAccountDomainSid(BinaryForm, resultSidBinary, ref sidLength)) { resultSid = new SecurityIdentifier(resultSidBinary, 0); return Interop.Errors.ERROR_SUCCESS; } else { resultSid = null; return Marshal.GetLastWin32Error(); } } // // Wrapper around advapi32.IsWellKnownSid // internal static bool IsWellKnownSid( SecurityIdentifier sid, WellKnownSidType type ) { byte[] BinaryForm = new byte[sid.BinaryLength]; sid.GetBinaryForm(BinaryForm, 0); if (FALSE == Interop.Advapi32.IsWellKnownSid(BinaryForm, (int)type)) { return false; } else { return true; } } } }
32.6
165
0.555808
[ "MIT" ]
AArnott/runtime
src/libraries/System.Security.Principal.Windows/src/System/Security/Principal/Win32.cs
10,106
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 wafv2-2019-07-29.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using System.Net; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.WAFV2.Model { /// <summary> /// A custom response to send to the client. You can define a custom response for rule /// actions and default web ACL actions that are set to <a>BlockAction</a>. /// /// /// <para> /// For information about customizing web requests and responses, see <a href="https://docs.aws.amazon.com/waf/latest/developerguide/waf-custom-request-response.html">Customizing /// web requests and responses in WAF</a> in the <a href="https://docs.aws.amazon.com/waf/latest/developerguide/waf-chapter.html">WAF /// Developer Guide</a>. /// </para> /// </summary> public partial class CustomResponse { private string _customResponseBodyKey; private int? _responseCode; private List<CustomHTTPHeader> _responseHeaders = new List<CustomHTTPHeader>(); /// <summary> /// Gets and sets the property CustomResponseBodyKey. /// <para> /// References the response body that you want WAF to return to the web request client. /// You can define a custom response for a rule action or a default web ACL action that /// is set to block. To do this, you first define the response body key and value in the /// <code>CustomResponseBodies</code> setting for the <a>WebACL</a> or <a>RuleGroup</a> /// where you want to use it. Then, in the rule action or web ACL default action <code>BlockAction</code> /// setting, you reference the response body using this key. /// </para> /// </summary> [AWSProperty(Min=1, Max=128)] public string CustomResponseBodyKey { get { return this._customResponseBodyKey; } set { this._customResponseBodyKey = value; } } // Check to see if CustomResponseBodyKey property is set internal bool IsSetCustomResponseBodyKey() { return this._customResponseBodyKey != null; } /// <summary> /// Gets and sets the property ResponseCode. /// <para> /// The HTTP status code to return to the client. /// </para> /// /// <para> /// For a list of status codes that you can use in your custom reqponses, see <a href="https://docs.aws.amazon.com/waf/latest/developerguide/customizing-the-response-status-codes.html">Supported /// status codes for custom response</a> in the <a href="https://docs.aws.amazon.com/waf/latest/developerguide/waf-chapter.html">WAF /// Developer Guide</a>. /// </para> /// </summary> [AWSProperty(Required=true, Min=200, Max=600)] public int ResponseCode { get { return this._responseCode.GetValueOrDefault(); } set { this._responseCode = value; } } // Check to see if ResponseCode property is set internal bool IsSetResponseCode() { return this._responseCode.HasValue; } /// <summary> /// Gets and sets the property ResponseHeaders. /// <para> /// The HTTP headers to use in the response. Duplicate header names are not allowed. /// </para> /// /// <para> /// For information about the limits on count and size for custom request and response /// settings, see <a href="https://docs.aws.amazon.com/waf/latest/developerguide/limits.html">WAF /// quotas</a> in the <a href="https://docs.aws.amazon.com/waf/latest/developerguide/waf-chapter.html">WAF /// Developer Guide</a>. /// </para> /// </summary> [AWSProperty(Min=1)] public List<CustomHTTPHeader> ResponseHeaders { get { return this._responseHeaders; } set { this._responseHeaders = value; } } // Check to see if ResponseHeaders property is set internal bool IsSetResponseHeaders() { return this._responseHeaders != null && this._responseHeaders.Count > 0; } } }
39.862903
202
0.632814
[ "Apache-2.0" ]
ChristopherButtars/aws-sdk-net
sdk/src/Services/WAFV2/Generated/Model/CustomResponse.cs
4,943
C#
using System; using System.Collections; using System.Runtime.InteropServices; using NUnit.Framework; using UnityEditor; using UnityEngine; using UnityEngine.TestTools; namespace Unity.WebRTC.RuntimeTest { [TestFixture, ConditionalIgnore("IgnoreHardwareEncoderTest", "Ignored hardware encoder test.")] class NativeAPITestWithHardwareEncoder : NativeAPITestWithSoftwareEncoder { [OneTimeSetUp] public new void OneTimeInit() { encoderType = EncoderType.Hardware; } } class NativeAPITestWithSoftwareEncoder { protected EncoderType encoderType; private static RenderTexture CreateRenderTexture(int width, int height) { var format = WebRTC.GetSupportedRenderTextureFormat(SystemInfo.graphicsDeviceType); var renderTexture = new RenderTexture(width, height, 0, format); renderTexture.Create(); return renderTexture; } [AOT.MonoPInvokeCallback(typeof(DelegateDebugLog))] protected static void DebugLog(string str) { Debug.Log(str); } [SetUp] public void Init() { NativeMethods.RegisterDebugLog(DebugLog); } [TearDown] public void CleanUp() { NativeMethods.RegisterDebugLog(null); } [OneTimeSetUp] public void OneTimeInit() { encoderType = EncoderType.Software; } [Test] public void CreateAndDestroyContext() { var context = NativeMethods.ContextCreate(0, encoderType); NativeMethods.ContextDestroy(0); } [Test] public void GetEncoderType() { var context = NativeMethods.ContextCreate(0, encoderType); Assert.AreEqual(encoderType, NativeMethods.ContextGetEncoderType(context)); NativeMethods.ContextDestroy(0); } [Test] public void CreateAndDeletePeerConnection() { var context = NativeMethods.ContextCreate(0, encoderType); var peer = NativeMethods.ContextCreatePeerConnection(context); NativeMethods.ContextDeletePeerConnection(context, peer); NativeMethods.ContextDestroy(0); } [AOT.MonoPInvokeCallback(typeof(DelegateNativePeerConnectionSetSessionDescSuccess))] static void PeerConnectionSetSessionDescSuccess(IntPtr connection) { } [AOT.MonoPInvokeCallback(typeof(DelegateNativePeerConnectionSetSessionDescFailure))] static void PeerConnectionSetSessionDescFailure(IntPtr connection, RTCError error) { } [Test] public void RegisterDelegateToPeerConnection() { var context = NativeMethods.ContextCreate(0, encoderType); var connection = NativeMethods.ContextCreatePeerConnection(context); NativeMethods.PeerConnectionRegisterOnSetSessionDescSuccess(context, connection, PeerConnectionSetSessionDescSuccess); NativeMethods.PeerConnectionRegisterOnSetSessionDescFailure(context, connection, PeerConnectionSetSessionDescFailure); NativeMethods.ContextDeletePeerConnection(context, connection); NativeMethods.ContextDestroy(0); } [Test] public void CreateAndDeleteDataChannel() { var context = NativeMethods.ContextCreate(0, encoderType); var peer = NativeMethods.ContextCreatePeerConnection(context); var init = new RTCDataChannelInit(true); var channel = NativeMethods.ContextCreateDataChannel(context, peer, "test", ref init); NativeMethods.ContextDeleteDataChannel(context, channel); NativeMethods.ContextDeletePeerConnection(context, peer); NativeMethods.ContextDestroy(0); } [Test] public void CreateAndDeleteMediaStream() { var context = NativeMethods.ContextCreate(0, encoderType); var stream = NativeMethods.ContextCreateMediaStream(context, "MediaStream"); NativeMethods.ContextDeleteMediaStream(context, stream); NativeMethods.ContextDestroy(0); } [AOT.MonoPInvokeCallback(typeof(DelegateNativeMediaStreamOnAddTrack))] static void MediaStreamOnAddTrack(IntPtr ptr, IntPtr track) { } [AOT.MonoPInvokeCallback(typeof(DelegateNativeMediaStreamOnRemoveTrack))] static void MediaStreamOnRemoveTrack(IntPtr ptr, IntPtr track) { } [Test] public void RegisterDelegateToMediaStream() { var context = NativeMethods.ContextCreate(0, encoderType); var stream = NativeMethods.ContextCreateMediaStream(context, "MediaStream"); NativeMethods.MediaStreamRegisterOnAddTrack(context, stream, MediaStreamOnAddTrack); NativeMethods.MediaStreamRegisterOnRemoveTrack(context, stream, MediaStreamOnRemoveTrack); NativeMethods.ContextDeleteMediaStream(context, stream); NativeMethods.ContextDestroy(0); } [Test] public void AddAndRemoveVideoTrackToPeerConnection() { var context = NativeMethods.ContextCreate(0, encoderType); var peer = NativeMethods.ContextCreatePeerConnection(context); var stream = NativeMethods.ContextCreateMediaStream(context, "MediaStream"); string streamId = NativeMethods.MediaStreamGetID(stream).AsAnsiStringWithFreeMem(); Assert.IsNotEmpty(streamId); const int width = 1280; const int height = 720; var renderTexture = CreateRenderTexture(width, height); var track = NativeMethods.ContextCreateVideoTrack(context, "video", renderTexture.GetNativeTexturePtr()); var sender = NativeMethods.PeerConnectionAddTrack(peer, track, streamId); NativeMethods.PeerConnectionRemoveTrack(peer, sender); NativeMethods.ContextDeleteMediaStreamTrack(context, track); NativeMethods.ContextDeleteMediaStream(context, stream); NativeMethods.ContextDeletePeerConnection(context, peer); NativeMethods.ContextDestroy(0); UnityEngine.Object.DestroyImmediate(renderTexture); } [Test] public void AddAndRemoveVideoTrackToMediaStream() { var context = NativeMethods.ContextCreate(0, encoderType); var stream = NativeMethods.ContextCreateMediaStream(context, "MediaStream"); const int width = 1280; const int height = 720; var renderTexture = CreateRenderTexture(width, height); var track = NativeMethods.ContextCreateVideoTrack(context, "video", renderTexture.GetNativeTexturePtr()); NativeMethods.MediaStreamAddTrack(stream, track); int trackSize = 0; var trackNativePtr = NativeMethods.MediaStreamGetVideoTracks(stream, ref trackSize); Assert.AreNotEqual(trackNativePtr, IntPtr.Zero); Assert.Greater(trackSize, 0); IntPtr[] tracksPtr = new IntPtr[trackSize]; Marshal.Copy(trackNativePtr, tracksPtr, 0, trackSize); Marshal.FreeCoTaskMem(trackNativePtr); NativeMethods.MediaStreamRemoveTrack(stream, track); NativeMethods.ContextDeleteMediaStreamTrack(context, track); NativeMethods.ContextDeleteMediaStream(context, stream); NativeMethods.ContextDestroy(0); UnityEngine.Object.DestroyImmediate(renderTexture); } [Test] public void AddAndRemoveAudioTrackToMediaStream() { var context = NativeMethods.ContextCreate(0, encoderType); var stream = NativeMethods.ContextCreateMediaStream(context, "MediaStream"); var track = NativeMethods.ContextCreateAudioTrack(context, "audio"); NativeMethods.MediaStreamAddTrack(stream, track); int trackSize = 0; var trackNativePtr = NativeMethods.MediaStreamGetAudioTracks(stream, ref trackSize); Assert.AreNotEqual(trackNativePtr, IntPtr.Zero); Assert.Greater(trackSize, 0); IntPtr[] tracksPtr = new IntPtr[trackSize]; Marshal.Copy(trackNativePtr, tracksPtr, 0, trackSize); Marshal.FreeCoTaskMem(trackNativePtr); NativeMethods.MediaStreamRemoveTrack(stream, track); NativeMethods.ContextDeleteMediaStreamTrack(context, track); NativeMethods.ContextDeleteMediaStream(context, stream); NativeMethods.ContextDestroy(0); } [Test] public void AddAndRemoveAudioTrack() { var context = NativeMethods.ContextCreate(0, encoderType); var peer = NativeMethods.ContextCreatePeerConnection(context); var stream = NativeMethods.ContextCreateMediaStream(context, "MediaStream"); var streamId = NativeMethods.MediaStreamGetID(stream).AsAnsiStringWithFreeMem(); Assert.IsNotEmpty(streamId); var track = NativeMethods.ContextCreateAudioTrack(context, "audio"); var sender = NativeMethods.PeerConnectionAddTrack(peer, track, streamId); NativeMethods.ContextDeleteMediaStreamTrack(context, track); NativeMethods.PeerConnectionRemoveTrack(peer, sender); NativeMethods.ContextDeleteMediaStream(context, stream); NativeMethods.ContextDeletePeerConnection(context, peer); NativeMethods.ContextDestroy(0); } [Test] public void CallGetRenderEventFunc() { var context = NativeMethods.ContextCreate(0, encoderType); var callback = NativeMethods.GetRenderEventFunc(context); Assert.AreNotEqual(callback, IntPtr.Zero); NativeMethods.ContextDestroy(0); NativeMethods.GetRenderEventFunc(IntPtr.Zero); } /// <todo> /// This unittest failed standalone mono 2019.3 on linux /// </todo> [UnityTest] [UnityPlatform(exclude = new[] { RuntimePlatform.LinuxPlayer })] public IEnumerator CallVideoEncoderMethods() { var context = NativeMethods.ContextCreate(0, encoderType); var peer = NativeMethods.ContextCreatePeerConnection(context); var stream = NativeMethods.ContextCreateMediaStream(context, "MediaStream"); var streamId = NativeMethods.MediaStreamGetID(stream).AsAnsiStringWithFreeMem(); Assert.IsNotEmpty(streamId); const int width = 1280; const int height = 720; var renderTexture = CreateRenderTexture(width, height); var track = NativeMethods.ContextCreateVideoTrack(context, "video", renderTexture.GetNativeTexturePtr()); var sender = NativeMethods.PeerConnectionAddTrack(peer, track, streamId); var callback = NativeMethods.GetRenderEventFunc(context); Assert.AreEqual(CodecInitializationResult.NotInitialized, NativeMethods.GetInitializationResult(context, track)); // TODO:: // note:: You must call `InitializeEncoder` method after `NativeMethods.ContextCaptureVideoStream` NativeMethods.ContextSetVideoEncoderParameter(context, track, width, height); VideoEncoderMethods.InitializeEncoder(callback, track); yield return new WaitForSeconds(1.0f); Assert.AreEqual(CodecInitializationResult.Success, NativeMethods.GetInitializationResult(context, track)); VideoEncoderMethods.Encode(callback, track); yield return new WaitForSeconds(1.0f); VideoEncoderMethods.FinalizeEncoder(callback, track); yield return new WaitForSeconds(1.0f); NativeMethods.PeerConnectionRemoveTrack(peer, sender); NativeMethods.ContextDeleteMediaStreamTrack(context, track); NativeMethods.ContextDeleteMediaStream(context, stream); NativeMethods.ContextDeletePeerConnection(context, peer); NativeMethods.ContextDestroy(0); UnityEngine.Object.DestroyImmediate(renderTexture); } } [TestFixture, ConditionalIgnore("IgnoreHardwareEncoderTest", "Ignored hardware encoder test.")] [UnityPlatform(RuntimePlatform.WindowsEditor, RuntimePlatform.OSXEditor, RuntimePlatform.LinuxEditor)] class NativeAPITestWithHardwareEncoderAndEnterPlayModeOptionsEnabled : NativeAPITestWithHardwareEncoder, IPrebuildSetup { public void Setup() { #if UNITY_EDITOR EditorSettings.enterPlayModeOptionsEnabled = true; EditorSettings.enterPlayModeOptions = EnterPlayModeOptions.DisableDomainReload | EnterPlayModeOptions.DisableSceneReload; #endif } } [UnityPlatform(RuntimePlatform.WindowsEditor, RuntimePlatform.OSXEditor, RuntimePlatform.LinuxEditor)] class NativeAPITestWithSoftwareEncoderAndEnterPlayModeOptionsEnabled : NativeAPITestWithSoftwareEncoder, IPrebuildSetup { public void Setup() { #if UNITY_EDITOR EditorSettings.enterPlayModeOptionsEnabled = true; EditorSettings.enterPlayModeOptions = EnterPlayModeOptions.DisableDomainReload | EnterPlayModeOptions.DisableSceneReload; #endif } } }
43.335484
130
0.676716
[ "Apache-2.0" ]
sokuhatiku/com.unity.webrtc
Tests/Runtime/NativeAPITest.cs
13,434
C#
using System; using Microsoft.VisualStudio.TestTools.UnitTesting; using Ethereum.Utilities; using System.Text; namespace Ethereum.Test { [TestClass] public class CompactEncoderTest { private readonly static byte T = 16; // terminator [TestMethod] public void TestCompactEncodeOne() { byte[] test = new byte[] { 1, 2, 3, 4, 5 }; byte[] expected = new byte[] { 0x11, 0x23, 0x45 }; byte[] result = CompactEncoder.CompactEncode(test); Assert.AreEqual(Encoding.ASCII.GetString(result), Encoding.ASCII.GetString(expected)); } [TestMethod] public void TestCompactEncodeTwo() { byte[] test = new byte[] { 0, 1, 2, 3, 4, 5 }; byte[] expected = new byte[] { 0x00, 0x01, 0x23, 0x45 }; byte[] result = CompactEncoder.CompactEncode(test); Assert.AreEqual(Encoding.ASCII.GetString(result), Encoding.ASCII.GetString(expected)); } [TestMethod] public void TestCompactEncodeThree() { byte[] test = new byte[] { 0, 15, 1, 12, 11, 8, T }; byte[] expected = new byte[] { 0x20, 0x0f, 0x1c, 0xb8 }; byte[] result = CompactEncoder.CompactEncode(test); Assert.AreEqual(Encoding.ASCII.GetString(result), Encoding.ASCII.GetString(expected)); } [TestMethod] public void TestCompactEncodeFour() { byte[] test = new byte[] { 15, 1, 12, 11, 8, T }; byte[] expected = new byte[] { 0x3f, 0x1c, 0xb8 }; byte[] result = CompactEncoder.CompactEncode(test); Assert.AreEqual(Encoding.ASCII.GetString(result), Encoding.ASCII.GetString(expected)); } [TestMethod] public void TestCompactHexDecode() { byte[] test = Encoding.ASCII.GetBytes("verb"); byte[] expected = new byte[] { 7, 6, 6, 5, 7, 2, 6, 2, 16 }; byte[] result = CompactEncoder.CompactHexDecode(test); Assert.AreEqual(Encoding.ASCII.GetString(result), Encoding.ASCII.GetString(expected)); } [TestMethod] public void TestCompactDecodeOne() { byte[] test = new byte[] { 0x11, 0x23, 0x45 }; byte[] expected = new byte[] { 1, 2, 3, 4, 5 }; byte[] result = CompactEncoder.CompactDecode(test); Assert.AreEqual(Encoding.ASCII.GetString(result), Encoding.ASCII.GetString(expected)); } [TestMethod] public void TestCompactDecodeTwo() { byte[] test = new byte[] { 0x00, 0x01, 0x23, 0x45 }; byte[] expected = new byte[] { 0, 1, 2, 3, 4, 5 }; byte[] result = CompactEncoder.CompactDecode(test); Assert.AreEqual(Encoding.ASCII.GetString(result), Encoding.ASCII.GetString(expected)); } [TestMethod] public void TestCompactDecodeThree() { byte[] test = new byte[] { 0x20, 0x0f, 0x1c, 0xb8 }; byte[] expected = new byte[] { 0, 15, 1, 12, 11, 8, T }; byte[] result = CompactEncoder.CompactDecode(test); Assert.AreEqual(Encoding.ASCII.GetString(result), Encoding.ASCII.GetString(expected)); } [TestMethod] public void TestCompactDecodeFour() { byte[] test = new byte[] { 0x3f, 0x1c, 0xb8 }; byte[] expected = new byte[] { 15, 1, 12, 11, 8, T }; byte[] result = CompactEncoder.CompactDecode(test); Assert.AreEqual(Encoding.ASCII.GetString(result), Encoding.ASCII.GetString(expected)); } } }
38.431579
98
0.570529
[ "MIT" ]
etherchain/cs-ethereum
Ethereum.Test/CompactEncoderTest.cs
3,653
C#
// The MIT License(MIT) // // Copyright(c) 2021 Alberto Rodriguez Orozco & LiveCharts Contributors // // 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 LiveChartsCore.Drawing; using LiveChartsCore.Kernel; using LiveChartsCore.Measure; using LiveChartsCore.SkiaSharpView.Drawing; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Collections.Specialized; using System.ComponentModel; using System.Drawing; using Xamarin.Essentials; using Xamarin.Forms.Xaml; using Xamarin.Forms; using c = Xamarin.Forms.Color; using LiveChartsCore.Kernel.Events; using LiveChartsCore.Kernel.Sketches; namespace LiveChartsCore.SkiaSharpView.Xamarin.Forms { /// <inheritdoc cref="ICartesianChartView{TDrawingContext}" /> [XamlCompilation(XamlCompilationOptions.Compile)] public partial class CartesianChart : ContentView, ICartesianChartView<SkiaSharpDrawingContext>, IMobileChart { #region fields /// <summary> /// The core /// </summary> protected Chart<SkiaSharpDrawingContext>? core; private readonly CollectionDeepObserver<ISeries> _seriesObserver; private readonly CollectionDeepObserver<IAxis> _xObserver; private readonly CollectionDeepObserver<IAxis> _yObserver; private readonly CollectionDeepObserver<Section<SkiaSharpDrawingContext>> _sectionsObserverer; private Grid? _grid; #endregion /// <summary> /// Initializes a new instance of the <see cref="CartesianChart"/> class. /// </summary> /// <exception cref="Exception">Default colors are not valid</exception> public CartesianChart() { InitializeComponent(); if (!LiveCharts.IsConfigured) LiveCharts.Configure(LiveChartsSkiaSharp.DefaultPlatformBuilder); var stylesBuilder = LiveCharts.CurrentSettings.GetTheme<SkiaSharpDrawingContext>(); var initializer = stylesBuilder.GetVisualsInitializer(); if (stylesBuilder.CurrentColors is null || stylesBuilder.CurrentColors.Length == 0) throw new Exception("Default colors are not valid"); initializer.ApplyStyleToChart(this); InitializeCore(); SizeChanged += OnSizeChanged; _seriesObserver = new CollectionDeepObserver<ISeries>(OnDeepCollectionChanged, OnDeepCollectionPropertyChanged, true); _xObserver = new CollectionDeepObserver<IAxis>(OnDeepCollectionChanged, OnDeepCollectionPropertyChanged, true); _yObserver = new CollectionDeepObserver<IAxis>(OnDeepCollectionChanged, OnDeepCollectionPropertyChanged, true); _sectionsObserverer = new CollectionDeepObserver<Section<SkiaSharpDrawingContext>>( OnDeepCollectionChanged, OnDeepCollectionPropertyChanged, true); XAxes = new List<IAxis>() { LiveCharts.CurrentSettings.AxisProvider() }; YAxes = new List<IAxis>() { LiveCharts.CurrentSettings.AxisProvider() }; Series = new ObservableCollection<ISeries>(); canvas.SkCanvasView.EnableTouchEvents = true; canvas.SkCanvasView.Touch += OnSkCanvasTouched; if (core is null) throw new Exception("Core not found!"); core.Measuring += OnCoreMeasuring; core.UpdateStarted += OnCoreUpdateStarted; core.UpdateFinished += OnCoreUpdateFinished; } #region bindable properties /// <summary> /// The sync context property. /// </summary> public static readonly BindableProperty SyncContextProperty = BindableProperty.Create( nameof(SyncContext), typeof(object), typeof(CartesianChart), new ObservableCollection<ISeries>(), BindingMode.Default, null, (BindableObject o, object oldValue, object newValue) => { var chart = (CartesianChart)o; chart.CoreCanvas.Sync = newValue; if (chart.core is null) return; chart.core.Update(); }); /// <summary> /// The series property /// </summary> public static readonly BindableProperty SeriesProperty = BindableProperty.Create( nameof(Series), typeof(IEnumerable<ISeries>), typeof(CartesianChart), new ObservableCollection<ISeries>(), BindingMode.Default, null, (BindableObject o, object oldValue, object newValue) => { var chart = (CartesianChart)o; var seriesObserver = chart._seriesObserver; seriesObserver.Dispose((IEnumerable<ISeries>)oldValue); seriesObserver.Initialize((IEnumerable<ISeries>)newValue); if (chart.core is null) return; chart.core.Update(); }); /// <summary> /// The x axes property /// </summary> public static readonly BindableProperty XAxesProperty = BindableProperty.Create( nameof(XAxes), typeof(IEnumerable<IAxis>), typeof(CartesianChart), new List<IAxis>() { new Axis() }, BindingMode.Default, null, (BindableObject o, object oldValue, object newValue) => { var chart = (CartesianChart)o; var observer = chart._xObserver; observer.Dispose((IEnumerable<IAxis>)oldValue); observer.Initialize((IEnumerable<IAxis>)newValue); if (chart.core is null) return; chart.core.Update(); }); /// <summary> /// The y axes property /// </summary> public static readonly BindableProperty YAxesProperty = BindableProperty.Create( nameof(YAxes), typeof(IEnumerable<IAxis>), typeof(CartesianChart), new List<IAxis>() { new Axis() }, BindingMode.Default, null, (BindableObject o, object oldValue, object newValue) => { var chart = (CartesianChart)o; var observer = chart._yObserver; observer.Dispose((IEnumerable<IAxis>)oldValue); observer.Initialize((IEnumerable<IAxis>)newValue); if (chart.core is null) return; chart.core.Update(); }); public static readonly BindableProperty SectionsProperty = BindableProperty.Create( nameof(Sections), typeof(IEnumerable<Section<SkiaSharpDrawingContext>>), typeof(CartesianChart), new List<Section<SkiaSharpDrawingContext>>(), BindingMode.Default, null, (BindableObject o, object oldValue, object newValue) => { var chart = (CartesianChart)o; var observer = chart._sectionsObserverer; observer.Dispose((IEnumerable<Section<SkiaSharpDrawingContext>>)oldValue); observer.Initialize((IEnumerable<Section<SkiaSharpDrawingContext>>)newValue); if (chart.core is null) return; chart.core.Update(); }); /// <summary> /// The draw margin frame property /// </summary> public static readonly BindableProperty DrawMarginFrameProperty = BindableProperty.Create( nameof(DrawMarginFrame), typeof(DrawMarginFrame<SkiaSharpDrawingContext>), typeof(CartesianChart), null, BindingMode.Default, null, OnBindablePropertyChanged); /// <summary> /// The draw margin property /// </summary> public static readonly BindableProperty DrawMarginProperty = BindableProperty.Create( nameof(DrawMargin), typeof(Margin), typeof(CartesianChart), null, BindingMode.Default, null, OnBindablePropertyChanged); /// <summary> /// The zoom mode property /// </summary> public static readonly BindableProperty ZoomModeProperty = BindableProperty.Create( nameof(ZoomMode), typeof(ZoomAndPanMode), typeof(CartesianChart), LiveCharts.CurrentSettings.DefaultZoomMode, BindingMode.Default, null); /// <summary> /// The zooming speed property /// </summary> public static readonly BindableProperty ZoomingSpeedProperty = BindableProperty.Create( nameof(ZoomingSpeed), typeof(double), typeof(CartesianChart), LiveCharts.CurrentSettings.DefaultZoomSpeed, BindingMode.Default, null); /// <summary> /// The animations speed property /// </summary> public static readonly BindableProperty AnimationsSpeedProperty = BindableProperty.Create( nameof(AnimationsSpeed), typeof(TimeSpan), typeof(CartesianChart), LiveCharts.CurrentSettings.DefaultAnimationsSpeed); /// <summary> /// The easing function property /// </summary> public static readonly BindableProperty EasingFunctionProperty = BindableProperty.Create( nameof(EasingFunction), typeof(Func<float, float>), typeof(CartesianChart), LiveCharts.CurrentSettings.DefaultEasingFunction); /// <summary> /// The legend position property /// </summary> public static readonly BindableProperty LegendPositionProperty = BindableProperty.Create( nameof(LegendPosition), typeof(LegendPosition), typeof(CartesianChart), LiveCharts.CurrentSettings.DefaultLegendPosition, propertyChanged: OnBindablePropertyChanged); /// <summary> /// The legend orientation property /// </summary> public static readonly BindableProperty LegendOrientationProperty = BindableProperty.Create( nameof(LegendOrientation), typeof(LegendOrientation), typeof(CartesianChart), LiveCharts.CurrentSettings.DefaultLegendOrientation, propertyChanged: OnBindablePropertyChanged); /// <summary> /// The legend template property /// </summary> public static readonly BindableProperty LegendTemplateProperty = BindableProperty.Create( nameof(LegendTemplate), typeof(DataTemplate), typeof(CartesianChart), null, propertyChanged: OnBindablePropertyChanged); /// <summary> /// The legend font family property /// </summary> public static readonly BindableProperty LegendFontFamilyProperty = BindableProperty.Create( nameof(LegendFontFamily), typeof(string), typeof(CartesianChart), null, propertyChanged: OnBindablePropertyChanged); /// <summary> /// The legend font size property /// </summary> public static readonly BindableProperty LegendFontSizeProperty = BindableProperty.Create( nameof(LegendFontSize), typeof(double), typeof(CartesianChart), 13d, propertyChanged: OnBindablePropertyChanged); /// <summary> /// The legend text color property /// </summary> public static readonly BindableProperty LegendTextBrushProperty = BindableProperty.Create( nameof(LegendTextBrush), typeof(c), typeof(CartesianChart), new c(35 / 255d, 35 / 255d, 35 / 255d), propertyChanged: OnBindablePropertyChanged); /// <summary> /// The legend background property /// </summary> public static readonly BindableProperty LegendBackgroundProperty = BindableProperty.Create( nameof(LegendTextBrush), typeof(c), typeof(CartesianChart), new c(250 / 255d, 250 / 255d, 250 / 255d), propertyChanged: OnBindablePropertyChanged); /// <summary> /// The legend font attributes property /// </summary> public static readonly BindableProperty LegendFontAttributesProperty = BindableProperty.Create( nameof(LegendFontAttributes), typeof(FontAttributes), typeof(CartesianChart), FontAttributes.None, propertyChanged: OnBindablePropertyChanged); /// <summary> /// The tool tip position property /// </summary> public static readonly BindableProperty TooltipPositionProperty = BindableProperty.Create( nameof(TooltipPosition), typeof(TooltipPosition), typeof(CartesianChart), LiveCharts.CurrentSettings.DefaultTooltipPosition, propertyChanged: OnBindablePropertyChanged); /// <summary> /// The too ltip finding strategy property /// </summary> public static readonly BindableProperty TooltipFindingStrategyProperty = BindableProperty.Create( nameof(TooltipFindingStrategy), typeof(TooltipFindingStrategy), typeof(CartesianChart), LiveCharts.CurrentSettings.DefaultTooltipFindingStrategy); /// <summary> /// The tool tip template property /// </summary> public static readonly BindableProperty TooltipTemplateProperty = BindableProperty.Create( nameof(TooltipTemplate), typeof(DataTemplate), typeof(CartesianChart), null, propertyChanged: OnBindablePropertyChanged); /// <summary> /// The tool tip font family property /// </summary> public static readonly BindableProperty TooltipFontFamilyProperty = BindableProperty.Create( nameof(TooltipFontFamily), typeof(string), typeof(CartesianChart), null, propertyChanged: OnBindablePropertyChanged); /// <summary> /// The tool tip font size property /// </summary> public static readonly BindableProperty TooltipFontSizeProperty = BindableProperty.Create( nameof(TooltipFontSize), typeof(double), typeof(CartesianChart), 13d, propertyChanged: OnBindablePropertyChanged); /// <summary> /// The tool tip text color property /// </summary> public static readonly BindableProperty TooltipTextBrushProperty = BindableProperty.Create( nameof(TooltipTextBrush), typeof(c), typeof(CartesianChart), new c(35 / 255d, 35 / 255d, 35 / 255d), propertyChanged: OnBindablePropertyChanged); /// <summary> /// The tool tip background property /// </summary> public static readonly BindableProperty TooltipBackgroundProperty = BindableProperty.Create( nameof(TooltipBackground), typeof(c), typeof(CartesianChart), new c(250 / 255d, 250 / 255d, 250 / 255d), propertyChanged: OnBindablePropertyChanged); /// <summary> /// The tool tip font attributes property /// </summary> public static readonly BindableProperty TooltipFontAttributesProperty = BindableProperty.Create( nameof(TooltipFontAttributes), typeof(FontAttributes), typeof(CartesianChart), FontAttributes.None, propertyChanged: OnBindablePropertyChanged); #endregion #region events /// <inheritdoc cref="IChartView{TDrawingContext}.Measuring" /> public event ChartEventHandler<SkiaSharpDrawingContext>? Measuring; /// <inheritdoc cref="IChartView{TDrawingContext}.UpdateStarted" /> public event ChartEventHandler<SkiaSharpDrawingContext>? UpdateStarted; /// <inheritdoc cref="IChartView{TDrawingContext}.UpdateFinished" /> public event ChartEventHandler<SkiaSharpDrawingContext>? UpdateFinished; #endregion #region properties /// <inheritdoc cref="IChartView.CoreChart" /> public IChart CoreChart => core ?? throw new Exception("Core not set yet."); System.Drawing.Color IChartView.BackColor { get => Background is not SolidColorBrush b ? new System.Drawing.Color() : System.Drawing.Color.FromArgb( (int)(b.Color.R * 255), (int)(b.Color.G * 255), (int)(b.Color.B * 255), (int)(b.Color.A * 255)); set => Background = new SolidColorBrush(new c(value.R / 255, value.G / 255, value.B / 255, value.A / 255)); } CartesianChart<SkiaSharpDrawingContext> ICartesianChartView<SkiaSharpDrawingContext>.Core => core is null ? throw new Exception("core not found") : (CartesianChart<SkiaSharpDrawingContext>)core; SizeF IChartView.ControlSize => new() { Width = (float)(canvas.Width * DeviceDisplay.MainDisplayInfo.Density), Height = (float)(canvas.Height * DeviceDisplay.MainDisplayInfo.Density) }; /// <inheritdoc cref="IChartView{TDrawingContext}.CoreCanvas" /> public MotionCanvas<SkiaSharpDrawingContext> CoreCanvas => canvas.CanvasCore; Grid IMobileChart.LayoutGrid => _grid ??= this.FindByName<Grid>("gridLayout"); BindableObject IMobileChart.Canvas => canvas; BindableObject IMobileChart.Legend => legend; /// <inheritdoc cref="IChartView.SyncContext" /> public object SyncContext { get => GetValue(SyncContextProperty); set => SetValue(SyncContextProperty, value); } /// <inheritdoc cref="IChartView.DrawMargin" /> public Margin? DrawMargin { get => (Margin)GetValue(DrawMarginProperty); set => SetValue(DrawMarginProperty, value); } /// <inheritdoc cref="ICartesianChartView{TDrawingContext}.Series" /> public IEnumerable<ISeries> Series { get => (IEnumerable<ISeries>)GetValue(SeriesProperty); set => SetValue(SeriesProperty, value); } /// <inheritdoc cref="ICartesianChartView{TDrawingContext}.XAxes" /> public IEnumerable<IAxis> XAxes { get => (IEnumerable<IAxis>)GetValue(XAxesProperty); set => SetValue(XAxesProperty, value); } /// <inheritdoc cref="ICartesianChartView{TDrawingContext}.YAxes" /> public IEnumerable<IAxis> YAxes { get => (IEnumerable<IAxis>)GetValue(YAxesProperty); set => SetValue(YAxesProperty, value); } /// <inheritdoc cref="ICartesianChartView{TDrawingContext}.Sections" /> public IEnumerable<Section<SkiaSharpDrawingContext>> Sections { get => (IEnumerable<Section<SkiaSharpDrawingContext>>)GetValue(SectionsProperty); set => SetValue(SectionsProperty, value); } /// <inheritdoc cref="ICartesianChartView{TDrawingContext}.DrawMarginFrame" /> public DrawMarginFrame<SkiaSharpDrawingContext> DrawMarginFrame { get => (DrawMarginFrame<SkiaSharpDrawingContext>)GetValue(DrawMarginFrameProperty); set => SetValue(DrawMarginFrameProperty, value); } /// <inheritdoc cref="IChartView.AnimationsSpeed" /> public TimeSpan AnimationsSpeed { get => (TimeSpan)GetValue(AnimationsSpeedProperty); set => SetValue(AnimationsSpeedProperty, value); } /// <inheritdoc cref="IChartView.EasingFunction" /> public Func<float, float>? EasingFunction { get => (Func<float, float>)GetValue(EasingFunctionProperty); set => SetValue(EasingFunctionProperty, value); } /// <inheritdoc cref="ICartesianChartView{TDrawingContext}.ZoomMode" /> public ZoomAndPanMode ZoomMode { get => (ZoomAndPanMode)GetValue(ZoomModeProperty); set => SetValue(ZoomModeProperty, value); } /// <inheritdoc cref="ICartesianChartView{TDrawingContext}.ZoomingSpeed" /> public double ZoomingSpeed { get => (double)GetValue(ZoomingSpeedProperty); set => SetValue(ZoomingSpeedProperty, value); } /// <inheritdoc cref="IChartView.LegendPosition" /> public LegendPosition LegendPosition { get => (LegendPosition)GetValue(LegendPositionProperty); set => SetValue(LegendPositionProperty, value); } /// <inheritdoc cref="IChartView.LegendOrientation" /> public LegendOrientation LegendOrientation { get => (LegendOrientation)GetValue(LegendOrientationProperty); set => SetValue(LegendOrientationProperty, value); } /// <summary> /// Gets or sets the legend template. /// </summary> /// <value> /// The legend template. /// </value> public DataTemplate LegendTemplate { get => (DataTemplate)GetValue(LegendTemplateProperty); set => SetValue(LegendTemplateProperty, value); } /// <summary> /// Gets or sets the default legend font family. /// </summary> /// <value> /// The legend font family. /// </value> public string LegendFontFamily { get => (string)GetValue(LegendFontFamilyProperty); set => SetValue(LegendFontFamilyProperty, value); } /// <summary> /// Gets or sets the default size of the legend font. /// </summary> /// <value> /// The size of the legend font. /// </value> public double LegendFontSize { get => (double)GetValue(LegendFontSizeProperty); set => SetValue(LegendFontSizeProperty, value); } /// <summary> /// Gets or sets the default color of the legend text. /// </summary> /// <value> /// The color of the legend text. /// </value> public c LegendTextBrush { get => (c)GetValue(LegendTextBrushProperty); set => SetValue(LegendTextBrushProperty, value); } /// <summary> /// Gets or sets the default color of the legend background. /// </summary> /// <value> /// The color of the legend background. /// </value> public c LegendBackground { get => (c)GetValue(LegendBackgroundProperty); set => SetValue(LegendBackgroundProperty, value); } /// <summary> /// Gets or sets the default legend font attributes. /// </summary> /// <value> /// The legend font attributes. /// </value> public FontAttributes LegendFontAttributes { get => (FontAttributes)GetValue(LegendFontAttributesProperty); set => SetValue(LegendFontAttributesProperty, value); } /// <inheritdoc cref="IChartView{TDrawingContext}.Legend" /> public IChartLegend<SkiaSharpDrawingContext>? Legend => legend; /// <inheritdoc cref="IChartView.TooltipPosition" /> public TooltipPosition TooltipPosition { get => (TooltipPosition)GetValue(TooltipPositionProperty); set => SetValue(TooltipPositionProperty, value); } /// <inheritdoc cref="ICartesianChartView{TDrawingContext}.TooltipFindingStrategy" /> public TooltipFindingStrategy TooltipFindingStrategy { get => (TooltipFindingStrategy)GetValue(TooltipFindingStrategyProperty); set => SetValue(TooltipFindingStrategyProperty, value); } /// <summary> /// Gets or sets the tool tip template. /// </summary> /// <value> /// The tool tip template. /// </value> public DataTemplate TooltipTemplate { get => (DataTemplate)GetValue(TooltipTemplateProperty); set => SetValue(TooltipTemplateProperty, value); } /// <summary> /// Gets or sets the default tool tip font family. /// </summary> /// <value> /// The tool tip font family. /// </value> public string TooltipFontFamily { get => (string)GetValue(TooltipFontFamilyProperty); set => SetValue(TooltipFontFamilyProperty, value); } /// <summary> /// Gets or sets the default size of the tool tip font. /// </summary> /// <value> /// The size of the tool tip font. /// </value> public double TooltipFontSize { get => (double)GetValue(TooltipFontSizeProperty); set => SetValue(TooltipFontSizeProperty, value); } /// <summary> /// Gets or sets the default color of the tool tip text. /// </summary> /// <value> /// The color of the tool tip text. /// </value> public c TooltipTextBrush { get => (c)GetValue(TooltipTextBrushProperty); set => SetValue(TooltipTextBrushProperty, value); } /// <summary> /// Gets or sets the default color of the tool tip background. /// </summary> /// <value> /// The color of the tool tip background. /// </value> public c TooltipBackground { get => (c)GetValue(TooltipBackgroundProperty); set => SetValue(TooltipBackgroundProperty, value); } /// <summary> /// Gets or sets the default tool tip font attributes. /// </summary> /// <value> /// The tool tip font attributes. /// </value> public FontAttributes TooltipFontAttributes { get => (FontAttributes)GetValue(TooltipFontAttributesProperty); set => SetValue(TooltipFontAttributesProperty, value); } /// <inheritdoc cref="IChartView{TDrawingContext}.Tooltip" /> public IChartTooltip<SkiaSharpDrawingContext>? Tooltip => tooltip; /// <inheritdoc cref="IChartView{TDrawingContext}.PointStates" /> public PointStatesDictionary<SkiaSharpDrawingContext> PointStates { get; set; } = new(); /// <inheritdoc cref="IChartView{TDrawingContext}.AutoUpdateEnabled" /> public bool AutoUpdateEnabled { get; set; } = true; /// <inheritdoc cref="IChartView.UpdaterThrottler" /> public TimeSpan UpdaterThrottler { get => core?.UpdaterThrottler ?? throw new Exception("core not set yet."); set { if (core is null) throw new Exception("core not set yet."); core.UpdaterThrottler = value; } } #endregion /// <inheritdoc cref="ICartesianChartView{TDrawingContext}.ScaleUIPoint(PointF, int, int)" /> public double[] ScaleUIPoint(PointF point, int xAxisIndex = 0, int yAxisIndex = 0) { if (core is null) throw new Exception("core not found"); var cartesianCore = (CartesianChart<SkiaSharpDrawingContext>)core; return cartesianCore.ScaleUIPoint(point, xAxisIndex, yAxisIndex); } /// <inheritdoc cref="IChartView{TDrawingContext}.ShowTooltip(IEnumerable{TooltipPoint})"/> public void ShowTooltip(IEnumerable<TooltipPoint> points) { if (tooltip is null || core is null) return; ((IChartTooltip<SkiaSharpDrawingContext>)tooltip).Show(points, core); } /// <inheritdoc cref="IChartView{TDrawingContext}.HideTooltip"/> public void HideTooltip() { if (tooltip is null || core is null) return; ((IChartTooltip<SkiaSharpDrawingContext>)tooltip).Hide(); } /// <inheritdoc cref="IChartView.SetTooltipStyle(System.Drawing.Color, System.Drawing.Color)"/> public void SetTooltipStyle(System.Drawing.Color background, System.Drawing.Color textColor) { TooltipBackground = background; TooltipTextBrush = textColor; } void IChartView.InvokeOnUIThread(Action action) { MainThread.BeginInvokeOnMainThread(action); } /// <inheritdoc cref="IChartView.SyncAction(Action)"/> public void SyncAction(Action action) { lock (CoreCanvas.Sync) { action(); } } /// <summary> /// Initializes the core. /// </summary> /// <returns></returns> protected void InitializeCore() { core = new CartesianChart<SkiaSharpDrawingContext>(this, LiveChartsSkiaSharp.DefaultPlatformBuilder, canvas.CanvasCore); core.Update(); } /// <summary> /// Called when a bindable property changed. /// </summary> /// <param name="o">The o.</param> /// <param name="oldValue">The old value.</param> /// <param name="newValue">The new value.</param> /// <returns></returns> protected static void OnBindablePropertyChanged(BindableObject o, object oldValue, object newValue) { var chart = (CartesianChart)o; if (chart.core is null) return; chart.core.Update(); } private void OnDeepCollectionChanged(object? sender, NotifyCollectionChangedEventArgs e) { if (core is null) return; core.Update(); } private void OnDeepCollectionPropertyChanged(object? sender, PropertyChangedEventArgs e) { if (core is null) return; core.Update(); } private void OnSizeChanged(object? sender, EventArgs e) { if (core is null) return; core.Update(); } private void PanGestureRecognizer_PanUpdated(object? sender, PanUpdatedEventArgs e) { if (core is null) return; if (e.StatusType != GestureStatus.Running) return; var c = (CartesianChart<SkiaSharpDrawingContext>)core; var delta = new PointF((float)e.TotalX, (float)e.TotalY); var args = new PanGestureEventArgs(delta); c.InvokePanGestrue(args); if (!args.Handled) c.Pan(delta); } private void PinchGestureRecognizer_PinchUpdated(object? sender, PinchGestureUpdatedEventArgs e) { if (e.Status != GestureStatus.Running || Math.Abs(e.Scale - 1) < 0.05 || core is null) return; var c = (CartesianChart<SkiaSharpDrawingContext>)core; var p = e.ScaleOrigin; var s = c.ControlSize; c.Zoom( new PointF((float)(p.X * s.Width), (float)(p.Y * s.Height)), e.Scale > 1 ? ZoomDirection.ZoomIn : ZoomDirection.ZoomOut); } private void OnSkCanvasTouched(object? sender, SkiaSharp.Views.Forms.SKTouchEventArgs e) { if (core is null) return; if (TooltipPosition == TooltipPosition.Hidden) return; var location = new PointF(e.Location.X, e.Location.Y); core.InvokePointerDown(location); ((IChartTooltip<SkiaSharpDrawingContext>)tooltip).Show(core.FindPointsNearTo(location), core); } private void OnCoreUpdateFinished(IChartView<SkiaSharpDrawingContext> chart) { UpdateFinished?.Invoke(this); } private void OnCoreUpdateStarted(IChartView<SkiaSharpDrawingContext> chart) { UpdateStarted?.Invoke(this); } private void OnCoreMeasuring(IChartView<SkiaSharpDrawingContext> chart) { Measuring?.Invoke(this); } } }
40.912609
202
0.618748
[ "MIT" ]
powerpdw/LiveCharts2
src/skiasharp/LiveChartsCore.SkiaSharp.Xamarin.Forms/CartesianChart.xaml.cs
32,773
C#
using HarmonyLib; using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; using Verse; namespace KeepColorsSeparate { public class KeepColorsSeparateMod: Mod { public KeepColorsSeparateMod(ModContentPack content): base(content) { var harmony = new Harmony("PeteTimesSix.KeepColorsSeparate"); harmony.PatchAll(Assembly.GetExecutingAssembly()); } } }
23.666667
75
0.714286
[ "MIT" ]
PeteTimesSix/KeepColorsSeparate
Source/KeepColorsSeparate/KeepColorsSeparate/KeepColorsSeparateMod.cs
499
C#
using Microsoft.AspNetCore.Identity; namespace ASPNETCoreIdentitySample.Services.Identity { /// <summary> /// More info: http://www.dotnettips.info/post/2582 /// </summary> public class CustomIdentityErrorDescriber : IdentityErrorDescriber { public override IdentityError ConcurrencyFailure() { return new IdentityError { Code = nameof(ConcurrencyFailure), Description = "رکورد جاری پیشتر ویرایش شده‌است و تغییرات شما آن‌را بازنویسی خواهد کرد." }; } public override IdentityError DefaultError() { return new IdentityError { Code = nameof(DefaultError), Description = "خطایی رخ داده‌است." }; } public override IdentityError DuplicateEmail(string email) { return new IdentityError { Code = nameof(DuplicateEmail), Description = string.Format("ایمیل '{0}' هم اکنون مورد استفاده است.", email) }; } public override IdentityError DuplicateRoleName(string role) { return new IdentityError { Code = nameof(DuplicateRoleName), Description = string.Format("نقش '{0}' هم اکنون مورد استفاده‌است.", role) }; } public override IdentityError DuplicateUserName(string userName) { return new IdentityError { Code = nameof(DuplicateUserName), Description = string.Format("نام کاربری '{0}' هم اکنون مورد استفاده‌است.", userName) }; } public override IdentityError InvalidEmail(string email) { return new IdentityError { Code = nameof(InvalidEmail), Description = string.Format("ایمیل '{0}' معتبر نیست.", email) }; } public override IdentityError InvalidRoleName(string role) { return new IdentityError { Code = nameof(InvalidRoleName), Description = string.Format("نقش '{0}' معتبر نیست.", role) }; } public override IdentityError InvalidToken() { return new IdentityError { Code = nameof(InvalidToken), Description = "توکن غیر معتبر." }; } public override IdentityError InvalidUserName(string userName) { return new IdentityError { Code = nameof(InvalidUserName), Description = string.Format("نام کاربری '{0}' معتبر نیست و تنها می‌تواند حاوی حروف و یا ارقام باشد.", userName) }; } public override IdentityError LoginAlreadyAssociated() { return new IdentityError { Code = nameof(LoginAlreadyAssociated), Description = "این کاربر پیشتر اضافه شده‌است." }; } public override IdentityError PasswordMismatch() { return new IdentityError { Code = nameof(PasswordMismatch), Description = "کلمه‌ی عبور نامعتبر." }; } public override IdentityError PasswordRequiresDigit() { return new IdentityError { Code = nameof(PasswordRequiresDigit), Description = "کلمه‌ی عبور باید حداقل دارای یک رقم بین 0 تا 9 باشد." }; } public override IdentityError PasswordRequiresLower() { return new IdentityError { Code = nameof(PasswordRequiresLower), Description = "کلمه‌ی عبور باید حداقل دارای یک حرف کوچک انگلیسی باشد." }; } public override IdentityError PasswordRequiresNonAlphanumeric() { return new IdentityError { Code = nameof(PasswordRequiresNonAlphanumeric), Description = "کلمه‌ی عبور باید حداقل دارای یک حرف خارج از حروف الفبای انگلیسی و همچنین اعداد باشد." }; } public override IdentityError PasswordRequiresUpper() { return new IdentityError { Code = nameof(PasswordRequiresUpper), Description = "کلمه‌ی عبور باید حداقل دارای یک حرف بزرگ انگلیسی باشد." }; } public override IdentityError PasswordTooShort(int length) { return new IdentityError { Code = nameof(PasswordTooShort), Description = string.Format("کلمه‌ی عبور باید حداقل {0} حرف باشد.", length) }; } public override IdentityError UserAlreadyHasPassword() { return new IdentityError { Code = nameof(UserAlreadyHasPassword), Description = "کلمه‌ی عبور کاربر پیشتر تنظیم شده‌است." }; } public override IdentityError UserAlreadyInRole(string role) { return new IdentityError { Code = nameof(UserAlreadyInRole), Description = string.Format("کاربر هم اکنون دارای نقش '{0}' است.", role) }; } public override IdentityError UserLockoutNotEnabled() { return new IdentityError { Code = nameof(UserLockoutNotEnabled), Description = "قفل شدن اکانت برای این کاربر تنظیم نشده‌است." }; } public override IdentityError UserNotInRole(string role) { return new IdentityError { Code = nameof(UserNotInRole), Description = "کاربر دارای نقش '{0}' نیست." }; } public override IdentityError PasswordRequiresUniqueChars(int uniqueChars) { return new IdentityError { Code = nameof(PasswordRequiresUniqueChars), Description = "کلمه‌ی عبور بايد حداقل داراى {0} حرف متفاوت باشد." }; } public override IdentityError RecoveryCodeRedemptionFailed() { return new IdentityError { Code = nameof(RecoveryCodeRedemptionFailed), Description = "بازيابى با شكست مواجه شد." }; } } }
31.442308
127
0.530428
[ "Apache-2.0" ]
majidbigdeli/Iddentity
src/ASPNETCoreIdentitySample.Services/Identity/CustomIdentityErrorDescriber.cs
7,231
C#
using GalaSoft.MvvmLight; using System.Threading; using Tuxblox.Model; namespace Tuxblox.ViewModel { /// <summary> /// This class contains properties that the main View can data bind to. /// <para> /// See http://www.mvvmlight.net /// </para> /// </summary> public class LoadingViewModel : ViewModelBase { private const string UpdatingText = "Updating"; private IDataService _DataService; private string _UpdatingString; private int _UpdatingCount; /// <summary> /// Get and sets the value of LoadingText property. /// </summary> public string UpdatingString { get { return _UpdatingString; } set { if (_UpdatingString != value) { Set(ref _UpdatingString, value); } } } /// <summary> /// Initializes a new instance of the LoadingViewModel class. /// </summary> public LoadingViewModel(IDataService dataService) { _DataService = dataService; UpdatingString = UpdatingText; var animateThread = new Thread(new ThreadStart(AnimateLoadingText)); animateThread.IsBackground = true; animateThread.Start(); } /// <summary> /// Cleanup view model. /// </summary> public override void Cleanup() { base.Cleanup(); } private void AnimateLoadingText() { _UpdatingCount = 0; while (true) { if (_UpdatingCount > 3) { _UpdatingCount = 0; } var localUpdatingString = UpdatingText; for (int i = 0; i < _UpdatingCount; i++) { localUpdatingString += " ."; } UpdatingString = localUpdatingString; _UpdatingCount++; Thread.Sleep(1000); } } } }
25.385542
80
0.497864
[ "MIT" ]
voodoo123x/TuxBlox
Tuxblox/ViewModel/LoadingViewModel.cs
2,109
C#
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AzureNative.RecoveryServices.V20210401.Outputs { /// <summary> /// Additional information of the container. /// </summary> [OutputType] public sealed class MabContainerExtendedInfoResponse { /// <summary> /// Type of backup items associated with this container. /// </summary> public readonly string? BackupItemType; /// <summary> /// List of backup items associated with this container. /// </summary> public readonly ImmutableArray<string> BackupItems; /// <summary> /// Latest backup status of this container. /// </summary> public readonly string? LastBackupStatus; /// <summary> /// Time stamp when this container was refreshed. /// </summary> public readonly string? LastRefreshedAt; /// <summary> /// Backup policy associated with this container. /// </summary> public readonly string? PolicyName; [OutputConstructor] private MabContainerExtendedInfoResponse( string? backupItemType, ImmutableArray<string> backupItems, string? lastBackupStatus, string? lastRefreshedAt, string? policyName) { BackupItemType = backupItemType; BackupItems = backupItems; LastBackupStatus = lastBackupStatus; LastRefreshedAt = lastRefreshedAt; PolicyName = policyName; } } }
30.416667
81
0.623014
[ "Apache-2.0" ]
polivbr/pulumi-azure-native
sdk/dotnet/RecoveryServices/V20210401/Outputs/MabContainerExtendedInfoResponse.cs
1,825
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. using Microsoft.MixedReality.Toolkit.Utilities; using System; using System.Collections.Generic; using UnityEngine; using UnityEngine.EventSystems; namespace Microsoft.MixedReality.Toolkit.Input { /// <summary> /// The Mixed Reality Toolkit's specific implementation of the <see cref="Microsoft.MixedReality.Toolkit.Input.IMixedRealityInputSystem"/> /// </summary> [HelpURL("https://microsoft.github.io/MixedRealityToolkit-Unity/Documentation/Input/Overview.html")] public class MixedRealityInputSystem : BaseDataProviderAccessCoreSystem, IMixedRealityInputSystem, IMixedRealityCapabilityCheck { /// <summary> /// Constructor. /// </summary> /// <param name="registrar">The <see cref="IMixedRealityServiceRegistrar"/> instance that loaded the service.</param> /// <param name="profile">The configuration profile for the service.</param> [Obsolete("This constructor is obsolete (registrar parameter is no longer required) and will be removed in a future version of the Microsoft Mixed Reality Toolkit.")] public MixedRealityInputSystem( IMixedRealityServiceRegistrar registrar, MixedRealityInputSystemProfile profile) : this(profile) { Registrar = registrar; } /// <summary> /// Constructor. /// </summary> /// <param name="profile">The configuration profile for the service.</param> public MixedRealityInputSystem( MixedRealityInputSystemProfile profile) : base(profile) { } /// <inheritdoc/> public override string Name { get; protected set; } = "Mixed Reality Input System"; /// <inheritdoc /> public event Action InputEnabled; /// <inheritdoc /> public event Action InputDisabled; /// <inheritdoc /> public HashSet<IMixedRealityInputSource> DetectedInputSources { get; } = new HashSet<IMixedRealityInputSource>(); /// <inheritdoc /> public HashSet<IMixedRealityController> DetectedControllers { get; } = new HashSet<IMixedRealityController>(); private MixedRealityInputSystemProfile inputSystemProfile = null; /// <inheritdoc/> public MixedRealityInputSystemProfile InputSystemProfile { get { if (inputSystemProfile == null) { inputSystemProfile = ConfigurationProfile as MixedRealityInputSystemProfile; } return inputSystemProfile; } } /// <inheritdoc /> public IMixedRealityFocusProvider FocusProvider => CoreServices.FocusProvider; /// <inheritdoc /> public IMixedRealityRaycastProvider RaycastProvider => CoreServices.RaycastProvider; /// <inheritdoc /> public IMixedRealityGazeProvider GazeProvider { get; private set; } /// <inheritdoc /> public IMixedRealityEyeGazeProvider EyeGazeProvider { get; private set; } private readonly Stack<GameObject> modalInputStack = new Stack<GameObject>(); private readonly Stack<GameObject> fallbackInputStack = new Stack<GameObject>(); /// <inheritdoc /> public bool IsInputEnabled => disabledRefCount <= 0; private int disabledRefCount; private bool isInputModuleAdded = false; private SourceStateEventData sourceStateEventData; private SourcePoseEventData<TrackingState> sourceTrackingEventData; private SourcePoseEventData<Vector2> sourceVector2EventData; private SourcePoseEventData<Vector3> sourcePositionEventData; private SourcePoseEventData<Quaternion> sourceRotationEventData; private SourcePoseEventData<MixedRealityPose> sourcePoseEventData; private FocusEventData focusEventData; private InputEventData inputEventData; private MixedRealityPointerEventData pointerEventData; private InputEventData<float> floatInputEventData; private InputEventData<Vector2> vector2InputEventData; private InputEventData<Vector3> positionInputEventData; private InputEventData<Quaternion> rotationInputEventData; private InputEventData<MixedRealityPose> poseInputEventData; private InputEventData<IDictionary<TrackedHandJoint, MixedRealityPose>> jointPoseInputEventData; private InputEventData<HandMeshInfo> handMeshInputEventData; private SpeechEventData speechEventData; private DictationEventData dictationEventData; private HandTrackingInputEventData handTrackingInputEventData; private MixedRealityInputActionRulesProfile CurrentInputActionRulesProfile { get; set; } #region IMixedRealityCapabilityCheck Implementation /// <inheritdoc /> public bool CheckCapability(MixedRealityCapability capability) { foreach (var deviceManager in GetDataProviders<IMixedRealityInputDeviceManager>()) { IMixedRealityCapabilityCheck capabilityChecker = deviceManager as IMixedRealityCapabilityCheck; // If one of the running data providers supports the requested capability, // the application has the needed support to leverage the desired functionality. if (capabilityChecker?.CheckCapability(capability) == true) { return true; } } // Check GazeProvider directly since not populated in data provider list but life-cycle is managed by InputSystem var gazeProvider_CapabilityCheck = GazeProvider as IMixedRealityCapabilityCheck; if (gazeProvider_CapabilityCheck?.CheckCapability(capability) == true) { return true; } return false; } #endregion IMixedRealityCapabilityCheck Implementation #region IMixedRealityService Implementation /// <inheritdoc /> /// <remarks> /// Input system is critical, so should be processed before all other managers /// </remarks> public override uint Priority => 1; /// <inheritdoc /> public override void Initialize() { MixedRealityInputSystemProfile profile = ConfigurationProfile as MixedRealityInputSystemProfile; if (profile == null) { Debug.LogError("The Input system is missing the required Input System Profile!"); return; } BaseInputModule[] inputModules = UnityEngine.Object.FindObjectsOfType<BaseInputModule>(); if (inputModules.Length == 0) { // There is no input module attached to the camera, add one. CameraCache.Main.gameObject.AddComponent<MixedRealityInputModule>(); isInputModuleAdded = true; } else if ((inputModules.Length == 1) && (inputModules[0] is MixedRealityInputModule)) { /* Nothing to do, a MixedRealityInputModule was applied in the editor. */ } else { Debug.LogError($"For Mixed Reality Toolkit input to work properly, please remove your other input module(s) and add a {typeof(MixedRealityInputModule).Name} to your main camera.", inputModules[0]); } if (InputSystemProfile == null) { Debug.LogError("The Input system is missing the required Input System Profile!"); return; } if (profile.InputActionRulesProfile != null) { CurrentInputActionRulesProfile = profile.InputActionRulesProfile; } else { Debug.LogError("The Input system is missing the required Input Action Rules Profile!"); return; } if (profile.PointerProfile != null) { InstantiateGazeProvider(profile.PointerProfile); } else { Debug.LogError("The Input system is missing the required Pointer Profile!"); return; } sourceStateEventData = new SourceStateEventData(EventSystem.current); sourceTrackingEventData = new SourcePoseEventData<TrackingState>(EventSystem.current); sourceVector2EventData = new SourcePoseEventData<Vector2>(EventSystem.current); sourcePositionEventData = new SourcePoseEventData<Vector3>(EventSystem.current); sourceRotationEventData = new SourcePoseEventData<Quaternion>(EventSystem.current); sourcePoseEventData = new SourcePoseEventData<MixedRealityPose>(EventSystem.current); focusEventData = new FocusEventData(EventSystem.current); inputEventData = new InputEventData(EventSystem.current); pointerEventData = new MixedRealityPointerEventData(EventSystem.current); floatInputEventData = new InputEventData<float>(EventSystem.current); vector2InputEventData = new InputEventData<Vector2>(EventSystem.current); positionInputEventData = new InputEventData<Vector3>(EventSystem.current); rotationInputEventData = new InputEventData<Quaternion>(EventSystem.current); poseInputEventData = new InputEventData<MixedRealityPose>(EventSystem.current); jointPoseInputEventData = new InputEventData<IDictionary<TrackedHandJoint, MixedRealityPose>>(EventSystem.current); handMeshInputEventData = new InputEventData<HandMeshInfo>(EventSystem.current); speechEventData = new SpeechEventData(EventSystem.current); dictationEventData = new DictationEventData(EventSystem.current); handTrackingInputEventData = new HandTrackingInputEventData(EventSystem.current); CreateDataProviders(); } /// <inheritdoc /> public override void Enable() { CreateDataProviders(); // Ensure data providers are enabled (performed by the base class) base.Enable(); InputEnabled?.Invoke(); } private void CreateDataProviders() { MixedRealityInputSystemProfile profile = ConfigurationProfile as MixedRealityInputSystemProfile; // If the system gets disabled, the gaze provider is destroyed. // Ensure that it gets recreated on when reenabled. if (GazeProvider == null) { InstantiateGazeProvider(profile?.PointerProfile); } if ((GetDataProviders().Count == 0) && (profile != null)) { // Register the input device managers. for (int i = 0; i < profile.DataProviderConfigurations.Length; i++) { MixedRealityInputDataProviderConfiguration configuration = profile.DataProviderConfigurations[i]; object[] args = { this, configuration.ComponentName, configuration.Priority, configuration.DeviceManagerProfile }; RegisterDataProvider<IMixedRealityInputDeviceManager>( configuration.ComponentType.Type, configuration.RuntimePlatform, args); } } } private void InstantiateGazeProvider(MixedRealityPointerProfile pointerProfile) { if (pointerProfile?.GazeProviderType?.Type != null) { GazeProvider = CameraCache.Main.gameObject.EnsureComponent(pointerProfile.GazeProviderType.Type) as IMixedRealityGazeProvider; GazeProvider.GazeCursorPrefab = pointerProfile.GazeCursorPrefab; // Current implementation implements both provider types in one concrete class. EyeGazeProvider = GazeProvider as IMixedRealityEyeGazeProvider; } else { Debug.LogError("The Input system is missing the required GazeProviderType!"); return; } } /// <inheritdoc /> public override void Reset() { base.Reset(); Disable(); Initialize(); Enable(); } /// <inheritdoc /> public override void Disable() { base.Disable(); // Input System adds a gaze provider component on the main camera, which needs to be removed when the input system is disabled/removed. // Otherwise the component would keep references to dead objects. // Unity's way to remove component is to destroy it. if (GazeProvider != null) { if (Application.isPlaying) { GazeProvider.GazePointer.BaseCursor.Destroy(); UnityEngine.Object.Destroy(GazeProvider as Component); } else { UnityEngine.Object.DestroyImmediate(GazeProvider as Component); } GazeProvider = null; } foreach(var provider in GetDataProviders<IMixedRealityInputDeviceManager>()) { if (provider != null) { UnregisterDataProvider<IMixedRealityInputDeviceManager>(provider); } } InputDisabled?.Invoke(); } public override void Destroy() { if (isInputModuleAdded) { var inputModule = CameraCache.Main.gameObject.GetComponent<MixedRealityInputModule>(); if (inputModule) { if (Application.isPlaying) { inputModule.DeactivateModule(); UnityEngine.Object.Destroy(inputModule); } else { UnityEngine.Object.DestroyImmediate(inputModule); } } } base.Destroy(); } #endregion IMixedRealityService Implementation #region IMixedRealityDataProviderAccess Implementation /// <inheritdoc /> public override IReadOnlyList<T> GetDataProviders<T>() { if (!typeof(IMixedRealityInputDeviceManager).IsAssignableFrom(typeof(T))) { return null; } return base.GetDataProviders<T>(); } /// <inheritdoc /> public override T GetDataProvider<T>(string name = null) { if (!typeof(IMixedRealityInputDeviceManager).IsAssignableFrom(typeof(T))) { return default(T); } return base.GetDataProvider<T>(name); } #endregion IMixedRealityDataProviderAccess Implementation #region IMixedRealityEventSystem Implementation /// <inheritdoc /> public override void HandleEvent<T>(BaseEventData eventData, ExecuteEvents.EventFunction<T> eventHandler) { if (disabledRefCount > 0) { return; } Debug.Assert(eventData != null); Debug.Assert(!(eventData is MixedRealityPointerEventData), "HandleEvent called with a pointer event. All events raised by pointer should call HandlePointerEvent"); var baseInputEventData = ExecuteEvents.ValidateEventData<BaseInputEventData>(eventData); DispatchEventToGlobalListeners(baseInputEventData, eventHandler); if (baseInputEventData.used) { // All global listeners get a chance to see the event, // but if any of them marked it used, // we stop the event from going any further. return; } if (baseInputEventData.InputSource.Pointers == null) { Debug.LogError($"InputSource {baseInputEventData.InputSource.SourceName} doesn't have any registered pointers! Input Sources without pointers should use the GazeProvider's pointer as a default fallback."); } var modalEventHandled = false; // Get the focused object for each pointer of the event source for (int i = 0; i < baseInputEventData.InputSource.Pointers.Length && !baseInputEventData.used; i++) { modalEventHandled = DispatchEventToObjectFocusedByPointer(baseInputEventData.InputSource.Pointers[i], baseInputEventData, modalEventHandled, eventHandler); } if (!baseInputEventData.used) { DispatchEventToFallbackHandlers(baseInputEventData, eventHandler); } } /// <summary> /// Handles focus changed events /// We send all focus events to all global listeners and the actual focus change receivers. the use flag is completely ignored to avoid any interception. /// </summary> private void HandleFocusChangedEvents(FocusEventData focusEventData, ExecuteEvents.EventFunction<IMixedRealityFocusChangedHandler> eventHandler) { Debug.Assert(focusEventData != null); DispatchEventToGlobalListeners(focusEventData, eventHandler); // Raise Focus Events on the old and new focused objects. if (focusEventData.OldFocusedObject != null) { ExecuteEvents.ExecuteHierarchy(focusEventData.OldFocusedObject, focusEventData, eventHandler); } if (focusEventData.NewFocusedObject != null) { ExecuteEvents.ExecuteHierarchy(focusEventData.NewFocusedObject, focusEventData, eventHandler); } // Raise Focus Events on the pointers cursor if it has one. if (focusEventData.Pointer != null && focusEventData.Pointer.BaseCursor != null) { try { // When shutting down a game, we can sometime get old references to game objects that have been cleaned up. // We'll ignore when this happens. ExecuteEvents.ExecuteHierarchy(focusEventData.Pointer.BaseCursor.GameObjectReference, focusEventData, eventHandler); } catch (Exception) { // ignored. } } } /// <summary> /// Handles focus enter and exit /// We send the focus event to all global listeners and the actual focus change receiver. the use flag is completely ignored to avoid any interception. /// </summary> private void HandleFocusEvent(GameObject eventTarget, FocusEventData focusEventData, ExecuteEvents.EventFunction<IMixedRealityFocusHandler> eventHandler) { Debug.Assert(focusEventData != null); DispatchEventToGlobalListeners(focusEventData, eventHandler); ExecuteEvents.ExecuteHierarchy(eventTarget, focusEventData, eventHandler); } /// <summary> /// Handles a pointer event /// Assumption: We only send pointer events to the objects that pointers are focusing, except for global event listeners (which listen to everything) /// In contract, all other events get sent to all other pointers attached to a given input source /// </summary> private void HandlePointerEvent<T>(BaseEventData eventData, ExecuteEvents.EventFunction<T> eventHandler) where T : IMixedRealityPointerHandler { if (disabledRefCount > 0) { return; } Debug.Assert(eventData != null); var baseInputEventData = ExecuteEvents.ValidateEventData<BaseInputEventData>(eventData); DispatchEventToGlobalListeners(baseInputEventData, eventHandler); if (baseInputEventData.used) { // All global listeners get a chance to see the event, // but if any of them marked it used, // we stop the event from going any further. return; } Debug.Assert(pointerEventData.Pointer != null, "Trying to dispatch event on pointer but pointerEventData is null"); DispatchEventToObjectFocusedByPointer(pointerEventData.Pointer, baseInputEventData, false, eventHandler); if (!baseInputEventData.used) { DispatchEventToFallbackHandlers(baseInputEventData, eventHandler); } } /// <summary> /// Dispatch an input event to all global event listeners /// Return true if the event has been handled by a global event listener /// </summary> private void DispatchEventToGlobalListeners<T>(BaseInputEventData baseInputEventData, ExecuteEvents.EventFunction<T> eventHandler) where T : IEventSystemHandler { Debug.Assert(baseInputEventData != null); Debug.Assert(!baseInputEventData.used); if (baseInputEventData.InputSource == null) { Debug.Assert(baseInputEventData.InputSource != null, $"Failed to find an input source for {baseInputEventData}"); } // Send the event to global listeners base.HandleEvent(baseInputEventData, eventHandler); } /// <summary> /// Dispatch a focus event to all global event listeners /// </summary> private void DispatchEventToGlobalListeners<T>(FocusEventData focusEventData, ExecuteEvents.EventFunction<T> eventHandler) where T : IEventSystemHandler { Debug.Assert(focusEventData != null); Debug.Assert(!focusEventData.used); // Send the event to global listeners base.HandleEvent(focusEventData, eventHandler); } private void DispatchEventToFallbackHandlers<T>(BaseInputEventData baseInputEventData, ExecuteEvents.EventFunction<T> eventHandler) where T : IEventSystemHandler { // If event was not handled by the focused object, pass it on to any fallback handlers if (!baseInputEventData.used && fallbackInputStack.Count > 0) { GameObject fallbackInput = fallbackInputStack.Peek(); ExecuteEvents.ExecuteHierarchy(fallbackInput, baseInputEventData, eventHandler); } } /// <summary> /// Dispatch an input event to the object focused by the given IMixedRealityPointer. /// If a modal dialog is active, dispatch the pointer event to that modal dialog /// Returns true if the event was handled by a modal handler /// </summary> private bool DispatchEventToObjectFocusedByPointer<T>(IMixedRealityPointer mixedRealityPointer, BaseInputEventData baseInputEventData, bool modalEventHandled, ExecuteEvents.EventFunction<T> eventHandler) where T : IEventSystemHandler { GameObject focusedObject = FocusProvider?.GetFocusedObject(mixedRealityPointer); // Handle modal input if one exists if (modalInputStack.Count > 0 && !modalEventHandled) { GameObject modalInput = modalInputStack.Peek(); if (modalInput != null) { // If there is a focused object in the hierarchy of the modal handler, start the event bubble there if (focusedObject != null && focusedObject.transform.IsChildOf(modalInput.transform)) { if (ExecuteEvents.ExecuteHierarchy(focusedObject, baseInputEventData, eventHandler) && baseInputEventData.used) { return true; } } // Otherwise, just invoke the event on the modal handler itself else { if (ExecuteEvents.ExecuteHierarchy(modalInput, baseInputEventData, eventHandler) && baseInputEventData.used) { return true; } } } else { Debug.LogError("ModalInput GameObject reference was null!\nDid this GameObject get destroyed?"); } } // If event was not handled by modal, pass it on to the current focused object if (focusedObject != null) { ExecuteEvents.ExecuteHierarchy(focusedObject, baseInputEventData, eventHandler); } return modalEventHandled; } /// <summary> /// Register a <see href="https://docs.unity3d.com/ScriptReference/GameObject.html">GameObject</see> to listen to events that will receive all input events, regardless /// of which other <see href="https://docs.unity3d.com/ScriptReference/GameObject.html">GameObject</see>s might have handled the event beforehand. /// </summary> /// <remarks>Useful for listening to events when the <see href="https://docs.unity3d.com/ScriptReference/GameObject.html">GameObject</see> is currently not being raycasted against by the <see cref="FocusProvider"/>.</remarks> /// <param name="listener">Listener to add.</param> public override void Register(GameObject listener) { base.Register(listener); } /// <summary> /// Unregister a <see href="https://docs.unity3d.com/ScriptReference/GameObject.html">GameObject</see> from listening to input events. /// </summary> public override void Unregister(GameObject listener) { base.Unregister(listener); } #endregion IMixedRealityEventSystem Implementation #region Input Disabled Options /// <summary> /// Push a disabled input state onto the input manager. /// While input is disabled no events will be sent out and the cursor displays /// a waiting animation. /// </summary> public void PushInputDisable() { ++disabledRefCount; if (disabledRefCount == 1) { InputDisabled?.Invoke(); if (GazeProvider != null) { GazeProvider.Enabled = false; } } } /// <summary> /// Pop disabled input state. When the last disabled state is /// popped off the stack input will be re-enabled. /// </summary> public void PopInputDisable() { --disabledRefCount; Debug.Assert(disabledRefCount >= 0, "Tried to pop more input disable than the amount pushed."); if (disabledRefCount == 0) { InputEnabled?.Invoke(); if (GazeProvider != null) { GazeProvider.Enabled = true; } } } /// <summary> /// Clear the input disable stack, which will immediately re-enable input. /// </summary> public void ClearInputDisableStack() { bool wasInputDisabled = disabledRefCount > 0; disabledRefCount = 0; if (wasInputDisabled) { InputEnabled?.Invoke(); if (GazeProvider != null) { GazeProvider.Enabled = true; } } } #endregion Input Disabled Options #region Modal Input Options /// <summary> /// Push a game object into the modal input stack. Any input handlers /// on the game object are given priority to input events before any focused objects. /// </summary> /// <param name="inputHandler">The input handler to push</param> public void PushModalInputHandler(GameObject inputHandler) { modalInputStack.Push(inputHandler); } /// <summary> /// Remove the last game object from the modal input stack. /// </summary> public void PopModalInputHandler() { if (modalInputStack.Count > 0) { modalInputStack.Pop(); } } /// <summary> /// Clear all modal input handlers off the stack. /// </summary> public void ClearModalInputStack() { modalInputStack.Clear(); } #endregion Modal Input Options #region Fallback Input Handler Options /// <summary> /// Push a game object into the fallback input stack. Any input handlers on /// the game object are given input events when no modal or focused objects consume the event. /// </summary> /// <param name="inputHandler">The input handler to push</param> public void PushFallbackInputHandler(GameObject inputHandler) { fallbackInputStack.Push(inputHandler); } /// <summary> /// Remove the last game object from the fallback input stack. /// </summary> public void PopFallbackInputHandler() { fallbackInputStack.Pop(); } /// <summary> /// Clear all fallback input handlers off the stack. /// </summary> public void ClearFallbackInputStack() { fallbackInputStack.Clear(); } #endregion Fallback Input Handler Options #region Input Events #region Input Source Events /// <inheritdoc /> public uint GenerateNewSourceId() { var newId = (uint)UnityEngine.Random.Range(1, int.MaxValue); foreach (var inputSource in DetectedInputSources) { if (inputSource.SourceId == newId) { return GenerateNewSourceId(); } } return newId; } /// <inheritdoc /> public IMixedRealityInputSource RequestNewGenericInputSource(string name, IMixedRealityPointer[] pointers = null, InputSourceType sourceType = InputSourceType.Other) { return new BaseGenericInputSource(name, pointers, sourceType); } #region Input Source State Events /// <inheritdoc /> public void RaiseSourceDetected(IMixedRealityInputSource source, IMixedRealityController controller = null) { // Create input event sourceStateEventData.Initialize(source, controller); if (DetectedInputSources.Contains(source)) { Debug.LogError($"{source.SourceName} has already been registered with the Input Manager!"); } DetectedInputSources.Add(source); if (controller != null) { DetectedControllers.Add(controller); } FocusProvider?.OnSourceDetected(sourceStateEventData); // Pass handler through HandleEvent to perform modal/fallback logic HandleEvent(sourceStateEventData, OnSourceDetectedEventHandler); } private static readonly ExecuteEvents.EventFunction<IMixedRealitySourceStateHandler> OnSourceDetectedEventHandler = delegate (IMixedRealitySourceStateHandler handler, BaseEventData eventData) { var casted = ExecuteEvents.ValidateEventData<SourceStateEventData>(eventData); handler.OnSourceDetected(casted); }; /// <inheritdoc /> public void RaiseSourceLost(IMixedRealityInputSource source, IMixedRealityController controller = null) { // Create input event sourceStateEventData.Initialize(source, controller); if (!DetectedInputSources.Contains(source)) { Debug.LogError($"{source.SourceName} was never registered with the Input Manager!"); } DetectedInputSources.Remove(source); if (controller != null) { DetectedControllers.Remove(controller); } // Pass handler through HandleEvent to perform modal/fallback logic // Events have to be handled before FocusProvider.OnSourceLost since they won't be passed on without a focused object HandleEvent(sourceStateEventData, OnSourceLostEventHandler); FocusProvider?.OnSourceLost(sourceStateEventData); } private static readonly ExecuteEvents.EventFunction<IMixedRealitySourceStateHandler> OnSourceLostEventHandler = delegate (IMixedRealitySourceStateHandler handler, BaseEventData eventData) { var casted = ExecuteEvents.ValidateEventData<SourceStateEventData>(eventData); handler.OnSourceLost(casted); }; #endregion Input Source State Events #region Input Source Pose Events /// <inheritdoc /> public void RaiseSourceTrackingStateChanged(IMixedRealityInputSource source, IMixedRealityController controller, TrackingState state) { // Create input event sourceTrackingEventData.Initialize(source, controller, state); // Pass handler through HandleEvent to perform modal/fallback logic HandleEvent(sourceTrackingEventData, OnSourceTrackingChangedEventHandler); } private static readonly ExecuteEvents.EventFunction<IMixedRealitySourcePoseHandler> OnSourceTrackingChangedEventHandler = delegate (IMixedRealitySourcePoseHandler handler, BaseEventData eventData) { var casted = ExecuteEvents.ValidateEventData<SourcePoseEventData<TrackingState>>(eventData); handler.OnSourcePoseChanged(casted); }; /// <inheritdoc /> public void RaiseSourcePositionChanged(IMixedRealityInputSource source, IMixedRealityController controller, Vector2 position) { // Create input event sourceVector2EventData.Initialize(source, controller, position); // Pass handler through HandleEvent to perform modal/fallback logic HandleEvent(sourceVector2EventData, OnSourcePoseVector2ChangedEventHandler); } private static readonly ExecuteEvents.EventFunction<IMixedRealitySourcePoseHandler> OnSourcePoseVector2ChangedEventHandler = delegate (IMixedRealitySourcePoseHandler handler, BaseEventData eventData) { var casted = ExecuteEvents.ValidateEventData<SourcePoseEventData<Vector2>>(eventData); handler.OnSourcePoseChanged(casted); }; /// <inheritdoc /> public void RaiseSourcePositionChanged(IMixedRealityInputSource source, IMixedRealityController controller, Vector3 position) { // Create input event sourcePositionEventData.Initialize(source, controller, position); // Pass handler through HandleEvent to perform modal/fallback logic HandleEvent(sourcePositionEventData, OnSourcePositionChangedEventHandler); } private static readonly ExecuteEvents.EventFunction<IMixedRealitySourcePoseHandler> OnSourcePositionChangedEventHandler = delegate (IMixedRealitySourcePoseHandler handler, BaseEventData eventData) { var casted = ExecuteEvents.ValidateEventData<SourcePoseEventData<Vector3>>(eventData); handler.OnSourcePoseChanged(casted); }; /// <inheritdoc /> public void RaiseSourceRotationChanged(IMixedRealityInputSource source, IMixedRealityController controller, Quaternion rotation) { // Create input event sourceRotationEventData.Initialize(source, controller, rotation); // Pass handler through HandleEvent to perform modal/fallback logic HandleEvent(sourceRotationEventData, OnSourceRotationChangedEventHandler); } private static readonly ExecuteEvents.EventFunction<IMixedRealitySourcePoseHandler> OnSourceRotationChangedEventHandler = delegate (IMixedRealitySourcePoseHandler handler, BaseEventData eventData) { var casted = ExecuteEvents.ValidateEventData<SourcePoseEventData<Quaternion>>(eventData); handler.OnSourcePoseChanged(casted); }; /// <inheritdoc /> public void RaiseSourcePoseChanged(IMixedRealityInputSource source, IMixedRealityController controller, MixedRealityPose position) { // Create input event sourcePoseEventData.Initialize(source, controller, position); // Pass handler through HandleEvent to perform modal/fallback logic HandleEvent(sourcePoseEventData, OnSourcePoseChangedEventHandler); } private static readonly ExecuteEvents.EventFunction<IMixedRealitySourcePoseHandler> OnSourcePoseChangedEventHandler = delegate (IMixedRealitySourcePoseHandler handler, BaseEventData eventData) { var casted = ExecuteEvents.ValidateEventData<SourcePoseEventData<MixedRealityPose>>(eventData); handler.OnSourcePoseChanged(casted); }; #endregion Input Source Pose Events #endregion Input Source Events #region Focus Events /// <inheritdoc /> public void RaisePreFocusChanged(IMixedRealityPointer pointer, GameObject oldFocusedObject, GameObject newFocusedObject) { focusEventData.Initialize(pointer, oldFocusedObject, newFocusedObject); HandleFocusChangedEvents(focusEventData, OnPreFocusChangedHandler); } private static readonly ExecuteEvents.EventFunction<IMixedRealityFocusChangedHandler> OnPreFocusChangedHandler = delegate (IMixedRealityFocusChangedHandler handler, BaseEventData eventData) { var casted = ExecuteEvents.ValidateEventData<FocusEventData>(eventData); handler.OnBeforeFocusChange(casted); }; /// <inheritdoc /> public void RaiseFocusChanged(IMixedRealityPointer pointer, GameObject oldFocusedObject, GameObject newFocusedObject) { focusEventData.Initialize(pointer, oldFocusedObject, newFocusedObject); HandleFocusChangedEvents(focusEventData, OnFocusChangedHandler); } private static readonly ExecuteEvents.EventFunction<IMixedRealityFocusChangedHandler> OnFocusChangedHandler = delegate (IMixedRealityFocusChangedHandler handler, BaseEventData eventData) { var casted = ExecuteEvents.ValidateEventData<FocusEventData>(eventData); handler.OnFocusChanged(casted); }; /// <inheritdoc /> public void RaiseFocusEnter(IMixedRealityPointer pointer, GameObject focusedObject) { focusEventData.Initialize(pointer); HandleFocusEvent(focusedObject, focusEventData, OnFocusEnterEventHandler); } private static readonly ExecuteEvents.EventFunction<IMixedRealityFocusHandler> OnFocusEnterEventHandler = delegate (IMixedRealityFocusHandler handler, BaseEventData eventData) { var casted = ExecuteEvents.ValidateEventData<FocusEventData>(eventData); handler.OnFocusEnter(casted); }; /// <inheritdoc /> public void RaiseFocusExit(IMixedRealityPointer pointer, GameObject unfocusedObject) { focusEventData.Initialize(pointer); HandleFocusEvent(unfocusedObject, focusEventData, OnFocusExitEventHandler); } private static readonly ExecuteEvents.EventFunction<IMixedRealityFocusHandler> OnFocusExitEventHandler = delegate (IMixedRealityFocusHandler handler, BaseEventData eventData) { var casted = ExecuteEvents.ValidateEventData<FocusEventData>(eventData); handler.OnFocusExit(casted); }; #endregion Focus Events #region Pointers #region Pointer Down private static readonly ExecuteEvents.EventFunction<IMixedRealityPointerHandler> OnPointerDownEventHandler = delegate (IMixedRealityPointerHandler handler, BaseEventData eventData) { var casted = ExecuteEvents.ValidateEventData<MixedRealityPointerEventData>(eventData); handler.OnPointerDown(casted); }; /// <inheritdoc /> public void RaisePointerDown(IMixedRealityPointer pointer, MixedRealityInputAction inputAction, Handedness handedness = Handedness.None, IMixedRealityInputSource inputSource = null) { // Only lock the object if there is a grabbable above in the hierarchy Transform currentObject = pointer.Result?.Details.Object?.transform; IMixedRealityPointerHandler ancestorPointerHandler = null; while(currentObject != null && ancestorPointerHandler == null) { foreach(var component in currentObject.GetComponents<Component>()) { if (component is IMixedRealityPointerHandler) { ancestorPointerHandler = (IMixedRealityPointerHandler) component; break; } } currentObject = currentObject.transform.parent; } pointer.IsFocusLocked = ancestorPointerHandler != null; pointerEventData.Initialize(pointer, inputAction, handedness, inputSource); HandlePointerEvent(pointerEventData, OnPointerDownEventHandler); } #endregion Pointer Down #region Pointer Dragged private static readonly ExecuteEvents.EventFunction<IMixedRealityPointerHandler> OnPointerDraggedEventHandler = delegate (IMixedRealityPointerHandler handler, BaseEventData eventData) { var casted = ExecuteEvents.ValidateEventData<MixedRealityPointerEventData>(eventData); handler.OnPointerDragged(casted); }; /// <inheritdoc /> public void RaisePointerDragged(IMixedRealityPointer pointer, MixedRealityInputAction inputAction, Handedness handedness = Handedness.None, IMixedRealityInputSource inputSource = null) { pointerEventData.Initialize(pointer, inputAction, handedness, inputSource); HandlePointerEvent(pointerEventData, OnPointerDraggedEventHandler); } #endregion Pointer Dragged #region Pointer Click private static readonly ExecuteEvents.EventFunction<IMixedRealityPointerHandler> OnInputClickedEventHandler = delegate (IMixedRealityPointerHandler handler, BaseEventData eventData) { var casted = ExecuteEvents.ValidateEventData<MixedRealityPointerEventData>(eventData); handler.OnPointerClicked(casted); }; /// <inheritdoc /> public void RaisePointerClicked(IMixedRealityPointer pointer, MixedRealityInputAction inputAction, int count, Handedness handedness = Handedness.None, IMixedRealityInputSource inputSource = null) { // Create input event pointerEventData.Initialize(pointer, inputAction, handedness, inputSource, count); HandleClick(); } private void HandleClick() { // Pass handler through HandleEvent to perform modal/fallback logic HandlePointerEvent(pointerEventData, OnInputClickedEventHandler); // NOTE: In Unity UI, a "click" happens on every pointer up, so we have RaisePointerUp call the PointerHandler. } #endregion Pointer Click #region Pointer Up private static readonly ExecuteEvents.EventFunction<IMixedRealityPointerHandler> OnPointerUpEventHandler = delegate (IMixedRealityPointerHandler handler, BaseEventData eventData) { var casted = ExecuteEvents.ValidateEventData<MixedRealityPointerEventData>(eventData); handler.OnPointerUp(casted); }; /// <inheritdoc /> public void RaisePointerUp(IMixedRealityPointer pointer, MixedRealityInputAction inputAction, Handedness handedness = Handedness.None, IMixedRealityInputSource inputSource = null) { pointerEventData.Initialize(pointer, inputAction, handedness, inputSource); HandlePointerEvent(pointerEventData, OnPointerUpEventHandler); pointer.IsFocusLocked = false; } #endregion Pointer Up #endregion Pointers #region Generic Input Events #region Input Down private static readonly ExecuteEvents.EventFunction<IMixedRealityInputHandler> OnInputDownEventHandler = delegate (IMixedRealityInputHandler handler, BaseEventData eventData) { var casted = ExecuteEvents.ValidateEventData<InputEventData>(eventData); handler.OnInputDown(casted); }; private static readonly ExecuteEvents.EventFunction<IMixedRealityBaseInputHandler> OnInputDownWithActionEventHandler = delegate (IMixedRealityBaseInputHandler handler, BaseEventData eventData) { var inputData = ExecuteEvents.ValidateEventData<InputEventData>(eventData); Debug.Assert(inputData.MixedRealityInputAction != MixedRealityInputAction.None); var inputHandler = handler as IMixedRealityInputHandler; if (inputHandler != null) { inputHandler.OnInputDown(inputData); } var actionHandler = handler as IMixedRealityInputActionHandler; if (actionHandler != null) { actionHandler.OnActionStarted(inputData); } }; /// <inheritdoc /> public void RaiseOnInputDown(IMixedRealityInputSource source, Handedness handedness, MixedRealityInputAction inputAction) { inputAction = ProcessRules(inputAction, true); // Create input event inputEventData.Initialize(source, handedness, inputAction); // Pass handler through HandleEvent to perform modal/fallback logic if (inputEventData.MixedRealityInputAction == MixedRealityInputAction.None) { HandleEvent(inputEventData, OnInputDownEventHandler); } else { HandleEvent(inputEventData, OnInputDownWithActionEventHandler); } } #endregion Input Down #region Input Up private static readonly ExecuteEvents.EventFunction<IMixedRealityInputHandler> OnInputUpEventHandler = delegate (IMixedRealityInputHandler handler, BaseEventData eventData) { var casted = ExecuteEvents.ValidateEventData<InputEventData>(eventData); handler.OnInputUp(casted); }; private static readonly ExecuteEvents.EventFunction<IMixedRealityBaseInputHandler> OnInputUpWithActionEventHandler = delegate (IMixedRealityBaseInputHandler handler, BaseEventData eventData) { var inputData = ExecuteEvents.ValidateEventData<InputEventData>(eventData); Debug.Assert(inputData.MixedRealityInputAction != MixedRealityInputAction.None); var inputHandler = handler as IMixedRealityInputHandler; if (inputHandler != null) { inputHandler.OnInputUp(inputData); } var actionHandler = handler as IMixedRealityInputActionHandler; if (actionHandler != null) { actionHandler.OnActionEnded(inputData); } }; /// <inheritdoc /> public void RaiseOnInputUp(IMixedRealityInputSource source, Handedness handedness, MixedRealityInputAction inputAction) { inputAction = ProcessRules(inputAction, false); // Create input event inputEventData.Initialize(source, handedness, inputAction); // Pass handler through HandleEvent to perform modal/fallback logic if (inputEventData.MixedRealityInputAction == MixedRealityInputAction.None) { HandleEvent(inputEventData, OnInputUpEventHandler); } else { HandleEvent(inputEventData, OnInputUpWithActionEventHandler); } } #endregion Input Up #region Float Input Changed private static readonly ExecuteEvents.EventFunction<IMixedRealityInputHandler<float>> OnFloatInputChanged = delegate (IMixedRealityInputHandler<float> handler, BaseEventData eventData) { var casted = ExecuteEvents.ValidateEventData<InputEventData<float>>(eventData); handler.OnInputChanged(casted); }; /// <inheritdoc /> public void RaiseFloatInputChanged(IMixedRealityInputSource source, Handedness handedness, MixedRealityInputAction inputAction, float inputValue) { inputAction = ProcessRules(inputAction, inputValue); // Create input event floatInputEventData.Initialize(source, handedness, inputAction, inputValue); // Pass handler through HandleEvent to perform modal/fallback logic HandleEvent(floatInputEventData, OnFloatInputChanged); } #endregion Float Input Changed #region Input Position Changed private static readonly ExecuteEvents.EventFunction<IMixedRealityInputHandler<Vector2>> OnTwoDoFInputChanged = delegate (IMixedRealityInputHandler<Vector2> handler, BaseEventData eventData) { var casted = ExecuteEvents.ValidateEventData<InputEventData<Vector2>>(eventData); handler.OnInputChanged(casted); }; /// <inheritdoc /> public void RaisePositionInputChanged(IMixedRealityInputSource source, Handedness handedness, MixedRealityInputAction inputAction, Vector2 inputPosition) { inputAction = ProcessRules(inputAction, inputPosition); // Create input event vector2InputEventData.Initialize(source, handedness, inputAction, inputPosition); // Pass handler through HandleEvent to perform modal/fallback logic HandleEvent(vector2InputEventData, OnTwoDoFInputChanged); } private static readonly ExecuteEvents.EventFunction<IMixedRealityInputHandler<Vector3>> OnPositionInputChanged = delegate (IMixedRealityInputHandler<Vector3> handler, BaseEventData eventData) { var casted = ExecuteEvents.ValidateEventData<InputEventData<Vector3>>(eventData); handler.OnInputChanged(casted); }; /// <inheritdoc /> public void RaisePositionInputChanged(IMixedRealityInputSource source, Handedness handedness, MixedRealityInputAction inputAction, Vector3 position) { inputAction = ProcessRules(inputAction, position); // Create input event positionInputEventData.Initialize(source, handedness, inputAction, position); // Pass handler through HandleEvent to perform modal/fallback logic HandleEvent(positionInputEventData, OnPositionInputChanged); } #endregion Input Position Changed #region Input Rotation Changed private static readonly ExecuteEvents.EventFunction<IMixedRealityInputHandler<Quaternion>> OnRotationInputChanged = delegate (IMixedRealityInputHandler<Quaternion> handler, BaseEventData eventData) { var casted = ExecuteEvents.ValidateEventData<InputEventData<Quaternion>>(eventData); handler.OnInputChanged(casted); }; /// <inheritdoc /> public void RaiseRotationInputChanged(IMixedRealityInputSource source, Handedness handedness, MixedRealityInputAction inputAction, Quaternion rotation) { inputAction = ProcessRules(inputAction, rotation); // Create input event rotationInputEventData.Initialize(source, handedness, inputAction, rotation); // Pass handler through HandleEvent to perform modal/fallback logic HandleEvent(positionInputEventData, OnRotationInputChanged); } #endregion Input Rotation Changed #region Input Pose Changed private static readonly ExecuteEvents.EventFunction<IMixedRealityInputHandler<MixedRealityPose>> OnPoseInputChanged = delegate (IMixedRealityInputHandler<MixedRealityPose> handler, BaseEventData eventData) { var casted = ExecuteEvents.ValidateEventData<InputEventData<MixedRealityPose>>(eventData); handler.OnInputChanged(casted); }; /// <inheritdoc /> public void RaisePoseInputChanged(IMixedRealityInputSource source, Handedness handedness, MixedRealityInputAction inputAction, MixedRealityPose inputData) { inputAction = ProcessRules(inputAction, inputData); // Create input event poseInputEventData.Initialize(source, handedness, inputAction, inputData); // Pass handler through HandleEvent to perform modal/fallback logic HandleEvent(poseInputEventData, OnPoseInputChanged); } #endregion Input Pose Changed #endregion Generic Input Events #region Gesture Events private static readonly ExecuteEvents.EventFunction<IMixedRealityGestureHandler> OnGestureStarted = delegate (IMixedRealityGestureHandler handler, BaseEventData eventData) { var casted = ExecuteEvents.ValidateEventData<InputEventData>(eventData); handler.OnGestureStarted(casted); }; private static readonly ExecuteEvents.EventFunction<IMixedRealityBaseInputHandler> OnGestureStartedWithAction = delegate (IMixedRealityBaseInputHandler handler, BaseEventData eventData) { var inputData = ExecuteEvents.ValidateEventData<InputEventData>(eventData); Debug.Assert(inputData.MixedRealityInputAction != MixedRealityInputAction.None); var gestureHandler = handler as IMixedRealityGestureHandler; if (gestureHandler != null) { gestureHandler.OnGestureStarted(inputData); } var actionHandler = handler as IMixedRealityInputActionHandler; if (actionHandler != null) { actionHandler.OnActionStarted(inputData); } }; /// <inheritdoc /> public void RaiseGestureStarted(IMixedRealityController controller, MixedRealityInputAction action) { action = ProcessRules(action, true); inputEventData.Initialize(controller.InputSource, controller.ControllerHandedness, action); if (action == MixedRealityInputAction.None) { HandleEvent(inputEventData, OnGestureStarted); } else { HandleEvent(inputEventData, OnGestureStartedWithAction); } } private static readonly ExecuteEvents.EventFunction<IMixedRealityGestureHandler> OnGestureUpdated = delegate (IMixedRealityGestureHandler handler, BaseEventData eventData) { var casted = ExecuteEvents.ValidateEventData<InputEventData>(eventData); handler.OnGestureUpdated(casted); }; /// <inheritdoc /> public void RaiseGestureUpdated(IMixedRealityController controller, MixedRealityInputAction action) { action = ProcessRules(action, true); inputEventData.Initialize(controller.InputSource, controller.ControllerHandedness, action); HandleEvent(inputEventData, OnGestureUpdated); } private static readonly ExecuteEvents.EventFunction<IMixedRealityGestureHandler<Vector2>> OnGestureVector2PositionUpdated = delegate (IMixedRealityGestureHandler<Vector2> handler, BaseEventData eventData) { var casted = ExecuteEvents.ValidateEventData<InputEventData<Vector2>>(eventData); handler.OnGestureUpdated(casted); }; /// <inheritdoc /> public void RaiseGestureUpdated(IMixedRealityController controller, MixedRealityInputAction action, Vector2 inputData) { action = ProcessRules(action, inputData); vector2InputEventData.Initialize(controller.InputSource, controller.ControllerHandedness, action, inputData); HandleEvent(vector2InputEventData, OnGestureVector2PositionUpdated); } private static readonly ExecuteEvents.EventFunction<IMixedRealityGestureHandler<Vector3>> OnGesturePositionUpdated = delegate (IMixedRealityGestureHandler<Vector3> handler, BaseEventData eventData) { var casted = ExecuteEvents.ValidateEventData<InputEventData<Vector3>>(eventData); handler.OnGestureUpdated(casted); }; /// <inheritdoc /> public void RaiseGestureUpdated(IMixedRealityController controller, MixedRealityInputAction action, Vector3 inputData) { action = ProcessRules(action, inputData); positionInputEventData.Initialize(controller.InputSource, controller.ControllerHandedness, action, inputData); HandleEvent(positionInputEventData, OnGesturePositionUpdated); } private static readonly ExecuteEvents.EventFunction<IMixedRealityGestureHandler<Quaternion>> OnGestureRotationUpdated = delegate (IMixedRealityGestureHandler<Quaternion> handler, BaseEventData eventData) { var casted = ExecuteEvents.ValidateEventData<InputEventData<Quaternion>>(eventData); handler.OnGestureUpdated(casted); }; /// <inheritdoc /> public void RaiseGestureUpdated(IMixedRealityController controller, MixedRealityInputAction action, Quaternion inputData) { action = ProcessRules(action, inputData); rotationInputEventData.Initialize(controller.InputSource, controller.ControllerHandedness, action, inputData); HandleEvent(rotationInputEventData, OnGestureRotationUpdated); } private static readonly ExecuteEvents.EventFunction<IMixedRealityGestureHandler<MixedRealityPose>> OnGesturePoseUpdated = delegate (IMixedRealityGestureHandler<MixedRealityPose> handler, BaseEventData eventData) { var casted = ExecuteEvents.ValidateEventData<InputEventData<MixedRealityPose>>(eventData); handler.OnGestureUpdated(casted); }; /// <inheritdoc /> public void RaiseGestureUpdated(IMixedRealityController controller, MixedRealityInputAction action, MixedRealityPose inputData) { action = ProcessRules(action, inputData); poseInputEventData.Initialize(controller.InputSource, controller.ControllerHandedness, action, inputData); HandleEvent(poseInputEventData, OnGesturePoseUpdated); } private static readonly ExecuteEvents.EventFunction<IMixedRealityGestureHandler> OnGestureCompleted = delegate (IMixedRealityGestureHandler handler, BaseEventData eventData) { var casted = ExecuteEvents.ValidateEventData<InputEventData>(eventData); handler.OnGestureCompleted(casted); }; private static readonly ExecuteEvents.EventFunction<IMixedRealityBaseInputHandler> OnGestureCompletedWithAction = delegate (IMixedRealityBaseInputHandler handler, BaseEventData eventData) { var inputData = ExecuteEvents.ValidateEventData<InputEventData>(eventData); Debug.Assert(inputData.MixedRealityInputAction != MixedRealityInputAction.None); var gestureHandler = handler as IMixedRealityGestureHandler; if (gestureHandler != null) { gestureHandler.OnGestureCompleted(inputData); } var actionHandler = handler as IMixedRealityInputActionHandler; if (actionHandler != null) { actionHandler.OnActionEnded(inputData); } }; /// <inheritdoc /> public void RaiseGestureCompleted(IMixedRealityController controller, MixedRealityInputAction action) { action = ProcessRules(action, false); inputEventData.Initialize(controller.InputSource, controller.ControllerHandedness, action); if (action == MixedRealityInputAction.None) { HandleEvent(inputEventData, OnGestureCompleted); } else { HandleEvent(inputEventData, OnGestureCompletedWithAction); } } private static readonly ExecuteEvents.EventFunction<IMixedRealityGestureHandler<Vector2>> OnGestureVector2PositionCompleted = delegate (IMixedRealityGestureHandler<Vector2> handler, BaseEventData eventData) { var casted = ExecuteEvents.ValidateEventData<InputEventData<Vector2>>(eventData); handler.OnGestureCompleted(casted); }; /// <inheritdoc /> public void RaiseGestureCompleted(IMixedRealityController controller, MixedRealityInputAction action, Vector2 inputData) { action = ProcessRules(action, inputData); vector2InputEventData.Initialize(controller.InputSource, controller.ControllerHandedness, action, inputData); HandleEvent(vector2InputEventData, OnGestureVector2PositionCompleted); } private static readonly ExecuteEvents.EventFunction<IMixedRealityGestureHandler<Vector3>> OnGesturePositionCompleted = delegate (IMixedRealityGestureHandler<Vector3> handler, BaseEventData eventData) { var casted = ExecuteEvents.ValidateEventData<InputEventData<Vector3>>(eventData); handler.OnGestureCompleted(casted); }; /// <inheritdoc /> public void RaiseGestureCompleted(IMixedRealityController controller, MixedRealityInputAction action, Vector3 inputData) { action = ProcessRules(action, inputData); positionInputEventData.Initialize(controller.InputSource, controller.ControllerHandedness, action, inputData); HandleEvent(positionInputEventData, OnGesturePositionCompleted); } private static readonly ExecuteEvents.EventFunction<IMixedRealityGestureHandler<Quaternion>> OnGestureRotationCompleted = delegate (IMixedRealityGestureHandler<Quaternion> handler, BaseEventData eventData) { var casted = ExecuteEvents.ValidateEventData<InputEventData<Quaternion>>(eventData); handler.OnGestureCompleted(casted); }; /// <inheritdoc /> public void RaiseGestureCompleted(IMixedRealityController controller, MixedRealityInputAction action, Quaternion inputData) { action = ProcessRules(action, inputData); rotationInputEventData.Initialize(controller.InputSource, controller.ControllerHandedness, action, inputData); HandleEvent(rotationInputEventData, OnGestureRotationCompleted); } private static readonly ExecuteEvents.EventFunction<IMixedRealityGestureHandler<MixedRealityPose>> OnGesturePoseCompleted = delegate (IMixedRealityGestureHandler<MixedRealityPose> handler, BaseEventData eventData) { var casted = ExecuteEvents.ValidateEventData<InputEventData<MixedRealityPose>>(eventData); handler.OnGestureCompleted(casted); }; /// <inheritdoc /> public void RaiseGestureCompleted(IMixedRealityController controller, MixedRealityInputAction action, MixedRealityPose inputData) { action = ProcessRules(action, inputData); poseInputEventData.Initialize(controller.InputSource, controller.ControllerHandedness, action, inputData); HandleEvent(poseInputEventData, OnGesturePoseCompleted); } private static readonly ExecuteEvents.EventFunction<IMixedRealityGestureHandler> OnGestureCanceled = delegate (IMixedRealityGestureHandler handler, BaseEventData eventData) { var casted = ExecuteEvents.ValidateEventData<InputEventData>(eventData); handler.OnGestureCanceled(casted); }; /// <inheritdoc /> public void RaiseGestureCanceled(IMixedRealityController controller, MixedRealityInputAction action) { action = ProcessRules(action, false); inputEventData.Initialize(controller.InputSource, controller.ControllerHandedness, action); HandleEvent(inputEventData, OnGestureCanceled); } #endregion Gesture Events #region Speech Keyword Events private static readonly ExecuteEvents.EventFunction<IMixedRealitySpeechHandler> OnSpeechKeywordRecognizedEventHandler = delegate (IMixedRealitySpeechHandler handler, BaseEventData eventData) { var casted = ExecuteEvents.ValidateEventData<SpeechEventData>(eventData); handler.OnSpeechKeywordRecognized(casted); }; private static readonly ExecuteEvents.EventFunction<IMixedRealityBaseInputHandler> OnSpeechKeywordRecognizedWithActionEventHandler = delegate (IMixedRealityBaseInputHandler handler, BaseEventData eventData) { var speechData = ExecuteEvents.ValidateEventData<SpeechEventData>(eventData); Debug.Assert(speechData.MixedRealityInputAction != MixedRealityInputAction.None); var speechHandler = handler as IMixedRealitySpeechHandler; if (speechHandler != null) { speechHandler.OnSpeechKeywordRecognized(speechData); } var actionHandler = handler as IMixedRealityInputActionHandler; if (actionHandler != null) { actionHandler.OnActionStarted(speechData); actionHandler.OnActionEnded(speechData); } }; /// <inheritdoc /> public void RaiseSpeechCommandRecognized(IMixedRealityInputSource source, RecognitionConfidenceLevel confidence, TimeSpan phraseDuration, DateTime phraseStartTime, SpeechCommands command) { // Create input event speechEventData.Initialize(source, confidence, phraseDuration, phraseStartTime, command); FocusProvider?.OnSpeechKeywordRecognized(speechEventData); // Pass handler through HandleEvent to perform modal/fallback logic if (command.Action == MixedRealityInputAction.None) { HandleEvent(speechEventData, OnSpeechKeywordRecognizedEventHandler); } else { HandleEvent(speechEventData, OnSpeechKeywordRecognizedWithActionEventHandler); } } #endregion Speech Keyword Events #region Dictation Events private static readonly ExecuteEvents.EventFunction<IMixedRealityDictationHandler> OnDictationHypothesisEventHandler = delegate (IMixedRealityDictationHandler handler, BaseEventData eventData) { var casted = ExecuteEvents.ValidateEventData<DictationEventData>(eventData); handler.OnDictationHypothesis(casted); }; /// <inheritdoc /> public void RaiseDictationHypothesis(IMixedRealityInputSource source, string dictationHypothesis, AudioClip dictationAudioClip = null) { // Create input event dictationEventData.Initialize(source, dictationHypothesis, dictationAudioClip); // Pass handler through HandleEvent to perform modal/fallback logic HandleEvent(dictationEventData, OnDictationHypothesisEventHandler); } private static readonly ExecuteEvents.EventFunction<IMixedRealityDictationHandler> OnDictationResultEventHandler = delegate (IMixedRealityDictationHandler handler, BaseEventData eventData) { var casted = ExecuteEvents.ValidateEventData<DictationEventData>(eventData); handler.OnDictationResult(casted); }; /// <inheritdoc /> public void RaiseDictationResult(IMixedRealityInputSource source, string dictationResult, AudioClip dictationAudioClip = null) { // Create input event dictationEventData.Initialize(source, dictationResult, dictationAudioClip); // Pass handler through HandleEvent to perform modal/fallback logic HandleEvent(dictationEventData, OnDictationResultEventHandler); } private static readonly ExecuteEvents.EventFunction<IMixedRealityDictationHandler> OnDictationCompleteEventHandler = delegate (IMixedRealityDictationHandler handler, BaseEventData eventData) { var casted = ExecuteEvents.ValidateEventData<DictationEventData>(eventData); handler.OnDictationComplete(casted); }; /// <inheritdoc /> public void RaiseDictationComplete(IMixedRealityInputSource source, string dictationResult, AudioClip dictationAudioClip) { // Create input event dictationEventData.Initialize(source, dictationResult, dictationAudioClip); // Pass handler through HandleEvent to perform modal/fallback logic HandleEvent(dictationEventData, OnDictationCompleteEventHandler); } private static readonly ExecuteEvents.EventFunction<IMixedRealityDictationHandler> OnDictationErrorEventHandler = delegate (IMixedRealityDictationHandler handler, BaseEventData eventData) { var casted = ExecuteEvents.ValidateEventData<DictationEventData>(eventData); handler.OnDictationError(casted); }; /// <inheritdoc /> public void RaiseDictationError(IMixedRealityInputSource source, string dictationResult, AudioClip dictationAudioClip = null) { // Create input event dictationEventData.Initialize(source, dictationResult, dictationAudioClip); // Pass handler through HandleEvent to perform modal/fallback logic HandleEvent(dictationEventData, OnDictationErrorEventHandler); } #endregion Dictation Events #region Hand Events private static readonly ExecuteEvents.EventFunction<IMixedRealityHandJointHandler> OnHandJointsUpdatedEventHandler = delegate (IMixedRealityHandJointHandler handler, BaseEventData eventData) { var casted = ExecuteEvents.ValidateEventData<InputEventData<IDictionary<TrackedHandJoint, MixedRealityPose>>>(eventData); handler.OnHandJointsUpdated(casted); }; public void RaiseHandJointsUpdated(IMixedRealityInputSource source, Handedness handedness, IDictionary<TrackedHandJoint, MixedRealityPose> jointPoses) { // Create input event jointPoseInputEventData.Initialize(source, handedness, MixedRealityInputAction.None, jointPoses); // Pass handler through HandleEvent to perform modal/fallback logic HandleEvent(jointPoseInputEventData, OnHandJointsUpdatedEventHandler); } private static readonly ExecuteEvents.EventFunction<IMixedRealityHandMeshHandler> OnHandMeshUpdatedEventHandler = delegate (IMixedRealityHandMeshHandler handler, BaseEventData eventData) { var casted = ExecuteEvents.ValidateEventData<InputEventData<HandMeshInfo>>(eventData); handler.OnHandMeshUpdated(casted); }; public void RaiseHandMeshUpdated(IMixedRealityInputSource source, Handedness handedness, HandMeshInfo handMeshInfo) { // Create input event handMeshInputEventData.Initialize(source, handedness, MixedRealityInputAction.None, handMeshInfo); // Pass handler through HandleEvent to perform modal/fallback logic HandleEvent(handMeshInputEventData, OnHandMeshUpdatedEventHandler); } private static readonly ExecuteEvents.EventFunction<IMixedRealityTouchHandler> OnTouchStartedEventHandler = delegate (IMixedRealityTouchHandler handler, BaseEventData eventData) { var casted = ExecuteEvents.ValidateEventData<HandTrackingInputEventData>(eventData); handler.OnTouchStarted(casted); }; /// <inheritdoc /> public void RaiseOnTouchStarted(IMixedRealityInputSource source, IMixedRealityController controller, Handedness handedness, Vector3 touchPoint) { // Create input event handTrackingInputEventData.Initialize(source, controller, handedness, touchPoint); // Pass handler through HandleEvent to perform modal/fallback logic HandleEvent(handTrackingInputEventData, OnTouchStartedEventHandler); } private static readonly ExecuteEvents.EventFunction<IMixedRealityTouchHandler> OnTouchCompletedEventHandler = delegate (IMixedRealityTouchHandler handler, BaseEventData eventData) { var casted = ExecuteEvents.ValidateEventData<HandTrackingInputEventData>(eventData); handler.OnTouchCompleted(casted); }; /// <inheritdoc /> public void RaiseOnTouchCompleted(IMixedRealityInputSource source, IMixedRealityController controller, Handedness handedness, Vector3 touchPoint) { // Create input event handTrackingInputEventData.Initialize(source, controller, handedness, touchPoint); // Pass handler through HandleEvent to perform modal/fallback logic HandleEvent(handTrackingInputEventData, OnTouchCompletedEventHandler); } private static readonly ExecuteEvents.EventFunction<IMixedRealityTouchHandler> OnTouchUpdatedEventHandler = delegate (IMixedRealityTouchHandler handler, BaseEventData eventData) { var casted = ExecuteEvents.ValidateEventData<HandTrackingInputEventData>(eventData); handler.OnTouchUpdated(casted); }; /// <inheritdoc /> public void RaiseOnTouchUpdated(IMixedRealityInputSource source, IMixedRealityController controller, Handedness handedness, Vector3 touchPoint) { // Create input event handTrackingInputEventData.Initialize(source, controller, handedness, touchPoint); // Pass handler through HandleEvent to perform modal/fallback logic HandleEvent(handTrackingInputEventData, OnTouchUpdatedEventHandler); } #endregion Hand Events #endregion Input Events #region Rules private static MixedRealityInputAction ProcessRules_Internal<T1, T2>(MixedRealityInputAction inputAction, T1[] inputActionRules, T2 criteria) where T1 : struct, IInputActionRule<T2> { for (int i = 0; i < inputActionRules.Length; i++) { if (inputActionRules[i].BaseAction == inputAction && inputActionRules[i].Criteria.Equals(criteria)) { if (inputActionRules[i].RuleAction == inputAction) { Debug.LogError("Input Action Rule cannot be the same as the rule's Base Action!"); return inputAction; } if (inputActionRules[i].BaseAction.AxisConstraint != inputActionRules[i].RuleAction.AxisConstraint) { Debug.LogError("Input Action Rule doesn't have the same Axis Constraint as the Base Action!"); return inputAction; } return inputActionRules[i].RuleAction; } } return inputAction; } private MixedRealityInputAction ProcessRules(MixedRealityInputAction inputAction, bool criteria) { if (CurrentInputActionRulesProfile != null && CurrentInputActionRulesProfile.InputActionRulesDigital?.Length > 0) { return ProcessRules_Internal(inputAction, CurrentInputActionRulesProfile.InputActionRulesDigital, criteria); } return inputAction; } private MixedRealityInputAction ProcessRules(MixedRealityInputAction inputAction, float criteria) { if (CurrentInputActionRulesProfile != null && CurrentInputActionRulesProfile.InputActionRulesSingleAxis?.Length > 0) { return ProcessRules_Internal(inputAction, CurrentInputActionRulesProfile.InputActionRulesSingleAxis, criteria); } return inputAction; } private MixedRealityInputAction ProcessRules(MixedRealityInputAction inputAction, Vector2 criteria) { if (CurrentInputActionRulesProfile != null && CurrentInputActionRulesProfile.InputActionRulesDualAxis?.Length > 0) { return ProcessRules_Internal(inputAction, CurrentInputActionRulesProfile.InputActionRulesDualAxis, criteria); } return inputAction; } private MixedRealityInputAction ProcessRules(MixedRealityInputAction inputAction, Vector3 criteria) { if (CurrentInputActionRulesProfile != null && CurrentInputActionRulesProfile.InputActionRulesVectorAxis?.Length > 0) { return ProcessRules_Internal(inputAction, CurrentInputActionRulesProfile.InputActionRulesVectorAxis, criteria); } return inputAction; } private MixedRealityInputAction ProcessRules(MixedRealityInputAction inputAction, Quaternion criteria) { if (CurrentInputActionRulesProfile != null && CurrentInputActionRulesProfile.InputActionRulesQuaternionAxis?.Length > 0) { return ProcessRules_Internal(inputAction, CurrentInputActionRulesProfile.InputActionRulesQuaternionAxis, criteria); } return inputAction; } private MixedRealityInputAction ProcessRules(MixedRealityInputAction inputAction, MixedRealityPose criteria) { if (CurrentInputActionRulesProfile != null && CurrentInputActionRulesProfile.InputActionRulesPoseAxis?.Length > 0) { return ProcessRules_Internal(inputAction, CurrentInputActionRulesProfile.InputActionRulesPoseAxis, criteria); } return inputAction; } #endregion Rules } }
44.697233
275
0.632652
[ "MIT" ]
MIT-Reality-Hack-2020/FocusField
handtest2/Assets/MixedRealityToolkit.Services/InputSystem/MixedRealityInputSystem.cs
82,377
C#
using System.Windows; namespace Millarow.Presentation.WPF.Input { public class MoverPerformManipulationEventArgs : MoverManipulationEventArgs { public MoverPerformManipulationEventArgs(UIElement sourceElement, RectManipulations manipulation, Vector sizeVector, Vector positionVector) : base(sourceElement, manipulation) { SizeVector = sizeVector; PositionVector = positionVector; } public Vector SizeVector { get; } public Vector PositionVector { get; } } }
30.5
147
0.695811
[ "MIT" ]
mcculic/millarowframework
src/Millarow.Presentation.WPF/Input/MoverPerformManipulationEventArgs.cs
551
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; namespace Microsoft.AspNetCore.SignalR.Tests { public static class ExceptionMessageExtensions { public static string GetLocalizationSafeMessage(this ArgumentException argEx) { // Strip off the last line since it's "Parameter Name: [parameterName]" and: // 1. We verify the parameter name separately // 2. It is localized, so we don't want our tests to break in non-US environments var message = argEx.Message; var lastNewline = message.LastIndexOf(" (Parameter", StringComparison.Ordinal); if (lastNewline < 0) { return message; } return message.Substring(0, lastNewline); } } }
34.346154
93
0.634938
[ "MIT" ]
48355746/AspNetCore
src/SignalR/common/testassets/Tests.Utils/ExceptionMessageExtensions.cs
893
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.Slb.Model.V20140515 { public class DescribeLoadBalancerHTTPListenerAttributeResponse : AcsResponse { private string requestId; private int? listenerPort; private int? backendServerPort; private int? bandwidth; private string status; private string securityStatus; private string xForwardedFor; private string scheduler; private string stickySession; private string stickySessionType; private int? cookieTimeout; private string cookie; private string healthCheck; private string healthCheckDomain; private string healthCheckURI; private int? healthyThreshold; private int? unhealthyThreshold; private int? healthCheckTimeout; private int? healthCheckInterval; private int? healthCheckConnectPort; private string healthCheckHttpCode; private string healthCheckMethod; private int? maxConnection; private string vServerGroupId; private string gzip; private string xForwardedFor_SLBIP; private string xForwardedFor_SLBID; private string xForwardedFor_proto; private string aclId; private string aclType; private string aclStatus; private string vpcIds; private string listenerForward; private int? forwardPort; private int? requestTimeout; private int? idleTimeout; private string description; private List<DescribeLoadBalancerHTTPListenerAttribute_Rule> rules; public string RequestId { get { return requestId; } set { requestId = value; } } public int? ListenerPort { get { return listenerPort; } set { listenerPort = value; } } public int? BackendServerPort { get { return backendServerPort; } set { backendServerPort = value; } } public int? Bandwidth { get { return bandwidth; } set { bandwidth = value; } } public string Status { get { return status; } set { status = value; } } public string SecurityStatus { get { return securityStatus; } set { securityStatus = value; } } public string XForwardedFor { get { return xForwardedFor; } set { xForwardedFor = value; } } public string Scheduler { get { return scheduler; } set { scheduler = value; } } public string StickySession { get { return stickySession; } set { stickySession = value; } } public string StickySessionType { get { return stickySessionType; } set { stickySessionType = value; } } public int? CookieTimeout { get { return cookieTimeout; } set { cookieTimeout = value; } } public string Cookie { get { return cookie; } set { cookie = value; } } public string HealthCheck { get { return healthCheck; } set { healthCheck = value; } } public string HealthCheckDomain { get { return healthCheckDomain; } set { healthCheckDomain = value; } } public string HealthCheckURI { get { return healthCheckURI; } set { healthCheckURI = value; } } public int? HealthyThreshold { get { return healthyThreshold; } set { healthyThreshold = value; } } public int? UnhealthyThreshold { get { return unhealthyThreshold; } set { unhealthyThreshold = value; } } public int? HealthCheckTimeout { get { return healthCheckTimeout; } set { healthCheckTimeout = value; } } public int? HealthCheckInterval { get { return healthCheckInterval; } set { healthCheckInterval = value; } } public int? HealthCheckConnectPort { get { return healthCheckConnectPort; } set { healthCheckConnectPort = value; } } public string HealthCheckHttpCode { get { return healthCheckHttpCode; } set { healthCheckHttpCode = value; } } public string HealthCheckMethod { get { return healthCheckMethod; } set { healthCheckMethod = value; } } public int? MaxConnection { get { return maxConnection; } set { maxConnection = value; } } public string VServerGroupId { get { return vServerGroupId; } set { vServerGroupId = value; } } public string Gzip { get { return gzip; } set { gzip = value; } } public string XForwardedFor_SLBIP { get { return xForwardedFor_SLBIP; } set { xForwardedFor_SLBIP = value; } } public string XForwardedFor_SLBID { get { return xForwardedFor_SLBID; } set { xForwardedFor_SLBID = value; } } public string XForwardedFor_proto { get { return xForwardedFor_proto; } set { xForwardedFor_proto = value; } } public string AclId { get { return aclId; } set { aclId = value; } } public string AclType { get { return aclType; } set { aclType = value; } } public string AclStatus { get { return aclStatus; } set { aclStatus = value; } } public string VpcIds { get { return vpcIds; } set { vpcIds = value; } } public string ListenerForward { get { return listenerForward; } set { listenerForward = value; } } public int? ForwardPort { get { return forwardPort; } set { forwardPort = value; } } public int? RequestTimeout { get { return requestTimeout; } set { requestTimeout = value; } } public int? IdleTimeout { get { return idleTimeout; } set { idleTimeout = value; } } public string Description { get { return description; } set { description = value; } } public List<DescribeLoadBalancerHTTPListenerAttribute_Rule> Rules { get { return rules; } set { rules = value; } } public class DescribeLoadBalancerHTTPListenerAttribute_Rule { private string ruleId; private string ruleName; private string domain; private string url; private string vServerGroupId; public string RuleId { get { return ruleId; } set { ruleId = value; } } public string RuleName { get { return ruleName; } set { ruleName = value; } } public string Domain { get { return domain; } set { domain = value; } } public string Url { get { return url; } set { url = value; } } public string VServerGroupId { get { return vServerGroupId; } set { vServerGroupId = value; } } } } }
13.437795
78
0.556076
[ "Apache-2.0" ]
fossabot/aliyun-openapi-net-sdk
aliyun-net-sdk-slb/Slb/Model/V20140515/DescribeLoadBalancerHTTPListenerAttributeResponse.cs
8,533
C#
using GalaSoft.MvvmLight.Views; using System; using System.Collections.Generic; using System.Text; using System.Linq; using Xamarin.Forms; namespace Vector.Explorer.ViewModel { public class NavigationService : INavigationService { INavigation _nav; static Dictionary<string, Type> _pages; public NavigationService(INavigation nav) { //set fields _nav = nav; if (_pages == null) _pages = GetPages(); } Dictionary<string, Type> GetPages() { return new Dictionary<string, Type>() { //register pages {Pages.NewConnection.ToString(), typeof(NewConnection) } }; } public string CurrentPageKey { get { var page = _nav.NavigationStack.LastOrDefault(); if (page == null) return null; var pageKey = _pages.FirstOrDefault(i => i.Value == page.GetType()); if (pageKey.Value == null) return null; return pageKey.Key; } } public void GoBack() { _nav.PopModalAsync(); } public void NavigateTo(string pageKey) { //get page if (!_pages.ContainsKey(pageKey)) return; var pageType = _pages[pageKey]; //create instance var page = Activator.CreateInstance(pageType) as Page; //navigate _nav.PushModalAsync(page); } public void NavigateTo(string pageKey, object parameter) { //get page if (!_pages.ContainsKey(pageKey)) return; var pageType = _pages[pageKey]; //create instance var page = Activator.CreateInstance(pageType, parameter) as Page; //navigate _nav.PushModalAsync(page); } } }
18.841463
72
0.671845
[ "MIT" ]
zaront/Vector
Vector.Explorer/Vector.Explorer/ViewModel/NavigationService.cs
1,547
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Roslyn.Compilers.CSharp.Emit { internal sealed class GenericMethodParameterDefinition : GenericParameterDefinition, Microsoft.Cci.IGenericMethodParameter { public GenericMethodParameterDefinition(Module moduleBeingBuilt, TypeParameterSymbol underlyingTypeParameter) : base(moduleBeingBuilt, underlyingTypeParameter) { } public override void Dispatch(Microsoft.Cci.IMetadataVisitor visitor) { visitor.Visit((Microsoft.Cci.IGenericMethodParameter)this); } Microsoft.Cci.IMethodDefinition Microsoft.Cci.IGenericMethodParameter.DefiningMethod { get { return (Microsoft.Cci.IMethodDefinition)ModuleBeingBuilt.Translate((MethodSymbol)UnderlyingTypeParameter.ContainingSymbol, true); } } Microsoft.Cci.IMethodReference Microsoft.Cci.IGenericMethodParameterReference.DefiningMethod { get { return ModuleBeingBuilt.Translate((MethodSymbol)UnderlyingTypeParameter.ContainingSymbol, true); } } protected override Microsoft.Cci.IArrayTypeReference AsArrayTypeReference { get { return null; } } protected override Microsoft.Cci.IDefinition AsDefinition { get { return null; } } protected override Microsoft.Cci.IFunctionPointerTypeReference AsFunctionPointerTypeReference { get { return null; } } protected override Microsoft.Cci.IGenericMethodParameter AsGenericMethodParameter { get { return this; } } protected override Microsoft.Cci.IGenericMethodParameterReference AsGenericMethodParameterReference { get { return this; } } protected override Microsoft.Cci.IGenericTypeInstanceReference AsGenericTypeInstanceReference { get { return null; } } protected override Microsoft.Cci.IGenericTypeParameter AsGenericTypeParameter { get { return null; } } protected override Microsoft.Cci.IGenericTypeParameterReference AsGenericTypeParameterReference { get { return null; } } protected override Microsoft.Cci.IManagedPointerTypeReference AsManagedPointerTypeReference { get { return null; } } protected override Microsoft.Cci.IModifiedTypeReference AsModifiedTypeReference { get { return null; } } protected override Microsoft.Cci.INamespaceTypeDefinition AsNamespaceTypeDefinition { get { return null; } } protected override Microsoft.Cci.INamespaceTypeReference AsNamespaceTypeReference { get { return null; } } protected override Microsoft.Cci.INestedTypeDefinition AsNestedTypeDefinition { get { return null; } } protected override Microsoft.Cci.INestedTypeReference AsNestedTypeReference { get { return null; } } protected override Microsoft.Cci.IPointerTypeReference AsPointerTypeReference { get { return null; } } protected override Microsoft.Cci.ISpecializedNestedTypeReference AsSpecializedNestedTypeReference { get { return null; } } protected override Microsoft.Cci.ITypeDefinition AsTypeDefinition { get { return null; } } } }
30.01626
145
0.642741
[ "Apache-2.0" ]
enginekit/copy_of_roslyn
Src/Compilers/CSharp/Source/Emitter/GenericMethodParameterDefinition.cs
3,694
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 amplify-2017-07-25.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using System.Net; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.Amplify.Model { /// <summary> /// Container for the parameters to the CreateWebhook operation. /// Create a new webhook on an App. /// </summary> public partial class CreateWebhookRequest : AmazonAmplifyRequest { private string _appId; private string _branchName; private string _description; /// <summary> /// Gets and sets the property AppId. /// <para> /// Unique Id for an Amplify App. /// </para> /// </summary> [AWSProperty(Required=true, Min=1, Max=255)] public string AppId { get { return this._appId; } set { this._appId = value; } } // Check to see if AppId property is set internal bool IsSetAppId() { return this._appId != null; } /// <summary> /// Gets and sets the property BranchName. /// <para> /// Name for a branch, part of an Amplify App. /// </para> /// </summary> [AWSProperty(Required=true, Min=1, Max=255)] public string BranchName { get { return this._branchName; } set { this._branchName = value; } } // Check to see if BranchName property is set internal bool IsSetBranchName() { return this._branchName != null; } /// <summary> /// Gets and sets the property Description. /// <para> /// Description for a webhook. /// </para> /// </summary> [AWSProperty(Max=1000)] public string Description { get { return this._description; } set { this._description = value; } } // Check to see if Description property is set internal bool IsSetDescription() { return this._description != null; } } }
28.606061
105
0.589689
[ "Apache-2.0" ]
Melvinerall/aws-sdk-net
sdk/src/Services/Amplify/Generated/Model/CreateWebhookRequest.cs
2,832
C#
//----------------------------------------------------------------------- // <copyright file="MixinPublicDataMembersAreInjectedIntoTarget.cs" company="Copacetic Software"> // Copyright (c) Copacetic Software. // <author>Philip Pittle</author> // <date>Wednesday, January 29, 2014 10:57:24 PM</date> // Licensed under the Apache License, Version 2.0, // you may not use this file except in compliance with this 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 CopaceticSoftware.pMixins.Tests.Common.Extensions; using NBehave.Spec.NUnit; using NUnit.Framework; namespace CopaceticSoftware.pMixins.CodeGenerator.Tests.IntegrationTests.CompileTests.BasicTests { [TestFixture] public class MixinPublicDataMembersAreInjectedIntoTarget : GenerateCodeAndCompileTestBase { protected override string SourceCode { get { return @" namespace Test { public class MixinWithPublicDataMembers { public string DataMemberForReadTest = ""ReadTest""; public string DataMemberForReadWriteTest; public int IntegerDataMember = 1; public System.Int32 IntegerDataMember2 = 42; public float FloatDataMember = 2f; public short ShortDataMember = 3; public double DoubleDataMember = 4d; public long LongDataMember = 5L; public char CharDataMember = '6'; public bool BoolDataMember = true; public byte ByteDataMember = 0; public uint UIntDataMember = 8; } [CopaceticSoftware.pMixins.Attributes.pMixin(Mixin = typeof (Test.MixinWithPublicDataMembers))] public partial class Target{} } "; } } [Test] public void CanReadDataMember() { //Assume DataMember will be exposed as Property CompilerResults .ExecutePropertyGet<string>( "Test.Target", "DataMemberForReadTest", BindingFlags.Instance | BindingFlags.GetProperty | BindingFlags.Public) .ShouldEqual("ReadTest"); CompilerResults .ExecutePropertyGet<int>( "Test.Target", "IntegerDataMember", BindingFlags.Instance | BindingFlags.GetProperty | BindingFlags.Public) .ShouldEqual(1); CompilerResults .ExecutePropertyGet<int>( "Test.Target", "IntegerDataMember2", BindingFlags.Instance | BindingFlags.GetProperty | BindingFlags.Public) .ShouldEqual(42); CompilerResults .ExecutePropertyGet<float>( "Test.Target", "FloatDataMember", BindingFlags.Instance | BindingFlags.GetProperty | BindingFlags.Public) .ShouldEqual(2f); CompilerResults .ExecutePropertyGet<short>( "Test.Target", "ShortDataMember", BindingFlags.Instance | BindingFlags.GetProperty | BindingFlags.Public) .ShouldEqual((short)3); CompilerResults .ExecutePropertyGet<double>( "Test.Target", "DoubleDataMember", BindingFlags.Instance | BindingFlags.GetProperty | BindingFlags.Public) .ShouldEqual(4d); CompilerResults .ExecutePropertyGet<long>( "Test.Target", "LongDataMember", BindingFlags.Instance | BindingFlags.GetProperty | BindingFlags.Public) .ShouldEqual(5L); CompilerResults .ExecutePropertyGet<char>( "Test.Target", "CharDataMember", BindingFlags.Instance | BindingFlags.GetProperty | BindingFlags.Public) .ShouldEqual('6'); CompilerResults .ExecutePropertyGet<bool>( "Test.Target", "BoolDataMember", BindingFlags.Instance | BindingFlags.GetProperty | BindingFlags.Public) .ShouldEqual(true); CompilerResults .ExecutePropertyGet<byte>( "Test.Target", "ByteDataMember", BindingFlags.Instance | BindingFlags.GetProperty | BindingFlags.Public) .ShouldEqual(byte.Parse("0")); CompilerResults .ExecutePropertyGet<uint>( "Test.Target", "UIntDataMember", BindingFlags.Instance | BindingFlags.GetProperty | BindingFlags.Public) .ShouldEqual((uint)8); } [Test] public void CanWriteToDataMember() { //Assume DataMember will be exposed as Property const string getSetDataMemberTest = "SuperDataMEmberTest!!"; var targetInstance = CompilerResults.TryLoadCompiledType("Test.Target"); if (null == targetInstance) Assert.Fail("Failed to load Test.Target instance"); ReflectionHelper.ExecutePropertySet( targetInstance, "DataMemberForReadWriteTest", getSetDataMemberTest); ReflectionHelper.ExecutePropertyGet<string>( targetInstance, "DataMemberForReadWriteTest") .ShouldEqual(getSetDataMemberTest); } } }
39.810651
123
0.517687
[ "Apache-2.0" ]
ppittle/pMixins
pMixins.CodeGenerator.Tests/IntegrationTests/CompileTests/BasicTests/MixinPublicDataMembersAreInjectedIntoTarget.cs
6,730
C#
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Reflection; namespace StudentRegistrationDemo2.Areas.HelpPage { /// <summary> /// This class will create an object of a given type and populate it with sample data. /// </summary> public class ObjectGenerator { internal const int DefaultCollectionSize = 2; private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator(); /// <summary> /// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types: /// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc. /// Complex types: POCO types. /// Nullables: <see cref="Nullable{T}"/>. /// Arrays: arrays of simple types or complex types. /// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/> /// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc /// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>. /// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>. /// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>An object of the given type.</returns> public object GenerateObject(Type type) { return GenerateObject(type, new Dictionary<Type, object>()); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")] private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences) { try { if (SimpleTypeObjectGenerator.CanGenerateObject(type)) { return SimpleObjectGenerator.GenerateObject(type); } if (type.IsArray) { return GenerateArray(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsGenericType) { return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IDictionary)) { return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences); } if (typeof(IDictionary).IsAssignableFrom(type)) { return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IList) || type == typeof(IEnumerable) || type == typeof(ICollection)) { return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences); } if (typeof(IList).IsAssignableFrom(type)) { return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IQueryable)) { return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsEnum) { return GenerateEnum(type); } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } } catch { // Returns null if anything fails return null; } return null; } private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences) { Type genericTypeDefinition = type.GetGenericTypeDefinition(); if (genericTypeDefinition == typeof(Nullable<>)) { return GenerateNullable(type, createdObjectReferences); } if (genericTypeDefinition == typeof(KeyValuePair<,>)) { return GenerateKeyValuePair(type, createdObjectReferences); } if (IsTuple(genericTypeDefinition)) { return GenerateTuple(type, createdObjectReferences); } Type[] genericArguments = type.GetGenericArguments(); if (genericArguments.Length == 1) { if (genericTypeDefinition == typeof(IList<>) || genericTypeDefinition == typeof(IEnumerable<>) || genericTypeDefinition == typeof(ICollection<>)) { Type collectionType = typeof(List<>).MakeGenericType(genericArguments); return GenerateCollection(collectionType, collectionSize, createdObjectReferences); } if (genericTypeDefinition == typeof(IQueryable<>)) { return GenerateQueryable(type, collectionSize, createdObjectReferences); } Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]); if (closedCollectionType.IsAssignableFrom(type)) { return GenerateCollection(type, collectionSize, createdObjectReferences); } } if (genericArguments.Length == 2) { if (genericTypeDefinition == typeof(IDictionary<,>)) { Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments); return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences); } Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]); if (closedDictionaryType.IsAssignableFrom(type)) { return GenerateDictionary(type, collectionSize, createdObjectReferences); } } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } return null; } private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = type.GetGenericArguments(); object[] parameterValues = new object[genericArgs.Length]; bool failedToCreateTuple = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < genericArgs.Length; i++) { parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences); failedToCreateTuple &= parameterValues[i] == null; } if (failedToCreateTuple) { return null; } object result = Activator.CreateInstance(type, parameterValues); return result; } private static bool IsTuple(Type genericTypeDefinition) { return genericTypeDefinition == typeof(Tuple<>) || genericTypeDefinition == typeof(Tuple<,>) || genericTypeDefinition == typeof(Tuple<,,>) || genericTypeDefinition == typeof(Tuple<,,,>) || genericTypeDefinition == typeof(Tuple<,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,,>); } private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = keyValuePairType.GetGenericArguments(); Type typeK = genericArgs[0]; Type typeV = genericArgs[1]; ObjectGenerator objectGenerator = new ObjectGenerator(); object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences); object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences); if (keyObject == null && valueObject == null) { // Failed to create key and values return null; } object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject); return result; } private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = arrayType.GetElementType(); Array result = Array.CreateInstance(type, size); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); result.SetValue(element, i); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences) { Type typeK = typeof(object); Type typeV = typeof(object); if (dictionaryType.IsGenericType) { Type[] genericArgs = dictionaryType.GetGenericArguments(); typeK = genericArgs[0]; typeV = genericArgs[1]; } object result = Activator.CreateInstance(dictionaryType); MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd"); MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey"); ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences); if (newKey == null) { // Cannot generate a valid key return null; } bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey }); if (!containsKey) { object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences); addMethod.Invoke(result, new object[] { newKey, newValue }); } } return result; } private static object GenerateEnum(Type enumType) { Array possibleValues = Enum.GetValues(enumType); if (possibleValues.Length > 0) { return possibleValues.GetValue(0); } return null; } private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences) { bool isGeneric = queryableType.IsGenericType; object list; if (isGeneric) { Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments()); list = GenerateCollection(listType, size, createdObjectReferences); } else { list = GenerateArray(typeof(object[]), size, createdObjectReferences); } if (list == null) { return null; } if (isGeneric) { Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments()); MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType }); return asQueryableMethod.Invoke(null, new[] { list }); } return Queryable.AsQueryable((IEnumerable)list); } private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = collectionType.IsGenericType ? collectionType.GetGenericArguments()[0] : typeof(object); object result = Activator.CreateInstance(collectionType); MethodInfo addMethod = collectionType.GetMethod("Add"); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); addMethod.Invoke(result, new object[] { element }); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences) { Type type = nullableType.GetGenericArguments()[0]; ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type, createdObjectReferences); } private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences) { object result = null; if (createdObjectReferences.TryGetValue(type, out result)) { // The object has been created already, just return it. This will handle the circular reference case. return result; } if (type.IsValueType) { result = Activator.CreateInstance(type); } else { ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes); if (defaultCtor == null) { // Cannot instantiate the type because it doesn't have a default constructor return null; } result = defaultCtor.Invoke(new object[0]); } createdObjectReferences.Add(type, result); SetPublicProperties(type, result, createdObjectReferences); SetPublicFields(type, result, createdObjectReferences); return result; } private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (PropertyInfo property in properties) { if (property.CanWrite) { object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences); property.SetValue(obj, propertyValue, null); } } } private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (FieldInfo field in fields) { object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences); field.SetValue(obj, fieldValue); } } private class SimpleTypeObjectGenerator { private long _index = 0; private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators(); [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")] private static Dictionary<Type, Func<long, object>> InitializeGenerators() { return new Dictionary<Type, Func<long, object>> { { typeof(Boolean), index => true }, { typeof(Byte), index => (Byte)64 }, { typeof(Char), index => (Char)65 }, { typeof(DateTime), index => DateTime.Now }, { typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) }, { typeof(DBNull), index => DBNull.Value }, { typeof(Decimal), index => (Decimal)index }, { typeof(Double), index => (Double)(index + 0.1) }, { typeof(Guid), index => Guid.NewGuid() }, { typeof(Int16), index => (Int16)(index % Int16.MaxValue) }, { typeof(Int32), index => (Int32)(index % Int32.MaxValue) }, { typeof(Int64), index => (Int64)index }, { typeof(Object), index => new object() }, { typeof(SByte), index => (SByte)64 }, { typeof(Single), index => (Single)(index + 0.1) }, { typeof(String), index => { return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index); } }, { typeof(TimeSpan), index => { return TimeSpan.FromTicks(1234567); } }, { typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) }, { typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) }, { typeof(UInt64), index => (UInt64)index }, { typeof(Uri), index => { return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index)); } }, }; } public static bool CanGenerateObject(Type type) { return DefaultGenerators.ContainsKey(type); } public object GenerateObject(Type type) { return DefaultGenerators[type](++_index); } } } }
42.776316
261
0.553471
[ "MIT" ]
prateekparallel/StudentRegistrationDemo2
StudentRegistrationDemo2/Areas/HelpPage/SampleGeneration/ObjectGenerator.cs
19,506
C#
using System; namespace PowerBlocks.Utilities { /// <summary> /// Contains an assortment of helper methods for the objects. /// </summary> public static class ObjectHelper { /// <summary> /// Safefully dispose a disposable object. If the object is null, then the method will safely return /// with no exceptions thrown. /// </summary> /// <param name="objectToDispose"></param> public static void SafeDispose(IDisposable objectToDispose) { if (objectToDispose != null) { objectToDispose.Dispose(); } } } }
22.625
102
0.683241
[ "MIT" ]
RaifordBrookshire/NetPowerBlocks
Source/PowerBlocksSolution/PowerBlocks/Utilities/ObjectHelper.cs
545
C#
/* * Copyright 2018 Mikhail Shiryaev * * 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. * * * Product : Rapid SCADA * Module : PlgSchBasicComp * Summary : Condition that defines a color * * Author : Mikhail Shiryaev * Created : 2018 * Modified : 2018 */ using Scada.Scheme.Model.DataTypes; using Scada.Scheme.Model.PropertyGrid; using System; using System.Drawing.Design; using System.Xml; using CM = System.ComponentModel; namespace Scada.Web.Plugins.SchBasicComp { /// <summary> /// Condition that defines a color /// <para>Условие, которое определяет цвет</para> /// </summary> [Serializable] public class ColorCondition : Condition { /// <summary> /// Конструктор /// </summary> public ColorCondition() : base() { Color = ""; } /// <summary> /// Получить или установить цвет, отображаемый при выполнении условия /// </summary> #region Attributes [DisplayName("Color"), Category(Categories.Appearance)] [CM.Editor(typeof(ColorEditor), typeof(UITypeEditor))] #endregion public string Color { get; set; } /// <summary> /// Загрузить условие из XML-узла /// </summary> public override void LoadFromXml(XmlNode xmlNode) { base.LoadFromXml(xmlNode); Color = xmlNode.GetChildAsString("Color"); } /// <summary> /// Сохранить условие в XML-узле /// </summary> public override void SaveToXml(XmlElement xmlElem) { base.SaveToXml(xmlElem); xmlElem.AppendElem("Color", Color); } /// <summary> /// Клонировать объект /// </summary> public override Condition Clone() { Condition clonedCondition = (Condition)ScadaUtils.DeepClone(this, PlgUtils.SerializationBinder); clonedCondition.SchemeDoc = SchemeDoc; return clonedCondition; } } }
28.318681
108
0.61234
[ "Apache-2.0" ]
carquiza/scada
ScadaWeb/ScadaScheme/PlgSchBasicComp/AppCode/SchBasicComp/ColorCondition.cs
2,735
C#
using System; using UnityEditor; using UnityEngine; using UnityEngine.UIElements; namespace Unity.DeviceSimulator { internal class DeviceView : IMGUIContainer { private Material m_PreviewMaterial; private Material m_DeviceMaterial; private Matrix4x4 m_DeviceToView; private Matrix4x4 m_ScreenToView; private int m_ScreenWidth; private int m_ScreenHeight; private float m_Rotation; private float m_Scale; private ScreenOrientation m_ScreenOrientation; private Vector4 m_BorderSize; private Vector4 m_ScreenInsets; private Texture m_PreviewTexture; private Texture m_OverlayTexture; private bool m_ShowSafeArea; private Rect m_SafeArea; private float m_SafeAreaLineWidth = 2f; private Color m_SafeAreaColor = Color.green; private Mesh m_SafeAreaMesh; private Mesh m_ScreenMesh; private Mesh m_OverlayMesh; private Mesh m_ProceduralOverlayMesh; public Quaternion Rotation { private get => Quaternion.Euler(0, 0, m_Rotation); set { m_Rotation = value.eulerAngles.z; ComputeBoundingBoxAndTransformations(); } } public float Scale { private get => m_Scale; set { m_Scale = value; ComputeBoundingBoxAndTransformations(); } } public Texture PreviewTexture { private get => m_PreviewTexture; set { m_PreviewTexture = value; } } public Texture OverlayTexture { private get => m_OverlayTexture; set { if (m_OverlayTexture != value) MarkDirtyRepaint(); m_OverlayTexture = value; } } public Vector4 ScreenInsets { private get => m_ScreenInsets; set { m_ScreenInsets = value; MarkDirtyRepaint(); } } public ScreenOrientation ScreenOrientation { private get => m_ScreenOrientation; set { m_ScreenOrientation = value; MarkDirtyRepaint(); } } public bool ShowSafeArea { private get => m_ShowSafeArea; set { m_ShowSafeArea = value; MarkDirtyRepaint(); } } public Rect SafeArea { private get => m_SafeArea; set { m_SafeArea = value; MarkDirtyRepaint(); } } public float SafeAreaLineWidth { private get => m_SafeAreaLineWidth; set { m_SafeAreaLineWidth = value; MarkDirtyRepaint(); } } public Color SafeAreaColor { private get => m_SafeAreaColor; set { m_SafeAreaColor = value; MarkDirtyRepaint(); } } public Matrix4x4 ViewToScreen { get; private set; } public event Action OnViewToScreenChanged; public DeviceView(Quaternion rotation, float scale) { m_Scale = scale; m_Rotation = rotation.eulerAngles.z; ComputeBoundingBoxAndTransformations(); onGUIHandler += OnIMGUIRendered; } public void SetDevice(int screenWidth, int screenHeight, Vector4 borderSize) { m_ScreenWidth = screenWidth; m_ScreenHeight = screenHeight; m_BorderSize = borderSize; ComputeBoundingBoxAndTransformations(); } private void OnIMGUIRendered() { if (EditorApplication.isPlaying && !EditorApplication.isPaused) EditorGUIUtility.keyboardControl = 0; var type = Event.current.type; if (type == EventType.Repaint) { if (PreviewTexture != null) { if (m_PreviewMaterial == null) m_PreviewMaterial = GUI.blitMaterial; if (m_DeviceMaterial == null) m_DeviceMaterial = new Material(Shader.Find("Hidden/Internal-GUITextureClip")); DrawScreen(); DrawOverlay(); DrawSafeArea(); } } } private void DrawSafeArea() { if (!ShowSafeArea) return; CreateSafeAreaMesh(); m_PreviewMaterial.mainTexture = null; m_PreviewMaterial.SetPass(0); Graphics.DrawMeshNow(m_SafeAreaMesh, m_ScreenToView); } private void DrawScreen() { if (PreviewTexture == null) return; CreateScreenMesh(); m_PreviewMaterial.mainTexture = PreviewTexture; m_PreviewMaterial.SetPass(0); Graphics.DrawMeshNow(m_ScreenMesh, m_ScreenToView); } private void DrawOverlay() { if (m_OverlayTexture == null) { DrawOverlayProcedural(); return; } CreateOverlayMesh(); m_DeviceMaterial.mainTexture = m_OverlayTexture; m_DeviceMaterial.SetPass(0); Graphics.DrawMeshNow(m_OverlayMesh, m_DeviceToView); } private void DrawOverlayProcedural() { m_PreviewMaterial.mainTexture = null; m_PreviewMaterial.SetPass(0); if (m_ProceduralOverlayMesh == null) CreateProceduralOverlayMesh(); Graphics.DrawMeshNow(m_ProceduralOverlayMesh, m_DeviceToView); } private void ComputeBoundingBoxAndTransformations() { var width = m_ScreenWidth + m_BorderSize.x + m_BorderSize.z; var height = m_ScreenHeight + m_BorderSize.y + m_BorderSize.w; var rotateScale = Matrix4x4.TRS(Vector3.zero, Rotation, new Vector3(Scale, Scale, 1)); var vertices = new Vector3[4]; vertices[0] = rotateScale.MultiplyPoint(new Vector3(0, 0, Vertex.nearZ)); vertices[1] = rotateScale.MultiplyPoint(new Vector3(width, 0, Vertex.nearZ)); vertices[2] = rotateScale.MultiplyPoint(new Vector3(width, height, Vertex.nearZ)); vertices[3] = rotateScale.MultiplyPoint(new Vector3(0, height, Vertex.nearZ)); var min = new Vector2(float.MaxValue, float.MaxValue); var max = new Vector2(float.MinValue, float.MinValue); foreach (var vertex in vertices) { if (vertex.x < min.x) min.x = vertex.x; if (vertex.x > max.x) max.x = vertex.x; if (vertex.y < min.y) min.y = vertex.y; if (vertex.y > max.y) max.y = vertex.y; } var boundingBox = max - min; style.width = boundingBox.x; style.height = boundingBox.y; m_DeviceToView = Matrix4x4.Translate(new Vector3(boundingBox.x / 2, boundingBox.y / 2)) * rotateScale * Matrix4x4.Translate(new Vector3(-width / 2, -height / 2)); m_ScreenToView = Matrix4x4.Translate(new Vector3(boundingBox.x / 2, boundingBox.y / 2)) * rotateScale * Matrix4x4.Translate(new Vector3(-width / 2 + m_BorderSize.x, -height / 2 + m_BorderSize.y)); ViewToScreen = m_ScreenToView.inverse; OnViewToScreenChanged?.Invoke(); MarkDirtyRepaint(); } private void CreateSafeAreaMesh() { var scaledLineWidth = m_SafeAreaLineWidth / Scale; var vertices = new Vector3[8]; vertices[0] = new Vector3(SafeArea.x, SafeArea.y, Vertex.nearZ); vertices[1] = new Vector3(SafeArea.x + SafeArea.width, SafeArea.y, Vertex.nearZ); vertices[2] = new Vector3(SafeArea.x + SafeArea.width, SafeArea.y + SafeArea.height, Vertex.nearZ); vertices[3] = new Vector3(SafeArea.x, SafeArea.y + SafeArea.height, Vertex.nearZ); vertices[4] = new Vector3(SafeArea.x + scaledLineWidth, SafeArea.y + scaledLineWidth, Vertex.nearZ); vertices[5] = new Vector3(SafeArea.x + SafeArea.width - scaledLineWidth, SafeArea.y + scaledLineWidth, Vertex.nearZ); vertices[6] = new Vector3(SafeArea.x + SafeArea.width - scaledLineWidth, SafeArea.y + SafeArea.height - scaledLineWidth, Vertex.nearZ); vertices[7] = new Vector3(SafeArea.x + scaledLineWidth, SafeArea.y + SafeArea.height - scaledLineWidth, Vertex.nearZ); if (m_SafeAreaMesh == null) m_SafeAreaMesh = new Mesh(); else m_SafeAreaMesh.Clear(); m_SafeAreaMesh.vertices = vertices; m_SafeAreaMesh.colors = new[] {m_SafeAreaColor, m_SafeAreaColor, m_SafeAreaColor, m_SafeAreaColor, m_SafeAreaColor, m_SafeAreaColor, m_SafeAreaColor, m_SafeAreaColor}; m_SafeAreaMesh.triangles = new[] {0, 4, 1, 1, 4, 5, 1, 5, 6, 1, 6, 2, 6, 7, 2, 7, 3, 2, 0, 3, 4, 3, 7, 4}; } private void CreateScreenMesh() { var vertices = new Vector3[4]; vertices[0] = new Vector3(ScreenInsets.x, ScreenInsets.y, Vertex.nearZ); vertices[1] = new Vector3(m_ScreenWidth - ScreenInsets.z, ScreenInsets.y, Vertex.nearZ); vertices[2] = new Vector3(m_ScreenWidth - ScreenInsets.z, m_ScreenHeight - ScreenInsets.w, Vertex.nearZ); vertices[3] = new Vector3(ScreenInsets.x, m_ScreenHeight - ScreenInsets.w, Vertex.nearZ); Vector2[] portraitUvs; if (SystemInfo.graphicsUVStartsAtTop) portraitUvs = new[] { new Vector2(0, 0), new Vector2(1, 0), new Vector2(1, 1), new Vector2(0, 1) }; else portraitUvs = new[] { new Vector2(0, 1), new Vector2(1, 1), new Vector2(1, 0), new Vector2(0, 0) }; var uvs = new Vector2[4]; var startPos = 0; switch (ScreenOrientation) { case ScreenOrientation.Portrait: startPos = 0; break; case ScreenOrientation.LandscapeRight: startPos = 1; break; case ScreenOrientation.PortraitUpsideDown: startPos = 2; break; case ScreenOrientation.LandscapeLeft: startPos = 3; break; } for (int index = 0; index < 4; ++index) { var uvIndex = (index + startPos) % 4; uvs[index] = portraitUvs[uvIndex]; } if (m_ScreenMesh == null) m_ScreenMesh = new Mesh(); else m_ScreenMesh.Clear(); m_ScreenMesh.vertices = vertices; m_ScreenMesh.uv = uvs; m_ScreenMesh.triangles = new[] {0, 1, 3, 1, 2, 3}; } private void CreateOverlayMesh() { var width = m_ScreenWidth + m_BorderSize.x + m_BorderSize.z; var height = m_ScreenHeight + m_BorderSize.y + m_BorderSize.w; var vertices = new Vector3[4]; vertices[0] = new Vector3(0, 0, Vertex.nearZ); vertices[1] = new Vector3(width, 0, Vertex.nearZ); vertices[2] = new Vector3(width, height, Vertex.nearZ); vertices[3] = new Vector3(0, height, Vertex.nearZ); if (m_OverlayMesh == null) m_OverlayMesh = new Mesh(); else m_OverlayMesh.Clear(); m_OverlayMesh.vertices = vertices; m_OverlayMesh.uv = new[] {new Vector2(0, 1), new Vector2(1, 1), new Vector2(1, 0), new Vector2(0, 0)}; m_OverlayMesh.triangles = new[] {0, 1, 3, 1, 2, 3}; } private void CreateProceduralOverlayMesh() { var width = m_ScreenWidth + m_BorderSize.x + m_BorderSize.z; var height = m_ScreenHeight + m_BorderSize.y + m_BorderSize.w; const float padding = 10;; var vertices = new Vector3[8]; vertices[0] = new Vector3(0, 0, Vertex.nearZ); vertices[1] = new Vector3(width, 0, Vertex.nearZ); vertices[2] = new Vector3(width, height, Vertex.nearZ); vertices[3] = new Vector3(0, height, Vertex.nearZ); vertices[4] = new Vector3(0 + padding, 0 + padding, Vertex.nearZ); vertices[5] = new Vector3(width - padding, 0 + padding, Vertex.nearZ); vertices[6] = new Vector3(width - padding, height - padding, Vertex.nearZ); vertices[7] = new Vector3(0 + padding, height - padding, Vertex.nearZ); var outerColor = EditorGUIUtility.isProSkin ? new Color(217f / 255, 217f / 255, 217f / 255) : new Color(100f / 255, 100f / 255, 100f / 255); if (m_ProceduralOverlayMesh == null) m_ProceduralOverlayMesh = new Mesh(); else m_ProceduralOverlayMesh.Clear(); m_ProceduralOverlayMesh.vertices = vertices; m_ProceduralOverlayMesh.colors = new[] { outerColor, outerColor, outerColor, outerColor, outerColor, outerColor, outerColor, outerColor }; m_ProceduralOverlayMesh.triangles = new[] { 0, 4, 1, 1, 4, 5, 1, 5, 6, 1, 6, 2, 6, 7, 2, 7, 3, 2, 0, 3, 4, 3, 7, 4 }; } } }
34.798005
208
0.544575
[ "MIT" ]
Eneye280/Movil-ShipGame_Imparable_PG
Movil_Imparable_PG/Library/PackageCache/com.unity.device-simulator@2.2.3-preview/Editor/uielements/DeviceView.cs
13,954
C#
using ExtendedXmlSerializer.Configuration; using ExtendedXmlSerializer.Tests.Support; using ExtendedXmlSerializer.Tests.TestObject; using FluentAssertions; using System.Collections.Generic; using Xunit; namespace ExtendedXmlSerializer.Tests.ExtensionModel.Xml.Classic { public class ClassicExtensionTests { [Fact] public void Verify() { var serializer = new ConfigurationContainer().EnableClassicMode() .Create(); var expected = TestClassOtherClass.Create(); #if CORE new SerializationSupport(serializer).Assert(expected, @"<?xml version=""1.0"" encoding=""utf-8""?><TestClassOtherClass xmlns=""clr-namespace:ExtendedXmlSerializer.Tests.TestObject;assembly=ExtendedXmlSerializer.Tests""><Other><Test><Id>2</Id><Name>Other Name</Name></Test><Double>7.3453145324</Double></Other><Primitive1><PropString>TestString</PropString><PropInt>-1</PropInt><PropuInt>2234</PropuInt><PropDecimal>3.346</PropDecimal><PropDecimalMinValue>-79228162514264337593543950335</PropDecimalMinValue><PropDecimalMaxValue>79228162514264337593543950335</PropDecimalMaxValue><PropFloat>7.4432</PropFloat><PropFloatNaN>NaN</PropFloatNaN><PropFloatPositiveInfinity>INF</PropFloatPositiveInfinity><PropFloatNegativeInfinity>-INF</PropFloatNegativeInfinity><PropFloatMinValue>-3.4028235E+38</PropFloatMinValue><PropFloatMaxValue>3.4028235E+38</PropFloatMaxValue><PropDouble>3.4234</PropDouble><PropDoubleNaN>NaN</PropDoubleNaN><PropDoublePositiveInfinity>INF</PropDoublePositiveInfinity><PropDoubleNegativeInfinity>-INF</PropDoubleNegativeInfinity><PropDoubleMinValue>-1.7976931348623157E+308</PropDoubleMinValue><PropDoubleMaxValue>1.7976931348623157E+308</PropDoubleMaxValue><PropEnum>EnumValue1</PropEnum><PropLong>234234142</PropLong><PropUlong>2345352534</PropUlong><PropShort>23</PropShort><PropUshort>2344</PropUshort><PropDateTime>2014-01-23T00:00:00</PropDateTime><PropByte>23</PropByte><PropSbyte>33</PropSbyte><PropChar>g</PropChar></Primitive1><Primitive2><PropString>TestString</PropString><PropInt>-1</PropInt><PropuInt>2234</PropuInt><PropDecimal>3.346</PropDecimal><PropDecimalMinValue>-79228162514264337593543950335</PropDecimalMinValue><PropDecimalMaxValue>79228162514264337593543950335</PropDecimalMaxValue><PropFloat>7.4432</PropFloat><PropFloatNaN>NaN</PropFloatNaN><PropFloatPositiveInfinity>INF</PropFloatPositiveInfinity><PropFloatNegativeInfinity>-INF</PropFloatNegativeInfinity><PropFloatMinValue>-3.4028235E+38</PropFloatMinValue><PropFloatMaxValue>3.4028235E+38</PropFloatMaxValue><PropDouble>3.4234</PropDouble><PropDoubleNaN>NaN</PropDoubleNaN><PropDoublePositiveInfinity>INF</PropDoublePositiveInfinity><PropDoubleNegativeInfinity>-INF</PropDoubleNegativeInfinity><PropDoubleMinValue>-1.7976931348623157E+308</PropDoubleMinValue><PropDoubleMaxValue>1.7976931348623157E+308</PropDoubleMaxValue><PropEnum>EnumValue1</PropEnum><PropLong>234234142</PropLong><PropUlong>2345352534</PropUlong><PropShort>23</PropShort><PropUshort>2344</PropUshort><PropDateTime>2014-01-23T00:00:00</PropDateTime><PropByte>23</PropByte><PropSbyte>33</PropSbyte><PropChar>g</PropChar></Primitive2><ListProperty><TestClassItem><Id>0</Id><Name>Name 000</Name></TestClassItem><TestClassItem><Id>1</Id><Name>Name 001</Name></TestClassItem><TestClassItem><Id>2</Id><Name>Name 002</Name></TestClassItem><TestClassItem><Id>3</Id><Name>Name 003</Name></TestClassItem><TestClassItem><Id>4</Id><Name>Name 004</Name></TestClassItem><TestClassItem><Id>5</Id><Name>Name 005</Name></TestClassItem><TestClassItem><Id>6</Id><Name>Name 006</Name></TestClassItem><TestClassItem><Id>7</Id><Name>Name 007</Name></TestClassItem><TestClassItem><Id>8</Id><Name>Name 008</Name></TestClassItem><TestClassItem><Id>9</Id><Name>Name 009</Name></TestClassItem><TestClassItem><Id>10</Id><Name>Name 0010</Name></TestClassItem><TestClassItem><Id>11</Id><Name>Name 0011</Name></TestClassItem><TestClassItem><Id>12</Id><Name>Name 0012</Name></TestClassItem><TestClassItem><Id>13</Id><Name>Name 0013</Name></TestClassItem><TestClassItem><Id>14</Id><Name>Name 0014</Name></TestClassItem><TestClassItem><Id>15</Id><Name>Name 0015</Name></TestClassItem><TestClassItem><Id>16</Id><Name>Name 0016</Name></TestClassItem><TestClassItem><Id>17</Id><Name>Name 0017</Name></TestClassItem><TestClassItem><Id>18</Id><Name>Name 0018</Name></TestClassItem><TestClassItem><Id>19</Id><Name>Name 0019</Name></TestClassItem></ListProperty></TestClassOtherClass>"); #else new SerializationSupport(serializer).Assert(expected, @"<?xml version=""1.0"" encoding=""utf-8""?><TestClassOtherClass xmlns=""clr-namespace:ExtendedXmlSerializer.Tests.TestObject;assembly=ExtendedXmlSerializer.Tests""><Other><Test><Id>2</Id><Name>Other Name</Name></Test><Double>7.3453145324</Double></Other><Primitive1><PropString>TestString</PropString><PropInt>-1</PropInt><PropuInt>2234</PropuInt><PropDecimal>3.346</PropDecimal><PropDecimalMinValue>-79228162514264337593543950335</PropDecimalMinValue><PropDecimalMaxValue>79228162514264337593543950335</PropDecimalMaxValue><PropFloat>7.4432</PropFloat><PropFloatNaN>NaN</PropFloatNaN><PropFloatPositiveInfinity>INF</PropFloatPositiveInfinity><PropFloatNegativeInfinity>-INF</PropFloatNegativeInfinity><PropFloatMinValue>-3.40282347E+38</PropFloatMinValue><PropFloatMaxValue>3.40282347E+38</PropFloatMaxValue><PropDouble>3.4234</PropDouble><PropDoubleNaN>NaN</PropDoubleNaN><PropDoublePositiveInfinity>INF</PropDoublePositiveInfinity><PropDoubleNegativeInfinity>-INF</PropDoubleNegativeInfinity><PropDoubleMinValue>-1.7976931348623157E+308</PropDoubleMinValue><PropDoubleMaxValue>1.7976931348623157E+308</PropDoubleMaxValue><PropEnum>EnumValue1</PropEnum><PropLong>234234142</PropLong><PropUlong>2345352534</PropUlong><PropShort>23</PropShort><PropUshort>2344</PropUshort><PropDateTime>2014-01-23T00:00:00</PropDateTime><PropByte>23</PropByte><PropSbyte>33</PropSbyte><PropChar>g</PropChar></Primitive1><Primitive2><PropString>TestString</PropString><PropInt>-1</PropInt><PropuInt>2234</PropuInt><PropDecimal>3.346</PropDecimal><PropDecimalMinValue>-79228162514264337593543950335</PropDecimalMinValue><PropDecimalMaxValue>79228162514264337593543950335</PropDecimalMaxValue><PropFloat>7.4432</PropFloat><PropFloatNaN>NaN</PropFloatNaN><PropFloatPositiveInfinity>INF</PropFloatPositiveInfinity><PropFloatNegativeInfinity>-INF</PropFloatNegativeInfinity><PropFloatMinValue>-3.40282347E+38</PropFloatMinValue><PropFloatMaxValue>3.40282347E+38</PropFloatMaxValue><PropDouble>3.4234</PropDouble><PropDoubleNaN>NaN</PropDoubleNaN><PropDoublePositiveInfinity>INF</PropDoublePositiveInfinity><PropDoubleNegativeInfinity>-INF</PropDoubleNegativeInfinity><PropDoubleMinValue>-1.7976931348623157E+308</PropDoubleMinValue><PropDoubleMaxValue>1.7976931348623157E+308</PropDoubleMaxValue><PropEnum>EnumValue1</PropEnum><PropLong>234234142</PropLong><PropUlong>2345352534</PropUlong><PropShort>23</PropShort><PropUshort>2344</PropUshort><PropDateTime>2014-01-23T00:00:00</PropDateTime><PropByte>23</PropByte><PropSbyte>33</PropSbyte><PropChar>g</PropChar></Primitive2><ListProperty><TestClassItem><Id>0</Id><Name>Name 000</Name></TestClassItem><TestClassItem><Id>1</Id><Name>Name 001</Name></TestClassItem><TestClassItem><Id>2</Id><Name>Name 002</Name></TestClassItem><TestClassItem><Id>3</Id><Name>Name 003</Name></TestClassItem><TestClassItem><Id>4</Id><Name>Name 004</Name></TestClassItem><TestClassItem><Id>5</Id><Name>Name 005</Name></TestClassItem><TestClassItem><Id>6</Id><Name>Name 006</Name></TestClassItem><TestClassItem><Id>7</Id><Name>Name 007</Name></TestClassItem><TestClassItem><Id>8</Id><Name>Name 008</Name></TestClassItem><TestClassItem><Id>9</Id><Name>Name 009</Name></TestClassItem><TestClassItem><Id>10</Id><Name>Name 0010</Name></TestClassItem><TestClassItem><Id>11</Id><Name>Name 0011</Name></TestClassItem><TestClassItem><Id>12</Id><Name>Name 0012</Name></TestClassItem><TestClassItem><Id>13</Id><Name>Name 0013</Name></TestClassItem><TestClassItem><Id>14</Id><Name>Name 0014</Name></TestClassItem><TestClassItem><Id>15</Id><Name>Name 0015</Name></TestClassItem><TestClassItem><Id>16</Id><Name>Name 0016</Name></TestClassItem><TestClassItem><Id>17</Id><Name>Name 0017</Name></TestClassItem><TestClassItem><Id>18</Id><Name>Name 0018</Name></TestClassItem><TestClassItem><Id>19</Id><Name>Name 0019</Name></TestClassItem></ListProperty></TestClassOtherClass>"); #endif } [Fact] public void BasicArray() { var serializer = new ConfigurationContainer().EnableClassicMode() .Create(); var expected = new[] {1, 2, 3, 4, 5}; var data = serializer.Serialize(expected); var actual = serializer.Deserialize<int[]>(data); Assert.Equal(expected, actual); } [Fact] public void BasicList() { var serializer = new ConfigurationContainer().EnableClassicMode() .Create(); var expected = new List<string> {"Hello", "World", "Hope", "This", "Works!"}; var data = serializer.Serialize(expected); var actual = serializer.Deserialize<List<string>>(data); actual.Capacity.Should() .Be(8); Assert.Equal(expected, actual); } [Fact] public void BasicHashSet() { var serializer = new ConfigurationContainer().EnableClassicMode() .Create(); var expected = new HashSet<string> {"Hello", "World", "Hope", "This", "Works!"}; var data = serializer.Serialize(expected); var actual = serializer.Deserialize<HashSet<string>>(data); Assert.True(actual.SetEquals(expected)); } [Fact] public void Dictionary() { var serializer = new ConfigurationContainer().EnableClassicMode() .Create(); var expected = new Dictionary<int, string> { {1, "First"}, {2, "Second"}, {3, "Other"} }; var data = serializer.Serialize(expected); var actual = serializer.Deserialize<Dictionary<int, string>>(data); Assert.NotNull(actual); Assert.Equal(expected.Count, actual.Count); foreach (var entry in actual) { Assert.Equal(expected[entry.Key], entry.Value); } } } }
122.380952
3,914
0.762743
[ "MIT" ]
ExtendedXmlSerializer/ExtendedXmlSerializer
test/ExtendedXmlSerializer.Tests/ExtensionModel/Xml/Classic/ClassicExtensionTests.cs
10,282
C#
using System; using Vostok.Hercules.Client.Abstractions.Events; namespace Vostok.Hercules.Client.Abstractions.Values { public abstract partial class HerculesValue { #region bool /// <summary> /// Returns <c>true</c> if this value is of <see cref="HerculesValueType.Bool"/> type, or <c>false</c> otherwise. /// </summary> public bool IsBool => this is HerculesValue<bool>; /// <summary> /// Returns the value cast to <see cref="bool"/>. Requires the value to have <see cref="HerculesValueType.Bool"/> type. /// <exception cref="InvalidCastException">The cast is not valid due to mismatching value type.</exception> /// </summary> public bool AsBool => As<bool>(); #endregion #region byte /// <summary> /// Returns <c>true</c> if this value is of <see cref="HerculesValueType.Byte"/> type, or <c>false</c> otherwise. /// </summary> public bool IsByte => this is HerculesValue<byte>; /// <summary> /// Returns the value cast to <see cref="byte"/>. Requires the value to have <see cref="HerculesValueType.Byte"/> type. /// <exception cref="InvalidCastException">The cast is not valid due to mismatching value type.</exception> /// </summary> public byte AsByte => As<byte>(); #endregion #region short /// <summary> /// Returns <c>true</c> if this value is of <see cref="HerculesValueType.Short"/> type, or <c>false</c> otherwise. /// </summary> public bool IsShort => this is HerculesValue<short>; /// <summary> /// Returns the value cast to <see cref="short"/>. Requires the value to have <see cref="HerculesValueType.Short"/> type. /// <exception cref="InvalidCastException">The cast is not valid due to mismatching value type.</exception> /// </summary> public short AsShort => As<short>(); #endregion #region int /// <summary> /// Returns <c>true</c> if this value is of <see cref="HerculesValueType.Int"/> type, or <c>false</c> otherwise. /// </summary> public bool IsInt => this is HerculesValue<int>; /// <summary> /// Returns the value cast to <see cref="int"/>. Requires the value to have <see cref="HerculesValueType.Int"/> type. /// <exception cref="InvalidCastException">The cast is not valid due to mismatching value type.</exception> /// </summary> public int AsInt => As<int>(); #endregion #region long /// <summary> /// Returns <c>true</c> if this value is of <see cref="HerculesValueType.Long"/> type, or <c>false</c> otherwise. /// </summary> public bool IsLong => this is HerculesValue<long>; /// <summary> /// Returns the value cast to <see cref="long"/>. Requires the value to have <see cref="HerculesValueType.Long"/> type. /// <exception cref="InvalidCastException">The cast is not valid due to mismatching value type.</exception> /// </summary> public long AsLong => As<long>(); #endregion #region float /// <summary> /// Returns <c>true</c> if this value is of <see cref="HerculesValueType.Float"/> type, or <c>false</c> otherwise. /// </summary> public bool IsFloat => this is HerculesValue<float>; /// <summary> /// Returns the value cast to <see cref="float"/>. Requires the value to have <see cref="HerculesValueType.Float"/> type. /// <exception cref="InvalidCastException">The cast is not valid due to mismatching value type.</exception> /// </summary> public float AsFloat => As<float>(); #endregion #region double /// <summary> /// Returns <c>true</c> if this value is of <see cref="HerculesValueType.Double"/> type, or <c>false</c> otherwise. /// </summary> public bool IsDouble => this is HerculesValue<double>; /// <summary> /// Returns the value cast to <see cref="double"/>. Requires the value to have <see cref="HerculesValueType.Double"/> type. /// <exception cref="InvalidCastException">The cast is not valid due to mismatching value type.</exception> /// </summary> public double AsDouble => As<double>(); #endregion #region Guid /// <summary> /// Returns <c>true</c> if this value is of <see cref="HerculesValueType.Guid"/> type, or <c>false</c> otherwise. /// </summary> public bool IsGuid => this is HerculesValue<Guid>; /// <summary> /// Returns the value cast to <see cref="Guid"/>. Requires the value to have <see cref="HerculesValueType.Guid"/> type. /// <exception cref="InvalidCastException">The cast is not valid due to mismatching value type.</exception> /// </summary> public Guid AsGuid => As<Guid>(); #endregion #region string /// <summary> /// Returns <c>true</c> if this value is of <see cref="HerculesValueType.String"/> type, or <c>false</c> otherwise. /// </summary> public bool IsString => this is HerculesValue<string>; /// <summary> /// Returns the value cast to <see cref="string"/>. Requires the value to have <see cref="HerculesValueType.String"/> type. /// <exception cref="InvalidCastException">The cast is not valid due to mismatching value type.</exception> /// </summary> public string AsString => As<string>(); #endregion #region HerculesVector /// <summary> /// Returns <c>true</c> if this value is of <see cref="HerculesValueType.Vector"/> type, or <c>false</c> otherwise. /// </summary> public bool IsVector => this is HerculesValue<HerculesVector>; /// <summary> /// Returns the value cast to <see cref="HerculesVector"/>. Requires the value to have <see cref="HerculesValueType.Vector"/> type. /// <exception cref="InvalidCastException">The cast is not valid due to mismatching value type.</exception> /// </summary> public HerculesVector AsVector => As<HerculesVector>(); #endregion #region HerculesTags /// <summary> /// Returns <c>true</c> if this value is of <see cref="HerculesValueType.Container"/> type, or <c>false</c> otherwise. /// </summary> public bool IsContainer => this is HerculesValue<HerculesTags>; /// <summary> /// Returns the value cast to <see cref="HerculesTags"/>. Requires the value to have <see cref="HerculesValueType.Container"/> type. /// <exception cref="InvalidCastException">The cast is not valid due to mismatching value type.</exception> /// </summary> public HerculesTags AsContainer => As<HerculesTags>(); #endregion #region HerculesNull /// <summary> /// Returns <c>true</c> if this value is of <see cref="HerculesValueType.Null"/> type, or <c>false</c> otherwise. /// </summary> public bool IsNull => this is HerculesValue<HerculesNull>; /// <summary> /// Returns the value cast to <see cref="HerculesNull"/>. Requires the value to have <see cref="HerculesValueType.Null"/> type. /// <exception cref="InvalidCastException">The cast is not valid due to mismatching value type.</exception> /// </summary> public HerculesNull AsNull => As<HerculesNull>(); #endregion } }
40.398936
140
0.607637
[ "MIT" ]
vostok/airlock.client.abstractions
Vostok.Hercules.Client.Abstractions/Values/HerculesValue.Boilerplate.cs
7,595
C#
namespace ControlzEx.Showcase.Views { using System; using System.Collections.ObjectModel; using System.ComponentModel; using System.Runtime.CompilerServices; using System.Windows; using System.Windows.Data; using ControlzEx.Theming; using JetBrains.Annotations; public partial class ThemingView : INotifyPropertyChanged { public ThemingView() { this.CurrentThemeCollection = new ObservableCollection<Theme>(); this.CurrentColorSchemeCollection = new ObservableCollection<string>(); this.Themes = new CompositeCollection { new CollectionContainer { Collection = ThemeManager.Current.Themes }, new CollectionContainer { Collection = this.CurrentThemeCollection } }; this.ColorSchemes = new CompositeCollection { new CollectionContainer { Collection = ThemeManager.Current.ColorSchemes }, new CollectionContainer { Collection = this.CurrentColorSchemeCollection } }; ThemeManager.Current.ThemeChanged += this.ThemeManager_ThemeChanged; this.InitializeComponent(); } protected override void OnInitialized(EventArgs e) { base.OnInitialized(e); var currentTheme = this.CurrentTheme; if (currentTheme is null == false && this.CurrentThemeCollection.Contains(currentTheme) == false) { this.CurrentThemeCollection.Clear(); this.CurrentThemeCollection.Add(currentTheme); this.CurrentColorSchemeCollection.Clear(); this.CurrentColorSchemeCollection.Add(currentTheme.ColorScheme); } } private void ThemeManager_ThemeChanged(object sender, ThemeChangedEventArgs e) { // Add the new theme first, if it's generated if (e.NewTheme is null == false && e.NewTheme.IsRuntimeGenerated) { this.CurrentThemeCollection.Add(e.NewTheme); if (e.OldTheme?.ColorScheme != e.NewTheme?.ColorScheme) { this.CurrentColorSchemeCollection.Add(e.NewTheme.ColorScheme); } } // Notify about selection change this.OnPropertyChanged(nameof(this.CurrentTheme)); this.OnPropertyChanged(nameof(this.CurrentColorScheme)); // Remove the old theme, if it's generated // We have to do this after the notification to ensure the selection does not get reset by the removal if (e.OldTheme is null == false && e.OldTheme.IsRuntimeGenerated) { this.CurrentThemeCollection.Remove(e.OldTheme); if (e.OldTheme?.ColorScheme != e.NewTheme?.ColorScheme) { this.CurrentColorSchemeCollection.Remove(e.OldTheme.ColorScheme); } } } public ObservableCollection<Theme> CurrentThemeCollection { get; } public CompositeCollection Themes { get; } public ObservableCollection<string> CurrentColorSchemeCollection { get; } public CompositeCollection ColorSchemes { get; } public Theme CurrentTheme { get => ThemeManager.Current.DetectTheme(); set { if (value is null) { return; } ThemeManager.Current.ChangeTheme(Application.Current, value); this.OnPropertyChanged(); this.OnPropertyChanged(nameof(this.CurrentBaseColor)); } } public string CurrentBaseColor { get => this.CurrentTheme.BaseColorScheme; set { if (string.IsNullOrEmpty(value) == false) { ThemeManager.Current.ChangeThemeBaseColor(Application.Current, value); } this.OnPropertyChanged(); this.OnPropertyChanged(nameof(this.CurrentTheme)); } } public string CurrentColorScheme { get => this.CurrentTheme.ColorScheme; set { if (string.IsNullOrEmpty(value) == false) { ThemeManager.Current.ChangeThemeColorScheme(Application.Current, value); } this.OnPropertyChanged(); this.OnPropertyChanged(nameof(this.CurrentTheme)); } } public event PropertyChangedEventHandler PropertyChanged; [NotifyPropertyChangedInvocator] protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null) { this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } private void SyncNow_OnClick(object sender, RoutedEventArgs e) { ThemeManager.Current.SyncTheme(); } } }
34.278912
211
0.592776
[ "MIT" ]
DavosLi0bnip/daranguizu
Others/ControlzEx/src/ControlzEx.Showcase/Views/ThemingView.xaml.cs
5,041
C#
namespace Shapes { public class Rectangle : Shape { //-------------- Fields ---------------- private double height; private double width; //----------- Constructors ------------- public Rectangle(double height, double width) { this.Height = height; this.Width = width; } //------------ Properties -------------- public double Height { get { return this.height; } private set { this.height = value; } } public double Width { get { return this.width; } private set { this.width = value; } } //------------- Methods ---------------- public override double CalculateArea() => this.Width * this.Height; public override double CalculatePerimeter() => this.Width * 2 + this.Height * 2; public override string Draw() { return base.Draw() + "Rectangle"; } } }
25.974359
88
0.45311
[ "MIT" ]
radrex/SoftuniCourses
C# Web Developer/C# Advanced/C# OOP/05.Polymorphism/Lab/P03_Shapes/Shapes/Shapes/Rectangle.cs
1,015
C#
using System; using System.Collections.Generic; using Microsoft.AspNetCore.Identity; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using Abp.Authorization; using Abp.Authorization.Users; using Abp.Configuration; using Abp.Domain.Repositories; using Abp.Domain.Uow; using Abp.Organizations; using Abp.Runtime.Caching; using ClubTest.Authorization.Roles; namespace ClubTest.Authorization.Users { public class UserManager : AbpUserManager<Role, User> { public UserManager( RoleManager roleManager, UserStore store, IOptions<IdentityOptions> optionsAccessor, IPasswordHasher<User> passwordHasher, IEnumerable<IUserValidator<User>> userValidators, IEnumerable<IPasswordValidator<User>> passwordValidators, ILookupNormalizer keyNormalizer, IdentityErrorDescriber errors, IServiceProvider services, ILogger<UserManager<User>> logger, IPermissionManager permissionManager, IUnitOfWorkManager unitOfWorkManager, ICacheManager cacheManager, IRepository<OrganizationUnit, long> organizationUnitRepository, IRepository<UserOrganizationUnit, long> userOrganizationUnitRepository, IOrganizationUnitSettings organizationUnitSettings, ISettingManager settingManager) : base( roleManager, store, optionsAccessor, passwordHasher, userValidators, passwordValidators, keyNormalizer, errors, services, logger, permissionManager, unitOfWorkManager, cacheManager, organizationUnitRepository, userOrganizationUnitRepository, organizationUnitSettings, settingManager) { } } }
34.440678
84
0.627461
[ "MIT" ]
metrodev-apps/ClubTest
aspnet-core/src/ClubTest.Core/Authorization/Users/UserManager.cs
2,034
C#
namespace BestService.Data { using System.Linq; using BestService.Data.Common.Models; using Microsoft.EntityFrameworkCore; internal static class EntityIndexesConfiguration { public static void Configure(ModelBuilder modelBuilder) { // IDeletableEntity.IsDeleted index var deletableEntityTypes = modelBuilder.Model .GetEntityTypes() .Where(et => et.ClrType != null && typeof(IDeletableEntity).IsAssignableFrom(et.ClrType)); foreach (var deletableEntityType in deletableEntityTypes) { modelBuilder.Entity(deletableEntityType.ClrType).HasIndex(nameof(IDeletableEntity.IsDeleted)); } } } }
31.083333
110
0.647453
[ "MIT" ]
vladosfi/BestService
Data/BestService.Data/EntityIndexesConfiguration.cs
748
C#
/* ======================================================================== * Copyright (c) 2005-2019 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 * * 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. * * The complete license agreement can be found here: * http://opcfoundation.org/License/MIT/1.00/ * ======================================================================*/ using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.Reflection; using System.Threading; using System.ServiceModel; using System.Runtime.Serialization; using System.Security.Cryptography.X509Certificates; using System.IO; using Opc.Ua.Client; using Opc.Ua.Client.Controls; namespace Opc.Ua.Sample.Controls { /// <summary> /// Prompts the user to create a new secure channel. /// </summary> public partial class PerformanceTestDlg : Form { public PerformanceTestDlg() { InitializeComponent(); this.Icon = ClientUtils.GetAppIcon(); } private object m_lock = new object(); private bool m_running; private ApplicationConfiguration m_configuration; private ConfiguredEndpointCollection m_endpoints; private ServiceMessageContext m_messageContext; private X509Certificate2 m_clientCertificate; private string m_filePath; /// <summary> /// Displays the dialog. /// </summary> public EndpointDescription ShowDialog( ApplicationConfiguration configuration, ConfiguredEndpointCollection endpoints, X509Certificate2 clientCertificate) { m_configuration = configuration; m_endpoints = endpoints; m_messageContext = configuration.CreateMessageContext(); m_clientCertificate = clientCertificate; m_running = false; m_filePath = @".\perftest.csv"; EndpointSelectorCTRL.Initialize(m_endpoints, configuration); lock (m_lock) { OkBTN.Enabled = m_running = false; } // show dialog. if (ShowDialog() != DialogResult.OK) { return null; } return null; } /// <summary> /// Loads previously saved results. /// </summary> private void LoadResults(string filePath) { Stream istrm = File.OpenRead(filePath); DataContractSerializer serializer = new DataContractSerializer(typeof(PerformanceTestResult[])); PerformanceTestResult[] results = (PerformanceTestResult[])serializer.ReadObject(istrm); istrm.Close(); ResultsCTRL.Clear(); foreach (PerformanceTestResult result in results) { ResultsCTRL.Add(result); } m_filePath = filePath; } /// <summary> /// Saves the current results. /// </summary> private void SaveResults(string filePath) { PerformanceTestResult[] results = ResultsCTRL.GetResults(); if (results.Length == 0) { return; } Stream ostrm = File.Open(filePath, FileMode.Create); StreamWriter writer = new StreamWriter(ostrm); writer.Write("Url"); writer.Write(",Protocol"); writer.Write(",SecurityMode"); writer.Write(",Algorithms"); writer.Write(",Encoding"); foreach (KeyValuePair<int,double> result in results[0].Results) { writer.Write(",{0} Values", result.Key); } writer.Write("\r\n"); for (int ii = 0; ii < results.Length; ii++) { EndpointDescription endpoint = results[ii].Endpoint.Description; Uri uri = new Uri(endpoint.EndpointUrl); writer.Write("{0}", uri); writer.Write(",{0}", uri.Scheme); writer.Write(",{0}", endpoint.SecurityMode); writer.Write(",{0}", SecurityPolicies.GetDisplayName(endpoint.SecurityPolicyUri)); writer.Write(",{0}", (results[ii].Endpoint.Configuration.UseBinaryEncoding)?"Binary":"XML"); foreach (KeyValuePair<int,double> result in results[ii].Results) { writer.Write(",{0}", result.Value); } writer.Write("\r\n"); } writer.Close(); m_filePath = filePath; } /// <summary> /// Called when the test completes. /// </summary> public void TestComplete(object state) { if (InvokeRequired) { BeginInvoke(new WaitCallback(TestComplete), state); return; } try { ProgressCTRL.Value = ProgressCTRL.Maximum; ResultsCTRL.Add((PerformanceTestResult)state); } catch (Exception e) { GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), e); } } /// <summary> /// Called to indicate the test progress. /// </summary> private void TestProgress(object state) { if (InvokeRequired) { BeginInvoke(new WaitCallback(TestProgress), state); return; } try { ProgressCTRL.Value = (int)state; } catch (Exception e) { GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), e); } } /// <summary> /// Called when the the test fails with an exception. /// </summary> private void TestException(object state) { if (InvokeRequired) { BeginInvoke(new WaitCallback(TestException), state); return; } try { OkBTN.Enabled = m_running = false; GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), (Exception)state); } catch (Exception e) { GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), e); } } /// <summary> /// Runs all tests in a background thread. /// </summary> private void DoAllTests(object state) { for (int ii = 0; ii < m_endpoints.Count; ii++) { try { DoTest(m_endpoints[ii]); } catch { // ignore. } } m_running = false; } /// <summary> /// Runs the test in a background thread. /// </summary> private void DoTest(object state) { try { DoTest((ConfiguredEndpoint)state); } catch (Exception e) { TestException(e); } m_running = false; } /// <summary> /// Runs the test in a background thread. /// </summary> private void DoTest(ConfiguredEndpoint endpoint) { PerformanceTestResult result = new PerformanceTestResult(endpoint, 100); result.Results.Add(1, -1); result.Results.Add(10, -1); result.Results.Add(50, -1); result.Results.Add(100, -1); result.Results.Add(250, -1); result.Results.Add(500, -1); try { // update the endpoint. if (endpoint.UpdateBeforeConnect) { endpoint.UpdateFromServer(); } SessionClient client = null; Uri url = new Uri(endpoint.Description.EndpointUrl); ITransportChannel channel = SessionChannel.Create( m_configuration, endpoint.Description, endpoint.Configuration, m_clientCertificate, m_messageContext); client = new SessionClient(channel); List<int> requestSizes = new List<int>(result.Results.Keys); for (int ii = 0; ii < requestSizes.Count; ii++) { // update the progress indicator. TestProgress((ii * 100) / requestSizes.Count); lock (m_lock) { if (!m_running) { break; } } int count = requestSizes[ii]; // initialize request. RequestHeader requestHeader = new RequestHeader(); requestHeader.ReturnDiagnostics = 5000; ReadValueIdCollection nodesToRead = new ReadValueIdCollection(count); for (int jj = 0; jj < count; jj++) { ReadValueId item = new ReadValueId(); item.NodeId = new NodeId((uint)jj, 1); item.AttributeId = Attributes.Value; nodesToRead.Add(item); } // ensure valid connection. DataValueCollection results = null; DiagnosticInfoCollection diagnosticInfos = null; client.Read( requestHeader, 0, TimestampsToReturn.Both, nodesToRead, out results, out diagnosticInfos); if (results.Count != count) { throw new ServiceResultException(StatusCodes.BadUnknownResponse); } // do test. DateTime start = DateTime.UtcNow; for (int jj = 0; jj < result.Iterations; jj++) { client.Read( requestHeader, 0, TimestampsToReturn.Both, nodesToRead, out results, out diagnosticInfos); if (results.Count != count) { throw new ServiceResultException(StatusCodes.BadUnknownResponse); } } DateTime finish = DateTime.UtcNow; long totalTicks = finish.Ticks - start.Ticks; decimal averageMilliseconds = ((((decimal)totalTicks) / ((decimal)result.Iterations))) / ((decimal)TimeSpan.TicksPerMillisecond); result.Results[requestSizes[ii]] = (double)averageMilliseconds; } } finally { TestComplete(result); } } private void EndpointSelectorCTRL_ConnectEndpoint(object sender, ConnectEndpointEventArgs e) { try { // check if a test is already running. lock (m_lock) { if (m_running) { throw new InvalidOperationException("A test is already running."); } } ConfiguredEndpoint endpoint = e.Endpoint; // start processing. OkBTN.Enabled = m_running = true; ThreadPool.QueueUserWorkItem(new WaitCallback(DoTest), endpoint); } catch (Exception exception) { GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); e.UpdateControl = false; } } private void OkBTN_Click(object sender, EventArgs e) { try { lock (m_lock) { m_running = true; } } catch (Exception exception) { GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); } } private void SaveBTN_Click(object sender, EventArgs e) { try { FileInfo fileInfo = new FileInfo(m_filePath); SaveFileDialog dialog = new SaveFileDialog(); dialog.CheckFileExists = false; dialog.CheckPathExists = true; dialog.DefaultExt = ".csv"; dialog.Filter = "Result Files (*.csv)|*.csv|All Files (*.*)|*.*"; dialog.ValidateNames = true; dialog.Title = "Save Performance Test Result File"; dialog.FileName = m_filePath; dialog.InitialDirectory = fileInfo.DirectoryName; dialog.RestoreDirectory = true; if (dialog.ShowDialog() != DialogResult.OK) { return; } SaveResults(dialog.FileName); } catch (Exception exception) { GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); } } private void LoadBTN_Click(object sender, EventArgs e) { try { FileInfo fileInfo = new FileInfo(m_filePath); OpenFileDialog dialog = new OpenFileDialog(); dialog.CheckFileExists = true; dialog.CheckPathExists = true; dialog.DefaultExt = ".csv"; dialog.Filter = "Result Files (*.csv)|*.csv|All Files (*.*)|*.*"; dialog.Multiselect = false; dialog.ValidateNames = true; dialog.Title = "Open Performance Test Result File"; dialog.FileName = m_filePath; dialog.InitialDirectory = fileInfo.DirectoryName; dialog.RestoreDirectory = true; if (dialog.ShowDialog() != DialogResult.OK) { return; } LoadResults(dialog.FileName); } catch (Exception exception) { GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); } } private void TestAllBTN_Click(object sender, EventArgs e) { try { if (m_running) { throw new InvalidOperationException("A test is already running."); } ResultsCTRL.Clear(); OkBTN.Enabled = m_running = true; ThreadPool.QueueUserWorkItem(new WaitCallback(DoAllTests), null); } catch (Exception exception) { GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); } } } /// <summary> /// The result of a performance test. /// </summary> [DataContract(Namespace = Namespaces.OpcUaXsd)] public class PerformanceTestResult { #region Constructors /// <summary> /// Initializes the object with the endpoint being tested an the number of iterations. /// </summary> public PerformanceTestResult(ConfiguredEndpoint endpoint, int iterations) { Initialize(); m_endpoint = endpoint; m_iterations = iterations; } /// <summary> /// Sets private members to default values. /// </summary> private void Initialize() { m_endpoint = null; m_iterations = 0; m_results = new Dictionary<int,double>(); } /// <summary> /// Initializes the object during deserialization. /// </summary> [OnDeserializing()] private void Initialize(StreamingContext context) { Initialize(); } #endregion #region Public Properties /// <summary> /// The endpoint that was tested. /// </summary> [DataMember(Order = 1)] public ConfiguredEndpoint Endpoint { get { return m_endpoint; } private set { m_endpoint = value; } } /// <summary> /// The number of iterations for each payload size. /// </summary> [DataMember(Order = 2)] public int Iterations { get { return m_iterations; } private set { m_iterations = value; } } /// <summary> /// The test results returned as an list. /// </summary> [DataMember(Name = "Result", Order = 3)] private List<PerformanceTestResultItem> TestCaseResults { get { List<PerformanceTestResultItem> results = new List<PerformanceTestResultItem>(); foreach (KeyValuePair<int,double> entry in m_results) { PerformanceTestResultItem item = new PerformanceTestResultItem(); item.Count = entry.Key; item.Average = entry.Value; results.Add(item); } return results; } set { m_results.Clear(); if (value != null) { foreach (PerformanceTestResultItem item in value) { m_results[item.Count] = item.Average; } } } } /// <summary> /// The average roundtrip time in milliseconds indexed by the payload size in bytes. /// </summary> public IDictionary<int,double> Results { get { return m_results; } } #endregion #region Private Fields private ConfiguredEndpoint m_endpoint; private int m_iterations; private Dictionary<int,double> m_results; #endregion } /// <summary> /// The result of a performance test. /// </summary> [DataContract(Namespace = Namespaces.OpcUaXsd)] public class PerformanceTestResultItem { #region Constructors /// <summary> /// Initializes with default values. /// </summary> public PerformanceTestResultItem() { Initialize(); } /// <summary> /// Sets private members to default values. /// </summary> private void Initialize() { m_count = 0; m_average = 0; } /// <summary> /// Initializes the object during deserialization. /// </summary> [OnDeserializing()] private void Initialize(StreamingContext context) { Initialize(); } #endregion #region Public Properties /// <summary> /// The number of items used in the test case. /// </summary> [DataMember(Order = 1)] public int Count { get { return m_count; } set { m_count = value; } } /// <summary> /// The average response time in milliseconds. /// </summary> [DataMember(Order = 2)] public double Average { get { return m_average; } set { m_average = value; } } #endregion #region Private Fields private int m_count; private double m_average; #endregion } }
30.943231
149
0.503763
[ "MIT" ]
AlexanderSemenyak/UA-.NETStandard-Samples
Samples/Controls.Net4/Common/PerformanceTestDlg.cs
21,258
C#
using Newtonsoft.Json; using System; namespace Dracoon.Sdk.SdkInternal.ApiModel { internal class ApiDownloadShare { [JsonProperty("id", NullValueHandling = NullValueHandling.Ignore)] public long ShareId { get; set; } [JsonProperty("name", NullValueHandling = NullValueHandling.Ignore)] public string Name { get; set; } [JsonProperty("nodeId", NullValueHandling = NullValueHandling.Ignore)] public long NodeId { get; set; } [JsonProperty("nodePath", NullValueHandling = NullValueHandling.Ignore)] public string NodePath { get; set; } [JsonProperty("accessKey", NullValueHandling = NullValueHandling.Ignore)] public string AccessKey { get; set; } [JsonProperty("cntDownloads", NullValueHandling = NullValueHandling.Ignore)] public int CurrentDownloadsCount { get; set; } [JsonProperty("createdAt", NullValueHandling = NullValueHandling.Ignore)] public DateTime CreatedAt { get; set; } [JsonProperty("createdBy", NullValueHandling = NullValueHandling.Ignore)] public ApiUserInfo CreatedBy { get; set; } [JsonProperty("notes", NullValueHandling = NullValueHandling.Ignore)] public string Notes { get; set; } [JsonProperty("internalNotes", NullValueHandling = NullValueHandling.Ignore)] public string InternalNotes { get; set; } [JsonProperty("showCreatorName", NullValueHandling = NullValueHandling.Ignore)] public bool ShowCreatorName { get; set; } [JsonProperty("ShowCreatorUsername", NullValueHandling = NullValueHandling.Ignore)] public bool ShowCreatorUserName { get; set; } [JsonProperty("isProtected", NullValueHandling = NullValueHandling.Ignore)] public bool IsProtected { get; set; } [JsonProperty("expireAt", NullValueHandling = NullValueHandling.Ignore)] public DateTime? ExpireAt { get; set; } [JsonProperty("maxDownloads", NullValueHandling = NullValueHandling.Ignore)] public int? MaxAllowedDownloads { get; set; } [JsonProperty("isEncrypted", NullValueHandling = NullValueHandling.Ignore)] public bool? IsEncrypted { get; set; } [JsonProperty("nodeType", NullValueHandling = NullValueHandling.Ignore)] public string Type { get; set; } [JsonProperty("dataUrl", NullValueHandling = NullValueHandling.Ignore)] public string DataUrl { get; set; } [JsonProperty("updatedAt", NullValueHandling = NullValueHandling.Ignore)] public DateTime? UpdatedAt { get; set; } [JsonProperty("updatedBy", NullValueHandling = NullValueHandling.Ignore)] public ApiUserInfo UpdatedBy { get; set; } } }
41.5
91
0.687842
[ "Apache-2.0" ]
dracoon/dracoon-csharp-sdk
DracoonSdk/SdkInternal/ApiModel/Shares/ApiDownloadShare.cs
2,741
C#
namespace Launcher.NotifyIcon.Interop { /// <summary> /// The notify icon version that is used. The higher /// the version, the more capabilities are available. /// </summary> public enum NotifyIconVersion { /// <summary> /// Default behavior (legacy Win95). Expects /// a <see cref="Launcher.NotifyIcon.Interop.NotifyIconData"/> size of 488. /// </summary> Win95 = 0x0, /// <summary> /// Behavior representing Win2000 an higher. Expects /// a <see cref="Launcher.NotifyIcon.Interop.NotifyIconData"/> size of 504. /// </summary> Win2000 = 0x3, /// <summary> /// Extended tooltip support, which is available for Vista and later. /// Detailed information about what the different versions do, can be found <a href="https://docs.microsoft.com/en-us/windows/win32/api/shellapi/nf-shellapi-shell_notifyicona">here</a> /// </summary> Vista = 0x4 } }
36.814815
192
0.612676
[ "MIT" ]
BadrtSoft/Fivem-Launcher-PHP
Launcher/NotifyIcon/Interop/NotifyIconVersion.cs
996
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.companyreg.Model.V20190508 { public class ReSubmitIcpSolutionResponse : AcsResponse { private string requestId; private bool? success; private string bizId; public string RequestId { get { return requestId; } set { requestId = value; } } public bool? Success { get { return success; } set { success = value; } } public string BizId { get { return bizId; } set { bizId = value; } } } }
20.183099
63
0.663643
[ "Apache-2.0" ]
aliyun/aliyun-openapi-net-sdk
aliyun-net-sdk-companyreg/Companyreg/Model/V20190508/ReSubmitIcpSolutionResponse.cs
1,433
C#
using DOS_Auth; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace DrinkOrderSystem.ClientSide { public partial class Login : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { //if (!AuthManager.IsLogined()) //{ // Response.Redirect("/ClientSide/Login.aspx"); // return; //} } protected void btnLogin_Click(object sender, EventArgs e) { this.lbMsg.Visible = false; string inp_Account = this.txtAccount.Text; string inp_PWD = this.txtPWD.Text; string msg; if (!AuthManager.TryLogin(inp_Account, inp_PWD, out msg)) { this.lbMsg.Visible = true; this.lbMsg.Text = msg; return; } else { Response.Redirect("/ServerSide/SystemAdmin/UserPage.aspx"); } } } }
23.76087
75
0.536139
[ "MIT" ]
yuchi0731/DrinkWork
DrinkOrderSystem/DrinkOrderSystem/ClientSide/Login.aspx.cs
1,095
C#
namespace BoatRacingSimulator.Models.Boats { using System; using Interfaces; using Utility; public class SailBoat : Boat { private int sailEfficiency; public SailBoat(string model, int weight, int sailEfficiency) : base(model, weight) { this.SailEfficiency = sailEfficiency; } public int SailEfficiency { get => this.sailEfficiency; private set { if (value < 1 || value > 100) { throw new ArgumentException(Constants.IncorrectSailEfficiencyMessage); } this.sailEfficiency = value; } } public override double CalculateRaceSpeed(IRace race) { //(Race Wind Speed * (Boat Sail Efficiency / 100)) – Boat’s Weight + (Race Ocean Current Speed / 2) return race.WindSpeed * (this.SailEfficiency / 100D) - this.Weight + (race.OceanCurrentSpeed / 2D); } public override int EngineCount => 0; } }
27.15
112
0.548803
[ "MIT" ]
pirocorp/C-OOP-Advanced
07. Workshops/03_BoatRacingSimulator/BoatRacingSimulator/Models/Boats/SailBoat.cs
1,092
C#
using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Reflection; using System.Windows; using System.Windows.Controls; using System.Windows.Input; using System.Windows.Interop; using System.Windows.Media; using System.Windows.Media.Animation; using System.Windows.Shapes; using System.Windows.Controls.Primitives; using JetBrains.Annotations; using MahApps.Metro.Controls.Dialogs; using MahApps.Metro.Native; namespace MahApps.Metro.Controls { /// <summary> /// An extended, metrofied Window class. /// </summary> [TemplatePart(Name = PART_Icon, Type = typeof(UIElement))] [TemplatePart(Name = PART_TitleBar, Type = typeof(UIElement))] [TemplatePart(Name = PART_WindowTitleBackground, Type = typeof(UIElement))] [TemplatePart(Name = PART_WindowTitleThumb, Type = typeof(Thumb))] [TemplatePart(Name = PART_FlyoutModalDragMoveThumb, Type = typeof(Thumb))] [TemplatePart(Name = PART_LeftWindowCommands, Type = typeof(WindowCommands))] [TemplatePart(Name = PART_RightWindowCommands, Type = typeof(WindowCommands))] [TemplatePart(Name = PART_WindowButtonCommands, Type = typeof(WindowButtonCommands))] [TemplatePart(Name = PART_OverlayBox, Type = typeof(Grid))] [TemplatePart(Name = PART_MetroActiveDialogContainer, Type = typeof(Grid))] [TemplatePart(Name = PART_MetroInactiveDialogsContainer, Type = typeof(Grid))] [TemplatePart(Name = PART_FlyoutModal, Type = typeof(Rectangle))] public class MetroWindow : Window { private const string PART_Icon = "PART_Icon"; private const string PART_TitleBar = "PART_TitleBar"; private const string PART_WindowTitleBackground = "PART_WindowTitleBackground"; private const string PART_WindowTitleThumb = "PART_WindowTitleThumb"; private const string PART_FlyoutModalDragMoveThumb = "PART_FlyoutModalDragMoveThumb"; private const string PART_LeftWindowCommands = "PART_LeftWindowCommands"; private const string PART_RightWindowCommands = "PART_RightWindowCommands"; private const string PART_WindowButtonCommands = "PART_WindowButtonCommands"; private const string PART_OverlayBox = "PART_OverlayBox"; private const string PART_MetroActiveDialogContainer = "PART_MetroActiveDialogContainer"; private const string PART_MetroInactiveDialogsContainer = "PART_MetroInactiveDialogsContainer"; private const string PART_FlyoutModal = "PART_FlyoutModal"; public static readonly DependencyProperty ShowIconOnTitleBarProperty = DependencyProperty.Register("ShowIconOnTitleBar", typeof(bool), typeof(MetroWindow), new PropertyMetadata(true, OnShowIconOnTitleBarPropertyChangedCallback)); public static readonly DependencyProperty IconEdgeModeProperty = DependencyProperty.Register("IconEdgeMode", typeof(EdgeMode), typeof(MetroWindow), new PropertyMetadata(EdgeMode.Aliased)); public static readonly DependencyProperty IconBitmapScalingModeProperty = DependencyProperty.Register("IconBitmapScalingMode", typeof(BitmapScalingMode), typeof(MetroWindow), new PropertyMetadata(BitmapScalingMode.HighQuality)); public static readonly DependencyProperty IconScalingModeProperty = DependencyProperty.Register("IconScalingMode", typeof(MultiFrameImageMode), typeof(MetroWindow), new FrameworkPropertyMetadata(MultiFrameImageMode.ScaleDownLargerFrame, FrameworkPropertyMetadataOptions.AffectsRender)); public static readonly DependencyProperty ShowTitleBarProperty = DependencyProperty.Register("ShowTitleBar", typeof(bool), typeof(MetroWindow), new PropertyMetadata(true, OnShowTitleBarPropertyChangedCallback, OnShowTitleBarCoerceValueCallback)); public static readonly DependencyProperty ShowDialogsOverTitleBarProperty = DependencyProperty.Register("ShowDialogsOverTitleBar", typeof(bool), typeof(MetroWindow), new FrameworkPropertyMetadata(true, FrameworkPropertyMetadataOptions.AffectsArrange | FrameworkPropertyMetadataOptions.AffectsMeasure | FrameworkPropertyMetadataOptions.AffectsRender)); public static readonly DependencyProperty ShowMinButtonProperty = DependencyProperty.Register("ShowMinButton", typeof(bool), typeof(MetroWindow), new PropertyMetadata(true)); public static readonly DependencyProperty ShowMaxRestoreButtonProperty = DependencyProperty.Register("ShowMaxRestoreButton", typeof(bool), typeof(MetroWindow), new PropertyMetadata(true)); public static readonly DependencyProperty ShowCloseButtonProperty = DependencyProperty.Register("ShowCloseButton", typeof(bool), typeof(MetroWindow), new PropertyMetadata(true)); public static readonly DependencyProperty IsMinButtonEnabledProperty = DependencyProperty.Register("IsMinButtonEnabled", typeof(bool), typeof(MetroWindow), new PropertyMetadata(true)); public static readonly DependencyProperty IsMaxRestoreButtonEnabledProperty = DependencyProperty.Register("IsMaxRestoreButtonEnabled", typeof(bool), typeof(MetroWindow), new PropertyMetadata(true)); public static readonly DependencyProperty IsCloseButtonEnabledProperty = DependencyProperty.Register("IsCloseButtonEnabled", typeof(bool), typeof(MetroWindow), new PropertyMetadata(true)); public static readonly DependencyProperty ShowSystemMenuOnRightClickProperty = DependencyProperty.Register("ShowSystemMenuOnRightClick", typeof(bool), typeof(MetroWindow), new PropertyMetadata(true)); public static readonly DependencyProperty TitlebarHeightProperty = DependencyProperty.Register("TitlebarHeight", typeof(int), typeof(MetroWindow), new PropertyMetadata(30, TitlebarHeightPropertyChangedCallback)); [Obsolete(@"This property will be deleted in the next release. You should use the new TitleCharacterCasing dependency property.")] public static readonly DependencyProperty TitleCapsProperty = DependencyProperty.Register("TitleCaps", typeof(bool), typeof(MetroWindow), new PropertyMetadata(true, (o, e) => ((MetroWindow)o).TitleCharacterCasing = (bool)e.NewValue ? CharacterCasing.Upper : CharacterCasing.Normal)); public static readonly DependencyProperty TitleCharacterCasingProperty = DependencyProperty.Register("TitleCharacterCasing", typeof(CharacterCasing), typeof(MetroWindow), new FrameworkPropertyMetadata(CharacterCasing.Upper, FrameworkPropertyMetadataOptions.Inherits | FrameworkPropertyMetadataOptions.AffectsMeasure), value => CharacterCasing.Normal <= (CharacterCasing)value && (CharacterCasing)value <= CharacterCasing.Upper); public static readonly DependencyProperty TitleAlignmentProperty = DependencyProperty.Register("TitleAlignment", typeof(HorizontalAlignment), typeof(MetroWindow), new PropertyMetadata(HorizontalAlignment.Stretch, PropertyChangedCallback)); public static readonly DependencyProperty SaveWindowPositionProperty = DependencyProperty.Register("SaveWindowPosition", typeof(bool), typeof(MetroWindow), new PropertyMetadata(false)); public static readonly DependencyProperty WindowPlacementSettingsProperty = DependencyProperty.Register("WindowPlacementSettings", typeof(IWindowPlacementSettings), typeof(MetroWindow), new PropertyMetadata(null)); public static readonly DependencyProperty TitleForegroundProperty = DependencyProperty.Register("TitleForeground", typeof(Brush), typeof(MetroWindow)); public static readonly DependencyProperty IgnoreTaskbarOnMaximizeProperty = DependencyProperty.Register("IgnoreTaskbarOnMaximize", typeof(bool), typeof(MetroWindow), new PropertyMetadata(false)); public static readonly DependencyProperty FlyoutsProperty = DependencyProperty.Register("Flyouts", typeof(FlyoutsControl), typeof(MetroWindow), new PropertyMetadata(null, UpdateLogicalChilds)); public static readonly DependencyProperty WindowTransitionsEnabledProperty = DependencyProperty.Register("WindowTransitionsEnabled", typeof(bool), typeof(MetroWindow), new PropertyMetadata(true)); public static readonly DependencyProperty MetroDialogOptionsProperty = DependencyProperty.Register("MetroDialogOptions", typeof(MetroDialogSettings), typeof(MetroWindow), new PropertyMetadata(new MetroDialogSettings())); public static readonly DependencyProperty WindowTitleBrushProperty = DependencyProperty.Register("WindowTitleBrush", typeof(Brush), typeof(MetroWindow), new PropertyMetadata(Brushes.Transparent)); public static readonly DependencyProperty NonActiveWindowTitleBrushProperty = DependencyProperty.Register("NonActiveWindowTitleBrush", typeof(Brush), typeof(MetroWindow), new PropertyMetadata(Brushes.Gray)); public static readonly DependencyProperty NonActiveBorderBrushProperty = DependencyProperty.Register("NonActiveBorderBrush", typeof(Brush), typeof(MetroWindow), new PropertyMetadata(Brushes.Gray)); public static readonly DependencyProperty GlowBrushProperty = DependencyProperty.Register("GlowBrush", typeof(Brush), typeof(MetroWindow), new PropertyMetadata(null)); public static readonly DependencyProperty NonActiveGlowBrushProperty = DependencyProperty.Register("NonActiveGlowBrush", typeof(Brush), typeof(MetroWindow), new PropertyMetadata(new SolidColorBrush(Color.FromRgb(153, 153, 153)))); // #999999 public static readonly DependencyProperty OverlayBrushProperty = DependencyProperty.Register("OverlayBrush", typeof(Brush), typeof(MetroWindow), new PropertyMetadata(new SolidColorBrush(Color.FromScRgb(255, 0, 0, 0)))); // BlackColorBrush public static readonly DependencyProperty OverlayOpacityProperty = DependencyProperty.Register("OverlayOpacity", typeof(double), typeof(MetroWindow), new PropertyMetadata(0.7d)); public static readonly DependencyProperty IconTemplateProperty = DependencyProperty.Register("IconTemplate", typeof(DataTemplate), typeof(MetroWindow), new PropertyMetadata(null)); public static readonly DependencyProperty TitleTemplateProperty = DependencyProperty.Register("TitleTemplate", typeof(DataTemplate), typeof(MetroWindow), new PropertyMetadata(null)); public static readonly DependencyProperty LeftWindowCommandsProperty = DependencyProperty.Register("LeftWindowCommands", typeof(WindowCommands), typeof(MetroWindow), new PropertyMetadata(null, UpdateLogicalChilds)); public static readonly DependencyProperty RightWindowCommandsProperty = DependencyProperty.Register("RightWindowCommands", typeof(WindowCommands), typeof(MetroWindow), new PropertyMetadata(null, UpdateLogicalChilds)); public static readonly DependencyProperty WindowButtonCommandsProperty = DependencyProperty.Register("WindowButtonCommands", typeof(WindowButtonCommands), typeof(MetroWindow), new PropertyMetadata(null, UpdateLogicalChilds)); public static readonly DependencyProperty LeftWindowCommandsOverlayBehaviorProperty = DependencyProperty.Register("LeftWindowCommandsOverlayBehavior", typeof(WindowCommandsOverlayBehavior), typeof(MetroWindow), new PropertyMetadata(WindowCommandsOverlayBehavior.Always)); public static readonly DependencyProperty RightWindowCommandsOverlayBehaviorProperty = DependencyProperty.Register("RightWindowCommandsOverlayBehavior", typeof(WindowCommandsOverlayBehavior), typeof(MetroWindow), new PropertyMetadata(WindowCommandsOverlayBehavior.Always)); public static readonly DependencyProperty WindowButtonCommandsOverlayBehaviorProperty = DependencyProperty.Register("WindowButtonCommandsOverlayBehavior", typeof(WindowCommandsOverlayBehavior), typeof(MetroWindow), new PropertyMetadata(WindowCommandsOverlayBehavior.Always)); public static readonly DependencyProperty IconOverlayBehaviorProperty = DependencyProperty.Register("IconOverlayBehavior", typeof(WindowCommandsOverlayBehavior), typeof(MetroWindow), new PropertyMetadata(WindowCommandsOverlayBehavior.Never)); [Obsolete(@"This property will be deleted in the next release. You should use LightMinButtonStyle or DarkMinButtonStyle in WindowButtonCommands to override the style.")] public static readonly DependencyProperty WindowMinButtonStyleProperty = DependencyProperty.Register("WindowMinButtonStyle", typeof(Style), typeof(MetroWindow), new PropertyMetadata(null, OnWindowButtonStyleChanged)); [Obsolete(@"This property will be deleted in the next release. You should use LightMaxButtonStyle or DarkMaxButtonStyle in WindowButtonCommands to override the style.")] public static readonly DependencyProperty WindowMaxButtonStyleProperty = DependencyProperty.Register("WindowMaxButtonStyle", typeof(Style), typeof(MetroWindow), new PropertyMetadata(null, OnWindowButtonStyleChanged)); [Obsolete(@"This property will be deleted in the next release. You should use LightCloseButtonStyle or DarkCloseButtonStyle in WindowButtonCommands to override the style.")] public static readonly DependencyProperty WindowCloseButtonStyleProperty = DependencyProperty.Register("WindowCloseButtonStyle", typeof(Style), typeof(MetroWindow), new PropertyMetadata(null, OnWindowButtonStyleChanged)); public static readonly DependencyProperty UseNoneWindowStyleProperty = DependencyProperty.Register("UseNoneWindowStyle", typeof(bool), typeof(MetroWindow), new PropertyMetadata(false, OnUseNoneWindowStylePropertyChangedCallback)); public static readonly DependencyProperty OverrideDefaultWindowCommandsBrushProperty = DependencyProperty.Register("OverrideDefaultWindowCommandsBrush", typeof(SolidColorBrush), typeof(MetroWindow)); [Obsolete(@"This property will be deleted in the next release. You should use BorderThickness=""0"" and a GlowBrush=""Black"" to get a drop shadow around the Window.")] public static readonly DependencyProperty EnableDWMDropShadowProperty = DependencyProperty.Register("EnableDWMDropShadow", typeof(bool), typeof(MetroWindow), new PropertyMetadata(false, OnEnableDWMDropShadowPropertyChangedCallback)); public static readonly DependencyProperty IsWindowDraggableProperty = DependencyProperty.Register("IsWindowDraggable", typeof(bool), typeof(MetroWindow), new PropertyMetadata(true)); FrameworkElement icon; UIElement titleBar; UIElement titleBarBackground; Thumb windowTitleThumb; Thumb flyoutModalDragMoveThumb; private IInputElement restoreFocus; internal ContentPresenter LeftWindowCommandsPresenter; internal ContentPresenter RightWindowCommandsPresenter; internal ContentPresenter WindowButtonCommandsPresenter; internal Grid overlayBox; internal Grid metroActiveDialogContainer; internal Grid metroInactiveDialogContainer; private Storyboard overlayStoryboard; Rectangle flyoutModal; public static readonly RoutedEvent FlyoutsStatusChangedEvent = EventManager.RegisterRoutedEvent( "FlyoutsStatusChanged", RoutingStrategy.Bubble, typeof(RoutedEventHandler), typeof(MetroWindow)); // Provide CLR accessors for the event public event RoutedEventHandler FlyoutsStatusChanged { add { AddHandler(FlyoutsStatusChangedEvent, value); } remove { RemoveHandler(FlyoutsStatusChangedEvent, value); } } /// <summary> /// Allows easy handling of window commands brush. Theme is also applied based on this brush. /// </summary> public SolidColorBrush OverrideDefaultWindowCommandsBrush { get { return (SolidColorBrush)this.GetValue(OverrideDefaultWindowCommandsBrushProperty); } set { this.SetValue(OverrideDefaultWindowCommandsBrushProperty, value); } } public MetroDialogSettings MetroDialogOptions { get { return (MetroDialogSettings)GetValue(MetroDialogOptionsProperty); } set { SetValue(MetroDialogOptionsProperty, value); } } [Obsolete(@"This property will be deleted in the next release. You should use BorderThickness=""0"" and a GlowBrush=""Black"" to get a drop shadow around the Window.")] public bool EnableDWMDropShadow { get { return (bool)GetValue(EnableDWMDropShadowProperty); } set { SetValue(EnableDWMDropShadowProperty, value); } } private static void OnEnableDWMDropShadowPropertyChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e) { if (e.NewValue != e.OldValue && (bool)e.NewValue) { var window = (MetroWindow)d; window.UseDropShadow(); } } private void UseDropShadow() { this.BorderThickness = new Thickness(0); this.BorderBrush = null; this.GlowBrush = Brushes.Black; } public bool IsWindowDraggable { get { return (bool)GetValue(IsWindowDraggableProperty); } set { SetValue(IsWindowDraggableProperty, value); } } public WindowCommandsOverlayBehavior LeftWindowCommandsOverlayBehavior { get { return (WindowCommandsOverlayBehavior)this.GetValue(LeftWindowCommandsOverlayBehaviorProperty); } set { SetValue(LeftWindowCommandsOverlayBehaviorProperty, value); } } public WindowCommandsOverlayBehavior RightWindowCommandsOverlayBehavior { get { return (WindowCommandsOverlayBehavior)this.GetValue(RightWindowCommandsOverlayBehaviorProperty); } set { SetValue(RightWindowCommandsOverlayBehaviorProperty, value); } } public WindowCommandsOverlayBehavior WindowButtonCommandsOverlayBehavior { get { return (WindowCommandsOverlayBehavior)this.GetValue(WindowButtonCommandsOverlayBehaviorProperty); } set { SetValue(WindowButtonCommandsOverlayBehaviorProperty, value); } } public WindowCommandsOverlayBehavior IconOverlayBehavior { get { return (WindowCommandsOverlayBehavior)this.GetValue(IconOverlayBehaviorProperty); } set { SetValue(IconOverlayBehaviorProperty, value); } } [Obsolete(@"This property will be deleted in the next release. You should use LightMinButtonStyle or DarkMinButtonStyle in WindowButtonCommands to override the style.")] public Style WindowMinButtonStyle { get { return (Style)this.GetValue(WindowMinButtonStyleProperty); } set { SetValue(WindowMinButtonStyleProperty, value); } } [Obsolete(@"This property will be deleted in the next release. You should use LightMaxButtonStyle or DarkMaxButtonStyle in WindowButtonCommands to override the style.")] public Style WindowMaxButtonStyle { get { return (Style)this.GetValue(WindowMaxButtonStyleProperty); } set { SetValue(WindowMaxButtonStyleProperty, value); } } [Obsolete(@"This property will be deleted in the next release. You should use LightCloseButtonStyle or DarkCloseButtonStyle in WindowButtonCommands to override the style.")] public Style WindowCloseButtonStyle { get { return (Style)this.GetValue(WindowCloseButtonStyleProperty); } set { SetValue(WindowCloseButtonStyleProperty, value); } } public static void OnWindowButtonStyleChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { if (e.NewValue == e.OldValue) { return; } var window = (MetroWindow) d; if (window.WindowButtonCommands != null) window.WindowButtonCommands.ApplyTheme(); } /// <summary> /// Gets/sets whether the window's entrance transition animation is enabled. /// </summary> public bool WindowTransitionsEnabled { get { return (bool)this.GetValue(WindowTransitionsEnabledProperty); } set { SetValue(WindowTransitionsEnabledProperty, value); } } /// <summary> /// Gets/sets the FlyoutsControl that hosts the window's flyouts. /// </summary> public FlyoutsControl Flyouts { get { return (FlyoutsControl)GetValue(FlyoutsProperty); } set { SetValue(FlyoutsProperty, value); } } /// <summary> /// Gets/sets the icon content template to show a custom icon. /// </summary> public DataTemplate IconTemplate { get { return (DataTemplate)GetValue(IconTemplateProperty); } set { SetValue(IconTemplateProperty, value); } } /// <summary> /// Gets/sets the title content template to show a custom title. /// </summary> public DataTemplate TitleTemplate { get { return (DataTemplate)GetValue(TitleTemplateProperty); } set { SetValue(TitleTemplateProperty, value); } } /// <summary> /// Gets/sets the left window commands that hosts the user commands. /// </summary> public WindowCommands LeftWindowCommands { get { return (WindowCommands)GetValue(LeftWindowCommandsProperty); } set { SetValue(LeftWindowCommandsProperty, value); } } /// <summary> /// Gets/sets the right window commands that hosts the user commands. /// </summary> public WindowCommands RightWindowCommands { get { return (WindowCommands)GetValue(RightWindowCommandsProperty); } set { SetValue(RightWindowCommandsProperty, value); } } /// <summary> /// Gets/sets the window button commands that hosts the min/max/close commands. /// </summary> public WindowButtonCommands WindowButtonCommands { get { return (WindowButtonCommands)GetValue(WindowButtonCommandsProperty); } set { SetValue(WindowButtonCommandsProperty, value); } } /// <summary> /// Gets/sets whether the window will ignore (and overlap) the taskbar when maximized. /// </summary> public bool IgnoreTaskbarOnMaximize { get { return (bool)this.GetValue(IgnoreTaskbarOnMaximizeProperty); } set { SetValue(IgnoreTaskbarOnMaximizeProperty, value); } } /// <summary> /// Gets/sets the brush used for the titlebar's foreground. /// </summary> public Brush TitleForeground { get { return (Brush)GetValue(TitleForegroundProperty); } set { SetValue(TitleForegroundProperty, value); } } /// <summary> /// Gets/sets whether the window will save it's position between loads. /// </summary> public bool SaveWindowPosition { get { return (bool)GetValue(SaveWindowPositionProperty); } set { SetValue(SaveWindowPositionProperty, value); } } public IWindowPlacementSettings WindowPlacementSettings { get { return (IWindowPlacementSettings)GetValue(WindowPlacementSettingsProperty); } set { SetValue(WindowPlacementSettingsProperty, value); } } /// <summary> /// Gets the window placement settings (can be overwritten). /// </summary> public virtual IWindowPlacementSettings GetWindowPlacementSettings() { return this.WindowPlacementSettings ?? new WindowApplicationSettings(this); } /// <summary> /// Get/sets whether the titlebar icon is visible or not. /// </summary> public bool ShowIconOnTitleBar { get { return (bool)GetValue(ShowIconOnTitleBarProperty); } set { SetValue(ShowIconOnTitleBarProperty, value); } } private static void OnShowIconOnTitleBarPropertyChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e) { var window = (MetroWindow)d; if (e.NewValue != e.OldValue) { window.SetVisibiltyForIcon(); } } /// <summary> /// Get/sets whether dialogs show over the title bar. /// </summary> public bool ShowDialogsOverTitleBar { get { return (bool)GetValue(ShowDialogsOverTitleBarProperty); } set { SetValue(ShowDialogsOverTitleBarProperty, value); } } /// <summary> /// Gets/sets edge mode of the titlebar icon. /// </summary> public EdgeMode IconEdgeMode { get { return (EdgeMode)this.GetValue(IconEdgeModeProperty); } set { SetValue(IconEdgeModeProperty, value); } } /// <summary> /// Gets/sets bitmap scaling mode of the titlebar icon. /// </summary> public BitmapScalingMode IconBitmapScalingMode { get { return (BitmapScalingMode)this.GetValue(IconBitmapScalingModeProperty); } set { SetValue(IconBitmapScalingModeProperty, value); } } /// <summary> /// Gets/sets icon scaling mode of the titlebar. /// </summary> public MultiFrameImageMode IconScalingMode { get { return (MultiFrameImageMode)this.GetValue(IconScalingModeProperty); } set { SetValue(IconScalingModeProperty, value); } } /// <summary> /// Gets/sets whether the TitleBar is visible or not. /// </summary> public bool ShowTitleBar { get { return (bool)GetValue(ShowTitleBarProperty); } set { SetValue(ShowTitleBarProperty, value); } } private static void OnShowTitleBarPropertyChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e) { var window = (MetroWindow)d; if (e.NewValue != e.OldValue) { window.SetVisibiltyForAllTitleElements((bool)e.NewValue); } } private static object OnShowTitleBarCoerceValueCallback(DependencyObject d, object value) { // if UseNoneWindowStyle = true no title bar should be shown if (((MetroWindow)d).UseNoneWindowStyle) { return false; } return value; } /// <summary> /// Gets/sets whether the WindowStyle is None or not. /// </summary> public bool UseNoneWindowStyle { get { return (bool)GetValue(UseNoneWindowStyleProperty); } set { SetValue(UseNoneWindowStyleProperty, value); } } private static void OnUseNoneWindowStylePropertyChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e) { if (e.NewValue != e.OldValue) { // if UseNoneWindowStyle = true no title bar should be shown var useNoneWindowStyle = (bool)e.NewValue; var window = (MetroWindow)d; window.ToggleNoneWindowStyle(useNoneWindowStyle, window.ShowTitleBar); } } private void ToggleNoneWindowStyle(bool useNoneWindowStyle, bool isTitleBarVisible) { // UseNoneWindowStyle means no title bar, window commands or min, max, close buttons if (useNoneWindowStyle) { ShowTitleBar = false; } else { ShowTitleBar = isTitleBarVisible; } if (LeftWindowCommandsPresenter != null) { LeftWindowCommandsPresenter.Visibility = useNoneWindowStyle ? Visibility.Collapsed : Visibility.Visible; } if (RightWindowCommandsPresenter != null) { RightWindowCommandsPresenter.Visibility = useNoneWindowStyle ? Visibility.Collapsed : Visibility.Visible; } } /// <summary> /// Gets/sets if the minimize button is visible. /// </summary> public bool ShowMinButton { get { return (bool)GetValue(ShowMinButtonProperty); } set { SetValue(ShowMinButtonProperty, value); } } /// <summary> /// Gets/sets if the Maximize/Restore button is visible. /// </summary> public bool ShowMaxRestoreButton { get { return (bool)GetValue(ShowMaxRestoreButtonProperty); } set { SetValue(ShowMaxRestoreButtonProperty, value); } } /// <summary> /// Gets/sets if the close button is visible. /// </summary> public bool ShowCloseButton { get { return (bool)GetValue(ShowCloseButtonProperty); } set { SetValue(ShowCloseButtonProperty, value); } } /// <summary> /// Gets/sets if the min button is enabled. /// </summary> public bool IsMinButtonEnabled { get { return (bool)GetValue(IsMinButtonEnabledProperty); } set { SetValue(IsMinButtonEnabledProperty, value); } } /// <summary> /// Gets/sets if the max/restore button is enabled. /// </summary> public bool IsMaxRestoreButtonEnabled { get { return (bool)GetValue(IsMaxRestoreButtonEnabledProperty); } set { SetValue(IsMaxRestoreButtonEnabledProperty, value); } } /// <summary> /// Gets/sets if the close button is enabled. /// </summary> public bool IsCloseButtonEnabled { get { return (bool)GetValue(IsCloseButtonEnabledProperty); } set { SetValue(IsCloseButtonEnabledProperty, value); } } /// <summary> /// Gets/sets if the the system menu should popup on right click. /// </summary> public bool ShowSystemMenuOnRightClick { get { return (bool)GetValue(ShowSystemMenuOnRightClickProperty); } set { SetValue(ShowSystemMenuOnRightClickProperty, value); } } /// <summary> /// Gets/sets the TitleBar's height. /// </summary> public int TitlebarHeight { get { return (int)GetValue(TitlebarHeightProperty); } set { SetValue(TitlebarHeightProperty, value); } } private static void TitlebarHeightPropertyChangedCallback(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs e) { var window = (MetroWindow)dependencyObject; if (e.NewValue != e.OldValue) { window.SetVisibiltyForAllTitleElements((int)e.NewValue > 0); } } private void SetVisibiltyForIcon() { if (this.icon != null) { var isVisible = (this.IconOverlayBehavior.HasFlag(WindowCommandsOverlayBehavior.HiddenTitleBar) && !this.ShowTitleBar) || (this.ShowIconOnTitleBar && this.ShowTitleBar); var iconVisibility = isVisible ? Visibility.Visible : Visibility.Collapsed; this.icon.Visibility = iconVisibility; } } private void SetVisibiltyForAllTitleElements(bool visible) { this.SetVisibiltyForIcon(); var newVisibility = visible && this.ShowTitleBar ? Visibility.Visible : Visibility.Collapsed; if (this.titleBar != null) { this.titleBar.Visibility = newVisibility; } if (this.titleBarBackground != null) { this.titleBarBackground.Visibility = newVisibility; } if (this.LeftWindowCommandsPresenter != null) { this.LeftWindowCommandsPresenter.Visibility = this.LeftWindowCommandsOverlayBehavior.HasFlag(WindowCommandsOverlayBehavior.HiddenTitleBar) ? Visibility.Visible : newVisibility; } if (this.RightWindowCommandsPresenter != null) { this.RightWindowCommandsPresenter.Visibility = this.RightWindowCommandsOverlayBehavior.HasFlag(WindowCommandsOverlayBehavior.HiddenTitleBar) ? Visibility.Visible : newVisibility; } if (this.WindowButtonCommandsPresenter != null) { this.WindowButtonCommandsPresenter.Visibility = this.WindowButtonCommandsOverlayBehavior.HasFlag(WindowCommandsOverlayBehavior.HiddenTitleBar) ? Visibility.Visible : newVisibility; } SetWindowEvents(); } /// <summary> /// Gets/sets if the TitleBar's text is automatically capitalized. /// </summary> [Obsolete(@"This property will be deleted in the next release. You should use the new TitleCharacterCasing dependency property.")] public bool TitleCaps { get { return (bool)GetValue(TitleCapsProperty); } set { SetValue(TitleCapsProperty, value); } } /// <summary> /// Character casing of the title /// </summary> public CharacterCasing TitleCharacterCasing { get { return (CharacterCasing)GetValue(TitleCharacterCasingProperty); } set { SetValue(TitleCharacterCasingProperty, value); } } /// <summary> /// Gets/sets the title horizontal alignment. /// </summary> public HorizontalAlignment TitleAlignment { get { return (HorizontalAlignment)GetValue(TitleAlignmentProperty); } set { SetValue(TitleAlignmentProperty, value); } } private static void PropertyChangedCallback(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs e) { var window = dependencyObject as MetroWindow; if (window != null) { window.SizeChanged -= window.MetroWindow_SizeChanged; if (e.NewValue is HorizontalAlignment && (HorizontalAlignment)e.NewValue == HorizontalAlignment.Center) { window.SizeChanged += window.MetroWindow_SizeChanged; } } } /// <summary> /// Gets/sets the brush used for the Window's title bar. /// </summary> public Brush WindowTitleBrush { get { return (Brush)GetValue(WindowTitleBrushProperty); } set { SetValue(WindowTitleBrushProperty, value); } } /// <summary> /// Gets/sets the brush used for the Window's glow. /// </summary> public Brush GlowBrush { get { return (Brush)GetValue(GlowBrushProperty); } set { SetValue(GlowBrushProperty, value); } } /// <summary> /// Gets/sets the brush used for the Window's non-active glow. /// </summary> public Brush NonActiveGlowBrush { get { return (Brush)GetValue(NonActiveGlowBrushProperty); } set { SetValue(NonActiveGlowBrushProperty, value); } } /// <summary> /// Gets/sets the brush used for the Window's non-active border. /// </summary> public Brush NonActiveBorderBrush { get { return (Brush)GetValue(NonActiveBorderBrushProperty); } set { SetValue(NonActiveBorderBrushProperty, value); } } /// <summary> /// Gets/sets the brush used for the Window's non-active title bar. /// </summary> public Brush NonActiveWindowTitleBrush { get { return (Brush)GetValue(NonActiveWindowTitleBrushProperty); } set { SetValue(NonActiveWindowTitleBrushProperty, value); } } /// <summary> /// Gets/sets the brush used for the dialog overlay. /// </summary> public Brush OverlayBrush { get { return (Brush)GetValue(OverlayBrushProperty); } set { SetValue(OverlayBrushProperty, value); } } /// <summary> /// Gets/sets the opacity used for the dialog overlay. /// </summary> public double OverlayOpacity { get { return (double)GetValue(OverlayOpacityProperty); } set { SetValue(OverlayOpacityProperty, value); } } [Obsolete("This property will be deleted in the next release.")] public string WindowTitle { get { return TitleCaps ? Title.ToUpper() : Title; } } /// <summary> /// Begins to show the MetroWindow's overlay effect. /// </summary> /// <returns>A task representing the process.</returns> public System.Threading.Tasks.Task ShowOverlayAsync() { if (overlayBox == null) throw new InvalidOperationException("OverlayBox can not be founded in this MetroWindow's template. Are you calling this before the window has loaded?"); var tcs = new System.Threading.Tasks.TaskCompletionSource<object>(); if (IsOverlayVisible() && overlayStoryboard == null) { //No Task.FromResult in .NET 4. tcs.SetResult(null); return tcs.Task; } Dispatcher.VerifyAccess(); overlayBox.Visibility = Visibility.Visible; var sb = ((Storyboard)this.Template.Resources["OverlayFastSemiFadeIn"]).Clone(); ((DoubleAnimation)sb.Children[0]).To = this.OverlayOpacity; EventHandler completionHandler = null; completionHandler = (sender, args) => { sb.Completed -= completionHandler; if (overlayStoryboard == sb) { overlayStoryboard = null; } tcs.TrySetResult(null); }; sb.Completed += completionHandler; overlayBox.BeginStoryboard(sb); overlayStoryboard = sb; return tcs.Task; } /// <summary> /// Begins to hide the MetroWindow's overlay effect. /// </summary> /// <returns>A task representing the process.</returns> public System.Threading.Tasks.Task HideOverlayAsync() { if (overlayBox == null) throw new InvalidOperationException("OverlayBox can not be founded in this MetroWindow's template. Are you calling this before the window has loaded?"); var tcs = new System.Threading.Tasks.TaskCompletionSource<object>(); if (overlayBox.Visibility == Visibility.Visible && overlayBox.Opacity == 0.0) { //No Task.FromResult in .NET 4. tcs.SetResult(null); return tcs.Task; } Dispatcher.VerifyAccess(); var sb = ((Storyboard)this.Template.Resources["OverlayFastSemiFadeOut"]).Clone(); ((DoubleAnimation)sb.Children[0]).To = 0d; EventHandler completionHandler = null; completionHandler = (sender, args) => { sb.Completed -= completionHandler; if (overlayStoryboard == sb) { overlayBox.Visibility = Visibility.Hidden; overlayStoryboard = null; } tcs.TrySetResult(null); }; sb.Completed += completionHandler; overlayBox.BeginStoryboard(sb); overlayStoryboard = sb; return tcs.Task; } public bool IsOverlayVisible() { if (overlayBox == null) throw new InvalidOperationException("OverlayBox can not be founded in this MetroWindow's template. Are you calling this before the window has loaded?"); return overlayBox.Visibility == Visibility.Visible && overlayBox.Opacity >= this.OverlayOpacity; } public void ShowOverlay() { overlayBox.Visibility = Visibility.Visible; overlayBox.SetCurrentValue(Grid.OpacityProperty, this.OverlayOpacity); } public void HideOverlay() { overlayBox.SetCurrentValue(Grid.OpacityProperty, 0.0); overlayBox.Visibility = System.Windows.Visibility.Hidden; } /// <summary> /// Stores the given element, or the last focused element via FocusManager, for restoring the focus after closing a dialog. /// </summary> /// <param name="thisElement">The element which will be focused again.</param> public void StoreFocus([CanBeNull] IInputElement thisElement = null) { Dispatcher.BeginInvoke(new Action(() => { restoreFocus = thisElement ?? (this.restoreFocus ?? FocusManager.GetFocusedElement(this)); })); } internal void RestoreFocus() { if (restoreFocus != null) { Dispatcher.BeginInvoke(new Action(() => { Keyboard.Focus(restoreFocus); restoreFocus = null; })); } } /// <summary> /// Clears the stored element which would get the focus after closing a dialog. /// </summary> public void ResetStoredFocus() { restoreFocus = null; } /// <summary> /// Initializes a new instance of the MahApps.Metro.Controls.MetroWindow class. /// </summary> public MetroWindow() { DataContextChanged += MetroWindow_DataContextChanged; Loaded += this.MetroWindow_Loaded; } #if NET4_5 protected override async void OnClosing(CancelEventArgs e) { // #2409: don't close window if there is a dialog still open var dialog = await this.GetCurrentDialogAsync<BaseMetroDialog>(); e.Cancel = dialog != null; base.OnClosing(e); } #else protected override void OnClosing(CancelEventArgs e) { // #2409: don't close window if there is a dialog still open var dialog = this.Invoke(() => this.metroActiveDialogContainer?.Children.OfType<BaseMetroDialog>().LastOrDefault()); e.Cancel = dialog != null; base.OnClosing(e); } #endif private void MetroWindow_DataContextChanged(object sender, DependencyPropertyChangedEventArgs e) { // MahApps add these controls to the window with AddLogicalChild method. // This has the side effect that the DataContext doesn't update, so do this now here. if (this.LeftWindowCommands != null) this.LeftWindowCommands.DataContext = this.DataContext; if (this.RightWindowCommands != null) this.RightWindowCommands.DataContext = this.DataContext; if (this.WindowButtonCommands != null) this.WindowButtonCommands.DataContext = this.DataContext; if (this.Flyouts != null) this.Flyouts.DataContext = this.DataContext; } private void MetroWindow_Loaded(object sender, RoutedEventArgs e) { if (EnableDWMDropShadow) { this.UseDropShadow(); } if (this.WindowTransitionsEnabled) { VisualStateManager.GoToState(this, "AfterLoaded", true); } this.ToggleNoneWindowStyle(this.UseNoneWindowStyle, this.ShowTitleBar); if (this.Flyouts == null) { this.Flyouts = new FlyoutsControl(); } this.ResetAllWindowCommandsBrush(); ThemeManager.IsThemeChanged += ThemeManagerOnIsThemeChanged; this.Unloaded += (o, args) => ThemeManager.IsThemeChanged -= ThemeManagerOnIsThemeChanged; } private void MetroWindow_SizeChanged(object sender, RoutedEventArgs e) { // this all works only for centered title if (TitleAlignment != HorizontalAlignment.Center) { return; } // Half of this MetroWindow var halfDistance = this.ActualWidth / 2; // Distance between center and left/right var distanceToCenter = this.titleBar.DesiredSize.Width / 2; // Distance between right edge from LeftWindowCommands to left window side var distanceFromLeft = this.icon.ActualWidth + this.LeftWindowCommands.ActualWidth; // Distance between left edge from RightWindowCommands to right window side var distanceFromRight = this.WindowButtonCommands.ActualWidth + this.RightWindowCommands.ActualWidth; // Margin const double horizontalMargin = 5.0; var dLeft = distanceFromLeft + distanceToCenter + horizontalMargin; var dRight = distanceFromRight + distanceToCenter + horizontalMargin; if ((dLeft < halfDistance) && (dRight < halfDistance)) { Grid.SetColumn(this.titleBar, 0); Grid.SetColumnSpan(this.titleBar, 5); } else { Grid.SetColumn(this.titleBar, 2); Grid.SetColumnSpan(this.titleBar, 1); } } private void ThemeManagerOnIsThemeChanged(object sender, OnThemeChangedEventArgs e) { if (e.Accent != null) { var flyouts = this.Flyouts.GetFlyouts().ToList(); // since we disabled the ThemeManager OnThemeChanged part, we must change all children flyouts too // e.g if the FlyoutsControl is hosted in a UserControl var allChildFlyouts = (this.Content as DependencyObject).FindChildren<FlyoutsControl>(true).ToList(); if (allChildFlyouts.Any()) { flyouts.AddRange(allChildFlyouts.SelectMany(flyoutsControl => flyoutsControl.GetFlyouts())); } if (!flyouts.Any()) { // we must update the window command brushes!!! this.ResetAllWindowCommandsBrush(); return; } foreach (var flyout in flyouts) { flyout.ChangeFlyoutTheme(e.Accent, e.AppTheme); } this.HandleWindowCommandsForFlyouts(flyouts); } } private void FlyoutsPreviewMouseDown(object sender, MouseButtonEventArgs e) { var element = (e.OriginalSource as DependencyObject); if (element != null) { // no preview if we just clicked these elements if (element.TryFindParent<Flyout>() != null || Equals(element, this.overlayBox) || element.TryFindParent<BaseMetroDialog>() != null || Equals(element.TryFindParent<ContentControl>(), this.icon) || element.TryFindParent<WindowCommands>() != null || element.TryFindParent<WindowButtonCommands>() != null) { return; } } if (Flyouts.OverrideExternalCloseButton == null) { foreach (var flyout in Flyouts.GetFlyouts().Where(x => x.IsOpen && x.ExternalCloseButton == e.ChangedButton && (!x.IsPinned || Flyouts.OverrideIsPinned))) { flyout.IsOpen = false; } } else if (Flyouts.OverrideExternalCloseButton == e.ChangedButton) { foreach (var flyout in Flyouts.GetFlyouts().Where(x => x.IsOpen && (!x.IsPinned || Flyouts.OverrideIsPinned))) { flyout.IsOpen = false; } } } private static void UpdateLogicalChilds(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs e) { var window = dependencyObject as MetroWindow; if (window == null) { return; } var oldChild = e.OldValue as FrameworkElement; if (oldChild != null) { window.RemoveLogicalChild(oldChild); } var newChild = e.NewValue as FrameworkElement; if (newChild != null) { window.AddLogicalChild(newChild); // Yes, that's crazy. But we must do this to enable all possible scenarios for setting DataContext // in a Window. Without set the DataContext at this point it can happen that e.g. a Flyout // doesn't get the same DataContext. // So now we can type // // this.InitializeComponent(); // this.DataContext = new MainViewModel(); // // or // // this.DataContext = new MainViewModel(); // this.InitializeComponent(); // newChild.DataContext = window.DataContext; } } protected override IEnumerator LogicalChildren { get { // cheat, make a list with all logical content and return the enumerator ArrayList children = new ArrayList { this.Content }; if (this.LeftWindowCommands != null) { children.Add(this.LeftWindowCommands); } if (this.RightWindowCommands != null) { children.Add(this.RightWindowCommands); } if (this.WindowButtonCommands != null) { children.Add(this.WindowButtonCommands); } if (this.Flyouts != null) { children.Add(this.Flyouts); } return children.GetEnumerator(); } } static MetroWindow() { DefaultStyleKeyProperty.OverrideMetadata(typeof(MetroWindow), new FrameworkPropertyMetadata(typeof(MetroWindow))); } public override void OnApplyTemplate() { base.OnApplyTemplate(); LeftWindowCommandsPresenter = GetTemplateChild(PART_LeftWindowCommands) as ContentPresenter; RightWindowCommandsPresenter = GetTemplateChild(PART_RightWindowCommands) as ContentPresenter; WindowButtonCommandsPresenter = GetTemplateChild(PART_WindowButtonCommands) as ContentPresenter; if (LeftWindowCommands == null) LeftWindowCommands = new WindowCommands(); if (RightWindowCommands == null) RightWindowCommands = new WindowCommands(); if (WindowButtonCommands == null) WindowButtonCommands = new WindowButtonCommands(); LeftWindowCommands.ParentWindow = this; RightWindowCommands.ParentWindow = this; WindowButtonCommands.ParentWindow = this; overlayBox = GetTemplateChild(PART_OverlayBox) as Grid; metroActiveDialogContainer = GetTemplateChild(PART_MetroActiveDialogContainer) as Grid; metroInactiveDialogContainer = GetTemplateChild(PART_MetroInactiveDialogsContainer) as Grid; flyoutModal = (Rectangle)GetTemplateChild(PART_FlyoutModal); flyoutModal.PreviewMouseDown += FlyoutsPreviewMouseDown; this.PreviewMouseDown += FlyoutsPreviewMouseDown; icon = GetTemplateChild(PART_Icon) as FrameworkElement; titleBar = GetTemplateChild(PART_TitleBar) as UIElement; titleBarBackground = GetTemplateChild(PART_WindowTitleBackground) as UIElement; this.windowTitleThumb = GetTemplateChild(PART_WindowTitleThumb) as Thumb; this.flyoutModalDragMoveThumb = GetTemplateChild(PART_FlyoutModalDragMoveThumb) as Thumb; this.SetVisibiltyForAllTitleElements(this.TitlebarHeight > 0); } protected IntPtr CriticalHandle { get { var value = typeof(Window) .GetProperty("CriticalHandle", BindingFlags.NonPublic | BindingFlags.Instance) .GetValue(this, new object[0]); return (IntPtr)value; } } private void ClearWindowEvents() { // clear all event handlers first: if (this.windowTitleThumb != null) { this.windowTitleThumb.PreviewMouseLeftButtonUp -= this.WindowTitleThumbOnPreviewMouseLeftButtonUp; this.windowTitleThumb.DragDelta -= this.WindowTitleThumbMoveOnDragDelta; this.windowTitleThumb.MouseDoubleClick -= this.WindowTitleThumbChangeWindowStateOnMouseDoubleClick; this.windowTitleThumb.MouseRightButtonUp -= this.WindowTitleThumbSystemMenuOnMouseRightButtonUp; } var thumbContentControl = this.titleBar as IMetroThumb; if (thumbContentControl != null) { thumbContentControl.PreviewMouseLeftButtonUp -= this.WindowTitleThumbOnPreviewMouseLeftButtonUp; thumbContentControl.DragDelta -= this.WindowTitleThumbMoveOnDragDelta; thumbContentControl.MouseDoubleClick -= this.WindowTitleThumbChangeWindowStateOnMouseDoubleClick; thumbContentControl.MouseRightButtonUp -= this.WindowTitleThumbSystemMenuOnMouseRightButtonUp; } if (this.flyoutModalDragMoveThumb != null) { this.flyoutModalDragMoveThumb.PreviewMouseLeftButtonUp -= this.WindowTitleThumbOnPreviewMouseLeftButtonUp; this.flyoutModalDragMoveThumb.DragDelta -= this.WindowTitleThumbMoveOnDragDelta; this.flyoutModalDragMoveThumb.MouseDoubleClick -= this.WindowTitleThumbChangeWindowStateOnMouseDoubleClick; this.flyoutModalDragMoveThumb.MouseRightButtonUp -= this.WindowTitleThumbSystemMenuOnMouseRightButtonUp; } if (icon != null) { icon.MouseDown -= IconMouseDown; } this.SizeChanged -= this.MetroWindow_SizeChanged; } private void SetWindowEvents() { // clear all event handlers first this.ClearWindowEvents(); // set mouse down/up for icon if (icon != null && icon.Visibility == Visibility.Visible) { icon.MouseDown += IconMouseDown; } if (this.windowTitleThumb != null) { this.windowTitleThumb.PreviewMouseLeftButtonUp += WindowTitleThumbOnPreviewMouseLeftButtonUp; this.windowTitleThumb.DragDelta += this.WindowTitleThumbMoveOnDragDelta; this.windowTitleThumb.MouseDoubleClick += this.WindowTitleThumbChangeWindowStateOnMouseDoubleClick; this.windowTitleThumb.MouseRightButtonUp += this.WindowTitleThumbSystemMenuOnMouseRightButtonUp; } var thumbContentControl = this.titleBar as IMetroThumb; if (thumbContentControl != null) { thumbContentControl.PreviewMouseLeftButtonUp += WindowTitleThumbOnPreviewMouseLeftButtonUp; thumbContentControl.DragDelta += this.WindowTitleThumbMoveOnDragDelta; thumbContentControl.MouseDoubleClick += this.WindowTitleThumbChangeWindowStateOnMouseDoubleClick; thumbContentControl.MouseRightButtonUp += this.WindowTitleThumbSystemMenuOnMouseRightButtonUp; } if (this.flyoutModalDragMoveThumb != null) { this.flyoutModalDragMoveThumb.PreviewMouseLeftButtonUp += WindowTitleThumbOnPreviewMouseLeftButtonUp; this.flyoutModalDragMoveThumb.DragDelta += this.WindowTitleThumbMoveOnDragDelta; this.flyoutModalDragMoveThumb.MouseDoubleClick += this.WindowTitleThumbChangeWindowStateOnMouseDoubleClick; this.flyoutModalDragMoveThumb.MouseRightButtonUp += this.WindowTitleThumbSystemMenuOnMouseRightButtonUp; } // handle size if we have a Grid for the title (e.g. clean window have a centered title) //if (titleBar != null && titleBar.GetType() == typeof(Grid)) if (titleBar != null && TitleAlignment == HorizontalAlignment.Center) { this.SizeChanged += this.MetroWindow_SizeChanged; } } private void IconMouseDown(object sender, MouseButtonEventArgs e) { if (e.ChangedButton == MouseButton.Left) { if (e.ClickCount == 2) { Close(); } else { ShowSystemMenuPhysicalCoordinates(this, PointToScreen(new Point(0, TitlebarHeight))); } } } private void WindowTitleThumbOnPreviewMouseLeftButtonUp(object sender, MouseButtonEventArgs e) { DoWindowTitleThumbOnPreviewMouseLeftButtonUp(this, e); } private void WindowTitleThumbMoveOnDragDelta(object sender, DragDeltaEventArgs dragDeltaEventArgs) { DoWindowTitleThumbMoveOnDragDelta(sender as IMetroThumb, this, dragDeltaEventArgs); } private void WindowTitleThumbChangeWindowStateOnMouseDoubleClick(object sender, MouseButtonEventArgs mouseButtonEventArgs) { DoWindowTitleThumbChangeWindowStateOnMouseDoubleClick(this, mouseButtonEventArgs); } private void WindowTitleThumbSystemMenuOnMouseRightButtonUp(object sender, MouseButtonEventArgs e) { DoWindowTitleThumbSystemMenuOnMouseRightButtonUp(this, e); } internal static void DoWindowTitleThumbOnPreviewMouseLeftButtonUp(MetroWindow window, MouseButtonEventArgs mouseButtonEventArgs) { if (mouseButtonEventArgs.Source == mouseButtonEventArgs.OriginalSource) { Mouse.Capture(null); } } internal static void DoWindowTitleThumbMoveOnDragDelta(IMetroThumb thumb, [NotNull] MetroWindow window, DragDeltaEventArgs dragDeltaEventArgs) { if (thumb == null) { throw new ArgumentNullException(nameof(thumb)); } if (window == null) { throw new ArgumentNullException(nameof(window)); } // drag only if IsWindowDraggable is set to true if (!window.IsWindowDraggable || (!(Math.Abs(dragDeltaEventArgs.HorizontalChange) > 2) && !(Math.Abs(dragDeltaEventArgs.VerticalChange) > 2))) { return; } // tage from DragMove internal code window.VerifyAccess(); //var cursorPos = WinApiHelper.GetPhysicalCursorPos(); // if the window is maximized dragging is only allowed on title bar (also if not visible) var windowIsMaximized = window.WindowState == WindowState.Maximized; var isMouseOnTitlebar = Mouse.GetPosition(thumb).Y <= window.TitlebarHeight && window.TitlebarHeight > 0; if (!isMouseOnTitlebar && windowIsMaximized) { return; } // for the touch usage UnsafeNativeMethods.ReleaseCapture(); if (windowIsMaximized) { //var cursorXPos = cursorPos.x; EventHandler windowOnStateChanged = null; windowOnStateChanged = (sender, args) => { //window.Top = 2; //window.Left = Math.Max(cursorXPos - window.RestoreBounds.Width / 2, 0); window.StateChanged -= windowOnStateChanged; if (window.WindowState == WindowState.Normal) { Mouse.Capture(thumb, CaptureMode.Element); } }; window.StateChanged += windowOnStateChanged; } var criticalHandle = window.CriticalHandle; // DragMove works too // window.DragMove(); // instead this 2 lines Standard.NativeMethods.SendMessage(criticalHandle, Standard.WM.SYSCOMMAND, (IntPtr)Standard.SC.MOUSEMOVE, IntPtr.Zero); Standard.NativeMethods.SendMessage(criticalHandle, Standard.WM.LBUTTONUP, IntPtr.Zero, IntPtr.Zero); } internal static void DoWindowTitleThumbChangeWindowStateOnMouseDoubleClick(MetroWindow window, MouseButtonEventArgs mouseButtonEventArgs) { // restore/maximize only with left button if (mouseButtonEventArgs.ChangedButton == MouseButton.Left) { // we can maximize or restore the window if the title bar height is set (also if title bar is hidden) var canResize = window.ResizeMode == ResizeMode.CanResizeWithGrip || window.ResizeMode == ResizeMode.CanResize; var mousePos = Mouse.GetPosition(window); var isMouseOnTitlebar = mousePos.Y <= window.TitlebarHeight && window.TitlebarHeight > 0; if (canResize && isMouseOnTitlebar) { if (window.WindowState == WindowState.Normal) { Microsoft.Windows.Shell.SystemCommands.MaximizeWindow(window); } else { Microsoft.Windows.Shell.SystemCommands.RestoreWindow(window); } mouseButtonEventArgs.Handled = true; } } } internal static void DoWindowTitleThumbSystemMenuOnMouseRightButtonUp(MetroWindow window, MouseButtonEventArgs e) { if (window.ShowSystemMenuOnRightClick) { // show menu only if mouse pos is on title bar or if we have a window with none style and no title bar var mousePos = e.GetPosition(window); if ((mousePos.Y <= window.TitlebarHeight && window.TitlebarHeight > 0) || (window.UseNoneWindowStyle && window.TitlebarHeight <= 0)) { ShowSystemMenuPhysicalCoordinates(window, window.PointToScreen(mousePos)); } } } /// <summary> /// Gets the template child with the given name. /// </summary> /// <typeparam name="T">The interface type inheirted from DependencyObject.</typeparam> /// <param name="name">The name of the template child.</param> internal T GetPart<T>(string name) where T : class { return GetTemplateChild(name) as T; } /// <summary> /// Gets the template child with the given name. /// </summary> /// <param name="name">The name of the template child.</param> internal DependencyObject GetPart(string name) { return GetTemplateChild(name); } private static void ShowSystemMenuPhysicalCoordinates(Window window, Point physicalScreenLocation) { if (window == null) return; var hwnd = new WindowInteropHelper(window).Handle; if (hwnd == IntPtr.Zero || !UnsafeNativeMethods.IsWindow(hwnd)) return; var hmenu = UnsafeNativeMethods.GetSystemMenu(hwnd, false); var cmd = UnsafeNativeMethods.TrackPopupMenuEx(hmenu, Constants.TPM_LEFTBUTTON | Constants.TPM_RETURNCMD, (int)physicalScreenLocation.X, (int)physicalScreenLocation.Y, hwnd, IntPtr.Zero); if (0 != cmd) UnsafeNativeMethods.PostMessage(hwnd, Constants.SYSCOMMAND, new IntPtr(cmd), IntPtr.Zero); } internal void HandleFlyoutStatusChange(Flyout flyout, IEnumerable<Flyout> visibleFlyouts) { //checks a recently opened flyout's position. if (flyout.Position == Position.Left || flyout.Position == Position.Right || flyout.Position == Position.Top) { //get it's zindex var zIndex = flyout.IsOpen ? Panel.GetZIndex(flyout) + 3 : visibleFlyouts.Count() + 2; // Note: ShowWindowCommandsOnTop is here for backwards compatibility reasons //if the the corresponding behavior has the right flag, set the window commands' and icon zIndex to a number that is higher than the flyout's. this.icon?.SetValue(Panel.ZIndexProperty, this.IconOverlayBehavior.HasFlag(WindowCommandsOverlayBehavior.Flyouts) ? zIndex : 1); this.LeftWindowCommandsPresenter?.SetValue(Panel.ZIndexProperty, this.LeftWindowCommandsOverlayBehavior.HasFlag(WindowCommandsOverlayBehavior.Flyouts) ? zIndex : 1); this.RightWindowCommandsPresenter?.SetValue(Panel.ZIndexProperty, this.RightWindowCommandsOverlayBehavior.HasFlag(WindowCommandsOverlayBehavior.Flyouts) ? zIndex : 1); this.WindowButtonCommandsPresenter?.SetValue(Panel.ZIndexProperty, this.WindowButtonCommandsOverlayBehavior.HasFlag(WindowCommandsOverlayBehavior.Flyouts) ? zIndex : 1); this.HandleWindowCommandsForFlyouts(visibleFlyouts); } if (this.flyoutModal != null) { this.flyoutModal.Visibility = visibleFlyouts.Any(x => x.IsModal) ? Visibility.Visible : Visibility.Hidden; } RaiseEvent(new FlyoutStatusChangedRoutedEventArgs(FlyoutsStatusChangedEvent, this) { ChangedFlyout = flyout }); } public class FlyoutStatusChangedRoutedEventArgs : RoutedEventArgs { internal FlyoutStatusChangedRoutedEventArgs(RoutedEvent rEvent, object source): base(rEvent, source) { } public Flyout ChangedFlyout { get; internal set; } } } }
47.667862
436
0.644901
[ "MIT" ]
ZENOSDUDIO/MahApps.Metro
src/MahApps.Metro/MahApps.Metro.Shared/Controls/MetroWindow.cs
66,451
C#
using System.Linq; using UnityEngine; public class ModBundleSelectPage : MonoBehaviour { public ModBundleInfoPage InfoPagePrefab = null; public UIElement PreviousButton = null; public UIElement NextButton = null; public UIElement[] Options = null; private int TotalPageCount { get { return ((_modWrappers.Length - 1) / Options.Length) + 1; } } private int OptionOffset { get { return _pageIndex * Options.Length; } } private bool PreviousEnabled { get { return _pageIndex > 0; } } private bool NextEnabled { get { return _pageIndex < TotalPageCount - 1; } } private ModSelectorService.ModWrapper[] _modWrappers = null; private int _pageIndex = 0; private Page _page = null; private void Awake() { _page = GetComponent<Page>(); for (int optionIndex = 0; optionIndex < Options.Length; ++optionIndex) { int localOptionIndex = optionIndex; KMSelectable selectable = Options[optionIndex].GetComponent<KMSelectable>(); selectable.OnInteract += delegate() { _page.GetPageWithComponent(InfoPagePrefab).ModWrapper = _modWrappers[OptionOffset + localOptionIndex]; _page.GoToPage(InfoPagePrefab); return true; }; } } private void OnEnable() { if (ModSelectorService.Instance == null) { return; } _modWrappers = ModSelectorService.Instance.GetModWrappers().ToArray(); System.Array.Sort(_modWrappers, (x, y) => string.Compare(x.ModTitle.Replace("The ", ""), y.ModTitle.Replace("The ", ""))); SetPage(0); } public void SetPage(int pageIndex) { if (_modWrappers == null) { return; } _pageIndex = Mathf.Clamp(pageIndex, 0, TotalPageCount - 1); for (int optionIndex = 0; optionIndex < Options.Length; ++optionIndex) { UIElement option = Options[optionIndex]; int trueOptionIndex = OptionOffset + optionIndex; if (trueOptionIndex < _modWrappers.Length) { option.gameObject.SetActive(true); option.Text = _modWrappers[trueOptionIndex].ModTitle; } else { option.gameObject.SetActive(false); } } _page.HeaderText = string.Format("<b>Select Mod For Info...</b>\n<size=16>Page {0} of {1}</size>", _pageIndex + 1, TotalPageCount); if (PreviousButton != null) { PreviousButton.CanSelect = PreviousEnabled; } if (NextButton != null) { NextButton.CanSelect = NextEnabled; } } public void NextPage() { SetPage(_pageIndex + 1); } public void PreviousPage() { SetPage(_pageIndex - 1); } }
23.984375
139
0.552443
[ "MIT" ]
AndrioCelos/ktanemod-modselector
Assets/Scripts/Pages/ModBundleSelectPage.cs
3,070
C#
using System; using System.ComponentModel.DataAnnotations.Schema; using Oqtane.Models; namespace Admin.PageSubscriberDashboard.Models { [Table("AdminPageSubscriberDashboard")] public class PageSubscriberDashboard : IAuditable { public int PageSubscriberDashboardId { get; set; } public int ModuleId { get; set; } public string Name { get; set; } public string CreatedBy { get; set; } public DateTime CreatedOn { get; set; } public string ModifiedBy { get; set; } public DateTime ModifiedOn { get; set; } } }
29.1
58
0.675258
[ "MIT" ]
rockydant/Utilities
Oqtane.Shared/Modules/Admin.PageSubscriberDashboard/Models/PageSubscriberDashboard.cs
582
C#
using System; using System.Drawing; using System.Drawing.Imaging; using System.IO; using System.Runtime.InteropServices; using System.Text; namespace DmitryBrant.ImageFormats { public static class TgaReader { public static Bitmap Load(string fileName) { Bitmap result = null; using (var fileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read)) { result = Load(fileStream); } return result; } public static Bitmap Load(Stream stream) { var binaryReader = new BinaryReader(stream); uint[] array = null; var b = (byte)stream.ReadByte(); var b2 = (byte)stream.ReadByte(); var b3 = (byte)stream.ReadByte(); var num = LittleEndian(binaryReader.ReadUInt16()); var num2 = LittleEndian(binaryReader.ReadUInt16()); var b4 = (byte)stream.ReadByte(); LittleEndian(binaryReader.ReadUInt16()); LittleEndian(binaryReader.ReadUInt16()); var num3 = LittleEndian(binaryReader.ReadUInt16()); var num4 = LittleEndian(binaryReader.ReadUInt16()); var b5 = (byte)stream.ReadByte(); var b6 = (byte)stream.ReadByte(); if (b2 > 1) { throw new ApplicationException("This is not a valid TGA file."); } if (b > 0) { var array2 = new byte[(int)b]; stream.Read(array2, 0, (int)b); Encoding.ASCII.GetString(array2); } if (b3 > 11 || (b3 > 3 && b3 < 9)) { throw new ApplicationException("This image type (" + b3 + ") is not supported."); } if (b5 != 8 && b5 != 15 && b5 != 16 && b5 != 24 && b5 != 32) { throw new ApplicationException("Number of bits per pixel (" + b5 + ") is not supported."); } if (b2 > 0 && b4 != 15 && b4 != 16 && b4 != 24 && b4 != 32) { throw new ApplicationException("Number of bits per color map (" + b5 + ") is not supported."); } var array3 = new byte[(int)(num3 * 4 * num4)]; try { if (b2 > 0) { var num5 = (int)(num + num2); array = new uint[num5]; if (b4 == 24) { for (var i = (int)num; i < num5; i++) { array[i] = 4278190080u; array[i] |= (uint)((uint)stream.ReadByte() << 16); array[i] |= (uint)((uint)stream.ReadByte() << 8); array[i] |= (uint)stream.ReadByte(); } } else if (b4 == 32) { for (var j = (int)num; j < num5; j++) { array[j] = 4278190080u; array[j] |= (uint)((uint)stream.ReadByte() << 16); array[j] |= (uint)((uint)stream.ReadByte() << 8); array[j] |= (uint)stream.ReadByte(); array[j] |= (uint)((uint)stream.ReadByte() << 24); } } else if (b4 == 15 || b4 == 16) { for (var k = (int)num; k < num5; k++) { var num6 = stream.ReadByte(); var num7 = stream.ReadByte(); array[k] = 4278190080u; array[k] |= (uint)((uint)((uint)(num6 & 31) << 3) << 16); array[k] |= (uint)((uint)((uint)(((num7 & 3) << 3) + ((num6 & 224) >> 5)) << 3) << 8); array[k] |= (uint)((uint)((num7 & 127) >> 2) << 3); } } } if (b3 == 1 || b3 == 2 || b3 == 3) { var array4 = new byte[(int)(num3 * (ushort)(b5 / 8))]; for (var l = (int)(num4 - 1); l >= 0; l--) { if (b5 <= 16) { if (b5 != 8) { if (b5 - 15 <= 1) { for (var m = 0; m < (int)num3; m++) { var num8 = stream.ReadByte(); var num9 = stream.ReadByte(); array3[4 * (l * (int)num3 + m)] = (byte)((num8 & 31) << 3); array3[4 * (l * (int)num3 + m) + 1] = (byte)(((num9 & 3) << 3) + ((num8 & 224) >> 5) << 3); array3[4 * (l * (int)num3 + m) + 2] = (byte)((num9 & 127) >> 2 << 3); array3[4 * (l * (int)num3 + m) + 3] = byte.MaxValue; } } } else { stream.Read(array4, 0, array4.Length); if (b3 == 1) { for (var n = 0; n < (int)num3; n++) { array3[4 * (l * (int)num3 + n)] = (byte)(array[(int)array4[n]] >> 16 & 255u); array3[4 * (l * (int)num3 + n) + 1] = (byte)(array[(int)array4[n]] >> 8 & 255u); array3[4 * (l * (int)num3 + n) + 2] = (byte)(array[(int)array4[n]] & 255u); array3[4 * (l * (int)num3 + n) + 3] = byte.MaxValue; } } else if (b3 == 3) { for (var num10 = 0; num10 < (int)num3; num10++) { array3[4 * (l * (int)num3 + num10)] = array4[num10]; array3[4 * (l * (int)num3 + num10) + 1] = array4[num10]; array3[4 * (l * (int)num3 + num10) + 2] = array4[num10]; array3[4 * (l * (int)num3 + num10) + 3] = byte.MaxValue; } } } } else if (b5 != 24) { if (b5 == 32) { stream.Read(array4, 0, array4.Length); for (var num11 = 0; num11 < (int)num3; num11++) { array3[4 * (l * (int)num3 + num11)] = array4[num11 * 4]; array3[4 * (l * (int)num3 + num11) + 1] = array4[num11 * 4 + 1]; array3[4 * (l * (int)num3 + num11) + 2] = array4[num11 * 4 + 2]; array3[4 * (l * (int)num3 + num11) + 3] = byte.MaxValue; } } } else { stream.Read(array4, 0, array4.Length); for (var num12 = 0; num12 < (int)num3; num12++) { array3[4 * (l * (int)num3 + num12)] = array4[num12 * 3]; array3[4 * (l * (int)num3 + num12) + 1] = array4[num12 * 3 + 1]; array3[4 * (l * (int)num3 + num12) + 2] = array4[num12 * 3 + 2]; array3[4 * (l * (int)num3 + num12) + 3] = byte.MaxValue; } } } } else if (b3 == 9 || b3 == 10 || b3 == 11) { var num13 = (int)(num4 - 1); var num14 = 0; var num15 = (int)(b5 / 8); var array4 = new byte[(int)(num3 * 4)]; while (num13 >= 0 && stream.Position < stream.Length) { var num16 = stream.ReadByte(); if (num16 < 128) { num16++; if (b5 <= 16) { if (b5 != 8) { if (b5 - 15 <= 1) { for (var num17 = 0; num17 < num16; num17++) { var num18 = stream.ReadByte(); var num19 = stream.ReadByte(); array3[4 * (num13 * (int)num3 + num14)] = (byte)((num18 & 31) << 3); array3[4 * (num13 * (int)num3 + num14) + 1] = (byte)(((num19 & 3) << 3) + ((num18 & 224) >> 5) << 3); array3[4 * (num13 * (int)num3 + num14) + 2] = (byte)((num19 & 127) >> 2 << 3); array3[4 * (num13 * (int)num3 + num14) + 3] = byte.MaxValue; num14++; if (num14 >= (int)num3) { num14 = 0; num13--; } } } } else { stream.Read(array4, 0, num16 * num15); if (b3 == 9) { for (var num20 = 0; num20 < num16; num20++) { array3[4 * (num13 * (int)num3 + num14)] = (byte)(array[(int)array4[num20]] >> 16 & 255u); array3[4 * (num13 * (int)num3 + num14) + 1] = (byte)(array[(int)array4[num20]] >> 8 & 255u); array3[4 * (num13 * (int)num3 + num14) + 2] = (byte)(array[(int)array4[num20]] & 255u); array3[4 * (num13 * (int)num3 + num14) + 3] = byte.MaxValue; num14++; if (num14 >= (int)num3) { num14 = 0; num13--; } } } else if (b3 == 11) { for (var num21 = 0; num21 < num16; num21++) { array3[4 * (num13 * (int)num3 + num14)] = array4[num21]; array3[4 * (num13 * (int)num3 + num14) + 1] = array4[num21]; array3[4 * (num13 * (int)num3 + num14) + 2] = array4[num21]; array3[4 * (num13 * (int)num3 + num14) + 3] = byte.MaxValue; num14++; if (num14 >= (int)num3) { num14 = 0; num13--; } } } } } else if (b5 != 24) { if (b5 == 32) { stream.Read(array4, 0, num16 * num15); for (var num22 = 0; num22 < num16; num22++) { array3[4 * (num13 * (int)num3 + num14)] = array4[num22 * 4]; array3[4 * (num13 * (int)num3 + num14) + 1] = array4[num22 * 4 + 1]; array3[4 * (num13 * (int)num3 + num14) + 2] = array4[num22 * 4 + 2]; array3[4 * (num13 * (int)num3 + num14) + 3] = byte.MaxValue; num14++; if (num14 >= (int)num3) { num14 = 0; num13--; } } } } else { stream.Read(array4, 0, num16 * num15); for (var num23 = 0; num23 < num16; num23++) { array3[4 * (num13 * (int)num3 + num14)] = array4[num23 * 3]; array3[4 * (num13 * (int)num3 + num14) + 1] = array4[num23 * 3 + 1]; array3[4 * (num13 * (int)num3 + num14) + 2] = array4[num23 * 3 + 2]; array3[4 * (num13 * (int)num3 + num14) + 3] = byte.MaxValue; num14++; if (num14 >= (int)num3) { num14 = 0; num13--; } } } } else { num16 = (num16 & 127) + 1; if (b5 <= 16) { if (b5 != 8) { if (b5 - 15 <= 1) { var num24 = stream.ReadByte(); var num25 = stream.ReadByte(); for (var num26 = 0; num26 < num16; num26++) { array3[4 * (num13 * (int)num3 + num14)] = (byte)((num24 & 31) << 3); array3[4 * (num13 * (int)num3 + num14) + 1] = (byte)(((num25 & 3) << 3) + ((num24 & 224) >> 5) << 3); array3[4 * (num13 * (int)num3 + num14) + 2] = (byte)((num25 & 127) >> 2 << 3); array3[4 * (num13 * (int)num3 + num14) + 3] = byte.MaxValue; num14++; if (num14 >= (int)num3) { num14 = 0; num13--; } } } } else { var num27 = stream.ReadByte(); if (b3 == 9) { for (var num28 = 0; num28 < num16; num28++) { array3[4 * (num13 * (int)num3 + num14)] = (byte)(array[num27] >> 16 & 255u); array3[4 * (num13 * (int)num3 + num14) + 1] = (byte)(array[num27] >> 8 & 255u); array3[4 * (num13 * (int)num3 + num14) + 2] = (byte)(array[num27] & 255u); array3[4 * (num13 * (int)num3 + num14) + 3] = byte.MaxValue; num14++; if (num14 >= (int)num3) { num14 = 0; num13--; } } } else if (b3 == 11) { for (var num29 = 0; num29 < num16; num29++) { array3[4 * (num13 * (int)num3 + num14)] = (byte)num27; array3[4 * (num13 * (int)num3 + num14) + 1] = (byte)num27; array3[4 * (num13 * (int)num3 + num14) + 2] = (byte)num27; array3[4 * (num13 * (int)num3 + num14) + 3] = byte.MaxValue; num14++; if (num14 >= (int)num3) { num14 = 0; num13--; } } } } } else if (b5 != 24) { if (b5 == 32) { var num30 = stream.ReadByte(); var num31 = stream.ReadByte(); var num32 = stream.ReadByte(); stream.ReadByte(); for (var num33 = 0; num33 < num16; num33++) { array3[4 * (num13 * (int)num3 + num14)] = (byte)num30; array3[4 * (num13 * (int)num3 + num14) + 1] = (byte)num31; array3[4 * (num13 * (int)num3 + num14) + 2] = (byte)num32; array3[4 * (num13 * (int)num3 + num14) + 3] = byte.MaxValue; num14++; if (num14 >= (int)num3) { num14 = 0; num13--; } } } } else { var num30 = stream.ReadByte(); var num31 = stream.ReadByte(); var num32 = stream.ReadByte(); for (var num34 = 0; num34 < num16; num34++) { array3[4 * (num13 * (int)num3 + num14)] = (byte)num30; array3[4 * (num13 * (int)num3 + num14) + 1] = (byte)num31; array3[4 * (num13 * (int)num3 + num14) + 2] = (byte)num32; array3[4 * (num13 * (int)num3 + num14) + 3] = byte.MaxValue; num14++; if (num14 >= (int)num3) { num14 = 0; num13--; } } } } } } } catch (Exception) { } var bitmap = new Bitmap((int)num3, (int)num4, PixelFormat.Format32bppArgb); var bitmapData = bitmap.LockBits(new Rectangle(0, 0, bitmap.Width, bitmap.Height), ImageLockMode.ReadWrite, PixelFormat.Format32bppArgb); Marshal.Copy(array3, 0, bitmapData.Scan0, (int)(num3 * 4 * num4)); bitmap.UnlockBits(bitmapData); var num35 = b6 >> 4 & 3; if (num35 == 1) { bitmap.RotateFlip(RotateFlipType.RotateNoneFlipX); } else if (num35 == 2) { bitmap.RotateFlip(RotateFlipType.Rotate180FlipX); } else if (num35 == 3) { bitmap.RotateFlip(RotateFlipType.Rotate180FlipNone); } return bitmap; } private static ushort LittleEndian(ushort val) { if (BitConverter.IsLittleEndian) { return val; } return conv_endian(val); } private static uint LittleEndian(uint val) { if (BitConverter.IsLittleEndian) { return val; } return conv_endian(val); } private static UInt16 conv_endian(UInt16 val) { UInt16 temp; temp = (UInt16)(val << 8); temp &= 0xFF00; temp |= (UInt16)((val >> 8) & 0xFF); return temp; } private static UInt32 conv_endian(UInt32 val) { var temp = (val & 0x000000FF) << 24; temp |= (val & 0x0000FF00) << 8; temp |= (val & 0x00FF0000) >> 8; temp |= (val & 0xFF000000) >> 24; return (temp); } } }
51.537778
149
0.27212
[ "Apache-2.0" ]
xafero/ImageFormats
Source/TgaReader.cs
23,194
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.md file in the project root for more information. using Moq.Protected; namespace Microsoft.VisualStudio.Telemetry { public class VsTelemetryServiceTests { [Fact] public void PostEvent_NullAsEventName_ThrowsArgumentNull() { var service = CreateInstance(); Assert.Throws<ArgumentNullException>("eventName", () => { service.PostEvent(null!); }); } [Fact] public void PostEvent_EmptyAsEventName_ThrowsArgument() { var service = CreateInstance(); Assert.Throws<ArgumentException>("eventName", () => { service.PostEvent(string.Empty); }); } [Fact] public void PostProperty_NullAsEventName_ThrowArgumentNull() { var service = CreateInstance(); Assert.Throws<ArgumentNullException>("eventName", () => { service.PostProperty(null!, "propName", "value"); }); } [Fact] public void PostProperty_EmptyAsEventName_ThrowArgument() { var service = CreateInstance(); Assert.Throws<ArgumentException>("eventName", () => { service.PostProperty(string.Empty, "propName", "value"); }); } [Fact] public void PostProperty_NullAsPropertyName_ThrowArgumentNull() { var service = CreateInstance(); Assert.Throws<ArgumentNullException>("propertyName", () => { service.PostProperty("event1", null!, "value"); }); } [Fact] public void PostProperty_EmptyAsPropertyName_ThrowArgument() { var service = CreateInstance(); Assert.Throws<ArgumentException>("propertyName", () => { service.PostProperty("event1", string.Empty, "value"); }); } [Fact] public void PostProperty_NullAsPropertyValue_ThrowArgumentNull() { var service = CreateInstance(); Assert.Throws<ArgumentNullException>("propertyValue", () => { service.PostProperty("event1", "propName", null!); }); } [Fact] public void PostProperties_NullAsEventName_ThrowArgumentNull() { var service = CreateInstance(); Assert.Throws<ArgumentNullException>("eventName", () => { service.PostProperties(null!, new[] { ("propertyName", (object)"propertyValue") }); }); } [Fact] public void PostProperties_EmptyAsEventName_ThrowArgument() { var service = CreateInstance(); Assert.Throws<ArgumentException>("eventName", () => { service.PostProperties(string.Empty, new[] { ("propertyName", (object)"propertyValue") }); }); } [Fact] public void PostProperties_NullAsPropertyName_ThrowArgumentNull() { var service = CreateInstance(); Assert.Throws<ArgumentNullException>("properties", () => { service.PostProperties("event1", null!); }); } [Fact] public void PostProperties_EmptyProperties_ThrowArgument() { var service = CreateInstance(); Assert.Throws<ArgumentException>("properties", () => { service.PostProperties("event1", Enumerable.Empty<(string propertyName, object propertyValue)>()); }); } [Fact] public void PostEvent_SendsTelemetryEvent() { TelemetryEvent? result = null; var service = CreateInstance((e) => { result = e; }); service.PostEvent(TelemetryEventName.UpToDateCheckSuccess); Assert.NotNull(result); Assert.Equal(TelemetryEventName.UpToDateCheckSuccess, result!.Name); } [Fact] public void PostProperty_SendsTelemetryEventWithProperty() { TelemetryEvent? result = null; var service = CreateInstance((e) => { result = e; }); service.PostProperty(TelemetryEventName.UpToDateCheckFail, TelemetryPropertyName.UpToDateCheckFailReason, "Reason"); Assert.NotNull(result); Assert.Equal(TelemetryEventName.UpToDateCheckFail, result.Name); Assert.Contains(new KeyValuePair<string, object>(TelemetryPropertyName.UpToDateCheckFailReason, "Reason"), result.Properties); } [Fact] public void PostProperties_SendsTelemetryEventWithProperties() { TelemetryEvent? result = null; var service = CreateInstance((e) => { result = e; }); service.PostProperties(TelemetryEventName.DesignTimeBuildComplete, new[] { (TelemetryPropertyName.DesignTimeBuildCompleteSucceeded, (object)true), (TelemetryPropertyName.DesignTimeBuildCompleteTargets, "Compile") }); Assert.NotNull(result); Assert.Equal(TelemetryEventName.DesignTimeBuildComplete, result.Name); Assert.Contains(new KeyValuePair<string, object>(TelemetryPropertyName.DesignTimeBuildCompleteSucceeded, true), result.Properties); Assert.Contains(new KeyValuePair<string, object>(TelemetryPropertyName.DesignTimeBuildCompleteTargets, "Compile"), result.Properties); } private static VsTelemetryService CreateInstance(Action<TelemetryEvent>? action = null) { if (action == null) return new VsTelemetryService(); // Override PostEventToSession to avoid actually sending to telemetry var mock = new Mock<VsTelemetryService>(); mock.Protected().Setup("PostEventToSession", ItExpr.IsAny<TelemetryEvent>()) .Callback(action); return mock.Object; } } }
34.385027
201
0.566252
[ "MIT" ]
adamint/project-system
tests/Microsoft.VisualStudio.ProjectSystem.Managed.VS.UnitTests/Telemetry/VsTelemetryServiceTests.cs
6,246
C#
// ReSharper disable PossibleNullReferenceException namespace Core6.UpgradeGuides._5to6 { using System.Collections.Generic; using System.Threading.Tasks; using NServiceBus; using NServiceBus.DeliveryConstraints; using NServiceBus.Extensibility; using NServiceBus.Routing; using NServiceBus.Transport; class RawSend { async Task RawSending(IDispatchMessages dispatcher) { #region DispatcherRawSending var headers = new Dictionary<string, string>(); var outgoingMessage = new OutgoingMessage("MessageId", headers, new byte[] { }); var constraints = new List<DeliveryConstraint> { new NonDurableDelivery() }; var address = new UnicastAddressTag("Destination"); var operation = new TransportOperation( message: outgoingMessage, addressTag: address, requiredDispatchConsistency: DispatchConsistency.Default, deliveryConstraints: constraints); var operations = new TransportOperations(operation); await dispatcher.Dispatch(operations, new TransportTransaction(), new ContextBag()) .ConfigureAwait(false); #endregion } } }
35.205128
96
0.608157
[ "Apache-2.0" ]
A-Franklin/docs.particular.net
Snippets/Core/Core_6/UpgradeGuides/5to6/RawSend.cs
1,337
C#
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; namespace Gimela.Data.DataStructures { /// <summary> /// 二叉树 /// </summary> /// <typeparam name="T">二叉树中节点内容类型</typeparam> [SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")] public class BinaryTree<T> : ICollection<T>, IEnumerable<T> where T : IComparable<T> { #region Constructor /// <summary> /// 二叉树 /// </summary> public BinaryTree() { NumberOfNodes = 0; } /// <summary> /// 二叉树 /// </summary> /// <param name="root">二叉树根节点</param> public BinaryTree(BinaryTreeNode<T> root) : this() { this.Root = root; } #endregion #region Properties /// <summary> /// 树的根节点 /// </summary> public BinaryTreeNode<T> Root { get; set; } /// <summary> /// 树中节点的数量 /// </summary> protected int NumberOfNodes { get; set; } /// <summary> /// 树是否为空 /// </summary> public bool IsEmpty { get { return Root == null; } } /// <summary> /// 获取树中节点的最小值 /// </summary> public T MinValue { get { if (IsEmpty) return default(T); BinaryTreeNode<T> minNode = Root; while (minNode.Left != null) minNode = minNode.Left; return minNode.Value; } } /// <summary> /// 获取树中节点的最大值 /// </summary> public T MaxValue { get { if (IsEmpty) return default(T); BinaryTreeNode<T> maxNode = Root; while (maxNode.Right != null) maxNode = maxNode.Right; return maxNode.Value; } } #endregion #region IEnumerable<T> Members /// <summary> /// Returns an enumerator that iterates through the collection. /// </summary> /// <returns> /// A <see cref="T:System.Collections.Generic.IEnumerator`1"></see> /// that can be used to iterate through the collection. /// </returns> public IEnumerator<T> GetEnumerator() { foreach (BinaryTreeNode<T> node in Traverse(Root)) { yield return node.Value; } } #endregion #region IEnumerable Members /// <summary> /// Returns an enumerator that iterates through a collection. /// </summary> /// <returns> /// An <see cref="T:System.Collections.IEnumerator"/> /// object that can be used to iterate through the collection. /// </returns> IEnumerator IEnumerable.GetEnumerator() { foreach (BinaryTreeNode<T> node in Traverse(Root)) { yield return node.Value; } } #endregion #region ICollection<T> Members /// <summary> /// 新增节点 /// </summary> /// <param name="item">The object to add to the /// <see cref="T:System.Collections.Generic.ICollection`1"></see>.</param> /// <exception cref="T:System.NotSupportedException">The /// <see cref="T:System.Collections.Generic.ICollection`1"></see> /// is read-only.</exception> public void Add(T item) { if (Root == null) { Root = new BinaryTreeNode<T>(item); ++NumberOfNodes; } else { Insert(item); } } /// <summary> /// 清除树 /// </summary> public void Clear() { Root = null; } /// <summary> /// 树中是否包含此节点 /// </summary> /// <param name="item">The object to locate in the /// <see cref="T:System.Collections.Generic.ICollection`1"></see>.</param> /// <returns> /// true if item is found in the /// <see cref="T:System.Collections.Generic.ICollection`1"></see>; otherwise, false. /// </returns> public bool Contains(T item) { if (IsEmpty) return false; BinaryTreeNode<T> currentNode = Root; while (currentNode != null) { int comparedValue = currentNode.Value.CompareTo(item); if (comparedValue == 0) return true; else if (comparedValue < 0) currentNode = currentNode.Left; else currentNode = currentNode.Right; } return false; } /// <summary> /// 将树中节点拷贝至目标数组 /// </summary> /// <param name="array">The array.</param> /// <param name="arrayIndex">Index of the array.</param> public void CopyTo(T[] array, int arrayIndex) { T[] tempArray = new T[NumberOfNodes]; int counter = 0; foreach (T value in this) { tempArray[counter] = value; ++counter; } Array.Copy(tempArray, 0, array, arrayIndex, Count); } /// <summary> /// 树中节点的数量 /// </summary> public int Count { get { return NumberOfNodes; } } /// <summary> /// 树是否为只读 /// </summary> public bool IsReadOnly { get { return false; } } /// <summary> /// 移除节点 /// </summary> /// <param name="item">节点值</param> /// <returns>是否移除成功</returns> public bool Remove(T item) { BinaryTreeNode<T> node = Find(item); if (node == null) return false; List<T> values = new List<T>(); foreach (BinaryTreeNode<T> l in Traverse(node.Left)) { values.Add(l.Value); } foreach (BinaryTreeNode<T> r in Traverse(node.Right)) { values.Add(r.Value); } if (node.Parent.Left == node) { node.Parent.Left = null; } else { node.Parent.Right = null; } node.Parent = null; foreach (T v in values) { this.Add(v); } return true; } #endregion #region Private Functions /// <summary> /// 查找指定值的节点 /// </summary> /// <param name="value">指定值</param> /// <returns> /// 指定值的节点 /// </returns> protected BinaryTreeNode<T> Find(T value) { foreach (BinaryTreeNode<T> node in Traverse(Root)) if (node.Value.Equals(value)) return node; return null; } /// <summary> /// 遍历树 /// </summary> /// <param name="node">遍历搜索的起始节点</param> /// <returns> /// The individual items from the tree /// </returns> [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures")] protected IEnumerable<BinaryTreeNode<T>> Traverse(BinaryTreeNode<T> node) { // 遍历左子树 if (node.Left != null) { foreach (BinaryTreeNode<T> left in Traverse(node.Left)) yield return left; } // 中序遍历二叉树, 顺序是 左子树,根,右子树 yield return node; // 遍历右子树 if (node.Right != null) { foreach (BinaryTreeNode<T> right in Traverse(node.Right)) yield return right; } } /// <summary> /// 插入节点 /// </summary> /// <param name="value">插入的节点值</param> protected void Insert(T value) { // 从根节点开始比较 BinaryTreeNode<T> currentNode = Root; while (true) { if (currentNode == null) throw new InvalidProgramException("The current tree node cannot be null."); // 比较当前节点与新节点的值 int comparedValue = currentNode.Value.CompareTo(value); if (comparedValue < 0) { // 当前节点值小于新节点值 if (currentNode.Left == null) { currentNode.Left = new BinaryTreeNode<T>(value, currentNode); ++NumberOfNodes; return; } else { currentNode = currentNode.Left; } } else if (comparedValue > 0) { // 当前节点值大于新节点值 if (currentNode.Right == null) { currentNode.Right = new BinaryTreeNode<T>(value, currentNode); ++NumberOfNodes; return; } else { currentNode = currentNode.Right; } } else { // 当前节点值等于新节点值 currentNode = currentNode.Right; } } } #endregion } }
22.076712
91
0.535617
[ "MIT" ]
J-W-Chan/Gimela
src/Foundation/Data/Gimela.Data.DataStructures/BinaryTree/BinaryTree.cs
8,534
C#
namespace SpontimePictures.Areas.HelpPage.ModelDescriptions { public class CollectionModelDescription : ModelDescription { public ModelDescription ElementDescription { get; set; } } }
29
64
0.758621
[ "MIT" ]
lukemuszynski/spnt-2015
SpontimeCluster/SpontimePictures/SpontimePictures/Areas/HelpPage/ModelDescriptions/CollectionModelDescription.cs
203
C#
using Borg.Infrastructure.Core.DDD.Contracts; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.Abstractions; using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Threading; using System.Threading.Tasks; namespace Borg.Framework.DAL { public interface IIStaticStore { IStaticEntityStore<TEntity> EntityStore<TEntity>() where TEntity : IEntity; } public interface IStaticEntityStore<out TEntity> where TEntity : IEntity { IQueryable<TEntity> Query { get; } } public abstract class StaticEntityStore<TEntity> : IStaticEntityStore<TEntity> where TEntity : IEntity { private static ReaderWriterLock _rwl = new ReaderWriterLock(); private const int _timeOut = 100; private readonly List<TEntity> _data = new List<TEntity>(); protected readonly ILogger _logger; protected StaticEntityStore(ILoggerFactory loggerFactory) { _logger = loggerFactory == null ? NullLogger.Instance : loggerFactory.CreateLogger(GetType()); } protected virtual Task Populate(IEnumerable<TEntity> collection) { _logger.Info("Populating static store for {type}", typeof(TEntity).FullName); var watch = Stopwatch.StartNew(); try { _rwl.AcquireReaderLock(_timeOut); try { _data.Clear(); _data.AddRange(collection); } finally { _rwl.ReleaseReaderLock(); var ellapsed = watch.Elapsed; watch.Stop(); watch = null; _logger.Info("Populatied static store for {type} in {time}", typeof(TEntity).FullName, ellapsed.ToString("G")); } } catch (ApplicationException ex) { _logger.Error(ex, "Failed to load static store for {type} - {reason}", typeof(TEntity).FullName, ex.ToString()); } return Task.CompletedTask; } public IQueryable<TEntity> Query { get; } } }
34.230769
131
0.596854
[ "Apache-2.0" ]
mitsbits/Bor
src/Framework/Borg.Framework/DAL/IStaticEntityStore.cs
2,227
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Security.Cryptography; using System.Text; using UnityEngine; namespace ActiveTextureManagement { class CacheController { static String MD5String = ""; static String LastFile = ""; public static GameDatabase.TextureInfo FetchCacheTexture(TexInfo Texture, bool compress, bool mipmaps, bool makeNotReadable) { String textureName = Texture.name; String originalTextureFile = KSPUtil.ApplicationRootPath + "GameData/" + textureName; String cacheFile = KSPUtil.ApplicationRootPath + "GameData/ActiveTextureManagement/textureCache/" + textureName; String cacheConfigFile = cacheFile + ".tcache"; cacheFile += ".pngcache"; if (File.Exists(cacheConfigFile)) { ConfigNode config = ConfigNode.Load(cacheConfigFile); string format = config.GetValue("orig_format"); String cacheHash = config.GetValue("md5"); int origWidth, origHeight; string origWidthString = config.GetValue("orig_width"); string origHeightString = config.GetValue("orig_height"); int.TryParse(origWidthString, out origWidth); int.TryParse(origHeightString, out origHeight); if (origWidthString == null || origHeightString == null || cacheHash == null || format == null) { return RebuildCache(Texture, compress, mipmaps, makeNotReadable); } originalTextureFile += format; String hashString = GetMD5String(originalTextureFile); Texture.Resize(origWidth, origHeight); if (format != null && File.Exists(originalTextureFile) && File.Exists(cacheFile)) { String cacheIsNormString = config.GetValue("is_normal"); String cacheWidthString = config.GetValue("width"); String cacheHeihtString = config.GetValue("height"); bool cacheIsNorm = false; int cacheWidth = 0; int cacheHeight = 0; bool.TryParse(cacheIsNormString, out cacheIsNorm); int.TryParse(cacheWidthString, out cacheWidth); int.TryParse(cacheHeihtString, out cacheHeight); if (cacheHash != hashString || cacheIsNorm != Texture.isNormalMap || Texture.resizeWidth != cacheWidth || Texture.resizeHeight != cacheHeight) { if (cacheHash != hashString) { ActiveTextureManagement.DBGLog(cacheHash + " != " + hashString); } if (cacheIsNorm != Texture.isNormalMap) { ActiveTextureManagement.DBGLog(cacheIsNorm + " != " + Texture.isNormalMap); } if (Texture.resizeWidth != cacheWidth) { ActiveTextureManagement.DBGLog(Texture.resizeWidth + " != " + cacheWidth); } if (Texture.resizeHeight != cacheHeight) { ActiveTextureManagement.DBGLog(Texture.resizeHeight + " != " + cacheHeight); } return RebuildCache(Texture, compress, mipmaps, makeNotReadable); } else if (cacheHash == hashString && !Texture.needsResize) { return RebuildCache(Texture, compress, mipmaps, makeNotReadable); } else { ActiveTextureManagement.DBGLog("Loading from cache... " + textureName); Texture.needsResize = false; Texture2D newTex = new Texture2D(4, 4); GameDatabase.TextureInfo cacheTexture = new GameDatabase.TextureInfo(newTex, Texture.isNormalMap, !makeNotReadable, compress); Texture.texture = cacheTexture; Texture.filename = cacheFile; TextureConverter.IMGToTexture(Texture, mipmaps, cacheIsNorm); cacheTexture.name = textureName; newTex.name = textureName; if (compress) { newTex.Compress(true); } newTex.Apply(mipmaps, makeNotReadable); return cacheTexture; } } else { return RebuildCache(Texture, compress, mipmaps, makeNotReadable); } } else { return RebuildCache(Texture, compress, mipmaps, makeNotReadable); } } private static GameDatabase.TextureInfo RebuildCache(TexInfo Texture, bool compress, bool mipmaps, bool makeNotReadable) { Texture.loadOriginalFirst = true; ActiveTextureManagement.DBGLog("Loading texture..."); TextureConverter.GetReadable(Texture, mipmaps); ActiveTextureManagement.DBGLog("Texture loaded."); GameDatabase.TextureInfo cacheTexture = Texture.texture; Texture2D tex = cacheTexture.texture; String textureName = cacheTexture.name; String cacheFile = KSPUtil.ApplicationRootPath + "GameData/ActiveTextureManagement/textureCache/" + textureName; if (Texture.needsResize) { ActiveTextureManagement.DBGLog("Rebuilding Cache... " + Texture.name); ActiveTextureManagement.DBGLog("Saving cache file " + cacheFile + ".pngcache"); TextureConverter.WriteTo(cacheTexture.texture, cacheFile + ".pngcache"); String originalTextureFile = Texture.filename; String cacheConfigFile = cacheFile + ".tcache"; ActiveTextureManagement.DBGLog("Created Config for" + originalTextureFile); String hashString = GetMD5String(originalTextureFile); ConfigNode config = new ConfigNode(); config.AddValue("md5", hashString); ActiveTextureManagement.DBGLog("md5: " + hashString); config.AddValue("orig_format", Path.GetExtension(originalTextureFile)); ActiveTextureManagement.DBGLog("orig_format: " + Path.GetExtension(originalTextureFile)); config.AddValue("orig_width", Texture.width.ToString()); ActiveTextureManagement.DBGLog("orig_width: " + Texture.width.ToString()); config.AddValue("orig_height", Texture.height.ToString()); ActiveTextureManagement.DBGLog("orig_height: " + Texture.height.ToString()); config.AddValue("is_normal", cacheTexture.isNormalMap.ToString()); ActiveTextureManagement.DBGLog("is_normal: " + cacheTexture.isNormalMap.ToString()); config.AddValue("width", Texture.resizeWidth.ToString()); ActiveTextureManagement.DBGLog("width: " + Texture.resizeWidth.ToString()); config.AddValue("height", Texture.resizeHeight.ToString()); ActiveTextureManagement.DBGLog("height: " + Texture.resizeHeight.ToString()); config.Save(cacheConfigFile); ActiveTextureManagement.DBGLog("Saved Config."); } else { String directory = Path.GetDirectoryName(cacheFile + ".none"); if (File.Exists(directory)) { File.Delete(directory); } Directory.CreateDirectory(directory); } if (compress) { tex.Compress(true); } cacheTexture.isCompressed = compress; if (!makeNotReadable) { tex.Apply(mipmaps); } else { tex.Apply(mipmaps, true); } cacheTexture.isReadable = !makeNotReadable; return cacheTexture; } static String GetMD5String(String file) { if(file == LastFile) { return MD5String; } if (File.Exists(file)) { FileStream stream = File.OpenRead(file); MD5 md5 = MD5.Create(); byte[] hash = md5.ComputeHash(stream); stream.Close(); MD5String = BitConverter.ToString(hash); LastFile = file; return MD5String; } else { return null; } } public static int MemorySaved(int originalWidth, int originalHeight, TextureFormat originalFormat, bool originalMipmaps, GameDatabase.TextureInfo Texture) { int width = Texture.texture.width; int height = Texture.texture.height; TextureFormat format = Texture.texture.format; bool mipmaps = Texture.texture.mipmapCount == 1 ? false : true; ActiveTextureManagement.DBGLog("Texture: " + Texture.name); ActiveTextureManagement.DBGLog("is normalmap: " + Texture.isNormalMap); Texture2D tex = Texture.texture; ActiveTextureManagement.DBGLog("originalWidth: " + originalWidth); ActiveTextureManagement.DBGLog("originalHeight: " + originalHeight); ActiveTextureManagement.DBGLog("originalFormat: " + originalFormat); ActiveTextureManagement.DBGLog("originalMipmaps: " + originalMipmaps); ActiveTextureManagement.DBGLog("width: " + width); ActiveTextureManagement.DBGLog("height: " + height); ActiveTextureManagement.DBGLog("format: " + format); ActiveTextureManagement.DBGLog("mipmaps: " + mipmaps); bool readable = true; try { tex.GetPixel(0, 0); } catch { readable = false; }; ActiveTextureManagement.DBGLog("readable: " + readable); if (readable != Texture.isReadable) { ActiveTextureManagement.DBGLog("Readbility does not match!"); } int oldSize = 0; int newSize = 0; switch (originalFormat) { case TextureFormat.ARGB32: case TextureFormat.RGBA32: case TextureFormat.BGRA32: oldSize = 4 * (originalWidth * originalHeight); break; case TextureFormat.RGB24: oldSize = 3 * (originalWidth * originalHeight); break; case TextureFormat.Alpha8: oldSize = originalWidth * originalHeight; break; case TextureFormat.DXT1: oldSize = (originalWidth * originalHeight) / 2; break; case TextureFormat.DXT5: oldSize = originalWidth * originalHeight; break; } switch (format) { case TextureFormat.ARGB32: case TextureFormat.RGBA32: case TextureFormat.BGRA32: newSize = 4 * (width * height); break; case TextureFormat.RGB24: newSize = 3 * (width * height); break; case TextureFormat.Alpha8: newSize = width * height; break; case TextureFormat.DXT1: newSize = (width * height) / 2; break; case TextureFormat.DXT5: newSize = width * height; break; } if (originalMipmaps) { oldSize += (int)(oldSize * .33f); } if (mipmaps) { newSize += (int)(newSize * .33f); } return (oldSize - newSize); } } }
44.663082
177
0.531579
[ "MIT", "Unlicense" ]
amo28/ActiveTextureManagement
ActiveTextureManagement/CacheController.cs
12,463
C#
using RuyaTabircim.Data.Model; using System.Collections.Generic; namespace RuyaTabircim.Data.Service.Interface { public interface IDreamService { Dream Get(string id); IEnumerable<DreamUser> GetAll(); IEnumerable<DreamUser> GetForReply(); IEnumerable<Dream> GetBySpiritId(string id); bool Send(RequestDream value); bool Reply(RequestDream value); bool Watch(string id, string spiritId); } }
27.117647
52
0.685466
[ "MIT" ]
doxa-labs/dream-reviews-app-api
RuyaTabircim.Data/Service/Interface/IDreamService.cs
463
C#
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AzureNative.Network.V20200701 { public static class GetVirtualHubBgpConnection { /// <summary> /// Virtual Appliance Site resource. /// </summary> public static Task<GetVirtualHubBgpConnectionResult> InvokeAsync(GetVirtualHubBgpConnectionArgs args, InvokeOptions? options = null) => Pulumi.Deployment.Instance.InvokeAsync<GetVirtualHubBgpConnectionResult>("azure-native:network/v20200701:getVirtualHubBgpConnection", args ?? new GetVirtualHubBgpConnectionArgs(), options.WithVersion()); } public sealed class GetVirtualHubBgpConnectionArgs : Pulumi.InvokeArgs { /// <summary> /// The name of the connection. /// </summary> [Input("connectionName", required: true)] public string ConnectionName { get; set; } = null!; /// <summary> /// The resource group name of the VirtualHub. /// </summary> [Input("resourceGroupName", required: true)] public string ResourceGroupName { get; set; } = null!; /// <summary> /// The name of the VirtualHub. /// </summary> [Input("virtualHubName", required: true)] public string VirtualHubName { get; set; } = null!; public GetVirtualHubBgpConnectionArgs() { } } [OutputType] public sealed class GetVirtualHubBgpConnectionResult { /// <summary> /// The current state of the VirtualHub to Peer. /// </summary> public readonly string ConnectionState; /// <summary> /// A unique read-only string that changes whenever the resource is updated. /// </summary> public readonly string Etag; /// <summary> /// Resource ID. /// </summary> public readonly string? Id; /// <summary> /// Name of the connection. /// </summary> public readonly string? Name; /// <summary> /// Peer ASN. /// </summary> public readonly double? PeerAsn; /// <summary> /// Peer IP. /// </summary> public readonly string? PeerIp; /// <summary> /// The provisioning state of the resource. /// </summary> public readonly string ProvisioningState; /// <summary> /// Connection type. /// </summary> public readonly string Type; [OutputConstructor] private GetVirtualHubBgpConnectionResult( string connectionState, string etag, string? id, string? name, double? peerAsn, string? peerIp, string provisioningState, string type) { ConnectionState = connectionState; Etag = etag; Id = id; Name = name; PeerAsn = peerAsn; PeerIp = peerIp; ProvisioningState = provisioningState; Type = type; } } }
29.39823
218
0.580072
[ "Apache-2.0" ]
polivbr/pulumi-azure-native
sdk/dotnet/Network/V20200701/GetVirtualHubBgpConnection.cs
3,322
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("Shuttle.Packager")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Shuttle.Packager")] [assembly: AssemblyCopyright("Copyright © 2018")] [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("4e7f1217-9f87-4b04-ac28-2731ef943090")] // 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.837838
84
0.747857
[ "BSD-3-Clause" ]
Shuttle/Shuttle.Packager
Shuttle.Packager/Properties/AssemblyInfo.cs
1,403
C#
// ========================================================================== // Squidex Headless CMS // ========================================================================== // Copyright (c) Squidex UG (haftungsbeschraenkt) // All rights reserved. Licensed under the MIT license. // ========================================================================== using FakeItEasy; using Squidex.Infrastructure.Commands; using Squidex.Infrastructure.EventSourcing; using Squidex.Infrastructure.States; using Squidex.Log; namespace Squidex.Infrastructure.TestHelpers { public sealed class MyDomainObject : DomainObject<MyDomainState> { public bool Recreate { get; set; } public bool RecreateEvent { get; set; } public int VersionsToKeep { get => Capacity; set => Capacity = value; } public MyDomainObject(IPersistenceFactory<MyDomainState> factory) : base(factory, A.Dummy<ISemanticLog>()) { } protected override bool CanRecreate(IEvent @event) { return RecreateEvent ? @event is ValueChanged : false; } protected override bool CanRecreate() { return Recreate; } protected override bool CanAcceptCreation(ICommand command) { if (command is CreateAuto update) { return update.Value != 99; } return true; } protected override bool CanAccept(ICommand command) { if (command is UpdateAuto update) { return update.Value != 99; } return true; } protected override bool IsDeleted(MyDomainState snapshot) { return snapshot.IsDeleted; } public override Task<CommandResult> ExecuteAsync(IAggregateCommand command) { switch (command) { case Upsert c: return Upsert(c, createAuto => { RaiseEvent(new ValueChanged { Value = createAuto.Value }); }); case CreateAuto c: return Create(c, createAuto => { RaiseEvent(new ValueChanged { Value = createAuto.Value }); }); case CreateCustom c: return CreateReturn(c, createCustom => { RaiseEvent(new ValueChanged { Value = createCustom.Value }); return "CREATED"; }); case UpdateAuto c: return Update(c, updateAuto => { RaiseEvent(new ValueChanged { Value = updateAuto.Value }); }); case UpdateCustom c: return UpdateReturn(c, updateCustom => { RaiseEvent(new ValueChanged { Value = updateCustom.Value }); return "UPDATED"; }); case Delete c: return Update(c, delete => { RaiseEvent(new Deleted()); }); case DeletePermanent c: return DeletePermanent(c, delete => { RaiseEvent(new Deleted()); }); default: throw new NotSupportedException(); } } } public sealed class Delete : MyCommand { } public sealed class DeletePermanent : MyCommand { } public sealed class Upsert : MyCommand { public long Value { get; set; } } public sealed class CreateAuto : MyCommand { public long Value { get; set; } } public sealed class CreateCustom : MyCommand { public long Value { get; set; } } public sealed class UpdateAuto : MyCommand { public long Value { get; set; } } public sealed class UpdateCustom : MyCommand { public long Value { get; set; } } }
27.649351
84
0.46759
[ "MIT" ]
Appleseed/squidex
backend/tests/Squidex.Infrastructure.Tests/TestHelpers/MyDomainObject.cs
4,260
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 elasticbeanstalk-2010-12-01.normal.json service model. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Net; using System.Text; using System.Xml.Serialization; using Amazon.ElasticBeanstalk.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; namespace Amazon.ElasticBeanstalk.Model.Internal.MarshallTransformations { /// <summary> /// Response Unmarshaller for ComposeEnvironments operation /// </summary> public class ComposeEnvironmentsResponseUnmarshaller : XmlResponseUnmarshaller { /// <summary> /// Unmarshaller the response from the service to the response class. /// </summary> /// <param name="context"></param> /// <returns></returns> public override AmazonWebServiceResponse Unmarshall(XmlUnmarshallerContext context) { ComposeEnvironmentsResponse response = new ComposeEnvironmentsResponse(); context.Read(); int targetDepth = context.CurrentDepth; while (context.ReadAtDepth(targetDepth)) { if (context.IsStartElement) { if(context.TestExpression("ComposeEnvironmentsResult", 2)) { UnmarshallResult(context, response); continue; } if (context.TestExpression("ResponseMetadata", 2)) { response.ResponseMetadata = ResponseMetadataUnmarshaller.Instance.Unmarshall(context); } } } return response; } private static void UnmarshallResult(XmlUnmarshallerContext context, ComposeEnvironmentsResponse response) { int originalDepth = context.CurrentDepth; int targetDepth = originalDepth + 1; if (context.IsStartOfDocument) targetDepth += 2; while (context.ReadAtDepth(originalDepth)) { if (context.IsStartElement || context.IsAttribute) { if (context.TestExpression("Environments/member", targetDepth)) { var unmarshaller = EnvironmentDescriptionUnmarshaller.Instance; var item = unmarshaller.Unmarshall(context); response.Environments.Add(item); continue; } if (context.TestExpression("NextToken", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; response.NextToken = unmarshaller.Unmarshall(context); continue; } } } return; } /// <summary> /// Unmarshaller error response to exception. /// </summary> /// <param name="context"></param> /// <param name="innerException"></param> /// <param name="statusCode"></param> /// <returns></returns> public override AmazonServiceException UnmarshallException(XmlUnmarshallerContext context, Exception innerException, HttpStatusCode statusCode) { ErrorResponse errorResponse = ErrorResponseUnmarshaller.GetInstance().Unmarshall(context); if (errorResponse.Code != null && errorResponse.Code.Equals("InsufficientPrivilegesException")) { return new InsufficientPrivilegesException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode); } if (errorResponse.Code != null && errorResponse.Code.Equals("TooManyEnvironmentsException")) { return new TooManyEnvironmentsException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode); } return new AmazonElasticBeanstalkException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode); } private static ComposeEnvironmentsResponseUnmarshaller _instance = new ComposeEnvironmentsResponseUnmarshaller(); internal static ComposeEnvironmentsResponseUnmarshaller GetInstance() { return _instance; } /// <summary> /// Gets the singleton. /// </summary> public static ComposeEnvironmentsResponseUnmarshaller Instance { get { return _instance; } } } }
39.048951
175
0.603152
[ "Apache-2.0" ]
Bio2hazard/aws-sdk-net
sdk/src/Services/ElasticBeanstalk/Generated/Model/Internal/MarshallTransformations/ComposeEnvironmentsResponseUnmarshaller.cs
5,584
C#
using System.Diagnostics.CodeAnalysis; using Ketchup.Core.Utilities; namespace Ketchup.Profession.Specification { public static class SpecificationExtensions { /// <summary> /// Combines the current specification instance with another specification instance /// and returns the combined specification which represents that both the current and /// the given specification must be satisfied by the given object. /// </summary> /// <param name="specification">The specification</param> /// <param name="other">The specification instance with which the current specification is combined.</param> /// <returns>The combined specification instance.</returns> public static ISpecification<T> And<T>([NotNull] this ISpecification<T> specification, [NotNull] ISpecification<T> other) { Check.NotNull(specification, nameof(specification)); Check.NotNull(other, nameof(other)); return new AndSpecification<T>(specification, other); } /// <summary> /// Combines the current specification instance with another specification instance /// and returns the combined specification which represents that either the current or /// the given specification should be satisfied by the given object. /// </summary> /// <param name="specification">The specification</param> /// <param name="other">The specification instance with which the current specification /// is combined.</param> /// <returns>The combined specification instance.</returns> public static ISpecification<T> Or<T>([NotNull] this ISpecification<T> specification, [NotNull] ISpecification<T> other) { Check.NotNull(specification, nameof(specification)); Check.NotNull(other, nameof(other)); return new OrSpecification<T>(specification, other); } /// <summary> /// Combines the current specification instance with another specification instance /// and returns the combined specification which represents that the current specification /// should be satisfied by the given object but the specified specification should not. /// </summary> /// <param name="specification">The specification</param> /// <param name="other">The specification instance with which the current specification /// is combined.</param> /// <returns>The combined specification instance.</returns> public static ISpecification<T> AndNot<T>([NotNull] this ISpecification<T> specification, [NotNull] ISpecification<T> other) { Check.NotNull(specification, nameof(specification)); Check.NotNull(other, nameof(other)); return new AndNotSpecification<T>(specification, other); } /// <summary> /// Reverses the current specification instance and returns a specification which represents /// the semantics opposite to the current specification. /// </summary> /// <returns>The reversed specification instance.</returns> public static ISpecification<T> Not<T>([NotNull] this ISpecification<T> specification) { Check.NotNull(specification, nameof(specification)); return new NotSpecification<T>(specification); } } }
48.842857
132
0.668909
[ "MIT" ]
microserviceframe/ketchup
core/src/Ketchup.Profession/Specification/SpecificationExtensions.cs
3,419
C#
using System.IO; using RhythmCodex.Psf.Models; namespace RhythmCodex.Psf.Streamers { public interface IPsfStreamReader { PsfChunk Read(Stream source); } }
17.5
37
0.714286
[ "MIT" ]
SaxxonPike/RhythmCodex
Source/RhythmCodex.Lib/Psf/Streamers/IPsfStreamReader.cs
175
C#
using System.Text.Json.Serialization; namespace Saison.Models.Beer { public class MediaVenueCategory { [JsonPropertyName("category_key")] public string CategoryKey { get; set; } [JsonPropertyName("category_name")] public string CategoryName { get; set; } [JsonPropertyName("category_id")] public string CategoryId { get; set; } [JsonPropertyName("is_primary")] public bool IsPrimary { get; set; } } }
25.263158
48
0.641667
[ "MIT" ]
MolinRE/saison
src/Models/Beer/MediaVenueCategory.cs
480
C#
public class WoodData { // Holds all Wood public int amtWood = 0; }
12
24
0.666667
[ "Apache-2.0" ]
Torquelus/LudumDare45
Assets/Scripts/Resource System/WoodData.cs
74
C#
namespace DisposableSample { class Program { static void Main() { using (var resource = new SomeResource()) { resource.Foo(); } } } }
15.928571
53
0.41704
[ "MIT" ]
Bazzaware/ProfessionalCSharp7
Memory/MemorySamples/DisposableSample/Program.cs
225
C#
// Generated class v2.19.0.0, don't modify using System; using System.Collections.Generic; using System.Collections.Specialized; using System.Linq; using System.Text; namespace NHtmlUnit.Javascript.Host.Html { public partial class HTMLTimeElement : NHtmlUnit.Javascript.Host.Html.HTMLElement, NHtmlUnit.Javascript.IScriptableWithFallbackGetter { static HTMLTimeElement() { ObjectWrapper.RegisterWrapperCreator((com.gargoylesoftware.htmlunit.javascript.host.html.HTMLTimeElement o) => new HTMLTimeElement(o)); } public HTMLTimeElement(com.gargoylesoftware.htmlunit.javascript.host.html.HTMLTimeElement wrappedObject) : base(wrappedObject) {} public new com.gargoylesoftware.htmlunit.javascript.host.html.HTMLTimeElement WObj { get { return (com.gargoylesoftware.htmlunit.javascript.host.html.HTMLTimeElement)WrappedObject; } } public HTMLTimeElement() : this(new com.gargoylesoftware.htmlunit.javascript.host.html.HTMLTimeElement()) {} } }
32.575758
137
0.723721
[ "Apache-2.0" ]
JonAnders/NHtmlUnit
app/NHtmlUnit/Generated/Javascript/Host/Html/HTMLTimeElement.cs
1,075
C#
using alps.net.api.parsing; using alps.net.api.src; using alps.net.api.util; using System.Collections.Generic; namespace alps.net.api.StandardPASS.BehaviorDescribingComponents { /// <summary> /// Class that represents a transition class /// </summary> public class Transition : BehaviorDescribingComponent, ITransition { protected IAction belongsToAction; protected IState sourceState; protected IState targetState; protected ITransitionCondition transitionCondition; private ITransition.TransitionType transitionType; protected readonly IDictionary<string, ITransition> implementedInterfaces = new Dictionary<string, ITransition>(); protected bool isAbstractType = false; private const string ABSTRACT_NAME = "AbstractPASSTransition"; /// <summary> /// Name of the class /// </summary> private const string className = "Transition"; public override string getClassName() { return className; } public override IParseablePASSProcessModelElement getParsedInstance() { return new Transition(); } protected Transition() { } /// <summary> /// /// </summary> /// <param name="label"></param> /// <param name="comment"></param> /// <param name="action"></param> /// <param name="sourceState"></param> /// <param name="targetState"></param> /// <param name="transitionCondition"></param> /// <param name="additionalAttribute"></param> /// <param name="transitionType"></param> public Transition(IState sourceState, IState targetState, string labelForID = null, ITransitionCondition transitionCondition = null, ITransition.TransitionType transitionType = ITransition.TransitionType.Standard, string comment = null, string additionalLabel = null, IList<IIncompleteTriple> additionalAttribute = null) : base(null, labelForID, comment, additionalLabel, additionalAttribute) { ISubjectBehavior behavior = null; if (sourceState != null) sourceState.getContainedBy(out behavior); if (behavior is null && targetState != null) targetState.getContainedBy(out behavior); if (behavior != null) setContainedBy(behavior); setSourceState(sourceState); setTargetState(targetState); setTransitionCondition(transitionCondition); setTransitionType(transitionType); } public Transition(ISubjectBehavior behavior, string labelForID = null, IState sourceState = null, IState targetState = null, ITransitionCondition transitionCondition = null, ITransition.TransitionType transitionType = ITransition.TransitionType.Standard, string comment = null, string additionalLabel = null, IList<IIncompleteTriple> additionalAttribute = null) : base(behavior, labelForID, comment, additionalLabel, additionalAttribute) { setSourceState(sourceState); setTargetState(targetState); setTransitionCondition(transitionCondition); setTransitionType(transitionType); } /// <summary> /// Used to set the action that belongs to this transition. /// Only called from inside the class, should not be visible to the user (the action is set/removed automatically when a source state is added/removed) /// </summary> protected void setBelongsToAction(IAction action, int removeCascadeDepth = 0) { IAction oldAction = belongsToAction; // Might set it to null this.belongsToAction = action; if (oldAction != null) { if (oldAction.Equals(action)) return; oldAction.unregister(this, removeCascadeDepth); removeTriple(new IncompleteTriple(OWLTags.stdBelongsTo, oldAction.getUriModelComponentID())); } if (!(action is null)) { publishElementAdded(action); action.register(this); addTriple(new IncompleteTriple(OWLTags.stdBelongsTo, action.getUriModelComponentID())); } } public virtual void setSourceState(IState sourceState, int removeCascadeDepth = 0) { IState oldSourceState = this.sourceState; // Might set it to null this.sourceState = sourceState; if (oldSourceState != null) { if (oldSourceState.Equals(sourceState)) return; oldSourceState.unregister(this, removeCascadeDepth); oldSourceState.removeOutgoingTransition(getModelComponentID()); setBelongsToAction(null); removeTriple(new IncompleteTriple(OWLTags.stdHasSourceState, oldSourceState.getUriModelComponentID())); } if (!(sourceState is null)) { publishElementAdded(sourceState); sourceState.register(this); sourceState.addOutgoingTransition(this); setBelongsToAction(sourceState.getAction()); addTriple(new IncompleteTriple(OWLTags.stdHasSourceState, sourceState.getUriModelComponentID())); } } public virtual void setTargetState(IState targetState, int removeCascadeDepth = 0) { IState oldState = this.targetState; // Might set it to null this.targetState = targetState; if (oldState != null) { if (oldState.Equals(targetState)) return; oldState.unregister(this, removeCascadeDepth); oldState.removeIncomingTransition(getModelComponentID()); removeTriple(new IncompleteTriple(OWLTags.stdHasTargetState, oldState.getUriModelComponentID())); } if (!(targetState is null)) { publishElementAdded(targetState); targetState.register(this); targetState.addIncomingTransition(this); addTriple(new IncompleteTriple(OWLTags.stdHasTargetState, targetState.getUriModelComponentID())); } } public virtual void setTransitionCondition(ITransitionCondition transitionCondition, int removeCascadeDepth = 0) { ITransitionCondition oldCond = transitionCondition; // Might set it to null this.transitionCondition = transitionCondition; if (oldCond != null) { if (oldCond.Equals(transitionCondition)) return; oldCond.unregister(this, removeCascadeDepth); removeTriple(new IncompleteTriple(OWLTags.stdHasTransitionCondition, oldCond.getUriModelComponentID())); } if (!(transitionCondition is null)) { publishElementAdded(transitionCondition); transitionCondition.register(this); addTriple(new IncompleteTriple(OWLTags.stdHasTransitionCondition, transitionCondition.getUriModelComponentID())); } } public IAction getBelongsToAction() { return belongsToAction; } public IState getSourceState() { return sourceState; } public IState getTargetState() { return targetState; } public ITransitionCondition getTransitionCondition() { return transitionCondition; } public void setTransitionType(ITransition.TransitionType type) { transitionType = type; } public ITransition.TransitionType getTransitionType() { return transitionType; } protected override bool parseAttribute(string predicate, string objectContent, string lang, string dataType, IParseablePASSProcessModelElement element) { if (element != null) { if (predicate.Contains(OWLTags.belongsTo) && element is IAction action) { setBelongsToAction(action); return true; } else if (predicate.Contains(OWLTags.hasTransitionCondition) && element is ITransitionCondition condition) { setTransitionCondition(condition); return true; } else if (element is IState state) { if (predicate.Contains(OWLTags.hasSourceState)) { setSourceState(state); return true; } else if (predicate.Contains(OWLTags.hasTargetState)) { setTargetState(state); return true; } } } else { if (predicate.Contains(OWLTags.type)) { if (objectContent.Contains(ABSTRACT_NAME)) { setIsAbstract(true); return true; } } } return base.parseAttribute(predicate, objectContent, lang, dataType, element); } public override ISet<IPASSProcessModelElement> getAllConnectedElements(ConnectedElementsSetSpecification specification) { ISet<IPASSProcessModelElement> baseElements = base.getAllConnectedElements(specification); if (getBelongsToAction() != null && specification == ConnectedElementsSetSpecification.ALL || specification == ConnectedElementsSetSpecification.TO_ADD) baseElements.Add(getBelongsToAction()); if (specification != ConnectedElementsSetSpecification.TO_ALWAYS_REMOVE) { if (getSourceState() != null) baseElements.Add(getSourceState()); if (getTargetState() != null) baseElements.Add(getTargetState()); } if (getTransitionCondition() != null) baseElements.Add(getTransitionCondition()); return baseElements; } public override void updateRemoved(IPASSProcessModelElement update, IPASSProcessModelElement caller, int removeCascadeDepth = 0) { base.updateRemoved(update, caller, removeCascadeDepth); if (update != null) { if (update is IAction action && action.Equals(getBelongsToAction())) setBelongsToAction(null, removeCascadeDepth); if (update is IState state) { if (state.Equals(getSourceState())) setSourceState(null, removeCascadeDepth); if (state.Equals(getTargetState())) setTargetState(null, removeCascadeDepth); } if (update is ITransitionCondition condition && condition.Equals(getTransitionCondition())) setTransitionCondition(null, removeCascadeDepth); } } public override void updateAdded(IPASSProcessModelElement update, IPASSProcessModelElement caller) { if (update != null) { if (!(caller is null) && caller.Equals(getSourceState())){ if (update is IAction action) { setBelongsToAction(action); } } } } public void setImplementedInterfaces(ISet<ITransition> implementedInterface, int removeCascadeDepth = 0) { foreach (ITransition implInterface in getImplementedInterfaces().Values) { removeImplementedInterfaces(implInterface.getModelComponentID(), removeCascadeDepth); } if (implementedInterface is null) return; foreach (ITransition implInterface in implementedInterface) { addImplementedInterface(implInterface); } } public void addImplementedInterface(ITransition implementedInterface) { if (implementedInterface is null) { return; } if (implementedInterfaces.TryAdd(implementedInterface.getModelComponentID(), implementedInterface)) { publishElementAdded(implementedInterface); implementedInterface.register(this); addTriple(new IncompleteTriple(OWLTags.abstrImplements, implementedInterface.getUriModelComponentID())); } } public void removeImplementedInterfaces(string id, int removeCascadeDepth = 0) { if (id is null) return; if (implementedInterfaces.TryGetValue(id, out ITransition implInterface)) { implementedInterfaces.Remove(id); implInterface.unregister(this, removeCascadeDepth); removeTriple(new IncompleteTriple(OWLTags.abstrImplements, implInterface.getUriModelComponentID())); } } public IDictionary<string, ITransition> getImplementedInterfaces() { return new Dictionary<string, ITransition>(implementedInterfaces); } public void setIsAbstract(bool isAbstract) { this.isAbstractType = isAbstract; if (isAbstract) { addTriple(new IncompleteTriple(OWLTags.rdfType, getExportTag() + ABSTRACT_NAME)); } else { removeTriple(new IncompleteTriple(OWLTags.rdfType, getExportTag() + ABSTRACT_NAME)); } } public bool isAbstract() { return isAbstractType; } } }
38.474255
164
0.586673
[ "MIT" ]
I2PM/alps.net.api
alps .net api/alps.net.api/StandardPASS/PassProcessModelElements/BehaviorDescribingComponents/Transition.cs
14,199
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using Amido.Stacks.Application.CQRS.Commands; using Amido.Stacks.Messaging.Azure.ServiceBus.Configuration; using Amido.Stacks.Messaging.Azure.ServiceBus.Factories; using Amido.Stacks.Messaging.Azure.ServiceBus.Serializers; using Amido.Stacks.Messaging.Commands; using Amido.Stacks.Messaging.Handlers; using Amido.Stacks.Messaging.Handlers.TestDependency; using Microsoft.Azure.ServiceBus; using Microsoft.Azure.ServiceBus.Core; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Options; using NSubstitute; using Xunit; namespace Amido.Stacks.Messaging.Azure.ServiceBus.Tests.UnitTests.Listeners { public class QueueListenerTests { ServiceBusConfiguration config; IServiceCollection services; List<IReceiverClient> receiverClients = new List<IReceiverClient>(); ITestable<NotifyCommand> testable; public QueueListenerTests() { testable = Substitute.For<ITestable<NotifyCommand>>(); config = new ServiceBusConfiguration() { Listener = new ServiceBusListenerConfiguration { Queues = new[] { new ServiceBusQueueListenerConfiguration { Alias = "c", Name = "CHARLIE" }, new ServiceBusQueueListenerConfiguration { Alias = "d", Name = "DELTA" } } } }; var receiverFactory = Substitute.For<IMessageReceiverClientFactory>(); receiverFactory.CreateReceiverClient(Arg.Any<ServiceBusEntityConfiguration>()).Returns((args) => { var cfg = (ServiceBusEntityConfiguration)args[0]; var client = Substitute.For<FakeSBClient>(); client.Path = cfg.Alias ?? cfg.Name; receiverClients.Add(client); return client; }); services = new ServiceCollection() .AddLogging() .AddTransient((b) => Options.Create(config)) .AddSingleton(receiverFactory) .AddTransient(_ => testable) ; } [Theory] [InlineData(nameof(JsonMessageSerializer), nameof(NotifyCommand))] [InlineData(nameof(JsonMessageSerializer), "")] [InlineData(nameof(CloudEventMessageSerializer), "")] public async Task Given_A_Message_Is_Received_From_UnknownType_Is_DeadLettered(string serializer, string enclosedTypeName) { //ARRANGE var guid = Guid.NewGuid(); services .AddTransient<ICommandHandler<NotifyCommand, bool>, NotifyCommandHandler>() .AddServiceBus() ; await services.BuildServiceProvider().GetService<IHostedService>().StartAsync(CancellationToken.None); Message msg = BuildMessage(serializer, guid); msg.SetLockOnMessage(); msg.UserProperties[MessageProperties.EnclosedMessageType.ToString()] = enclosedTypeName; //ACT var client = (FakeSBClient)receiverClients.First(); await client.SendAsyncToReceiver(msg); ////ASSERT testable.Received(0).Complete(Arg.Any<NotifyCommand>()); await client.Received(1).DeadLetterAsync(Arg.Any<string>(), Arg.Any<string>(), Arg.Any<string>()); } [Theory] [InlineData(nameof(JsonMessageSerializer))] [InlineData(nameof(CloudEventMessageSerializer))] public async Task Given_A_Message_Is_Received_From_KnownType_Is_Sent_To_Right_Hanler(string serializer) { //ARRANGE var guid = Guid.NewGuid(); services .AddTransient<ICommandHandler<NotifyCommand, bool>, NotifyCommandHandler>() .AddServiceBus() ; await services.BuildServiceProvider().GetService<IHostedService>().StartAsync(CancellationToken.None); Message msg = BuildMessage(serializer, guid); msg.SetLockOnMessage(); //ACT var client = (FakeSBClient)receiverClients.First(); await client.SendAsyncToReceiver(msg); ////ASSERT testable.Received(1).Complete(Arg.Is<NotifyCommand>(m => m.CorrelationId == guid)); } [Theory] [InlineData(nameof(JsonMessageSerializer))] [InlineData(nameof(CloudEventMessageSerializer))] public async Task Given_A_Message_Is_Received_From_KnownType_NoHandlerAvailable_Should_DeadLetter(string serializer) { //ARRANGE var guid = Guid.NewGuid(); services.AddServiceBus(); await services.BuildServiceProvider().GetService<IHostedService>().StartAsync(CancellationToken.None); Message msg = BuildMessage(serializer, guid); msg.SetLockOnMessage(); //ACT var client = (FakeSBClient)receiverClients.First(); await client.SendAsyncToReceiver(msg); ////ASSERT testable.Received(0).Complete(Arg.Any<NotifyCommand>()); await client.Received(1).DeadLetterAsync(Arg.Any<string>(), Arg.Any<string>(), Arg.Any<string>()); } private static Message BuildMessage(string serializer, Guid guid) { var obj = new NotifyCommand(guid, "123"); if (serializer == nameof(CloudEventMessageSerializer)) return new CloudEventMessageSerializer().Build<ICommand>(obj); else return new JsonMessageSerializer().Build<ICommand>(obj); } } }
35.922619
130
0.607788
[ "MIT" ]
amido/stacks-dotnet-packages-messaging-asb
src/Amido.Stacks.Messaging.Azure.ServiceBus.Tests/UnitTests/Listeners/QueueListenerTests.cs
6,037
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; using System.Collections.Generic; using System.Diagnostics; using System.Runtime.CompilerServices; using System.Text; // // Note: F# compiler depends on the exact tuple hashing algorithm. Do not ever change it. // namespace System { /// <summary> /// Helper so we can call some tuple methods recursively without knowing the underlying types. /// </summary> internal interface ITupleInternal : ITuple { string ToString(StringBuilder sb); int GetHashCode(IEqualityComparer comparer); } public static class Tuple { public static Tuple<T1> Create<T1>(T1 item1) { return new Tuple<T1>(item1); } public static Tuple<T1, T2> Create<T1, T2>(T1 item1, T2 item2) { return new Tuple<T1, T2>(item1, item2); } public static Tuple<T1, T2, T3> Create<T1, T2, T3>(T1 item1, T2 item2, T3 item3) { return new Tuple<T1, T2, T3>(item1, item2, item3); } public static Tuple<T1, T2, T3, T4> Create<T1, T2, T3, T4>(T1 item1, T2 item2, T3 item3, T4 item4) { return new Tuple<T1, T2, T3, T4>(item1, item2, item3, item4); } public static Tuple<T1, T2, T3, T4, T5> Create<T1, T2, T3, T4, T5>(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5) { return new Tuple<T1, T2, T3, T4, T5>(item1, item2, item3, item4, item5); } public static Tuple<T1, T2, T3, T4, T5, T6> Create<T1, T2, T3, T4, T5, T6>(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6) { return new Tuple<T1, T2, T3, T4, T5, T6>(item1, item2, item3, item4, item5, item6); } public static Tuple<T1, T2, T3, T4, T5, T6, T7> Create<T1, T2, T3, T4, T5, T6, T7>(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6, T7 item7) { return new Tuple<T1, T2, T3, T4, T5, T6, T7>(item1, item2, item3, item4, item5, item6, item7); } public static Tuple<T1, T2, T3, T4, T5, T6, T7, Tuple<T8>> Create<T1, T2, T3, T4, T5, T6, T7, T8>(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6, T7 item7, T8 item8) { return new Tuple<T1, T2, T3, T4, T5, T6, T7, Tuple<T8>>(item1, item2, item3, item4, item5, item6, item7, new Tuple<T8>(item8)); } // From System.Web.Util.HashCodeCombiner internal static int CombineHashCodes(int h1, int h2) { return (((h1 << 5) + h1) ^ h2); } internal static int CombineHashCodes(int h1, int h2, int h3) { return CombineHashCodes(CombineHashCodes(h1, h2), h3); } internal static int CombineHashCodes(int h1, int h2, int h3, int h4) { return CombineHashCodes(CombineHashCodes(h1, h2), CombineHashCodes(h3, h4)); } internal static int CombineHashCodes(int h1, int h2, int h3, int h4, int h5) { return CombineHashCodes(CombineHashCodes(h1, h2, h3, h4), h5); } internal static int CombineHashCodes(int h1, int h2, int h3, int h4, int h5, int h6) { return CombineHashCodes(CombineHashCodes(h1, h2, h3, h4), CombineHashCodes(h5, h6)); } internal static int CombineHashCodes(int h1, int h2, int h3, int h4, int h5, int h6, int h7) { return CombineHashCodes(CombineHashCodes(h1, h2, h3, h4), CombineHashCodes(h5, h6, h7)); } internal static int CombineHashCodes(int h1, int h2, int h3, int h4, int h5, int h6, int h7, int h8) { return CombineHashCodes(CombineHashCodes(h1, h2, h3, h4), CombineHashCodes(h5, h6, h7, h8)); } } [Serializable] [System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public class Tuple<T1> : IStructuralEquatable, IStructuralComparable, IComparable, ITupleInternal, ITuple { private readonly T1 m_Item1; // Do not rename (binary serialization) public T1 Item1 => m_Item1; public Tuple(T1 item1) { m_Item1 = item1; } public override bool Equals(object? obj) { return ((IStructuralEquatable)this).Equals(obj, EqualityComparer<object>.Default); } bool IStructuralEquatable.Equals(object? other, IEqualityComparer comparer) { if (other == null) return false; if (!(other is Tuple<T1> objTuple)) { return false; } return comparer.Equals(m_Item1, objTuple.m_Item1); } int IComparable.CompareTo(object? obj) { return ((IStructuralComparable)this).CompareTo(obj, Comparer<object>.Default); } int IStructuralComparable.CompareTo(object? other, IComparer comparer) { if (other == null) return 1; if (!(other is Tuple<T1> objTuple)) { throw new ArgumentException(SR.Format(SR.ArgumentException_TupleIncorrectType, GetType()), nameof(other)); } return comparer.Compare(m_Item1, objTuple.m_Item1); } public override int GetHashCode() { return ((IStructuralEquatable)this).GetHashCode(EqualityComparer<object>.Default); } int IStructuralEquatable.GetHashCode(IEqualityComparer comparer) { return comparer.GetHashCode(m_Item1!); } int ITupleInternal.GetHashCode(IEqualityComparer comparer) { return ((IStructuralEquatable)this).GetHashCode(comparer); } public override string ToString() { StringBuilder sb = new StringBuilder(); sb.Append('('); return ((ITupleInternal)this).ToString(sb); } string ITupleInternal.ToString(StringBuilder sb) { sb.Append(m_Item1); sb.Append(')'); return sb.ToString(); } /// <summary> /// The number of positions in this data structure. /// </summary> int ITuple.Length => 1; /// <summary> /// Get the element at position <param name="index"/>. /// </summary> object? ITuple.this[int index] { get { if (index != 0) { throw new IndexOutOfRangeException(); } return Item1; } } } [Serializable] [System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public class Tuple<T1, T2> : IStructuralEquatable, IStructuralComparable, IComparable, ITupleInternal, ITuple { private readonly T1 m_Item1; // Do not rename (binary serialization) private readonly T2 m_Item2; // Do not rename (binary serialization) public T1 Item1 => m_Item1; public T2 Item2 => m_Item2; public Tuple(T1 item1, T2 item2) { m_Item1 = item1; m_Item2 = item2; } public override bool Equals(object? obj) { return ((IStructuralEquatable)this).Equals(obj, EqualityComparer<object>.Default); ; } bool IStructuralEquatable.Equals(object? other, IEqualityComparer comparer) { if (other == null) return false; if (!(other is Tuple<T1, T2> objTuple)) { return false; } return comparer.Equals(m_Item1, objTuple.m_Item1) && comparer.Equals(m_Item2, objTuple.m_Item2); } int IComparable.CompareTo(object? obj) { return ((IStructuralComparable)this).CompareTo(obj, Comparer<object>.Default); } int IStructuralComparable.CompareTo(object? other, IComparer comparer) { if (other == null) return 1; if (!(other is Tuple<T1, T2> objTuple)) { throw new ArgumentException(SR.Format(SR.ArgumentException_TupleIncorrectType, GetType()), nameof(other)); } int c = 0; c = comparer.Compare(m_Item1, objTuple.m_Item1); if (c != 0) return c; return comparer.Compare(m_Item2, objTuple.m_Item2); } public override int GetHashCode() { return ((IStructuralEquatable)this).GetHashCode(EqualityComparer<object>.Default); } int IStructuralEquatable.GetHashCode(IEqualityComparer comparer) { return Tuple.CombineHashCodes(comparer.GetHashCode(m_Item1!), comparer.GetHashCode(m_Item2!)); } int ITupleInternal.GetHashCode(IEqualityComparer comparer) { return ((IStructuralEquatable)this).GetHashCode(comparer); } public override string ToString() { StringBuilder sb = new StringBuilder(); sb.Append('('); return ((ITupleInternal)this).ToString(sb); } string ITupleInternal.ToString(StringBuilder sb) { sb.Append(m_Item1); sb.Append(", "); sb.Append(m_Item2); sb.Append(')'); return sb.ToString(); } /// <summary> /// The number of positions in this data structure. /// </summary> int ITuple.Length => 2; /// <summary> /// Get the element at position <param name="index"/>. /// </summary> object? ITuple.this[int index] { get { return index switch { 0 => Item1, 1 => Item2, _ => throw new IndexOutOfRangeException(), }; } } } [Serializable] [System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public class Tuple<T1, T2, T3> : IStructuralEquatable, IStructuralComparable, IComparable, ITupleInternal, ITuple { private readonly T1 m_Item1; // Do not rename (binary serialization) private readonly T2 m_Item2; // Do not rename (binary serialization) private readonly T3 m_Item3; // Do not rename (binary serialization) public T1 Item1 => m_Item1; public T2 Item2 => m_Item2; public T3 Item3 => m_Item3; public Tuple(T1 item1, T2 item2, T3 item3) { m_Item1 = item1; m_Item2 = item2; m_Item3 = item3; } public override bool Equals(object? obj) { return ((IStructuralEquatable)this).Equals(obj, EqualityComparer<object>.Default); ; } bool IStructuralEquatable.Equals(object? other, IEqualityComparer comparer) { if (other == null) return false; if (!(other is Tuple<T1, T2, T3> objTuple)) { return false; } return comparer.Equals(m_Item1, objTuple.m_Item1) && comparer.Equals(m_Item2, objTuple.m_Item2) && comparer.Equals(m_Item3, objTuple.m_Item3); } int IComparable.CompareTo(object? obj) { return ((IStructuralComparable)this).CompareTo(obj, Comparer<object>.Default); } int IStructuralComparable.CompareTo(object? other, IComparer comparer) { if (other == null) return 1; if (!(other is Tuple<T1, T2, T3> objTuple)) { throw new ArgumentException(SR.Format(SR.ArgumentException_TupleIncorrectType, GetType()), nameof(other)); } int c = 0; c = comparer.Compare(m_Item1, objTuple.m_Item1); if (c != 0) return c; c = comparer.Compare(m_Item2, objTuple.m_Item2); if (c != 0) return c; return comparer.Compare(m_Item3, objTuple.m_Item3); } public override int GetHashCode() { return ((IStructuralEquatable)this).GetHashCode(EqualityComparer<object>.Default); } int IStructuralEquatable.GetHashCode(IEqualityComparer comparer) { return Tuple.CombineHashCodes(comparer.GetHashCode(m_Item1!), comparer.GetHashCode(m_Item2!), comparer.GetHashCode(m_Item3!)); } int ITupleInternal.GetHashCode(IEqualityComparer comparer) { return ((IStructuralEquatable)this).GetHashCode(comparer); } public override string ToString() { StringBuilder sb = new StringBuilder(); sb.Append('('); return ((ITupleInternal)this).ToString(sb); } string ITupleInternal.ToString(StringBuilder sb) { sb.Append(m_Item1); sb.Append(", "); sb.Append(m_Item2); sb.Append(", "); sb.Append(m_Item3); sb.Append(')'); return sb.ToString(); } /// <summary> /// The number of positions in this data structure. /// </summary> int ITuple.Length => 3; /// <summary> /// Get the element at position <param name="index"/>. /// </summary> object? ITuple.this[int index] { get { return index switch { 0 => Item1, 1 => Item2, 2 => Item3, _ => throw new IndexOutOfRangeException(), }; } } } [Serializable] [System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public class Tuple<T1, T2, T3, T4> : IStructuralEquatable, IStructuralComparable, IComparable, ITupleInternal, ITuple { private readonly T1 m_Item1; // Do not rename (binary serialization) private readonly T2 m_Item2; // Do not rename (binary serialization) private readonly T3 m_Item3; // Do not rename (binary serialization) private readonly T4 m_Item4; // Do not rename (binary serialization) public T1 Item1 => m_Item1; public T2 Item2 => m_Item2; public T3 Item3 => m_Item3; public T4 Item4 => m_Item4; public Tuple(T1 item1, T2 item2, T3 item3, T4 item4) { m_Item1 = item1; m_Item2 = item2; m_Item3 = item3; m_Item4 = item4; } public override bool Equals(object? obj) { return ((IStructuralEquatable)this).Equals(obj, EqualityComparer<object>.Default); ; } bool IStructuralEquatable.Equals(object? other, IEqualityComparer comparer) { if (other == null) return false; if (!(other is Tuple<T1, T2, T3, T4> objTuple)) { return false; } return comparer.Equals(m_Item1, objTuple.m_Item1) && comparer.Equals(m_Item2, objTuple.m_Item2) && comparer.Equals(m_Item3, objTuple.m_Item3) && comparer.Equals(m_Item4, objTuple.m_Item4); } int IComparable.CompareTo(object? obj) { return ((IStructuralComparable)this).CompareTo(obj, Comparer<object>.Default); } int IStructuralComparable.CompareTo(object? other, IComparer comparer) { if (other == null) return 1; if (!(other is Tuple<T1, T2, T3, T4> objTuple)) { throw new ArgumentException(SR.Format(SR.ArgumentException_TupleIncorrectType, GetType()), nameof(other)); } int c = 0; c = comparer.Compare(m_Item1, objTuple.m_Item1); if (c != 0) return c; c = comparer.Compare(m_Item2, objTuple.m_Item2); if (c != 0) return c; c = comparer.Compare(m_Item3, objTuple.m_Item3); if (c != 0) return c; return comparer.Compare(m_Item4, objTuple.m_Item4); } public override int GetHashCode() { return ((IStructuralEquatable)this).GetHashCode(EqualityComparer<object>.Default); } int IStructuralEquatable.GetHashCode(IEqualityComparer comparer) { return Tuple.CombineHashCodes(comparer.GetHashCode(m_Item1!), comparer.GetHashCode(m_Item2!), comparer.GetHashCode(m_Item3!), comparer.GetHashCode(m_Item4!)); } int ITupleInternal.GetHashCode(IEqualityComparer comparer) { return ((IStructuralEquatable)this).GetHashCode(comparer); } public override string ToString() { StringBuilder sb = new StringBuilder(); sb.Append('('); return ((ITupleInternal)this).ToString(sb); } string ITupleInternal.ToString(StringBuilder sb) { sb.Append(m_Item1); sb.Append(", "); sb.Append(m_Item2); sb.Append(", "); sb.Append(m_Item3); sb.Append(", "); sb.Append(m_Item4); sb.Append(')'); return sb.ToString(); } /// <summary> /// The number of positions in this data structure. /// </summary> int ITuple.Length => 4; /// <summary> /// Get the element at position <param name="index"/>. /// </summary> object? ITuple.this[int index] { get { return index switch { 0 => Item1, 1 => Item2, 2 => Item3, 3 => Item4, _ => throw new IndexOutOfRangeException(), }; } } } [Serializable] [System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public class Tuple<T1, T2, T3, T4, T5> : IStructuralEquatable, IStructuralComparable, IComparable, ITupleInternal, ITuple { private readonly T1 m_Item1; // Do not rename (binary serialization) private readonly T2 m_Item2; // Do not rename (binary serialization) private readonly T3 m_Item3; // Do not rename (binary serialization) private readonly T4 m_Item4; // Do not rename (binary serialization) private readonly T5 m_Item5; // Do not rename (binary serialization) public T1 Item1 => m_Item1; public T2 Item2 => m_Item2; public T3 Item3 => m_Item3; public T4 Item4 => m_Item4; public T5 Item5 => m_Item5; public Tuple(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5) { m_Item1 = item1; m_Item2 = item2; m_Item3 = item3; m_Item4 = item4; m_Item5 = item5; } public override bool Equals(object? obj) { return ((IStructuralEquatable)this).Equals(obj, EqualityComparer<object>.Default); ; } bool IStructuralEquatable.Equals(object? other, IEqualityComparer comparer) { if (other == null) return false; if (!(other is Tuple<T1, T2, T3, T4, T5> objTuple)) { return false; } return comparer.Equals(m_Item1, objTuple.m_Item1) && comparer.Equals(m_Item2, objTuple.m_Item2) && comparer.Equals(m_Item3, objTuple.m_Item3) && comparer.Equals(m_Item4, objTuple.m_Item4) && comparer.Equals(m_Item5, objTuple.m_Item5); } int IComparable.CompareTo(object? obj) { return ((IStructuralComparable)this).CompareTo(obj, Comparer<object>.Default); } int IStructuralComparable.CompareTo(object? other, IComparer comparer) { if (other == null) return 1; if (!(other is Tuple<T1, T2, T3, T4, T5> objTuple)) { throw new ArgumentException(SR.Format(SR.ArgumentException_TupleIncorrectType, GetType()), nameof(other)); } int c = 0; c = comparer.Compare(m_Item1, objTuple.m_Item1); if (c != 0) return c; c = comparer.Compare(m_Item2, objTuple.m_Item2); if (c != 0) return c; c = comparer.Compare(m_Item3, objTuple.m_Item3); if (c != 0) return c; c = comparer.Compare(m_Item4, objTuple.m_Item4); if (c != 0) return c; return comparer.Compare(m_Item5, objTuple.m_Item5); } public override int GetHashCode() { return ((IStructuralEquatable)this).GetHashCode(EqualityComparer<object>.Default); } int IStructuralEquatable.GetHashCode(IEqualityComparer comparer) { return Tuple.CombineHashCodes(comparer.GetHashCode(m_Item1!), comparer.GetHashCode(m_Item2!), comparer.GetHashCode(m_Item3!), comparer.GetHashCode(m_Item4!), comparer.GetHashCode(m_Item5!)); } int ITupleInternal.GetHashCode(IEqualityComparer comparer) { return ((IStructuralEquatable)this).GetHashCode(comparer); } public override string ToString() { StringBuilder sb = new StringBuilder(); sb.Append('('); return ((ITupleInternal)this).ToString(sb); } string ITupleInternal.ToString(StringBuilder sb) { sb.Append(m_Item1); sb.Append(", "); sb.Append(m_Item2); sb.Append(", "); sb.Append(m_Item3); sb.Append(", "); sb.Append(m_Item4); sb.Append(", "); sb.Append(m_Item5); sb.Append(')'); return sb.ToString(); } /// <summary> /// The number of positions in this data structure. /// </summary> int ITuple.Length => 5; /// <summary> /// Get the element at position <param name="index"/>. /// </summary> object? ITuple.this[int index] { get { return index switch { 0 => Item1, 1 => Item2, 2 => Item3, 3 => Item4, 4 => Item5, _ => throw new IndexOutOfRangeException(), }; } } } [Serializable] [System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public class Tuple<T1, T2, T3, T4, T5, T6> : IStructuralEquatable, IStructuralComparable, IComparable, ITupleInternal, ITuple { private readonly T1 m_Item1; // Do not rename (binary serialization) private readonly T2 m_Item2; // Do not rename (binary serialization) private readonly T3 m_Item3; // Do not rename (binary serialization) private readonly T4 m_Item4; // Do not rename (binary serialization) private readonly T5 m_Item5; // Do not rename (binary serialization) private readonly T6 m_Item6; // Do not rename (binary serialization) public T1 Item1 => m_Item1; public T2 Item2 => m_Item2; public T3 Item3 => m_Item3; public T4 Item4 => m_Item4; public T5 Item5 => m_Item5; public T6 Item6 => m_Item6; public Tuple(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6) { m_Item1 = item1; m_Item2 = item2; m_Item3 = item3; m_Item4 = item4; m_Item5 = item5; m_Item6 = item6; } public override bool Equals(object? obj) { return ((IStructuralEquatable)this).Equals(obj, EqualityComparer<object>.Default); ; } bool IStructuralEquatable.Equals(object? other, IEqualityComparer comparer) { if (other == null) return false; if (!(other is Tuple<T1, T2, T3, T4, T5, T6> objTuple)) { return false; } return comparer.Equals(m_Item1, objTuple.m_Item1) && comparer.Equals(m_Item2, objTuple.m_Item2) && comparer.Equals(m_Item3, objTuple.m_Item3) && comparer.Equals(m_Item4, objTuple.m_Item4) && comparer.Equals(m_Item5, objTuple.m_Item5) && comparer.Equals(m_Item6, objTuple.m_Item6); } int IComparable.CompareTo(object? obj) { return ((IStructuralComparable)this).CompareTo(obj, Comparer<object>.Default); } int IStructuralComparable.CompareTo(object? other, IComparer comparer) { if (other == null) return 1; if (!(other is Tuple<T1, T2, T3, T4, T5, T6> objTuple)) { throw new ArgumentException(SR.Format(SR.ArgumentException_TupleIncorrectType, GetType()), nameof(other)); } int c = 0; c = comparer.Compare(m_Item1, objTuple.m_Item1); if (c != 0) return c; c = comparer.Compare(m_Item2, objTuple.m_Item2); if (c != 0) return c; c = comparer.Compare(m_Item3, objTuple.m_Item3); if (c != 0) return c; c = comparer.Compare(m_Item4, objTuple.m_Item4); if (c != 0) return c; c = comparer.Compare(m_Item5, objTuple.m_Item5); if (c != 0) return c; return comparer.Compare(m_Item6, objTuple.m_Item6); } public override int GetHashCode() { return ((IStructuralEquatable)this).GetHashCode(EqualityComparer<object>.Default); } int IStructuralEquatable.GetHashCode(IEqualityComparer comparer) { return Tuple.CombineHashCodes(comparer.GetHashCode(m_Item1!), comparer.GetHashCode(m_Item2!), comparer.GetHashCode(m_Item3!), comparer.GetHashCode(m_Item4!), comparer.GetHashCode(m_Item5!), comparer.GetHashCode(m_Item6!)); } int ITupleInternal.GetHashCode(IEqualityComparer comparer) { return ((IStructuralEquatable)this).GetHashCode(comparer); } public override string ToString() { StringBuilder sb = new StringBuilder(); sb.Append('('); return ((ITupleInternal)this).ToString(sb); } string ITupleInternal.ToString(StringBuilder sb) { sb.Append(m_Item1); sb.Append(", "); sb.Append(m_Item2); sb.Append(", "); sb.Append(m_Item3); sb.Append(", "); sb.Append(m_Item4); sb.Append(", "); sb.Append(m_Item5); sb.Append(", "); sb.Append(m_Item6); sb.Append(')'); return sb.ToString(); } /// <summary> /// The number of positions in this data structure. /// </summary> int ITuple.Length => 6; /// <summary> /// Get the element at position <param name="index"/>. /// </summary> object? ITuple.this[int index] { get { return index switch { 0 => Item1, 1 => Item2, 2 => Item3, 3 => Item4, 4 => Item5, 5 => Item6, _ => throw new IndexOutOfRangeException(), }; } } } [Serializable] [System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public class Tuple<T1, T2, T3, T4, T5, T6, T7> : IStructuralEquatable, IStructuralComparable, IComparable, ITupleInternal, ITuple { private readonly T1 m_Item1; // Do not rename (binary serialization) private readonly T2 m_Item2; // Do not rename (binary serialization) private readonly T3 m_Item3; // Do not rename (binary serialization) private readonly T4 m_Item4; // Do not rename (binary serialization) private readonly T5 m_Item5; // Do not rename (binary serialization) private readonly T6 m_Item6; // Do not rename (binary serialization) private readonly T7 m_Item7; // Do not rename (binary serialization) public T1 Item1 => m_Item1; public T2 Item2 => m_Item2; public T3 Item3 => m_Item3; public T4 Item4 => m_Item4; public T5 Item5 => m_Item5; public T6 Item6 => m_Item6; public T7 Item7 => m_Item7; public Tuple(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6, T7 item7) { m_Item1 = item1; m_Item2 = item2; m_Item3 = item3; m_Item4 = item4; m_Item5 = item5; m_Item6 = item6; m_Item7 = item7; } public override bool Equals(object? obj) { return ((IStructuralEquatable)this).Equals(obj, EqualityComparer<object>.Default); ; } bool IStructuralEquatable.Equals(object? other, IEqualityComparer comparer) { if (other == null) return false; if (!(other is Tuple<T1, T2, T3, T4, T5, T6, T7> objTuple)) { return false; } return comparer.Equals(m_Item1, objTuple.m_Item1) && comparer.Equals(m_Item2, objTuple.m_Item2) && comparer.Equals(m_Item3, objTuple.m_Item3) && comparer.Equals(m_Item4, objTuple.m_Item4) && comparer.Equals(m_Item5, objTuple.m_Item5) && comparer.Equals(m_Item6, objTuple.m_Item6) && comparer.Equals(m_Item7, objTuple.m_Item7); } int IComparable.CompareTo(object? obj) { return ((IStructuralComparable)this).CompareTo(obj, Comparer<object>.Default); } int IStructuralComparable.CompareTo(object? other, IComparer comparer) { if (other == null) return 1; if (!(other is Tuple<T1, T2, T3, T4, T5, T6, T7> objTuple)) { throw new ArgumentException(SR.Format(SR.ArgumentException_TupleIncorrectType, GetType()), nameof(other)); } int c = 0; c = comparer.Compare(m_Item1, objTuple.m_Item1); if (c != 0) return c; c = comparer.Compare(m_Item2, objTuple.m_Item2); if (c != 0) return c; c = comparer.Compare(m_Item3, objTuple.m_Item3); if (c != 0) return c; c = comparer.Compare(m_Item4, objTuple.m_Item4); if (c != 0) return c; c = comparer.Compare(m_Item5, objTuple.m_Item5); if (c != 0) return c; c = comparer.Compare(m_Item6, objTuple.m_Item6); if (c != 0) return c; return comparer.Compare(m_Item7, objTuple.m_Item7); } public override int GetHashCode() { return ((IStructuralEquatable)this).GetHashCode(EqualityComparer<object>.Default); } int IStructuralEquatable.GetHashCode(IEqualityComparer comparer) { return Tuple.CombineHashCodes(comparer.GetHashCode(m_Item1!), comparer.GetHashCode(m_Item2!), comparer.GetHashCode(m_Item3!), comparer.GetHashCode(m_Item4!), comparer.GetHashCode(m_Item5!), comparer.GetHashCode(m_Item6!), comparer.GetHashCode(m_Item7!)); } int ITupleInternal.GetHashCode(IEqualityComparer comparer) { return ((IStructuralEquatable)this).GetHashCode(comparer); } public override string ToString() { StringBuilder sb = new StringBuilder(); sb.Append('('); return ((ITupleInternal)this).ToString(sb); } string ITupleInternal.ToString(StringBuilder sb) { sb.Append(m_Item1); sb.Append(", "); sb.Append(m_Item2); sb.Append(", "); sb.Append(m_Item3); sb.Append(", "); sb.Append(m_Item4); sb.Append(", "); sb.Append(m_Item5); sb.Append(", "); sb.Append(m_Item6); sb.Append(", "); sb.Append(m_Item7); sb.Append(')'); return sb.ToString(); } /// <summary> /// The number of positions in this data structure. /// </summary> int ITuple.Length => 7; /// <summary> /// Get the element at position <param name="index"/>. /// </summary> object? ITuple.this[int index] { get { return index switch { 0 => Item1, 1 => Item2, 2 => Item3, 3 => Item4, 4 => Item5, 5 => Item6, 6 => Item7, _ => throw new IndexOutOfRangeException(), }; } } } [Serializable] [System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public class Tuple<T1, T2, T3, T4, T5, T6, T7, TRest> : IStructuralEquatable, IStructuralComparable, IComparable, ITupleInternal, ITuple where TRest : notnull { private readonly T1 m_Item1; // Do not rename (binary serialization) private readonly T2 m_Item2; // Do not rename (binary serialization) private readonly T3 m_Item3; // Do not rename (binary serialization) private readonly T4 m_Item4; // Do not rename (binary serialization) private readonly T5 m_Item5; // Do not rename (binary serialization) private readonly T6 m_Item6; // Do not rename (binary serialization) private readonly T7 m_Item7; // Do not rename (binary serialization) private readonly TRest m_Rest; // Do not rename (binary serialization) public T1 Item1 => m_Item1; public T2 Item2 => m_Item2; public T3 Item3 => m_Item3; public T4 Item4 => m_Item4; public T5 Item5 => m_Item5; public T6 Item6 => m_Item6; public T7 Item7 => m_Item7; public TRest Rest => m_Rest; public Tuple(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6, T7 item7, TRest rest) { if (!(rest is ITupleInternal)) { throw new ArgumentException(SR.ArgumentException_TupleLastArgumentNotATuple); } m_Item1 = item1; m_Item2 = item2; m_Item3 = item3; m_Item4 = item4; m_Item5 = item5; m_Item6 = item6; m_Item7 = item7; m_Rest = rest; } public override bool Equals(object? obj) { return ((IStructuralEquatable)this).Equals(obj, EqualityComparer<object>.Default); ; } bool IStructuralEquatable.Equals(object? other, IEqualityComparer comparer) { if (other == null) return false; if (!(other is Tuple<T1, T2, T3, T4, T5, T6, T7, TRest> objTuple)) { return false; } return comparer.Equals(m_Item1, objTuple.m_Item1) && comparer.Equals(m_Item2, objTuple.m_Item2) && comparer.Equals(m_Item3, objTuple.m_Item3) && comparer.Equals(m_Item4, objTuple.m_Item4) && comparer.Equals(m_Item5, objTuple.m_Item5) && comparer.Equals(m_Item6, objTuple.m_Item6) && comparer.Equals(m_Item7, objTuple.m_Item7) && comparer.Equals(m_Rest, objTuple.m_Rest); } int IComparable.CompareTo(object? obj) { return ((IStructuralComparable)this).CompareTo(obj, Comparer<object>.Default); } int IStructuralComparable.CompareTo(object? other, IComparer comparer) { if (other == null) return 1; if (!(other is Tuple<T1, T2, T3, T4, T5, T6, T7, TRest> objTuple)) { throw new ArgumentException(SR.Format(SR.ArgumentException_TupleIncorrectType, GetType()), nameof(other)); } int c = 0; c = comparer.Compare(m_Item1, objTuple.m_Item1); if (c != 0) return c; c = comparer.Compare(m_Item2, objTuple.m_Item2); if (c != 0) return c; c = comparer.Compare(m_Item3, objTuple.m_Item3); if (c != 0) return c; c = comparer.Compare(m_Item4, objTuple.m_Item4); if (c != 0) return c; c = comparer.Compare(m_Item5, objTuple.m_Item5); if (c != 0) return c; c = comparer.Compare(m_Item6, objTuple.m_Item6); if (c != 0) return c; c = comparer.Compare(m_Item7, objTuple.m_Item7); if (c != 0) return c; return comparer.Compare(m_Rest, objTuple.m_Rest); } public override int GetHashCode() { return ((IStructuralEquatable)this).GetHashCode(EqualityComparer<object>.Default); } int IStructuralEquatable.GetHashCode(IEqualityComparer comparer) { // We want to have a limited hash in this case. We'll use the last 8 elements of the tuple ITupleInternal t = (ITupleInternal)m_Rest; if (t.Length >= 8) { return t.GetHashCode(comparer); } // In this case, the rest memeber has less than 8 elements so we need to combine some our elements with the elements in rest int k = 8 - t.Length; switch (k) { case 1: return Tuple.CombineHashCodes(comparer.GetHashCode(m_Item7!), t.GetHashCode(comparer)); case 2: return Tuple.CombineHashCodes(comparer.GetHashCode(m_Item6!), comparer.GetHashCode(m_Item7!), t.GetHashCode(comparer)); case 3: return Tuple.CombineHashCodes(comparer.GetHashCode(m_Item5!), comparer.GetHashCode(m_Item6!), comparer.GetHashCode(m_Item7!), t.GetHashCode(comparer)); case 4: return Tuple.CombineHashCodes(comparer.GetHashCode(m_Item4!), comparer.GetHashCode(m_Item5!), comparer.GetHashCode(m_Item6!), comparer.GetHashCode(m_Item7!), t.GetHashCode(comparer)); case 5: return Tuple.CombineHashCodes(comparer.GetHashCode(m_Item3!), comparer.GetHashCode(m_Item4!), comparer.GetHashCode(m_Item5!), comparer.GetHashCode(m_Item6!), comparer.GetHashCode(m_Item7!), t.GetHashCode(comparer)); case 6: return Tuple.CombineHashCodes(comparer.GetHashCode(m_Item2!), comparer.GetHashCode(m_Item3!), comparer.GetHashCode(m_Item4!), comparer.GetHashCode(m_Item5!), comparer.GetHashCode(m_Item6!), comparer.GetHashCode(m_Item7!), t.GetHashCode(comparer)); case 7: return Tuple.CombineHashCodes(comparer.GetHashCode(m_Item1!), comparer.GetHashCode(m_Item2!), comparer.GetHashCode(m_Item3!), comparer.GetHashCode(m_Item4!), comparer.GetHashCode(m_Item5!), comparer.GetHashCode(m_Item6!), comparer.GetHashCode(m_Item7!), t.GetHashCode(comparer)); } Debug.Fail("Missed all cases for computing Tuple hash code"); return -1; } int ITupleInternal.GetHashCode(IEqualityComparer comparer) { return ((IStructuralEquatable)this).GetHashCode(comparer); } public override string ToString() { StringBuilder sb = new StringBuilder(); sb.Append('('); return ((ITupleInternal)this).ToString(sb); } string ITupleInternal.ToString(StringBuilder sb) { sb.Append(m_Item1); sb.Append(", "); sb.Append(m_Item2); sb.Append(", "); sb.Append(m_Item3); sb.Append(", "); sb.Append(m_Item4); sb.Append(", "); sb.Append(m_Item5); sb.Append(", "); sb.Append(m_Item6); sb.Append(", "); sb.Append(m_Item7); sb.Append(", "); return ((ITupleInternal)m_Rest).ToString(sb); } /// <summary> /// The number of positions in this data structure. /// </summary> int ITuple.Length => 7 + ((ITupleInternal)Rest).Length; /// <summary> /// Get the element at position <param name="index"/>. /// </summary> object? ITuple.this[int index] { get { return index switch { 0 => Item1, 1 => Item2, 2 => Item3, 3 => Item4, 4 => Item5, 5 => Item6, 6 => Item7, _ => ((ITupleInternal)Rest)[index - 7], }; } } } }
34.630653
382
0.561658
[ "MIT" ]
ReidB-MSFT/coreclr
src/System.Private.CoreLib/shared/System/Tuple.cs
41,349
C#
using UnityEngine; using System.Collections.Generic; using System; using UnityEngine.UI; using UnityEngine.EventSystems; namespace XCharts.Runtime { /// <summary> /// The base class of all charts. /// |所有Chart的基类。 /// </summary> public partial class BaseChart { /// <summary> /// The name of chart. /// |</summary> public string chartName { get { return m_ChartName; } set { if (!string.IsNullOrEmpty(value) && XChartsMgr.ContainsChart(value)) { Debug.LogError("chartName repeated:" + value); } else { m_ChartName = value; } } } /// <summary> /// The theme. /// |</summary> public ThemeStyle theme { get { return m_Theme; } set { m_Theme = value; } } /// <summary> /// Global parameter setting component. /// |全局设置组件。 /// </summary> public Settings settings { get { return m_Settings; } } /// <summary> /// The x of chart. /// |图表的X /// </summary> public float chartX { get { return m_ChartX; } } /// <summary> /// The y of chart. /// |图表的Y /// </summary> public float chartY { get { return m_ChartY; } } /// <summary> /// The width of chart. /// |图表的宽 /// </summary> public float chartWidth { get { return m_ChartWidth; } } /// <summary> /// The height of chart. /// |图表的高 /// </summary> public float chartHeight { get { return m_ChartHeight; } } public Vector2 chartMinAnchor { get { return m_ChartMinAnchor; } } public Vector2 chartMaxAnchor { get { return m_ChartMaxAnchor; } } public Vector2 chartPivot { get { return m_ChartPivot; } } public Vector2 chartSizeDelta { get { return m_ChartSizeDelta; } } /// <summary> /// The position of chart. /// |图表的左下角起始坐标。 /// </summary> public Vector3 chartPosition { get { return m_ChartPosition; } } public Rect chartRect { get { return m_ChartRect; } } public Action onInit { set { m_OnInit = value; } } public Action onUpdate { set { m_OnUpdate = value; } } /// <summary> /// 自定义绘制回调。在绘制Serie前调用。 /// </summary> public Action<VertexHelper> onDraw { set { m_OnDrawBase = value; } } /// <summary> /// 自定义Serie绘制回调。在每个Serie绘制完前调用。 /// </summary> public Action<VertexHelper, Serie> onDrawBeforeSerie { set { m_OnDrawSerieBefore = value; } } /// <summary> /// 自定义Serie绘制回调。在每个Serie绘制完后调用。 /// </summary> public Action<VertexHelper, Serie> onDrawAfterSerie { set { m_OnDrawSerieAfter = value; } } /// <summary> /// 自定义Top绘制回调。在绘制Tooltip前调用。 /// </summary> public Action<VertexHelper> onDrawTop { set { m_OnDrawTop = value; } } /// <summary> /// 自定义仪表盘指针绘制委托。 /// </summary> public CustomDrawGaugePointerFunction customDrawGaugePointerFunction { set { m_CustomDrawGaugePointerFunction = value; } get { return m_CustomDrawGaugePointerFunction; } } /// <summary> /// the callback function of click pie area. /// |点击饼图区域回调。参数:PointerEventData,SerieIndex,SerieDataIndex /// </summary> public Action<PointerEventData, int, int> onPointerClickPie { set { m_OnPointerClickPie = value; m_ForceOpenRaycastTarget = true; } get { return m_OnPointerClickPie; } } /// <summary> /// the callback function of click bar. /// |点击柱形图柱条回调。参数:eventData, dataIndex /// </summary> public Action<PointerEventData, int> onPointerClickBar { set { m_OnPointerClickBar = value; m_ForceOpenRaycastTarget = true; } } /// <summary> /// 坐标轴变更数据索引时回调。参数:axis, dataIndex/dataValue /// </summary> public Action<Axis, double> onAxisPointerValueChanged { set { m_OnAxisPointerValueChanged = value; } get { return m_OnAxisPointerValueChanged; } } public void Init(bool defaultChart = true) { if (defaultChart) { OnInit(); DefaultChart(); } else { OnBeforeSerialize(); } } /// <summary> /// Redraw chart in next frame. /// |在下一帧刷新整个图表。 /// </summary> public void RefreshChart() { foreach (var serie in m_Series) serie.ResetInteract(); m_RefreshChart = true; if (m_Painter) m_Painter.Refresh(); } /// <summary> /// Redraw chart serie in next frame. /// |在下一帧刷新图表的指定serie。 /// </summary> public void RefreshChart(int serieIndex) { RefreshPainter(GetSerie(serieIndex)); } /// <summary> /// Redraw chart serie in next frame. /// |在下一帧刷新图表的指定serie。 /// </summary> public void RefreshChart(Serie serie) { if (serie == null) return; serie.ResetInteract(); RefreshPainter(serie); } /// <summary> /// Remove all series and legend data. /// |It just emptying all of serie's data without emptying the list of series. /// |清除所有数据,系列中只是移除数据,列表会保留。 /// </summary> public virtual void ClearData() { foreach (var serie in m_Series) serie.ClearData(); foreach (var component in m_Components) component.ClearData(); m_CheckAnimation = false; RefreshChart(); } /// <summary> /// Remove all data from series and legend. /// |The series list is also cleared. /// |清除所有系列和图例数据,系列的列表也会被清除。 /// </summary> public virtual void RemoveData() { foreach (var component in m_Components) component.ClearData(); m_Series.Clear(); m_SerieHandlers.Clear(); m_CheckAnimation = false; RefreshChart(); } /// <summary> /// Remove legend and serie by name. /// |清除指定系列名称的数据。 /// </summary> /// <param name="serieName">the name of serie</param> public virtual void RemoveData(string serieName) { RemoveSerie(serieName); foreach (var component in m_Components) { if (component is Legend) { var legend = component as Legend; legend.RemoveData(serieName); } } RefreshChart(); } public virtual void UpdateLegendColor(string legendName, bool active) { var legendIndex = m_LegendRealShowName.IndexOf(legendName); if (legendIndex >= 0) { foreach (var component in m_Components) { if (component is Legend) { var legend = component as Legend; var iconColor = LegendHelper.GetIconColor(this, legend, legendIndex, legendName, active); var contentColor = LegendHelper.GetContentColor(legendIndex, legend, m_Theme, active); legend.UpdateButtonColor(legendName, iconColor); legend.UpdateContentColor(legendName, contentColor); } } } } /// <summary> /// Whether serie is activated. /// |获得指定图例名字的系列是否显示。 /// </summary> /// <param name="legendName"></param> /// <returns></returns> public virtual bool IsActiveByLegend(string legendName) { foreach (var serie in m_Series) { if (serie.show && legendName.Equals(serie.serieName)) { return true; } else { foreach (var serieData in serie.data) { if (serieData.show && legendName.Equals(serieData.name)) { return true; } } } } return false; } /// <summary> /// Update chart theme. /// |切换内置主题。 /// </summary> /// <param name="theme">theme</param> public bool UpdateTheme(ThemeType theme) { if (theme == ThemeType.Custom) { Debug.LogError("UpdateTheme: not support switch to Custom theme."); return false; } if (m_Theme.sharedTheme == null) m_Theme.sharedTheme = XCThemeMgr.GetTheme(ThemeType.Default); m_Theme.sharedTheme.CopyTheme(theme); return true; } /// <summary> /// Update chart theme info. /// |切换图表主题。 /// </summary> /// <param name="theme">theme</param> public void UpdateTheme(Theme theme) { m_Theme.sharedTheme = theme; SetAllComponentDirty(); #if UNITY_EDITOR UnityEditor.EditorUtility.SetDirty(this); #endif } /// <summary> /// Whether series animation enabel. /// |启用或关闭起始动画。 /// </summary> /// <param name="flag"></param> public void AnimationEnable(bool flag) { foreach (var serie in m_Series) serie.AnimationEnable(flag); } /// <summary> /// fadeIn animation. /// |开始渐入动画。 /// </summary> public void AnimationFadeIn() { foreach (var serie in m_Series) serie.AnimationFadeIn(); } /// <summary> /// fadeIn animation. /// |开始渐出动画。 /// </summary> public void AnimationFadeOut() { foreach (var serie in m_Series) serie.AnimationFadeOut(); } /// <summary> /// Pause animation. /// |暂停动画。 /// </summary> public void AnimationPause() { foreach (var serie in m_Series) serie.AnimationPause(); } /// <summary> /// Stop play animation. /// |继续动画。 /// </summary> public void AnimationResume() { foreach (var serie in m_Series) serie.AnimationResume(); } /// <summary> /// Reset animation. /// |重置动画。 /// </summary> public void AnimationReset() { foreach (var serie in m_Series) serie.AnimationReset(); } /// <summary> /// 点击图例按钮 /// </summary> /// <param name="legendIndex">图例按钮索引</param> /// <param name="legendName">图例按钮名称</param> /// <param name="show">显示还是隐藏</param> public void ClickLegendButton(int legendIndex, string legendName, bool show) { OnLegendButtonClick(legendIndex, legendName, show); RefreshChart(); } /// <summary> /// 坐标是否在图表范围内 /// </summary> /// <param name="local"></param> /// <returns></returns> public bool IsInChart(Vector2 local) { return IsInChart(local.x, local.y); } public bool IsInChart(float x, float y) { if (x < m_ChartX || x > m_ChartX + m_ChartWidth || y < m_ChartY || y > m_ChartY + m_ChartHeight) { return false; } return true; } public void ClampInChart(ref Vector3 pos) { if (!IsInChart(pos.x, pos.y)) { if (pos.x < m_ChartX) pos.x = m_ChartX; if (pos.x > m_ChartX + m_ChartWidth) pos.x = m_ChartX + m_ChartWidth; if (pos.y < m_ChartY) pos.y = m_ChartY; if (pos.y > m_ChartY + m_ChartHeight) pos.y = m_ChartY + m_ChartHeight; } } public Vector3 ClampInGrid(GridCoord grid, Vector3 pos) { if (grid.Contains(pos)) return pos; else { // var pos = new Vector3(pos.x, pos.y); if (pos.x < grid.context.x) pos.x = grid.context.x; if (pos.x > grid.context.x + grid.context.width) pos.x = grid.context.x + grid.context.width; if (pos.y < grid.context.y) pos.y = grid.context.y; if (pos.y > grid.context.y + grid.context.height) pos.y = grid.context.y + grid.context.height; return pos; } } /// <summary> /// 转换X轴和Y轴的配置 /// </summary> /// <param name="index">坐标轴索引,0或1</param> public void CovertXYAxis(int index) { List<MainComponent> m_XAxes; List<MainComponent> m_YAxes; m_ComponentMaps.TryGetValue(typeof(XAxis), out m_XAxes); m_ComponentMaps.TryGetValue(typeof(YAxis), out m_YAxes); if (index >= 0 && index <= 1) { var xAxis = m_XAxes[index] as XAxis; var yAxis = m_YAxes[index] as YAxis; var tempX = xAxis.Clone(); xAxis.Copy(yAxis); yAxis.Copy(tempX); xAxis.context.offset = 0; yAxis.context.offset = 0; xAxis.context.minValue = 0; xAxis.context.maxValue = 0; yAxis.context.minValue = 0; yAxis.context.maxValue = 0; RefreshChart(); } } /// <summary> /// 在下一帧刷新DataZoom /// </summary> public void RefreshDataZoom() { foreach (var handler in m_ComponentHandlers) { if (handler is DataZoomHandler) { (handler as DataZoomHandler).RefreshDataZoomLabel(); } } } /// <summary> /// 设置可缓存的最大数据量。当数据量超过该值时,会自动删除第一个值再加入最新值。 /// </summary> public void SetMaxCache(int maxCache) { foreach (var serie in m_Series) serie.maxCache = maxCache; foreach (var component in m_Components) { if (component is Axis) { (component as Axis).maxCache = maxCache; } } } public Vector3 GetTitlePosition(Title title) { return chartPosition + title.location.GetPosition(chartWidth, chartHeight); } public int GetLegendRealShowNameIndex(string name) { return m_LegendRealShowName.IndexOf(name); } public Color32 GetLegendRealShowNameColor(string name) { var index = GetLegendRealShowNameIndex(name); return theme.GetColor(index); } /// <summary> /// 设置Base Painter的材质球 /// </summary> /// <param name="material"></param> public void SetBasePainterMaterial(Material material) { settings.basePainterMaterial = material; if (m_Painter != null) { m_Painter.material = material; } } /// <summary> /// 设置Serie Painter的材质球 /// </summary> /// <param name="material"></param> public void SetSeriePainterMaterial(Material material) { settings.basePainterMaterial = material; if (m_PainterList != null) { foreach (var painter in m_PainterList) painter.material = material; } } /// <summary> /// 设置Top Painter的材质球 /// </summary> /// <param name="material"></param> public void SetTopPainterMaterial(Material material) { settings.topPainterMaterial = material; if (m_PainterTop != null) { m_PainterTop.material = material; } } public Color32 GetChartBackgroundColor() { var background = GetChartComponent<Background>(); return theme.GetBackgroundColor(background); } } }
32.306796
179
0.502224
[ "MIT" ]
XCharts-Team/XCharts
Runtime/Internal/BaseChart.API.cs
17,506
C#
using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace _10_1_2_3_7 { class Program { static void Main(string[] args) { Console.WriteLine("[1,100]:"); //handle FileStream fs1 = new FileStream("3or7uNoviRed.txt", FileMode.Create); FileStream fs2 = new FileStream("3or7saZarezima.txt", FileMode.Create); //writer StreamWriter sw1 = new StreamWriter(fs1); StreamWriter sw2 = new StreamWriter(fs2); for (int i = 0; i <= 100; i++) { if (i % 3 == 0 || i % 7 == 0) { sw1.WriteLine(i); sw2.Write(i + ", "); } } sw1.Flush(); sw2.Flush(); sw1.Close(); sw2.Close(); fs1.Close(); fs2.Close(); fs1 = new FileStream("3or7uNoviRed.txt", FileMode.Open); StreamReader sr1 = new StreamReader(fs1); string procitano = sr1.ReadToEnd(); Console.WriteLine("Ispis iz datoteke 3or7uNoviRed.txt"); Console.WriteLine(procitano); //////////// fs2 = new FileStream("3or7saZarezima.txt", FileMode.Open); StreamReader sr2 = new StreamReader(fs2); string procitano2 = sr2.ReadToEnd(); Console.WriteLine("Ispis iz datoteke 3or7saZarezima.txt"); Console.WriteLine(procitano2); Console.ReadLine(); } } }
21.45679
83
0.49252
[ "MIT" ]
staman1702/AlgebraCSharp2019-1
ConsoleApp1/10_1_2_3-7/Program.cs
1,740
C#
using foodtruacker.Application.BoundedContexts.UserAccountManagement.QueryObjects; using foodtruacker.Domain.BoundedContexts.UserAccountManagement.Events; using foodtruacker.QueryRepository.Repository; using MediatR; using System; using System.Threading; using System.Threading.Tasks; namespace foodtruacker.Application.BoundedContexts.UserAccountManagement.Projections { public class AdminAccountChangedEmailProjection : INotificationHandler<AdminAccountChangedEmailEvent> { private readonly IProjectionRepository<AdminInfo> _repository; public AdminAccountChangedEmailProjection(IProjectionRepository<AdminInfo> repository) { _repository = repository ?? throw new ArgumentNullException(nameof(repository)); } public async Task Handle(AdminAccountChangedEmailEvent @event, CancellationToken cancellationToken) { var admin = await _repository.FindByIdAsync(@event.AggregateId); if (admin is not null) { admin.Version = @event.AggregateVersion; await _repository.UpdateAsync(admin); } else { } } } }
34.771429
107
0.700904
[ "MIT" ]
hiiammalte/foodtruacker
foodtruacker.Application/BoundedContexts/UserAccountManagement/Projections/AdminAccountChangedEmailProjection.cs
1,219
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 Microsoft.Data.DataView; namespace Microsoft.ML.Data { /// <summary> /// Base class for creating a cursor on top of another cursor that does not add or remove rows. /// It forces one-to-one correspondence between items in the input cursor and this cursor. /// It delegates all ICursor functionality except Dispose() to the root cursor. /// Dispose is virtual with the default implementation delegating to the input cursor. /// </summary> [BestFriend] internal abstract class SynchronizedCursorBase : DataViewRowCursor { protected readonly IChannel Ch; /// <summary> /// The synchronized cursor base, as it merely passes through requests for all "positional" calls (including /// <see cref="MoveNext"/>, <see cref="Position"/>, <see cref="Batch"/>, and so forth), offers an opportunity /// for optimization for "wrapping" cursors (which are themselves often <see cref="SynchronizedCursorBase"/> /// implementors) to get this root cursor. But, this can only be done by exposing this root cursor, as we do here. /// Internal code should be quite careful in using this as the potential for misuse is quite high. /// </summary> internal readonly DataViewRowCursor Root; private bool _disposed; protected DataViewRowCursor Input { get; } public sealed override long Position => Root.Position; public sealed override long Batch => Root.Batch; /// <summary> /// Convenience property for checking whether the cursor is in a good state where values /// can be retrieved, that is, whenever <see cref="Position"/> is non-negative. /// </summary> protected bool IsGood => Position >= 0; protected SynchronizedCursorBase(IChannelProvider provider, DataViewRowCursor input) { Contracts.AssertValue(provider); Ch = provider.Start("Cursor"); Ch.AssertValue(input); Input = input; // If this thing happens to be itself an instance of this class (which, practically, it will // be in the majority of situations), we can treat the input as likewise being a passthrough, // thereby saving lots of "nested" calls on the stack when doing common operations like movement. Root = Input is SynchronizedCursorBase syncInput ? syncInput.Root : input; } protected override void Dispose(bool disposing) { if (_disposed) return; if (disposing) { Input.Dispose(); Ch.Dispose(); } base.Dispose(disposing); _disposed = true; } public sealed override bool MoveNext() => Root.MoveNext(); public sealed override ValueGetter<DataViewRowId> GetIdGetter() => Input.GetIdGetter(); } }
42.863014
122
0.647172
[ "MIT" ]
IndigoShock/machinelearning
src/Microsoft.ML.Core/Data/SynchronizedCursorBase.cs
3,129
C#
// // AddOptionalParameterToInvocationAction.cs // // Author: // Luís Reis <luiscubal@gmail.com> // // Copyright (c) 2013 Luís Reis // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System; using ICSharpCode.NRefactory.CSharp; using System.Collections.Generic; using System.Linq; using ICSharpCode.NRefactory.CSharp.Resolver; using ICSharpCode.NRefactory.Semantics; using ICSharpCode.NRefactory.Xml; using ICSharpCode.NRefactory.Documentation; using ICSharpCode.NRefactory.TypeSystem; namespace ICSharpCode.NRefactory.CSharp.Refactoring { [ContextAction("Add one or more optional parameters to an invocation, using their default values", Description = "Add one or more optional parameters to an invocation.")] public class AddOptionalParameterToInvocationAction : CodeActionProvider { public override IEnumerable<CodeAction> GetActions(RefactoringContext context) { var invocationExpression = context.GetNode<InvocationExpression>(); if (invocationExpression == null) yield break; var resolveResult = context.Resolve(invocationExpression) as CSharpInvocationResolveResult; if (resolveResult == null) { yield break; } var method = (IMethod)resolveResult.Member; bool[] parameterIsSpecified = new bool[method.Parameters.Count]; var argumentToParameterMap = resolveResult.GetArgumentToParameterMap(); if (argumentToParameterMap != null) { foreach (int paramIndex in argumentToParameterMap) parameterIsSpecified[paramIndex] = true; } else { for (int i = 0; i < Math.Min(resolveResult.Arguments.Count, parameterIsSpecified.Length); i++) { parameterIsSpecified[i] = true; } } var missingParameters = new List<IParameter>(); for (int i = 0; i < method.Parameters.Count; i++) { if (!parameterIsSpecified[i] && method.Parameters[i].IsOptional) missingParameters.Add(method.Parameters[i]); } foreach (var parameterToAdd in missingParameters) { //Add specific parameter yield return new CodeAction(string.Format(context.TranslateString("Add optional parameter \"{0}\""), parameterToAdd.Name), script => { var newInvocation = (InvocationExpression)invocationExpression.Clone(); AddArgument(newInvocation, parameterToAdd, parameterToAdd == missingParameters.First()); script.Replace(invocationExpression, newInvocation); }, invocationExpression); } if (missingParameters.Count > 1) { //Add all parameters at once yield return new CodeAction(context.TranslateString("Add all optional parameters"), script => { var newInvocation = (InvocationExpression)invocationExpression.Clone(); foreach (var parameterToAdd in missingParameters) { //We'll add the remaining parameters, in the order they were declared in the function AddArgument(newInvocation, parameterToAdd, true); } script.Replace(invocationExpression, newInvocation); }, invocationExpression); } } static void AddArgument(InvocationExpression newNode, IParameter parameterToAdd, bool isNextInSequence) { Expression defaultValue; if (parameterToAdd.ConstantValue == null) { defaultValue = new NullReferenceExpression(); } else { defaultValue = new PrimitiveExpression(parameterToAdd.ConstantValue); } Expression newArgument; if (newNode.Arguments.Any(argument => argument is NamedExpression) || !isNextInSequence) { newArgument = new NamedArgumentExpression(parameterToAdd.Name, defaultValue); } else { newArgument = defaultValue; } newNode.Arguments.Add(newArgument); } } }
39.041322
105
0.730737
[ "MIT" ]
fuse-open/fuse-studio
3rdparty/NRefactory/ICSharpCode.NRefactory.CSharp.Refactoring/CodeActions/AddOptionalParameterToInvocationAction.cs
4,726
C#
namespace Dalian.Models { public class SiteTags { public string SiteId { get; set; } public string TagId { get; set; } } }
18.875
42
0.576159
[ "MIT" ]
06b/Dalian
src/Dalian/Models/SitesTags.cs
153
C#
using System; using System.Collections.Generic; using Dfc.CourseDirectory.Core.Models; namespace Dfc.CourseDirectory.Core.DataStore.Sql.Models { public class TLevel { public Guid TLevelId { get; set; } public TLevelStatus TLevelStatus { get; set; } public TLevelDefinition TLevelDefinition { get; set; } public Guid ProviderId { get; set; } public string ProviderName { get; set; } public string WhoFor { get; set; } public string EntryRequirements { get; set; } public string WhatYoullLearn { get; set; } public string HowYoullLearn { get; set; } public string HowYoullBeAssessed { get; set; } public string WhatYouCanDoNext { get; set; } public string YourReference { get; set; } public DateTime StartDate { get; set; } public IReadOnlyList<TLevelLocation> Locations { get; set; } public string Website { get; set; } public DateTime CreatedOn { get; set; } public DateTime UpdatedOn { get; set; } } }
37.607143
68
0.647673
[ "MIT" ]
SkillsFundingAgency/dfc-coursedirectory
src/Dfc.CourseDirectory.Core/DataStore/Sql/Models/TLevel.cs
1,055
C#
using DiligentEngine; using Engine.Resources; using FreeImageAPI; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DiligentEngine.GltfPbr { /// <summary> /// This loader can load the textures from https://cc0textures.com. It will reformat for the gltf renderer. /// </summary> public class CC0TextureLoader { private readonly TextureLoader textureLoader; private readonly IResourceProvider<CC0TextureLoader> resourceProvider; public CC0TextureLoader(TextureLoader textureLoader, IResourceProvider<CC0TextureLoader> resourceProvider) { this.textureLoader = textureLoader; this.resourceProvider = resourceProvider; } public CC0TextureResult LoadTextureSet(String basePath, String ext = "jpg", string colorPath = null, string colorExt = null) { //In this function the auto pointers are handed off to the result, which will be managed by the caller to erase the resources. var result = new CC0TextureResult(); var colorMapPath = $"{colorPath ?? basePath}_Color.{colorExt ?? ext}"; var normalMapPath = $"{basePath}_Normal.{ext}"; var roughnessMapPath = $"{basePath}_Roughness.{ext}"; var metalnessMapPath = $"{basePath}_Metalness.{ext}"; var ambientOcclusionMapPath = $"{basePath}_AmbientOcclusion.{ext}"; if (resourceProvider.fileExists(colorMapPath)) { using (var stream = resourceProvider.openFile(colorMapPath)) { var baseColorMap = textureLoader.LoadTexture(stream, "baseColorMap", RESOURCE_DIMENSION.RESOURCE_DIM_TEX_2D_ARRAY, false); result.SetBaseColorMap(baseColorMap); } } if (resourceProvider.fileExists(normalMapPath)) { using (var stream = resourceProvider.openFile(normalMapPath)) { using var map = FreeImageBitmap.FromStream(stream); map.ConvertColorDepth(FREE_IMAGE_COLOR_DEPTH.FICD_32_BPP); //Cheat and convert color depth CC0TextureLoader.FixCC0Normal(map); var normalMap = textureLoader.CreateTextureFromImage(map, 0, "normalTexture", RESOURCE_DIMENSION.RESOURCE_DIM_TEX_2D_ARRAY, false); result.SetNormalMap(normalMap); } } { FreeImageBitmap roughnessBmp = null; FreeImageBitmap metalnessBmp = null; try { if (resourceProvider.fileExists(roughnessMapPath)) { using var stream = resourceProvider.openFile(roughnessMapPath); roughnessBmp = FreeImageBitmap.FromStream(stream); } if (resourceProvider.fileExists(metalnessMapPath)) { using var stream = resourceProvider.openFile(metalnessMapPath); metalnessBmp = FreeImageBitmap.FromStream(stream); } if (roughnessBmp != null || metalnessBmp != null) { int width = 0; int height = 0; if(roughnessBmp != null) { width = roughnessBmp.Width; height = roughnessBmp.Height; } if(metalnessBmp != null) { width = metalnessBmp.Width; height = metalnessBmp.Height; } using var physicalDescriptorBmp = new FreeImageBitmap(width, height, PixelFormat.Format32bppArgb); unsafe { var firstPixel = ((uint*)physicalDescriptorBmp.Scan0.ToPointer()) - ((physicalDescriptorBmp.Height - 1) * physicalDescriptorBmp.Width); var size = physicalDescriptorBmp.Width * physicalDescriptorBmp.Height; var span = new Span<UInt32>(firstPixel, size); span.Fill(PbrRenderer.DefaultPhysical); } if (metalnessBmp != null) { physicalDescriptorBmp.SetChannel(metalnessBmp, FREE_IMAGE_COLOR_CHANNEL.FICC_BLUE); } if (roughnessBmp != null) { physicalDescriptorBmp.SetChannel(roughnessBmp, FREE_IMAGE_COLOR_CHANNEL.FICC_GREEN); } var physicalDescriptorMap = textureLoader.CreateTextureFromImage(physicalDescriptorBmp, 0, "physicalDescriptorMap", RESOURCE_DIMENSION.RESOURCE_DIM_TEX_2D_ARRAY, false); result.SetPhysicalDescriptorMap(physicalDescriptorMap); } } finally { roughnessBmp?.Dispose(); metalnessBmp?.Dispose(); } } if (resourceProvider.fileExists(ambientOcclusionMapPath)) { using (var stream = resourceProvider.openFile(normalMapPath)) { var map = textureLoader.LoadTexture(stream, "ambientOcclusionMap", RESOURCE_DIMENSION.RESOURCE_DIM_TEX_2D_ARRAY, false); result.SetAmbientOcclusionMap(map); } } return result; } /// <summary> /// CC0 textures use an inverted y axis compared to our lights, so invert it here. /// </summary> /// <param name="map"></param> public static void FixCC0Normal(FreeImageBitmap map) { unsafe { //This is assuming axgx layout like everything else, dont really care about r and b since g is //always the same and that is what we want to flip. var firstPixel = (uint*)((byte*)map.Scan0.ToPointer() + (map.Height - 1) * map.Stride); var lastPixel = map.Width * map.Height; for (var i = 0; i < lastPixel; ++i) { uint pixelValue = firstPixel[i]; uint normalY = 0x0000ff00 & pixelValue; normalY >>= 8; normalY = 255 - normalY; normalY <<= 8; firstPixel[i] = (pixelValue & 0xffff00ff) + normalY; } } } } }
43.069182
193
0.533148
[ "MIT" ]
AnomalousMedical/Adventure
DiligentEngine.GltfPbr/CC0TextureLoader.cs
6,850
C#
using System.Collections.Generic; using System.Linq; namespace FluentWPFSample.Views { /// <summary> /// RevealStyles.xaml の相互作用ロジック /// </summary> public partial class RevealStyles { public RevealStyles() { InitializeComponent(); var dic = new Dictionary<int, string> { {1, "Tipo 1"}, {2, "Tipo 2"}, {3, "Tipo 3"}, {4, "Tipo 4"}, {5, "Tipo 5"} }; ComboBoxEdge.ItemsSource = dic.ToList(); ComboBoxEdge.DisplayMemberPath = "Value"; ComboBoxEdge.SelectedValuePath = "Key"; } } }
22.741935
53
0.475177
[ "MIT" ]
FactorySI/FluentWPF
Sample/FluentWPFSample/Views/RevealStyles.xaml.cs
725
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using Dfc.CourseDirectory.Core.DataStore; using Dfc.CourseDirectory.Core.Models; using Dfc.CourseDirectory.Core.Validation; using Dfc.CourseDirectory.WebV2.MultiPageTransaction; using FluentValidation; using MediatR; using OneOf; using OneOf.Types; namespace Dfc.CourseDirectory.WebV2.Features.NewApprenticeshipProvider.ApprenticeshipEmployerLocationsRegions { using CommandResponse = OneOf<ModelWithErrors<Command>, Success>; public class Query : IRequest<Command> { public Guid ProviderId { get; set; } } public class Command : IRequest<CommandResponse> { public Guid ProviderId { get; set; } public IReadOnlyCollection<string> RegionIds { get; set; } } public class Handler : IRequestHandler<Query, Command>, IRequestHandler<Command, CommandResponse> { private readonly MptxInstanceContext<FlowModel> _flow; private readonly IRegionCache _regionCache; public Handler(MptxInstanceContext<FlowModel> flow, IRegionCache regionCache) { _flow = flow; _regionCache = regionCache; } public Task<Command> Handle(Query request, CancellationToken cancellationToken) { ValidateFlowState(); var command = new Command() { ProviderId = request.ProviderId, RegionIds = _flow.State.ApprenticeshipLocationSubRegionIds ?? Array.Empty<string>() }; return Task.FromResult(command); } public async Task<CommandResponse> Handle(Command request, CancellationToken cancellationToken) { ValidateFlowState(); var allRegions = await _regionCache.GetAllRegions(); var validator = new CommandValidator(allRegions); var validationResult = await validator.ValidateAsync(request); if (!validationResult.IsValid) { request.RegionIds ??= new List<string>(); return new ModelWithErrors<Command>(request, validationResult); } _flow.Update(s => s.SetApprenticeshipLocationRegionIds(request.RegionIds)); return new Success(); } private void ValidateFlowState() { if ((_flow.State.ApprenticeshipLocationType != ApprenticeshipLocationType.EmployerBased && _flow.State.ApprenticeshipLocationType != ApprenticeshipLocationType.ClassroomBasedAndEmployerBased) || _flow.State.ApprenticeshipIsNational != false) { throw new InvalidStateException(); } } private class CommandValidator : AbstractValidator<Command> { public CommandValidator(IReadOnlyCollection<Region> allRegions) { RuleFor(c => c.RegionIds) .Transform(v => { if (v == null) { return v; } var regionIds = allRegions.Select(r => r.Id); var subRegionIds = allRegions.SelectMany(r => r.SubRegions).Select(sr => sr.Id); var allRegionIds = regionIds.Concat(subRegionIds).ToList(); // Remove any IDs that are not regions or sub-regions return v.Intersect(allRegionIds).ToList(); }) .NotEmpty() .WithMessage("Select at least one sub-region"); } } } }
33.945455
119
0.598822
[ "MIT" ]
uk-gov-mirror/SkillsFundingAgency.dfc-coursedirectory
src/Dfc.CourseDirectory.WebV2/Features/NewApprenticeshipProvider/ApprenticeshipEmployerLocationsRegions.cs
3,736
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; namespace MyFirstMvcApp { public class Program { public static void Main(string[] args) { CreateHostBuilder(args).Build().Run(); } public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); }); } }
25.740741
70
0.646043
[ "MIT" ]
TinuMurani/MyFirstMvcApp
MyFirstMvcApp/MyFirstMvcApp/Program.cs
695
C#
namespace SberAcquiringClient.Types.Interfaces { /// <summary> /// Данные, необходимые для работы с платежным шлюзом /// </summary> public interface ISberAcquiringApiSettings { /// <summary> /// Имя пользователя /// </summary> string UserName { get; set; } /// <summary> /// Пароль /// </summary> string Password { get; set; } /// <summary> /// Токен /// </summary> string Token { get; set; } /// <summary> /// Адрес платежного шлюза /// </summary> string ApiHost { get; set; } } }
22.75
57
0.497645
[ "MIT" ]
ExLuzZziVo/SberAcquiringClient
SberAcquiringClient/Types/Interfaces/ISberAcquiringApiSettings.cs
727
C#
using UnityEngine; using UnityEditor; namespace Klak.Wiring { [CanEditMultipleObjects] [CustomEditor(typeof(FloatValue))] public class FloatValueEditor : Editor { public override void OnInspectorGUI() { serializedObject.Update(); DrawPropertiesExcluding(serializedObject, new string[] {"m_Script"}); serializedObject.ApplyModifiedProperties(); } } }
22.842105
81
0.652074
[ "MIT" ]
Adjuvant/videolab
Assets/Klak/Wiring/Editor/Input/FloatValueEditor.cs
436
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; using System.Collections.Generic; using System.Linq; using System.Management.Automation; using Microsoft.Azure.Commands.Compute.Automation.Models; using Microsoft.Azure.Commands.ResourceManager.Common.ArgumentCompleters; using Microsoft.Azure.Management.Compute; using Microsoft.Azure.Management.Compute.Models; using Microsoft.WindowsAzure.Commands.Utilities.Common; namespace Microsoft.Azure.Commands.Compute.Automation { [Cmdlet(VerbsCommon.Remove, ResourceManager.Common.AzureRMConstants.AzureRMPrefix + "Image", DefaultParameterSetName = "DefaultParameter", SupportsShouldProcess = true)] [OutputType(typeof(PSOperationStatusResponse))] public partial class RemoveAzureRmImage : ComputeAutomationBaseCmdlet { public override void ExecuteCmdlet() { base.ExecuteCmdlet(); ExecuteClientAction(() => { if (ShouldProcess(this.ImageName, VerbsCommon.Remove) && (this.Force.IsPresent || this.ShouldContinue(Properties.Resources.ResourceRemovalConfirmation, "Remove-AzImage operation"))) { string resourceGroupName = this.ResourceGroupName; string imageName = this.ImageName; var result = ImagesClient.DeleteWithHttpMessagesAsync(resourceGroupName, imageName).GetAwaiter().GetResult(); PSOperationStatusResponse output = new PSOperationStatusResponse { StartTime = this.StartTime, EndTime = DateTime.Now }; if (result != null && result.Request != null && result.Request.RequestUri != null) { output.Name = GetOperationIdFromUrlString(result.Request.RequestUri.ToString()); } WriteObject(output); } }); } [Parameter( ParameterSetName = "DefaultParameter", Position = 0, Mandatory = true, ValueFromPipelineByPropertyName = true)] [ResourceGroupCompleter] public string ResourceGroupName { get; set; } [Parameter( ParameterSetName = "DefaultParameter", Position = 1, Mandatory = true, ValueFromPipelineByPropertyName = true)] [ResourceNameCompleter("Microsoft.Compute/images", "ResourceGroupName")] [Alias("Name")] public string ImageName { get; set; } [Parameter( ParameterSetName = "DefaultParameter", Mandatory = false)] public SwitchParameter Force { get; set; } [Parameter(Mandatory = false, HelpMessage = "Run cmdlet in the background")] public SwitchParameter AsJob { get; set; } } }
40.178947
174
0.620906
[ "MIT" ]
AladdinBI/azure-powershell
src/Compute/Compute/Generated/Image/ImageDeleteMethod.cs
3,723
C#
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AzureNextGen.Media.V20200501.Outputs { [OutputType] public sealed class SystemDataResponse { /// <summary> /// The timestamp of resource creation (UTC). /// </summary> public readonly string? CreatedAt; /// <summary> /// The identity that created the resource. /// </summary> public readonly string? CreatedBy; /// <summary> /// The type of identity that created the resource. /// </summary> public readonly string? CreatedByType; /// <summary> /// The timestamp of resource last modification (UTC) /// </summary> public readonly string? LastModifiedAt; /// <summary> /// The identity that last modified the resource. /// </summary> public readonly string? LastModifiedBy; /// <summary> /// The type of identity that last modified the resource. /// </summary> public readonly string? LastModifiedByType; [OutputConstructor] private SystemDataResponse( string? createdAt, string? createdBy, string? createdByType, string? lastModifiedAt, string? lastModifiedBy, string? lastModifiedByType) { CreatedAt = createdAt; CreatedBy = createdBy; CreatedByType = createdByType; LastModifiedAt = lastModifiedAt; LastModifiedBy = lastModifiedBy; LastModifiedByType = lastModifiedByType; } } }
29.5
81
0.601695
[ "Apache-2.0" ]
pulumi/pulumi-azure-nextgen
sdk/dotnet/Media/V20200501/Outputs/SystemDataResponse.cs
1,888
C#
/* Yet Another Forum.NET * Copyright (C) 2003-2005 Bjørnar Henden * Copyright (C) 2006-2013 Jaben Cargman * Copyright (C) 2014-2022 Ingo Herbote * https://www.yetanotherforum.net/ * * 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 * https://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ namespace YAF.Web.EventsArgs { using System; using YAF.Types; /// <summary> /// The pop event args. /// </summary> public class PopEventArgs : EventArgs { #region Constructors and Destructors /// <summary> /// Initializes a new instance of the <see cref="PopEventArgs"/> class. /// </summary> /// <param name="eventArgument"> /// The event argument. /// </param> public PopEventArgs([NotNull] string eventArgument) { this.Item = eventArgument; } #endregion #region Properties /// <summary> /// Gets Item. /// </summary> public string Item { get; } #endregion } }
29.983333
80
0.629794
[ "Apache-2.0" ]
correaAlex/YAFNET
yafsrc/YAF.Web/EventsArgs/PopEventArgs.cs
1,741
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is regenerated. namespace Microsoft.Azure.PowerShell.Cmdlets.HealthBot.Models { using Microsoft.Azure.PowerShell.Cmdlets.HealthBot.Runtime.PowerShell; /// <summary> /// A PowerShell PSTypeConverter to support converting to an instance of <see cref="Any" /> /// </summary> public partial class AnyTypeConverter : global::System.Management.Automation.PSTypeConverter { /// <summary> /// Determines if the converter can convert the <see cref="sourceValue"/> parameter to the <see cref="destinationType" /> /// parameter. /// </summary> /// <param name="sourceValue">the <see cref="System.Object"/> to convert from</param> /// <param name="destinationType">the <see cref="System.Type" /> to convert to</param> /// <returns> /// <c>true</c> if the converter can convert the <see cref="sourceValue"/> parameter to the <see cref="destinationType" /> /// parameter, otherwise <c>false</c>. /// </returns> public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); /// <summary> /// Determines if the converter can convert the <see cref="sourceValue"/> parameter to the <see cref="destinationType" /> /// parameter. /// </summary> /// <param name="sourceValue">the <see cref="System.Object" /> instance to check if it can be converted to the <see cref="Any" /// /> type.</param> /// <returns> /// <c>true</c> if the instance could be converted to a <see cref="Any" /> type, otherwise <c>false</c> /// </returns> public static bool CanConvertFrom(dynamic sourceValue) { if (null == sourceValue) { return true; } global::System.Type type = sourceValue.GetType(); if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) { // we say yest to PSObjects return true; } if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) { // we say yest to Hashtables/dictionaries return true; } try { if (null != sourceValue.ToJsonString()) { return true; } } catch { // Not one of our objects } try { string text = sourceValue.ToString()?.Trim(); return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.HealthBot.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.HealthBot.Runtime.Json.JsonType.Object; } catch { // Doesn't look like it can be treated as JSON } return false; } /// <summary> /// Determines if the <see cref="sourceValue" /> parameter can be converted to the <see cref="destinationType" /> parameter /// </summary> /// <param name="sourceValue">the <see cref="System.Object"/> to convert from</param> /// <param name="destinationType">the <see cref="System.Type" /> to convert to</param> /// <returns> /// <c>true</c> if the converter can convert the <see cref="sourceValue" /> parameter to the <see cref="destinationType" /> /// parameter, otherwise <c>false</c> /// </returns> public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; /// <summary> /// Converts the <see cref="sourceValue" /> parameter to the <see cref="destinationType" /> parameter using <see cref="formatProvider" /// /> and <see cref="ignoreCase" /> /// </summary> /// <param name="sourceValue">the <see cref="System.Object"/> to convert from</param> /// <param name="destinationType">the <see cref="System.Type" /> to convert to</param> /// <param name="formatProvider">not used by this TypeConverter.</param> /// <param name="ignoreCase">when set to <c>true</c>, will ignore the case when converting.</param> /// <returns> /// an instance of <see cref="Any" />, or <c>null</c> if there is no suitable conversion. /// </returns> public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); /// <summary> /// Converts the <see cref="sourceValue" /> parameter to the <see cref="destinationType" /> parameter using <see cref="formatProvider" /// /> and <see cref="ignoreCase" /> /// </summary> /// <param name="sourceValue">the value to convert into an instance of <see cref="Any" />.</param> /// <returns> /// an instance of <see cref="Any" />, or <c>null</c> if there is no suitable conversion. /// </returns> public static Microsoft.Azure.PowerShell.Cmdlets.HealthBot.Models.IAny ConvertFrom(dynamic sourceValue) { if (null == sourceValue) { return null; } global::System.Type type = sourceValue.GetType(); if (typeof(Microsoft.Azure.PowerShell.Cmdlets.HealthBot.Models.IAny).IsAssignableFrom(type)) { return sourceValue; } try { return Any.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; } catch { // Unable to use JSON pattern } if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) { return Any.DeserializeFromPSObject(sourceValue); } if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) { return Any.DeserializeFromDictionary(sourceValue); } return null; } /// <summary>NotImplemented -- this will return <c>null</c></summary> /// <param name="sourceValue">the <see cref="System.Object"/> to convert from</param> /// <param name="destinationType">the <see cref="System.Type" /> to convert to</param> /// <param name="formatProvider">not used by this TypeConverter.</param> /// <param name="ignoreCase">when set to <c>true</c>, will ignore the case when converting.</param> /// <returns>will always return <c>null</c>.</returns> public override object ConvertTo(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => null; } }
50.44898
249
0.579558
[ "MIT" ]
3quanfeng/azure-powershell
src/HealthBot/generated/api/Models/Any.TypeConverter.cs
7,270
C#